aboutsummaryrefslogtreecommitdiffstats
path: root/security
diff options
context:
space:
mode:
Diffstat (limited to 'security')
-rw-r--r--security/Kconfig44
-rw-r--r--security/apparmor/.gitignore1
-rw-r--r--security/apparmor/Makefile38
-rw-r--r--security/apparmor/apparmorfs.c13
-rw-r--r--security/apparmor/include/file.h3
-rw-r--r--security/apparmor/include/match.h3
-rw-r--r--security/apparmor/lsm.c18
-rw-r--r--security/apparmor/match.c4
-rw-r--r--security/apparmor/path.c2
-rw-r--r--security/apparmor/policy.c2
-rw-r--r--security/apparmor/policy_unpack.c6
-rw-r--r--security/capability.c35
-rw-r--r--security/commoncap.c120
-rw-r--r--security/device_cgroup.c11
-rw-r--r--security/inode.c10
-rw-r--r--security/integrity/ima/ima.h21
-rw-r--r--security/integrity/ima/ima_api.c13
-rw-r--r--security/integrity/ima/ima_iint.c153
-rw-r--r--security/integrity/ima/ima_main.c204
-rw-r--r--security/integrity/ima/ima_policy.c2
-rw-r--r--security/keys/Makefile2
-rw-r--r--security/keys/compat.c67
-rw-r--r--security/keys/encrypted.c902
-rw-r--r--security/keys/encrypted.h54
-rw-r--r--security/keys/gc.c14
-rw-r--r--security/keys/internal.h44
-rw-r--r--security/keys/key.c345
-rw-r--r--security/keys/keyctl.c502
-rw-r--r--security/keys/keyring.c367
-rw-r--r--security/keys/permission.c33
-rw-r--r--security/keys/proc.c19
-rw-r--r--security/keys/process_keys.c150
-rw-r--r--security/keys/request_key.c180
-rw-r--r--security/keys/request_key_auth.c67
-rw-r--r--security/keys/trusted.c1180
-rw-r--r--security/keys/trusted.h134
-rw-r--r--security/keys/user_defined.c53
-rw-r--r--security/lsm_audit.c59
-rw-r--r--security/security.c104
-rw-r--r--security/selinux/Makefile21
-rw-r--r--security/selinux/avc.c63
-rw-r--r--security/selinux/exports.c49
-rw-r--r--security/selinux/hooks.c566
-rw-r--r--security/selinux/include/avc.h20
-rw-r--r--security/selinux/include/classmap.h11
-rw-r--r--security/selinux/include/security.h36
-rw-r--r--security/selinux/include/xfrm.h2
-rw-r--r--security/selinux/netif.c18
-rw-r--r--security/selinux/netlabel.c2
-rw-r--r--security/selinux/netnode.c1
-rw-r--r--security/selinux/nlmsgtab.c2
-rw-r--r--security/selinux/selinuxfs.c939
-rw-r--r--security/selinux/ss/Makefile9
-rw-r--r--security/selinux/ss/avtab.c46
-rw-r--r--security/selinux/ss/avtab.h26
-rw-r--r--security/selinux/ss/conditional.c131
-rw-r--r--security/selinux/ss/conditional.h2
-rw-r--r--security/selinux/ss/ebitmap.c81
-rw-r--r--security/selinux/ss/ebitmap.h2
-rw-r--r--security/selinux/ss/mls.c30
-rw-r--r--security/selinux/ss/mls.h3
-rw-r--r--security/selinux/ss/policydb.c1817
-rw-r--r--security/selinux/ss/policydb.h59
-rw-r--r--security/selinux/ss/services.c596
-rw-r--r--security/selinux/ss/sidtab.c39
-rw-r--r--security/selinux/ss/sidtab.h2
-rw-r--r--security/selinux/ss/status.c126
-rw-r--r--security/selinux/xfrm.c8
-rw-r--r--security/smack/smack.h67
-rw-r--r--security/smack/smack_access.c90
-rw-r--r--security/smack/smack_lsm.c673
-rw-r--r--security/smack/smackfs.c424
-rw-r--r--security/tomoyo/common.c34
-rw-r--r--security/tomoyo/file.c6
-rw-r--r--security/tomoyo/load_policy.c2
-rw-r--r--security/tomoyo/memory.c1
-rw-r--r--security/tomoyo/mount.c3
-rw-r--r--security/tomoyo/realpath.c3
-rw-r--r--security/tomoyo/util.c2
79 files changed, 8144 insertions, 2847 deletions
diff --git a/security/Kconfig b/security/Kconfig
index bd72ae623494..e0f08b52e4ab 100644
--- a/security/Kconfig
+++ b/security/Kconfig
@@ -21,6 +21,37 @@ config KEYS
21 21
22 If you are unsure as to whether this is required, answer N. 22 If you are unsure as to whether this is required, answer N.
23 23
24config TRUSTED_KEYS
25 tristate "TRUSTED KEYS"
26 depends on KEYS && TCG_TPM
27 select CRYPTO
28 select CRYPTO_HMAC
29 select CRYPTO_SHA1
30 help
31 This option provides support for creating, sealing, and unsealing
32 keys in the kernel. Trusted keys are random number symmetric keys,
33 generated and RSA-sealed by the TPM. The TPM only unseals the keys,
34 if the boot PCRs and other criteria match. Userspace will only ever
35 see encrypted blobs.
36
37 If you are unsure as to whether this is required, answer N.
38
39config ENCRYPTED_KEYS
40 tristate "ENCRYPTED KEYS"
41 depends on KEYS && TRUSTED_KEYS
42 select CRYPTO_AES
43 select CRYPTO_CBC
44 select CRYPTO_SHA256
45 select CRYPTO_RNG
46 help
47 This option provides support for create/encrypting/decrypting keys
48 in the kernel. Encrypted keys are kernel generated random numbers,
49 which are encrypted/decrypted with a 'master' symmetric key. The
50 'master' key can be either a trusted-key or user-key type.
51 Userspace only ever sees/stores encrypted blobs.
52
53 If you are unsure as to whether this is required, answer N.
54
24config KEYS_DEBUG_PROC_KEYS 55config KEYS_DEBUG_PROC_KEYS
25 bool "Enable the /proc/keys file by which keys may be viewed" 56 bool "Enable the /proc/keys file by which keys may be viewed"
26 depends on KEYS 57 depends on KEYS
@@ -39,6 +70,18 @@ config KEYS_DEBUG_PROC_KEYS
39 70
40 If you are unsure as to whether this is required, answer N. 71 If you are unsure as to whether this is required, answer N.
41 72
73config SECURITY_DMESG_RESTRICT
74 bool "Restrict unprivileged access to the kernel syslog"
75 default n
76 help
77 This enforces restrictions on unprivileged users reading the kernel
78 syslog via dmesg(8).
79
80 If this option is not selected, no restrictions will be enforced
81 unless the dmesg_restrict sysctl is explicitly set to (1).
82
83 If you are unsure how to answer this question, answer N.
84
42config SECURITY 85config SECURITY
43 bool "Enable different security models" 86 bool "Enable different security models"
44 depends on SYSFS 87 depends on SYSFS
@@ -124,6 +167,7 @@ config INTEL_TXT
124config LSM_MMAP_MIN_ADDR 167config LSM_MMAP_MIN_ADDR
125 int "Low address space for LSM to protect from user allocation" 168 int "Low address space for LSM to protect from user allocation"
126 depends on SECURITY && SECURITY_SELINUX 169 depends on SECURITY && SECURITY_SELINUX
170 default 32768 if ARM
127 default 65536 171 default 65536
128 help 172 help
129 This is the portion of low virtual memory which should be protected 173 This is the portion of low virtual memory which should be protected
diff --git a/security/apparmor/.gitignore b/security/apparmor/.gitignore
index 0a0a99f3b083..4d995aeaebc0 100644
--- a/security/apparmor/.gitignore
+++ b/security/apparmor/.gitignore
@@ -3,3 +3,4 @@
3# 3#
4af_names.h 4af_names.h
5capability_names.h 5capability_names.h
6rlim_names.h
diff --git a/security/apparmor/Makefile b/security/apparmor/Makefile
index f204869399ea..2dafe50a2e25 100644
--- a/security/apparmor/Makefile
+++ b/security/apparmor/Makefile
@@ -6,19 +6,47 @@ apparmor-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 \ 6 path.o domain.o policy.o policy_unpack.o procattr.o lsm.o \
7 resource.o sid.o file.o 7 resource.o sid.o file.o
8 8
9clean-files: capability_names.h af_names.h 9clean-files := capability_names.h rlim_names.h
10 10
11
12# Build a lower case string table of capability names
13# Transforms lines from
14# #define CAP_DAC_OVERRIDE 1
15# to
16# [1] = "dac_override",
11quiet_cmd_make-caps = GEN $@ 17quiet_cmd_make-caps = GEN $@
12cmd_make-caps = echo "static const char *capability_names[] = {" > $@ ; sed -n -e "/CAP_FS_MASK/d" -e "s/^\#define[ \\t]\\+CAP_\\([A-Z0-9_]\\+\\)[ \\t]\\+\\([0-9]\\+\\)\$$/[\\2] = \"\\1\",/p" $< | tr A-Z a-z >> $@ ; echo "};" >> $@ 18cmd_make-caps = echo "static const char *capability_names[] = {" > $@ ;\
19 sed $< >>$@ -r -n -e '/CAP_FS_MASK/d' \
20 -e 's/^\#define[ \t]+CAP_([A-Z0-9_]+)[ \t]+([0-9]+)/[\2] = "\L\1",/p';\
21 echo "};" >> $@
22
13 23
24# Build a lower case string table of rlimit names.
25# Transforms lines from
26# #define RLIMIT_STACK 3 /* max stack size */
27# to
28# [RLIMIT_STACK] = "stack",
29#
30# and build a second integer table (with the second sed cmd), that maps
31# RLIMIT defines to the order defined in asm-generic/resource.h Thi is
32# required by policy load to map policy ordering of RLIMITs to internal
33# ordering for architectures that redefine an RLIMIT.
34# Transforms lines from
35# #define RLIMIT_STACK 3 /* max stack size */
36# to
37# RLIMIT_STACK,
14quiet_cmd_make-rlim = GEN $@ 38quiet_cmd_make-rlim = GEN $@
15cmd_make-rlim = echo "static const char *rlim_names[] = {" > $@ ; sed -n --e "/AF_MAX/d" -e "s/^\# \\?define[ \\t]\\+RLIMIT_\\([A-Z0-9_]\\+\\)[ \\t]\\+\\([0-9]\\+\\)\\(.*\\)\$$/[\\2] = \"\\1\",/p" $< | tr A-Z a-z >> $@ ; echo "};" >> $@ ; echo "static const int rlim_map[] = {" >> $@ ; sed -n -e "/AF_MAX/d" -e "s/^\# \\?define[ \\t]\\+\\(RLIMIT_[A-Z0-9_]\\+\\)[ \\t]\\+\\([0-9]\\+\\)\\(.*\\)\$$/\\1,/p" $< >> $@ ; echo "};" >> $@ 39cmd_make-rlim = echo "static const char *rlim_names[] = {" > $@ ;\
40 sed $< >> $@ -r -n \
41 -e 's/^\# ?define[ \t]+(RLIMIT_([A-Z0-9_]+)).*/[\1] = "\L\2",/p';\
42 echo "};" >> $@ ;\
43 echo "static const int rlim_map[] = {" >> $@ ;\
44 sed -r -n "s/^\# ?define[ \t]+(RLIMIT_[A-Z0-9_]+).*/\1,/p" $< >> $@ ;\
45 echo "};" >> $@
16 46
17$(obj)/capability.o : $(obj)/capability_names.h 47$(obj)/capability.o : $(obj)/capability_names.h
18$(obj)/resource.o : $(obj)/rlim_names.h 48$(obj)/resource.o : $(obj)/rlim_names.h
19$(obj)/capability_names.h : $(srctree)/include/linux/capability.h 49$(obj)/capability_names.h : $(srctree)/include/linux/capability.h
20 $(call cmd,make-caps) 50 $(call cmd,make-caps)
21$(obj)/af_names.h : $(srctree)/include/linux/socket.h
22 $(call cmd,make-af)
23$(obj)/rlim_names.h : $(srctree)/include/asm-generic/resource.h 51$(obj)/rlim_names.h : $(srctree)/include/asm-generic/resource.h
24 $(call cmd,make-rlim) 52 $(call cmd,make-rlim)
diff --git a/security/apparmor/apparmorfs.c b/security/apparmor/apparmorfs.c
index 7320331b44ab..0848292982a2 100644
--- a/security/apparmor/apparmorfs.c
+++ b/security/apparmor/apparmorfs.c
@@ -29,7 +29,7 @@
29 * aa_simple_write_to_buffer - common routine for getting policy from user 29 * aa_simple_write_to_buffer - common routine for getting policy from user
30 * @op: operation doing the user buffer copy 30 * @op: operation doing the user buffer copy
31 * @userbuf: user buffer to copy data from (NOT NULL) 31 * @userbuf: user buffer to copy data from (NOT NULL)
32 * @alloc_size: size of user buffer 32 * @alloc_size: size of user buffer (REQUIRES: @alloc_size >= @copy_size)
33 * @copy_size: size of data to copy from user buffer 33 * @copy_size: size of data to copy from user buffer
34 * @pos: position write is at in the file (NOT NULL) 34 * @pos: position write is at in the file (NOT NULL)
35 * 35 *
@@ -42,6 +42,8 @@ static char *aa_simple_write_to_buffer(int op, const char __user *userbuf,
42{ 42{
43 char *data; 43 char *data;
44 44
45 BUG_ON(copy_size > alloc_size);
46
45 if (*pos != 0) 47 if (*pos != 0)
46 /* only writes from pos 0, that is complete writes */ 48 /* only writes from pos 0, that is complete writes */
47 return ERR_PTR(-ESPIPE); 49 return ERR_PTR(-ESPIPE);
@@ -86,7 +88,8 @@ static ssize_t profile_load(struct file *f, const char __user *buf, size_t size,
86} 88}
87 89
88static const struct file_operations aa_fs_profile_load = { 90static const struct file_operations aa_fs_profile_load = {
89 .write = profile_load 91 .write = profile_load,
92 .llseek = default_llseek,
90}; 93};
91 94
92/* .replace file hook fn to load and/or replace policy */ 95/* .replace file hook fn to load and/or replace policy */
@@ -107,7 +110,8 @@ static ssize_t profile_replace(struct file *f, const char __user *buf,
107} 110}
108 111
109static const struct file_operations aa_fs_profile_replace = { 112static const struct file_operations aa_fs_profile_replace = {
110 .write = profile_replace 113 .write = profile_replace,
114 .llseek = default_llseek,
111}; 115};
112 116
113/* .remove file hook fn to remove loaded policy */ 117/* .remove file hook fn to remove loaded policy */
@@ -134,7 +138,8 @@ static ssize_t profile_remove(struct file *f, const char __user *buf,
134} 138}
135 139
136static const struct file_operations aa_fs_profile_remove = { 140static const struct file_operations aa_fs_profile_remove = {
137 .write = profile_remove 141 .write = profile_remove,
142 .llseek = default_llseek,
138}; 143};
139 144
140/** Base file system setup **/ 145/** Base file system setup **/
diff --git a/security/apparmor/include/file.h b/security/apparmor/include/file.h
index be36feabb16a..ab8c6d87f758 100644
--- a/security/apparmor/include/file.h
+++ b/security/apparmor/include/file.h
@@ -15,12 +15,11 @@
15#ifndef __AA_FILE_H 15#ifndef __AA_FILE_H
16#define __AA_FILE_H 16#define __AA_FILE_H
17 17
18#include <linux/path.h>
19
20#include "domain.h" 18#include "domain.h"
21#include "match.h" 19#include "match.h"
22 20
23struct aa_profile; 21struct aa_profile;
22struct path;
24 23
25/* 24/*
26 * We use MAY_EXEC, MAY_WRITE, MAY_READ, MAY_APPEND and the following flags 25 * We use MAY_EXEC, MAY_WRITE, MAY_READ, MAY_APPEND and the following flags
diff --git a/security/apparmor/include/match.h b/security/apparmor/include/match.h
index 734a6d35112c..a4a863997bd5 100644
--- a/security/apparmor/include/match.h
+++ b/security/apparmor/include/match.h
@@ -15,6 +15,7 @@
15#ifndef __AA_MATCH_H 15#ifndef __AA_MATCH_H
16#define __AA_MATCH_H 16#define __AA_MATCH_H
17 17
18#include <linux/kref.h>
18#include <linux/workqueue.h> 19#include <linux/workqueue.h>
19 20
20#define DFA_NOMATCH 0 21#define DFA_NOMATCH 0
@@ -27,7 +28,7 @@
27 * The format used for transition tables is based on the GNU flex table 28 * The format used for transition tables is based on the GNU flex table
28 * file format (--tables-file option; see Table File Format in the flex 29 * file format (--tables-file option; see Table File Format in the flex
29 * info pages and the flex sources for documentation). The magic number 30 * info pages and the flex sources for documentation). The magic number
30 * used in the header is 0x1B5E783D insted of 0xF13C57B1 though, because 31 * used in the header is 0x1B5E783D instead of 0xF13C57B1 though, because
31 * the YY_ID_CHK (check) and YY_ID_DEF (default) tables are used 32 * the YY_ID_CHK (check) and YY_ID_DEF (default) tables are used
32 * slightly differently (see the apparmor-parser package). 33 * slightly differently (see the apparmor-parser package).
33 */ 34 */
diff --git a/security/apparmor/lsm.c b/security/apparmor/lsm.c
index cf1de4462ccd..3d2fd141dff7 100644
--- a/security/apparmor/lsm.c
+++ b/security/apparmor/lsm.c
@@ -22,6 +22,7 @@
22#include <linux/ctype.h> 22#include <linux/ctype.h>
23#include <linux/sysctl.h> 23#include <linux/sysctl.h>
24#include <linux/audit.h> 24#include <linux/audit.h>
25#include <linux/user_namespace.h>
25#include <net/sock.h> 26#include <net/sock.h>
26 27
27#include "include/apparmor.h" 28#include "include/apparmor.h"
@@ -136,11 +137,11 @@ static int apparmor_capget(struct task_struct *target, kernel_cap_t *effective,
136} 137}
137 138
138static int apparmor_capable(struct task_struct *task, const struct cred *cred, 139static int apparmor_capable(struct task_struct *task, const struct cred *cred,
139 int cap, int audit) 140 struct user_namespace *ns, int cap, int audit)
140{ 141{
141 struct aa_profile *profile; 142 struct aa_profile *profile;
142 /* cap_capable returns 0 on success, else -EPERM */ 143 /* cap_capable returns 0 on success, else -EPERM */
143 int error = cap_capable(task, cred, cap, audit); 144 int error = cap_capable(task, cred, ns, cap, audit);
144 if (!error) { 145 if (!error) {
145 profile = aa_cred_profile(cred); 146 profile = aa_cred_profile(cred);
146 if (!unconfined(profile)) 147 if (!unconfined(profile))
@@ -592,7 +593,8 @@ static int apparmor_setprocattr(struct task_struct *task, char *name,
592 sa.aad.op = OP_SETPROCATTR; 593 sa.aad.op = OP_SETPROCATTR;
593 sa.aad.info = name; 594 sa.aad.info = name;
594 sa.aad.error = -EINVAL; 595 sa.aad.error = -EINVAL;
595 return aa_audit(AUDIT_APPARMOR_DENIED, NULL, GFP_KERNEL, 596 return aa_audit(AUDIT_APPARMOR_DENIED,
597 __aa_current_profile(), GFP_KERNEL,
596 &sa, NULL); 598 &sa, NULL);
597 } 599 }
598 } else if (strcmp(name, "exec") == 0) { 600 } else if (strcmp(name, "exec") == 0) {
@@ -610,7 +612,7 @@ static int apparmor_setprocattr(struct task_struct *task, char *name,
610static int apparmor_task_setrlimit(struct task_struct *task, 612static int apparmor_task_setrlimit(struct task_struct *task,
611 unsigned int resource, struct rlimit *new_rlim) 613 unsigned int resource, struct rlimit *new_rlim)
612{ 614{
613 struct aa_profile *profile = aa_current_profile(); 615 struct aa_profile *profile = __aa_current_profile();
614 int error = 0; 616 int error = 0;
615 617
616 if (!unconfined(profile)) 618 if (!unconfined(profile))
@@ -693,11 +695,9 @@ static struct kernel_param_ops param_ops_aalockpolicy = {
693 695
694static int param_set_audit(const char *val, struct kernel_param *kp); 696static int param_set_audit(const char *val, struct kernel_param *kp);
695static int param_get_audit(char *buffer, struct kernel_param *kp); 697static int param_get_audit(char *buffer, struct kernel_param *kp);
696#define param_check_audit(name, p) __param_check(name, p, int)
697 698
698static int param_set_mode(const char *val, struct kernel_param *kp); 699static int param_set_mode(const char *val, struct kernel_param *kp);
699static int param_get_mode(char *buffer, struct kernel_param *kp); 700static int param_get_mode(char *buffer, struct kernel_param *kp);
700#define param_check_mode(name, p) __param_check(name, p, int)
701 701
702/* Flag values, also controllable via /sys/module/apparmor/parameters 702/* Flag values, also controllable via /sys/module/apparmor/parameters
703 * We define special types as we want to do additional mediation. 703 * We define special types as we want to do additional mediation.
@@ -922,7 +922,7 @@ static int __init apparmor_init(void)
922 error = register_security(&apparmor_ops); 922 error = register_security(&apparmor_ops);
923 if (error) { 923 if (error) {
924 AA_ERROR("Unable to register AppArmor\n"); 924 AA_ERROR("Unable to register AppArmor\n");
925 goto register_security_out; 925 goto set_init_cxt_out;
926 } 926 }
927 927
928 /* Report that AppArmor successfully initialized */ 928 /* Report that AppArmor successfully initialized */
@@ -936,6 +936,9 @@ static int __init apparmor_init(void)
936 936
937 return error; 937 return error;
938 938
939set_init_cxt_out:
940 aa_free_task_context(current->real_cred->security);
941
939register_security_out: 942register_security_out:
940 aa_free_root_ns(); 943 aa_free_root_ns();
941 944
@@ -944,7 +947,6 @@ alloc_out:
944 947
945 apparmor_enabled = 0; 948 apparmor_enabled = 0;
946 return error; 949 return error;
947
948} 950}
949 951
950security_initcall(apparmor_init); 952security_initcall(apparmor_init);
diff --git a/security/apparmor/match.c b/security/apparmor/match.c
index 5cb4dc1f6992..94de6b4907c8 100644
--- a/security/apparmor/match.c
+++ b/security/apparmor/match.c
@@ -194,8 +194,8 @@ void aa_dfa_free_kref(struct kref *kref)
194 * @flags: flags controlling what type of accept tables are acceptable 194 * @flags: flags controlling what type of accept tables are acceptable
195 * 195 *
196 * Unpack a dfa that has been serialized. To find information on the dfa 196 * Unpack a dfa that has been serialized. To find information on the dfa
197 * format look in Documentation/apparmor.txt 197 * format look in Documentation/security/apparmor.txt
198 * Assumes the dfa @blob stream has been aligned on a 8 byte boundry 198 * Assumes the dfa @blob stream has been aligned on a 8 byte boundary
199 * 199 *
200 * Returns: an unpacked dfa ready for matching or ERR_PTR on failure 200 * Returns: an unpacked dfa ready for matching or ERR_PTR on failure
201 */ 201 */
diff --git a/security/apparmor/path.c b/security/apparmor/path.c
index 82396050f186..36cc0cc39e78 100644
--- a/security/apparmor/path.c
+++ b/security/apparmor/path.c
@@ -72,10 +72,8 @@ static int d_namespace_path(struct path *path, char *buf, int buflen,
72 path_get(&root); 72 path_get(&root);
73 } 73 }
74 74
75 spin_lock(&dcache_lock);
76 tmp = root; 75 tmp = root;
77 res = __d_path(path, &tmp, buf, buflen); 76 res = __d_path(path, &tmp, buf, buflen);
78 spin_unlock(&dcache_lock);
79 77
80 *name = res; 78 *name = res;
81 /* handle error conditions - and still allow a partial path to 79 /* handle error conditions - and still allow a partial path to
diff --git a/security/apparmor/policy.c b/security/apparmor/policy.c
index 52cc865f1464..4f0eadee78b8 100644
--- a/security/apparmor/policy.c
+++ b/security/apparmor/policy.c
@@ -306,7 +306,7 @@ static struct aa_namespace *alloc_namespace(const char *prefix,
306 return ns; 306 return ns;
307 307
308fail_unconfined: 308fail_unconfined:
309 kzfree(ns->base.name); 309 kzfree(ns->base.hname);
310fail_ns: 310fail_ns:
311 kzfree(ns); 311 kzfree(ns);
312 return NULL; 312 return NULL;
diff --git a/security/apparmor/policy_unpack.c b/security/apparmor/policy_unpack.c
index eb3700e9fd37..d6d9a57b5652 100644
--- a/security/apparmor/policy_unpack.c
+++ b/security/apparmor/policy_unpack.c
@@ -12,8 +12,8 @@
12 * published by the Free Software Foundation, version 2 of the 12 * published by the Free Software Foundation, version 2 of the
13 * License. 13 * License.
14 * 14 *
15 * AppArmor uses a serialized binary format for loading policy. 15 * AppArmor uses a serialized binary format for loading policy. To find
16 * To find policy format documentation look in Documentation/apparmor.txt 16 * policy format documentation look in Documentation/security/apparmor.txt
17 * All policy is validated before it is used. 17 * All policy is validated before it is used.
18 */ 18 */
19 19
@@ -359,7 +359,7 @@ fail:
359 * @e: serialized data extent information (NOT NULL) 359 * @e: serialized data extent information (NOT NULL)
360 * @profile: profile to add the accept table to (NOT NULL) 360 * @profile: profile to add the accept table to (NOT NULL)
361 * 361 *
362 * Returns: 1 if table succesfully unpacked 362 * Returns: 1 if table successfully unpacked
363 */ 363 */
364static bool unpack_trans_table(struct aa_ext *e, struct aa_profile *profile) 364static bool unpack_trans_table(struct aa_ext *e, struct aa_profile *profile)
365{ 365{
diff --git a/security/capability.c b/security/capability.c
index 95a6599a37bb..bbb51156261b 100644
--- a/security/capability.c
+++ b/security/capability.c
@@ -12,7 +12,7 @@
12 12
13#include <linux/security.h> 13#include <linux/security.h>
14 14
15static int cap_sysctl(ctl_table *table, int op) 15static int cap_syslog(int type)
16{ 16{
17 return 0; 17 return 0;
18} 18}
@@ -54,6 +54,11 @@ static int cap_sb_copy_data(char *orig, char *copy)
54 return 0; 54 return 0;
55} 55}
56 56
57static int cap_sb_remount(struct super_block *sb, void *data)
58{
59 return 0;
60}
61
57static int cap_sb_kern_mount(struct super_block *sb, int flags, void *data) 62static int cap_sb_kern_mount(struct super_block *sb, int flags, void *data)
58{ 63{
59 return 0; 64 return 0;
@@ -113,7 +118,8 @@ static void cap_inode_free_security(struct inode *inode)
113} 118}
114 119
115static int cap_inode_init_security(struct inode *inode, struct inode *dir, 120static int cap_inode_init_security(struct inode *inode, struct inode *dir,
116 char **name, void **value, size_t *len) 121 const struct qstr *qstr, char **name,
122 void **value, size_t *len)
117{ 123{
118 return -EOPNOTSUPP; 124 return -EOPNOTSUPP;
119} 125}
@@ -175,7 +181,7 @@ static int cap_inode_follow_link(struct dentry *dentry,
175 return 0; 181 return 0;
176} 182}
177 183
178static int cap_inode_permission(struct inode *inode, int mask) 184static int cap_inode_permission(struct inode *inode, int mask, unsigned flags)
179{ 185{
180 return 0; 186 return 0;
181} 187}
@@ -543,7 +549,7 @@ static int cap_sem_semop(struct sem_array *sma, struct sembuf *sops,
543} 549}
544 550
545#ifdef CONFIG_SECURITY_NETWORK 551#ifdef CONFIG_SECURITY_NETWORK
546static int cap_unix_stream_connect(struct socket *sock, struct socket *other, 552static int cap_unix_stream_connect(struct sock *sock, struct sock *other,
547 struct sock *newsk) 553 struct sock *newsk)
548{ 554{
549 return 0; 555 return 0;
@@ -677,7 +683,18 @@ static void cap_inet_conn_established(struct sock *sk, struct sk_buff *skb)
677{ 683{
678} 684}
679 685
686static int cap_secmark_relabel_packet(u32 secid)
687{
688 return 0;
689}
680 690
691static void cap_secmark_refcount_inc(void)
692{
693}
694
695static void cap_secmark_refcount_dec(void)
696{
697}
681 698
682static void cap_req_classify_flow(const struct request_sock *req, 699static void cap_req_classify_flow(const struct request_sock *req,
683 struct flowi *fl) 700 struct flowi *fl)
@@ -744,7 +761,7 @@ static int cap_xfrm_policy_lookup(struct xfrm_sec_ctx *ctx, u32 sk_sid, u8 dir)
744 761
745static int cap_xfrm_state_pol_flow_match(struct xfrm_state *x, 762static int cap_xfrm_state_pol_flow_match(struct xfrm_state *x,
746 struct xfrm_policy *xp, 763 struct xfrm_policy *xp,
747 struct flowi *fl) 764 const struct flowi *fl)
748{ 765{
749 return 1; 766 return 1;
750} 767}
@@ -777,7 +794,8 @@ static int cap_secid_to_secctx(u32 secid, char **secdata, u32 *seclen)
777 794
778static int cap_secctx_to_secid(const char *secdata, u32 seclen, u32 *secid) 795static int cap_secctx_to_secid(const char *secdata, u32 seclen, u32 *secid)
779{ 796{
780 return -EOPNOTSUPP; 797 *secid = 0;
798 return 0;
781} 799}
782 800
783static void cap_release_secctx(char *secdata, u32 seclen) 801static void cap_release_secctx(char *secdata, u32 seclen)
@@ -863,7 +881,6 @@ void __init security_fixup_ops(struct security_operations *ops)
863 set_to_cap_if_null(ops, capable); 881 set_to_cap_if_null(ops, capable);
864 set_to_cap_if_null(ops, quotactl); 882 set_to_cap_if_null(ops, quotactl);
865 set_to_cap_if_null(ops, quota_on); 883 set_to_cap_if_null(ops, quota_on);
866 set_to_cap_if_null(ops, sysctl);
867 set_to_cap_if_null(ops, syslog); 884 set_to_cap_if_null(ops, syslog);
868 set_to_cap_if_null(ops, settime); 885 set_to_cap_if_null(ops, settime);
869 set_to_cap_if_null(ops, vm_enough_memory); 886 set_to_cap_if_null(ops, vm_enough_memory);
@@ -875,6 +892,7 @@ void __init security_fixup_ops(struct security_operations *ops)
875 set_to_cap_if_null(ops, sb_alloc_security); 892 set_to_cap_if_null(ops, sb_alloc_security);
876 set_to_cap_if_null(ops, sb_free_security); 893 set_to_cap_if_null(ops, sb_free_security);
877 set_to_cap_if_null(ops, sb_copy_data); 894 set_to_cap_if_null(ops, sb_copy_data);
895 set_to_cap_if_null(ops, sb_remount);
878 set_to_cap_if_null(ops, sb_kern_mount); 896 set_to_cap_if_null(ops, sb_kern_mount);
879 set_to_cap_if_null(ops, sb_show_options); 897 set_to_cap_if_null(ops, sb_show_options);
880 set_to_cap_if_null(ops, sb_statfs); 898 set_to_cap_if_null(ops, sb_statfs);
@@ -1018,6 +1036,9 @@ void __init security_fixup_ops(struct security_operations *ops)
1018 set_to_cap_if_null(ops, inet_conn_request); 1036 set_to_cap_if_null(ops, inet_conn_request);
1019 set_to_cap_if_null(ops, inet_csk_clone); 1037 set_to_cap_if_null(ops, inet_csk_clone);
1020 set_to_cap_if_null(ops, inet_conn_established); 1038 set_to_cap_if_null(ops, inet_conn_established);
1039 set_to_cap_if_null(ops, secmark_relabel_packet);
1040 set_to_cap_if_null(ops, secmark_refcount_inc);
1041 set_to_cap_if_null(ops, secmark_refcount_dec);
1021 set_to_cap_if_null(ops, req_classify_flow); 1042 set_to_cap_if_null(ops, req_classify_flow);
1022 set_to_cap_if_null(ops, tun_dev_create); 1043 set_to_cap_if_null(ops, tun_dev_create);
1023 set_to_cap_if_null(ops, tun_dev_post_create); 1044 set_to_cap_if_null(ops, tun_dev_post_create);
diff --git a/security/commoncap.c b/security/commoncap.c
index 9d172e6e330c..a93b3b733079 100644
--- a/security/commoncap.c
+++ b/security/commoncap.c
@@ -27,7 +27,7 @@
27#include <linux/sched.h> 27#include <linux/sched.h>
28#include <linux/prctl.h> 28#include <linux/prctl.h>
29#include <linux/securebits.h> 29#include <linux/securebits.h>
30#include <linux/syslog.h> 30#include <linux/user_namespace.h>
31 31
32/* 32/*
33 * If a non-root user executes a setuid-root binary in 33 * If a non-root user executes a setuid-root binary in
@@ -53,13 +53,12 @@ static void warn_setuid_and_fcaps_mixed(const char *fname)
53 53
54int cap_netlink_send(struct sock *sk, struct sk_buff *skb) 54int cap_netlink_send(struct sock *sk, struct sk_buff *skb)
55{ 55{
56 NETLINK_CB(skb).eff_cap = current_cap();
57 return 0; 56 return 0;
58} 57}
59 58
60int cap_netlink_recv(struct sk_buff *skb, int cap) 59int cap_netlink_recv(struct sk_buff *skb, int cap)
61{ 60{
62 if (!cap_raised(NETLINK_CB(skb).eff_cap, cap)) 61 if (!cap_raised(current_cap(), cap))
63 return -EPERM; 62 return -EPERM;
64 return 0; 63 return 0;
65} 64}
@@ -69,6 +68,7 @@ EXPORT_SYMBOL(cap_netlink_recv);
69 * cap_capable - Determine whether a task has a particular effective capability 68 * cap_capable - Determine whether a task has a particular effective capability
70 * @tsk: The task to query 69 * @tsk: The task to query
71 * @cred: The credentials to use 70 * @cred: The credentials to use
71 * @ns: The user namespace in which we need the capability
72 * @cap: The capability to check for 72 * @cap: The capability to check for
73 * @audit: Whether to write an audit message or not 73 * @audit: Whether to write an audit message or not
74 * 74 *
@@ -80,10 +80,30 @@ EXPORT_SYMBOL(cap_netlink_recv);
80 * cap_has_capability() returns 0 when a task has a capability, but the 80 * cap_has_capability() returns 0 when a task has a capability, but the
81 * kernel's capable() and has_capability() returns 1 for this case. 81 * kernel's capable() and has_capability() returns 1 for this case.
82 */ 82 */
83int cap_capable(struct task_struct *tsk, const struct cred *cred, int cap, 83int cap_capable(struct task_struct *tsk, const struct cred *cred,
84 int audit) 84 struct user_namespace *targ_ns, int cap, int audit)
85{ 85{
86 return cap_raised(cred->cap_effective, cap) ? 0 : -EPERM; 86 for (;;) {
87 /* The creator of the user namespace has all caps. */
88 if (targ_ns != &init_user_ns && targ_ns->creator == cred->user)
89 return 0;
90
91 /* Do we have the necessary capabilities? */
92 if (targ_ns == cred->user->user_ns)
93 return cap_raised(cred->cap_effective, cap) ? 0 : -EPERM;
94
95 /* Have we tried all of the parent namespaces? */
96 if (targ_ns == &init_user_ns)
97 return -EPERM;
98
99 /*
100 *If you have a capability in a parent user ns, then you have
101 * it over all children user namespaces as well.
102 */
103 targ_ns = targ_ns->creator->user_ns;
104 }
105
106 /* We never get here */
87} 107}
88 108
89/** 109/**
@@ -94,7 +114,7 @@ int cap_capable(struct task_struct *tsk, const struct cred *cred, int cap,
94 * Determine whether the current process may set the system clock and timezone 114 * Determine whether the current process may set the system clock and timezone
95 * information, returning 0 if permission granted, -ve if denied. 115 * information, returning 0 if permission granted, -ve if denied.
96 */ 116 */
97int cap_settime(struct timespec *ts, struct timezone *tz) 117int cap_settime(const struct timespec *ts, const struct timezone *tz)
98{ 118{
99 if (!capable(CAP_SYS_TIME)) 119 if (!capable(CAP_SYS_TIME))
100 return -EPERM; 120 return -EPERM;
@@ -107,18 +127,30 @@ int cap_settime(struct timespec *ts, struct timezone *tz)
107 * @child: The process to be accessed 127 * @child: The process to be accessed
108 * @mode: The mode of attachment. 128 * @mode: The mode of attachment.
109 * 129 *
130 * If we are in the same or an ancestor user_ns and have all the target
131 * task's capabilities, then ptrace access is allowed.
132 * If we have the ptrace capability to the target user_ns, then ptrace
133 * access is allowed.
134 * Else denied.
135 *
110 * Determine whether a process may access another, returning 0 if permission 136 * Determine whether a process may access another, returning 0 if permission
111 * granted, -ve if denied. 137 * granted, -ve if denied.
112 */ 138 */
113int cap_ptrace_access_check(struct task_struct *child, unsigned int mode) 139int cap_ptrace_access_check(struct task_struct *child, unsigned int mode)
114{ 140{
115 int ret = 0; 141 int ret = 0;
142 const struct cred *cred, *child_cred;
116 143
117 rcu_read_lock(); 144 rcu_read_lock();
118 if (!cap_issubset(__task_cred(child)->cap_permitted, 145 cred = current_cred();
119 current_cred()->cap_permitted) && 146 child_cred = __task_cred(child);
120 !capable(CAP_SYS_PTRACE)) 147 if (cred->user->user_ns == child_cred->user->user_ns &&
121 ret = -EPERM; 148 cap_issubset(child_cred->cap_permitted, cred->cap_permitted))
149 goto out;
150 if (ns_capable(child_cred->user->user_ns, CAP_SYS_PTRACE))
151 goto out;
152 ret = -EPERM;
153out:
122 rcu_read_unlock(); 154 rcu_read_unlock();
123 return ret; 155 return ret;
124} 156}
@@ -127,18 +159,30 @@ int cap_ptrace_access_check(struct task_struct *child, unsigned int mode)
127 * cap_ptrace_traceme - Determine whether another process may trace the current 159 * cap_ptrace_traceme - Determine whether another process may trace the current
128 * @parent: The task proposed to be the tracer 160 * @parent: The task proposed to be the tracer
129 * 161 *
162 * If parent is in the same or an ancestor user_ns and has all current's
163 * capabilities, then ptrace access is allowed.
164 * If parent has the ptrace capability to current's user_ns, then ptrace
165 * access is allowed.
166 * Else denied.
167 *
130 * Determine whether the nominated task is permitted to trace the current 168 * Determine whether the nominated task is permitted to trace the current
131 * process, returning 0 if permission is granted, -ve if denied. 169 * process, returning 0 if permission is granted, -ve if denied.
132 */ 170 */
133int cap_ptrace_traceme(struct task_struct *parent) 171int cap_ptrace_traceme(struct task_struct *parent)
134{ 172{
135 int ret = 0; 173 int ret = 0;
174 const struct cred *cred, *child_cred;
136 175
137 rcu_read_lock(); 176 rcu_read_lock();
138 if (!cap_issubset(current_cred()->cap_permitted, 177 cred = __task_cred(parent);
139 __task_cred(parent)->cap_permitted) && 178 child_cred = current_cred();
140 !has_capability(parent, CAP_SYS_PTRACE)) 179 if (cred->user->user_ns == child_cred->user->user_ns &&
141 ret = -EPERM; 180 cap_issubset(child_cred->cap_permitted, cred->cap_permitted))
181 goto out;
182 if (has_ns_capability(parent, child_cred->user->user_ns, CAP_SYS_PTRACE))
183 goto out;
184 ret = -EPERM;
185out:
142 rcu_read_unlock(); 186 rcu_read_unlock();
143 return ret; 187 return ret;
144} 188}
@@ -178,7 +222,8 @@ static inline int cap_inh_is_capped(void)
178 /* they are so limited unless the current task has the CAP_SETPCAP 222 /* they are so limited unless the current task has the CAP_SETPCAP
179 * capability 223 * capability
180 */ 224 */
181 if (cap_capable(current, current_cred(), CAP_SETPCAP, 225 if (cap_capable(current, current_cred(),
226 current_cred()->user->user_ns, CAP_SETPCAP,
182 SECURITY_CAP_AUDIT) == 0) 227 SECURITY_CAP_AUDIT) == 0)
183 return 0; 228 return 0;
184 return 1; 229 return 1;
@@ -484,15 +529,10 @@ skip:
484 new->suid = new->fsuid = new->euid; 529 new->suid = new->fsuid = new->euid;
485 new->sgid = new->fsgid = new->egid; 530 new->sgid = new->fsgid = new->egid;
486 531
487 /* For init, we want to retain the capabilities set in the initial 532 if (effective)
488 * task. Thus we skip the usual capability rules 533 new->cap_effective = new->cap_permitted;
489 */ 534 else
490 if (!is_global_init(current)) { 535 cap_clear(new->cap_effective);
491 if (effective)
492 new->cap_effective = new->cap_permitted;
493 else
494 cap_clear(new->cap_effective);
495 }
496 bprm->cap_effective = effective; 536 bprm->cap_effective = effective;
497 537
498 /* 538 /*
@@ -719,14 +759,11 @@ static int cap_safe_nice(struct task_struct *p)
719/** 759/**
720 * cap_task_setscheduler - Detemine if scheduler policy change is permitted 760 * cap_task_setscheduler - Detemine if scheduler policy change is permitted
721 * @p: The task to affect 761 * @p: The task to affect
722 * @policy: The policy to effect
723 * @lp: The parameters to the scheduling policy
724 * 762 *
725 * Detemine if the requested scheduler policy change is permitted for the 763 * Detemine if the requested scheduler policy change is permitted for the
726 * specified task, returning 0 if permission is granted, -ve if denied. 764 * specified task, returning 0 if permission is granted, -ve if denied.
727 */ 765 */
728int cap_task_setscheduler(struct task_struct *p, int policy, 766int cap_task_setscheduler(struct task_struct *p)
729 struct sched_param *lp)
730{ 767{
731 return cap_safe_nice(p); 768 return cap_safe_nice(p);
732} 769}
@@ -833,7 +870,8 @@ int cap_task_prctl(int option, unsigned long arg2, unsigned long arg3,
833 & (new->securebits ^ arg2)) /*[1]*/ 870 & (new->securebits ^ arg2)) /*[1]*/
834 || ((new->securebits & SECURE_ALL_LOCKS & ~arg2)) /*[2]*/ 871 || ((new->securebits & SECURE_ALL_LOCKS & ~arg2)) /*[2]*/
835 || (arg2 & ~(SECURE_ALL_LOCKS | SECURE_ALL_BITS)) /*[3]*/ 872 || (arg2 & ~(SECURE_ALL_LOCKS | SECURE_ALL_BITS)) /*[3]*/
836 || (cap_capable(current, current_cred(), CAP_SETPCAP, 873 || (cap_capable(current, current_cred(),
874 current_cred()->user->user_ns, CAP_SETPCAP,
837 SECURITY_CAP_AUDIT) != 0) /*[4]*/ 875 SECURITY_CAP_AUDIT) != 0) /*[4]*/
838 /* 876 /*
839 * [1] no changing of bits that are locked 877 * [1] no changing of bits that are locked
@@ -887,24 +925,6 @@ error:
887} 925}
888 926
889/** 927/**
890 * cap_syslog - Determine whether syslog function is permitted
891 * @type: Function requested
892 * @from_file: Whether this request came from an open file (i.e. /proc)
893 *
894 * Determine whether the current process is permitted to use a particular
895 * syslog function, returning 0 if permission is granted, -ve if not.
896 */
897int cap_syslog(int type, bool from_file)
898{
899 if (type != SYSLOG_ACTION_OPEN && from_file)
900 return 0;
901 if ((type != SYSLOG_ACTION_READ_ALL &&
902 type != SYSLOG_ACTION_SIZE_BUFFER) && !capable(CAP_SYS_ADMIN))
903 return -EPERM;
904 return 0;
905}
906
907/**
908 * cap_vm_enough_memory - Determine whether a new virtual mapping is permitted 928 * cap_vm_enough_memory - Determine whether a new virtual mapping is permitted
909 * @mm: The VM space in which the new mapping is to be made 929 * @mm: The VM space in which the new mapping is to be made
910 * @pages: The size of the mapping 930 * @pages: The size of the mapping
@@ -916,7 +936,7 @@ int cap_vm_enough_memory(struct mm_struct *mm, long pages)
916{ 936{
917 int cap_sys_admin = 0; 937 int cap_sys_admin = 0;
918 938
919 if (cap_capable(current, current_cred(), CAP_SYS_ADMIN, 939 if (cap_capable(current, current_cred(), &init_user_ns, CAP_SYS_ADMIN,
920 SECURITY_CAP_NOAUDIT) == 0) 940 SECURITY_CAP_NOAUDIT) == 0)
921 cap_sys_admin = 1; 941 cap_sys_admin = 1;
922 return __vm_enough_memory(mm, pages, cap_sys_admin); 942 return __vm_enough_memory(mm, pages, cap_sys_admin);
@@ -943,7 +963,7 @@ int cap_file_mmap(struct file *file, unsigned long reqprot,
943 int ret = 0; 963 int ret = 0;
944 964
945 if (addr < dac_mmap_min_addr) { 965 if (addr < dac_mmap_min_addr) {
946 ret = cap_capable(current, current_cred(), CAP_SYS_RAWIO, 966 ret = cap_capable(current, current_cred(), &init_user_ns, CAP_SYS_RAWIO,
947 SECURITY_CAP_AUDIT); 967 SECURITY_CAP_AUDIT);
948 /* set PF_SUPERPRIV if it turns out we allow the low mmap */ 968 /* set PF_SUPERPRIV if it turns out we allow the low mmap */
949 if (ret == 0) 969 if (ret == 0)
diff --git a/security/device_cgroup.c b/security/device_cgroup.c
index 8d9c48f13774..1be68269e1c2 100644
--- a/security/device_cgroup.c
+++ b/security/device_cgroup.c
@@ -62,8 +62,7 @@ static inline struct dev_cgroup *task_devcgroup(struct task_struct *task)
62struct cgroup_subsys devices_subsys; 62struct cgroup_subsys devices_subsys;
63 63
64static int devcgroup_can_attach(struct cgroup_subsys *ss, 64static int devcgroup_can_attach(struct cgroup_subsys *ss,
65 struct cgroup *new_cgroup, struct task_struct *task, 65 struct cgroup *new_cgroup, struct task_struct *task)
66 bool threadgroup)
67{ 66{
68 if (current != task && !capable(CAP_SYS_ADMIN)) 67 if (current != task && !capable(CAP_SYS_ADMIN))
69 return -EPERM; 68 return -EPERM;
@@ -475,17 +474,11 @@ struct cgroup_subsys devices_subsys = {
475 .subsys_id = devices_subsys_id, 474 .subsys_id = devices_subsys_id,
476}; 475};
477 476
478int devcgroup_inode_permission(struct inode *inode, int mask) 477int __devcgroup_inode_permission(struct inode *inode, int mask)
479{ 478{
480 struct dev_cgroup *dev_cgroup; 479 struct dev_cgroup *dev_cgroup;
481 struct dev_whitelist_item *wh; 480 struct dev_whitelist_item *wh;
482 481
483 dev_t device = inode->i_rdev;
484 if (!device)
485 return 0;
486 if (!S_ISBLK(inode->i_mode) && !S_ISCHR(inode->i_mode))
487 return 0;
488
489 rcu_read_lock(); 482 rcu_read_lock();
490 483
491 dev_cgroup = task_devcgroup(current); 484 dev_cgroup = task_devcgroup(current);
diff --git a/security/inode.c b/security/inode.c
index 8c777f022ad1..c4df2fbebe6b 100644
--- a/security/inode.c
+++ b/security/inode.c
@@ -53,6 +53,7 @@ static const struct file_operations default_file_ops = {
53 .read = default_read_file, 53 .read = default_read_file,
54 .write = default_write_file, 54 .write = default_write_file,
55 .open = default_open, 55 .open = default_open,
56 .llseek = noop_llseek,
56}; 57};
57 58
58static struct inode *get_inode(struct super_block *sb, int mode, dev_t dev) 59static struct inode *get_inode(struct super_block *sb, int mode, dev_t dev)
@@ -60,6 +61,7 @@ static struct inode *get_inode(struct super_block *sb, int mode, dev_t dev)
60 struct inode *inode = new_inode(sb); 61 struct inode *inode = new_inode(sb);
61 62
62 if (inode) { 63 if (inode) {
64 inode->i_ino = get_next_ino();
63 inode->i_mode = mode; 65 inode->i_mode = mode;
64 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME; 66 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
65 switch (mode & S_IFMT) { 67 switch (mode & S_IFMT) {
@@ -129,17 +131,17 @@ static int fill_super(struct super_block *sb, void *data, int silent)
129 return simple_fill_super(sb, SECURITYFS_MAGIC, files); 131 return simple_fill_super(sb, SECURITYFS_MAGIC, files);
130} 132}
131 133
132static int get_sb(struct file_system_type *fs_type, 134static struct dentry *get_sb(struct file_system_type *fs_type,
133 int flags, const char *dev_name, 135 int flags, const char *dev_name,
134 void *data, struct vfsmount *mnt) 136 void *data)
135{ 137{
136 return get_sb_single(fs_type, flags, data, fill_super, mnt); 138 return mount_single(fs_type, flags, data, fill_super);
137} 139}
138 140
139static struct file_system_type fs_type = { 141static struct file_system_type fs_type = {
140 .owner = THIS_MODULE, 142 .owner = THIS_MODULE,
141 .name = "securityfs", 143 .name = "securityfs",
142 .get_sb = get_sb, 144 .mount = get_sb,
143 .kill_sb = kill_litter_super, 145 .kill_sb = kill_litter_super,
144}; 146};
145 147
diff --git a/security/integrity/ima/ima.h b/security/integrity/ima/ima.h
index 3fbcd1dda0ef..08408bd71462 100644
--- a/security/integrity/ima/ima.h
+++ b/security/integrity/ima/ima.h
@@ -70,6 +70,7 @@ int ima_init(void);
70void ima_cleanup(void); 70void ima_cleanup(void);
71int ima_fs_init(void); 71int ima_fs_init(void);
72void ima_fs_cleanup(void); 72void ima_fs_cleanup(void);
73int ima_inode_alloc(struct inode *inode);
73int ima_add_template_entry(struct ima_template_entry *entry, int violation, 74int ima_add_template_entry(struct ima_template_entry *entry, int violation,
74 const char *op, struct inode *inode); 75 const char *op, struct inode *inode);
75int ima_calc_hash(struct file *file, char *digest); 76int ima_calc_hash(struct file *file, char *digest);
@@ -96,24 +97,20 @@ static inline unsigned long ima_hash_key(u8 *digest)
96} 97}
97 98
98/* iint cache flags */ 99/* iint cache flags */
99#define IMA_MEASURED 1 100#define IMA_MEASURED 0x01
100 101
101/* integrity data associated with an inode */ 102/* integrity data associated with an inode */
102struct ima_iint_cache { 103struct ima_iint_cache {
104 struct rb_node rb_node; /* rooted in ima_iint_tree */
105 struct inode *inode; /* back pointer to inode in question */
103 u64 version; /* track inode changes */ 106 u64 version; /* track inode changes */
104 unsigned long flags; 107 unsigned char flags;
105 u8 digest[IMA_DIGEST_SIZE]; 108 u8 digest[IMA_DIGEST_SIZE];
106 struct mutex mutex; /* protects: version, flags, digest */ 109 struct mutex mutex; /* protects: version, flags, digest */
107 long readcount; /* measured files readcount */
108 long writecount; /* measured files writecount */
109 long opencount; /* opens reference count */
110 struct kref refcount; /* ima_iint_cache reference count */
111 struct rcu_head rcu;
112}; 110};
113 111
114/* LIM API function definitions */ 112/* LIM API function definitions */
115int ima_must_measure(struct ima_iint_cache *iint, struct inode *inode, 113int ima_must_measure(struct inode *inode, int mask, int function);
116 int mask, int function);
117int ima_collect_measurement(struct ima_iint_cache *iint, struct file *file); 114int ima_collect_measurement(struct ima_iint_cache *iint, struct file *file);
118void ima_store_measurement(struct ima_iint_cache *iint, struct file *file, 115void ima_store_measurement(struct ima_iint_cache *iint, struct file *file,
119 const unsigned char *filename); 116 const unsigned char *filename);
@@ -122,13 +119,11 @@ int ima_store_template(struct ima_template_entry *entry, int violation,
122void ima_template_show(struct seq_file *m, void *e, 119void ima_template_show(struct seq_file *m, void *e,
123 enum ima_show_type show); 120 enum ima_show_type show);
124 121
125/* radix tree calls to lookup, insert, delete 122/* rbtree tree calls to lookup, insert, delete
126 * integrity data associated with an inode. 123 * integrity data associated with an inode.
127 */ 124 */
128struct ima_iint_cache *ima_iint_insert(struct inode *inode); 125struct ima_iint_cache *ima_iint_insert(struct inode *inode);
129struct ima_iint_cache *ima_iint_find_get(struct inode *inode); 126struct ima_iint_cache *ima_iint_find(struct inode *inode);
130void iint_free(struct kref *kref);
131void iint_rcu_free(struct rcu_head *rcu);
132 127
133/* IMA policy related functions */ 128/* IMA policy related functions */
134enum ima_hooks { FILE_CHECK = 1, FILE_MMAP, BPRM_CHECK }; 129enum ima_hooks { FILE_CHECK = 1, FILE_MMAP, BPRM_CHECK };
diff --git a/security/integrity/ima/ima_api.c b/security/integrity/ima/ima_api.c
index 52015d098fdf..da36d2c085a4 100644
--- a/security/integrity/ima/ima_api.c
+++ b/security/integrity/ima/ima_api.c
@@ -105,20 +105,13 @@ err_out:
105 * mask: contains the permission mask 105 * mask: contains the permission mask
106 * fsmagic: hex value 106 * fsmagic: hex value
107 * 107 *
108 * Must be called with iint->mutex held. 108 * Return 0 to measure. For matching a DONT_MEASURE policy, no policy,
109 * 109 * or other error, return an error code.
110 * Return 0 to measure. Return 1 if already measured.
111 * For matching a DONT_MEASURE policy, no policy, or other
112 * error, return an error code.
113*/ 110*/
114int ima_must_measure(struct ima_iint_cache *iint, struct inode *inode, 111int ima_must_measure(struct inode *inode, int mask, int function)
115 int mask, int function)
116{ 112{
117 int must_measure; 113 int must_measure;
118 114
119 if (iint->flags & IMA_MEASURED)
120 return 1;
121
122 must_measure = ima_match_policy(inode, function, mask); 115 must_measure = ima_match_policy(inode, function, mask);
123 return must_measure ? 0 : -EACCES; 116 return must_measure ? 0 : -EACCES;
124} 117}
diff --git a/security/integrity/ima/ima_iint.c b/security/integrity/ima/ima_iint.c
index afba4aef812f..4ae73040ab7b 100644
--- a/security/integrity/ima/ima_iint.c
+++ b/security/integrity/ima/ima_iint.c
@@ -12,98 +12,119 @@
12 * File: ima_iint.c 12 * File: ima_iint.c
13 * - implements the IMA hooks: ima_inode_alloc, ima_inode_free 13 * - implements the IMA hooks: ima_inode_alloc, ima_inode_free
14 * - cache integrity information associated with an inode 14 * - cache integrity information associated with an inode
15 * using a radix tree. 15 * using a rbtree tree.
16 */ 16 */
17#include <linux/slab.h> 17#include <linux/slab.h>
18#include <linux/module.h> 18#include <linux/module.h>
19#include <linux/spinlock.h> 19#include <linux/spinlock.h>
20#include <linux/radix-tree.h> 20#include <linux/rbtree.h>
21#include "ima.h" 21#include "ima.h"
22 22
23RADIX_TREE(ima_iint_store, GFP_ATOMIC); 23static struct rb_root ima_iint_tree = RB_ROOT;
24DEFINE_SPINLOCK(ima_iint_lock); 24static DEFINE_SPINLOCK(ima_iint_lock);
25static struct kmem_cache *iint_cache __read_mostly; 25static struct kmem_cache *iint_cache __read_mostly;
26 26
27int iint_initialized = 0; 27int iint_initialized = 0;
28 28
29/* ima_iint_find_get - return the iint associated with an inode 29/*
30 * 30 * __ima_iint_find - return the iint associated with an inode
31 * ima_iint_find_get gets a reference to the iint. Caller must
32 * remember to put the iint reference.
33 */ 31 */
34struct ima_iint_cache *ima_iint_find_get(struct inode *inode) 32static struct ima_iint_cache *__ima_iint_find(struct inode *inode)
35{ 33{
36 struct ima_iint_cache *iint; 34 struct ima_iint_cache *iint;
35 struct rb_node *n = ima_iint_tree.rb_node;
36
37 assert_spin_locked(&ima_iint_lock);
38
39 while (n) {
40 iint = rb_entry(n, struct ima_iint_cache, rb_node);
41
42 if (inode < iint->inode)
43 n = n->rb_left;
44 else if (inode > iint->inode)
45 n = n->rb_right;
46 else
47 break;
48 }
49 if (!n)
50 return NULL;
37 51
38 rcu_read_lock();
39 iint = radix_tree_lookup(&ima_iint_store, (unsigned long)inode);
40 if (!iint)
41 goto out;
42 kref_get(&iint->refcount);
43out:
44 rcu_read_unlock();
45 return iint; 52 return iint;
46} 53}
47 54
48/** 55/*
49 * ima_inode_alloc - allocate an iint associated with an inode 56 * ima_iint_find - return the iint associated with an inode
50 * @inode: pointer to the inode
51 */ 57 */
52int ima_inode_alloc(struct inode *inode) 58struct ima_iint_cache *ima_iint_find(struct inode *inode)
53{ 59{
54 struct ima_iint_cache *iint = NULL; 60 struct ima_iint_cache *iint;
55 int rc = 0;
56
57 iint = kmem_cache_alloc(iint_cache, GFP_NOFS);
58 if (!iint)
59 return -ENOMEM;
60 61
61 rc = radix_tree_preload(GFP_NOFS); 62 if (!IS_IMA(inode))
62 if (rc < 0) 63 return NULL;
63 goto out;
64 64
65 spin_lock(&ima_iint_lock); 65 spin_lock(&ima_iint_lock);
66 rc = radix_tree_insert(&ima_iint_store, (unsigned long)inode, iint); 66 iint = __ima_iint_find(inode);
67 spin_unlock(&ima_iint_lock); 67 spin_unlock(&ima_iint_lock);
68 radix_tree_preload_end();
69out:
70 if (rc < 0)
71 kmem_cache_free(iint_cache, iint);
72 68
73 return rc; 69 return iint;
74} 70}
75 71
76/* iint_free - called when the iint refcount goes to zero */ 72static void iint_free(struct ima_iint_cache *iint)
77void iint_free(struct kref *kref)
78{ 73{
79 struct ima_iint_cache *iint = container_of(kref, struct ima_iint_cache,
80 refcount);
81 iint->version = 0; 74 iint->version = 0;
82 iint->flags = 0UL; 75 iint->flags = 0UL;
83 if (iint->readcount != 0) {
84 printk(KERN_INFO "%s: readcount: %ld\n", __func__,
85 iint->readcount);
86 iint->readcount = 0;
87 }
88 if (iint->writecount != 0) {
89 printk(KERN_INFO "%s: writecount: %ld\n", __func__,
90 iint->writecount);
91 iint->writecount = 0;
92 }
93 if (iint->opencount != 0) {
94 printk(KERN_INFO "%s: opencount: %ld\n", __func__,
95 iint->opencount);
96 iint->opencount = 0;
97 }
98 kref_init(&iint->refcount);
99 kmem_cache_free(iint_cache, iint); 76 kmem_cache_free(iint_cache, iint);
100} 77}
101 78
102void iint_rcu_free(struct rcu_head *rcu_head) 79/**
80 * ima_inode_alloc - allocate an iint associated with an inode
81 * @inode: pointer to the inode
82 */
83int ima_inode_alloc(struct inode *inode)
103{ 84{
104 struct ima_iint_cache *iint = container_of(rcu_head, 85 struct rb_node **p;
105 struct ima_iint_cache, rcu); 86 struct rb_node *new_node, *parent = NULL;
106 kref_put(&iint->refcount, iint_free); 87 struct ima_iint_cache *new_iint, *test_iint;
88 int rc;
89
90 new_iint = kmem_cache_alloc(iint_cache, GFP_NOFS);
91 if (!new_iint)
92 return -ENOMEM;
93
94 new_iint->inode = inode;
95 new_node = &new_iint->rb_node;
96
97 mutex_lock(&inode->i_mutex); /* i_flags */
98 spin_lock(&ima_iint_lock);
99
100 p = &ima_iint_tree.rb_node;
101 while (*p) {
102 parent = *p;
103 test_iint = rb_entry(parent, struct ima_iint_cache, rb_node);
104
105 rc = -EEXIST;
106 if (inode < test_iint->inode)
107 p = &(*p)->rb_left;
108 else if (inode > test_iint->inode)
109 p = &(*p)->rb_right;
110 else
111 goto out_err;
112 }
113
114 inode->i_flags |= S_IMA;
115 rb_link_node(new_node, parent, p);
116 rb_insert_color(new_node, &ima_iint_tree);
117
118 spin_unlock(&ima_iint_lock);
119 mutex_unlock(&inode->i_mutex); /* i_flags */
120
121 return 0;
122out_err:
123 spin_unlock(&ima_iint_lock);
124 mutex_unlock(&inode->i_mutex); /* i_flags */
125 iint_free(new_iint);
126
127 return rc;
107} 128}
108 129
109/** 130/**
@@ -116,11 +137,15 @@ void ima_inode_free(struct inode *inode)
116{ 137{
117 struct ima_iint_cache *iint; 138 struct ima_iint_cache *iint;
118 139
140 if (!IS_IMA(inode))
141 return;
142
119 spin_lock(&ima_iint_lock); 143 spin_lock(&ima_iint_lock);
120 iint = radix_tree_delete(&ima_iint_store, (unsigned long)inode); 144 iint = __ima_iint_find(inode);
145 rb_erase(&iint->rb_node, &ima_iint_tree);
121 spin_unlock(&ima_iint_lock); 146 spin_unlock(&ima_iint_lock);
122 if (iint) 147
123 call_rcu(&iint->rcu, iint_rcu_free); 148 iint_free(iint);
124} 149}
125 150
126static void init_once(void *foo) 151static void init_once(void *foo)
@@ -131,10 +156,6 @@ static void init_once(void *foo)
131 iint->version = 0; 156 iint->version = 0;
132 iint->flags = 0UL; 157 iint->flags = 0UL;
133 mutex_init(&iint->mutex); 158 mutex_init(&iint->mutex);
134 iint->readcount = 0;
135 iint->writecount = 0;
136 iint->opencount = 0;
137 kref_init(&iint->refcount);
138} 159}
139 160
140static int __init ima_iintcache_init(void) 161static int __init ima_iintcache_init(void)
diff --git a/security/integrity/ima/ima_main.c b/security/integrity/ima/ima_main.c
index e662b89d4079..39d66dc2b8e9 100644
--- a/security/integrity/ima/ima_main.c
+++ b/security/integrity/ima/ima_main.c
@@ -36,179 +36,71 @@ static int __init hash_setup(char *str)
36} 36}
37__setup("ima_hash=", hash_setup); 37__setup("ima_hash=", hash_setup);
38 38
39struct ima_imbalance {
40 struct hlist_node node;
41 unsigned long fsmagic;
42};
43
44/* 39/*
45 * ima_limit_imbalance - emit one imbalance message per filesystem type 40 * ima_rdwr_violation_check
46 * 41 *
47 * Maintain list of filesystem types that do not measure files properly. 42 * Only invalidate the PCR for measured files:
48 * Return false if unknown, true if known.
49 */
50static bool ima_limit_imbalance(struct file *file)
51{
52 static DEFINE_SPINLOCK(ima_imbalance_lock);
53 static HLIST_HEAD(ima_imbalance_list);
54
55 struct super_block *sb = file->f_dentry->d_sb;
56 struct ima_imbalance *entry;
57 struct hlist_node *node;
58 bool found = false;
59
60 rcu_read_lock();
61 hlist_for_each_entry_rcu(entry, node, &ima_imbalance_list, node) {
62 if (entry->fsmagic == sb->s_magic) {
63 found = true;
64 break;
65 }
66 }
67 rcu_read_unlock();
68 if (found)
69 goto out;
70
71 entry = kmalloc(sizeof(*entry), GFP_NOFS);
72 if (!entry)
73 goto out;
74 entry->fsmagic = sb->s_magic;
75 spin_lock(&ima_imbalance_lock);
76 /*
77 * we could have raced and something else might have added this fs
78 * to the list, but we don't really care
79 */
80 hlist_add_head_rcu(&entry->node, &ima_imbalance_list);
81 spin_unlock(&ima_imbalance_lock);
82 printk(KERN_INFO "IMA: unmeasured files on fsmagic: %lX\n",
83 entry->fsmagic);
84out:
85 return found;
86}
87
88/* ima_read_write_check - reflect possible reading/writing errors in the PCR.
89 *
90 * When opening a file for read, if the file is already open for write,
91 * the file could change, resulting in a file measurement error.
92 *
93 * Opening a file for write, if the file is already open for read, results
94 * in a time of measure, time of use (ToMToU) error.
95 *
96 * In either case invalidate the PCR.
97 */
98enum iint_pcr_error { TOMTOU, OPEN_WRITERS };
99static void ima_read_write_check(enum iint_pcr_error error,
100 struct ima_iint_cache *iint,
101 struct inode *inode,
102 const unsigned char *filename)
103{
104 switch (error) {
105 case TOMTOU:
106 if (iint->readcount > 0)
107 ima_add_violation(inode, filename, "invalid_pcr",
108 "ToMToU");
109 break;
110 case OPEN_WRITERS:
111 if (iint->writecount > 0)
112 ima_add_violation(inode, filename, "invalid_pcr",
113 "open_writers");
114 break;
115 }
116}
117
118/*
119 * Update the counts given an fmode_t
120 */
121static void ima_inc_counts(struct ima_iint_cache *iint, fmode_t mode)
122{
123 BUG_ON(!mutex_is_locked(&iint->mutex));
124
125 iint->opencount++;
126 if ((mode & (FMODE_READ | FMODE_WRITE)) == FMODE_READ)
127 iint->readcount++;
128 if (mode & FMODE_WRITE)
129 iint->writecount++;
130}
131
132/*
133 * ima_counts_get - increment file counts
134 *
135 * Maintain read/write counters for all files, but only
136 * invalidate the PCR for measured files:
137 * - Opening a file for write when already open for read, 43 * - Opening a file for write when already open for read,
138 * results in a time of measure, time of use (ToMToU) error. 44 * results in a time of measure, time of use (ToMToU) error.
139 * - Opening a file for read when already open for write, 45 * - Opening a file for read when already open for write,
140 * could result in a file measurement error. 46 * could result in a file measurement error.
141 * 47 *
142 */ 48 */
143void ima_counts_get(struct file *file) 49static void ima_rdwr_violation_check(struct file *file)
144{ 50{
145 struct dentry *dentry = file->f_path.dentry; 51 struct dentry *dentry = file->f_path.dentry;
146 struct inode *inode = dentry->d_inode; 52 struct inode *inode = dentry->d_inode;
147 fmode_t mode = file->f_mode; 53 fmode_t mode = file->f_mode;
148 struct ima_iint_cache *iint;
149 int rc; 54 int rc;
55 bool send_tomtou = false, send_writers = false;
150 56
151 if (!iint_initialized || !S_ISREG(inode->i_mode)) 57 if (!S_ISREG(inode->i_mode) || !ima_initialized)
152 return; 58 return;
153 iint = ima_iint_find_get(inode); 59
154 if (!iint) 60 mutex_lock(&inode->i_mutex); /* file metadata: permissions, xattr */
155 return;
156 mutex_lock(&iint->mutex);
157 if (!ima_initialized)
158 goto out;
159 rc = ima_must_measure(iint, inode, MAY_READ, FILE_CHECK);
160 if (rc < 0)
161 goto out;
162 61
163 if (mode & FMODE_WRITE) { 62 if (mode & FMODE_WRITE) {
164 ima_read_write_check(TOMTOU, iint, inode, dentry->d_name.name); 63 if (atomic_read(&inode->i_readcount) && IS_IMA(inode))
64 send_tomtou = true;
165 goto out; 65 goto out;
166 } 66 }
167 ima_read_write_check(OPEN_WRITERS, iint, inode, dentry->d_name.name);
168out:
169 ima_inc_counts(iint, file->f_mode);
170 mutex_unlock(&iint->mutex);
171 67
172 kref_put(&iint->refcount, iint_free); 68 rc = ima_must_measure(inode, MAY_READ, FILE_CHECK);
69 if (rc < 0)
70 goto out;
71
72 if (atomic_read(&inode->i_writecount) > 0)
73 send_writers = true;
74out:
75 mutex_unlock(&inode->i_mutex);
76
77 if (send_tomtou)
78 ima_add_violation(inode, dentry->d_name.name, "invalid_pcr",
79 "ToMToU");
80 if (send_writers)
81 ima_add_violation(inode, dentry->d_name.name, "invalid_pcr",
82 "open_writers");
173} 83}
174 84
175/* 85static void ima_check_last_writer(struct ima_iint_cache *iint,
176 * Decrement ima counts 86 struct inode *inode,
177 */ 87 struct file *file)
178static void ima_dec_counts(struct ima_iint_cache *iint, struct inode *inode,
179 struct file *file)
180{ 88{
181 mode_t mode = file->f_mode; 89 mode_t mode = file->f_mode;
182 BUG_ON(!mutex_is_locked(&iint->mutex));
183 90
184 iint->opencount--; 91 mutex_lock(&iint->mutex);
185 if ((mode & (FMODE_READ | FMODE_WRITE)) == FMODE_READ) 92 if (mode & FMODE_WRITE &&
186 iint->readcount--; 93 atomic_read(&inode->i_writecount) == 1 &&
187 if (mode & FMODE_WRITE) { 94 iint->version != inode->i_version)
188 iint->writecount--; 95 iint->flags &= ~IMA_MEASURED;
189 if (iint->writecount == 0) { 96 mutex_unlock(&iint->mutex);
190 if (iint->version != inode->i_version)
191 iint->flags &= ~IMA_MEASURED;
192 }
193 }
194
195 if (((iint->opencount < 0) ||
196 (iint->readcount < 0) ||
197 (iint->writecount < 0)) &&
198 !ima_limit_imbalance(file)) {
199 printk(KERN_INFO "%s: open/free imbalance (r:%ld w:%ld o:%ld)\n",
200 __func__, iint->readcount, iint->writecount,
201 iint->opencount);
202 dump_stack();
203 }
204} 97}
205 98
206/** 99/**
207 * ima_file_free - called on __fput() 100 * ima_file_free - called on __fput()
208 * @file: pointer to file structure being freed 101 * @file: pointer to file structure being freed
209 * 102 *
210 * Flag files that changed, based on i_version; 103 * Flag files that changed, based on i_version
211 * and decrement the iint readcount/writecount.
212 */ 104 */
213void ima_file_free(struct file *file) 105void ima_file_free(struct file *file)
214{ 106{
@@ -217,14 +109,12 @@ void ima_file_free(struct file *file)
217 109
218 if (!iint_initialized || !S_ISREG(inode->i_mode)) 110 if (!iint_initialized || !S_ISREG(inode->i_mode))
219 return; 111 return;
220 iint = ima_iint_find_get(inode); 112
113 iint = ima_iint_find(inode);
221 if (!iint) 114 if (!iint)
222 return; 115 return;
223 116
224 mutex_lock(&iint->mutex); 117 ima_check_last_writer(iint, inode, file);
225 ima_dec_counts(iint, inode, file);
226 mutex_unlock(&iint->mutex);
227 kref_put(&iint->refcount, iint_free);
228} 118}
229 119
230static int process_measurement(struct file *file, const unsigned char *filename, 120static int process_measurement(struct file *file, const unsigned char *filename,
@@ -236,12 +126,22 @@ static int process_measurement(struct file *file, const unsigned char *filename,
236 126
237 if (!ima_initialized || !S_ISREG(inode->i_mode)) 127 if (!ima_initialized || !S_ISREG(inode->i_mode))
238 return 0; 128 return 0;
239 iint = ima_iint_find_get(inode); 129
240 if (!iint) 130 rc = ima_must_measure(inode, mask, function);
241 return -ENOMEM; 131 if (rc != 0)
132 return rc;
133retry:
134 iint = ima_iint_find(inode);
135 if (!iint) {
136 rc = ima_inode_alloc(inode);
137 if (!rc || rc == -EEXIST)
138 goto retry;
139 return rc;
140 }
242 141
243 mutex_lock(&iint->mutex); 142 mutex_lock(&iint->mutex);
244 rc = ima_must_measure(iint, inode, mask, function); 143
144 rc = iint->flags & IMA_MEASURED ? 1 : 0;
245 if (rc != 0) 145 if (rc != 0)
246 goto out; 146 goto out;
247 147
@@ -250,7 +150,6 @@ static int process_measurement(struct file *file, const unsigned char *filename,
250 ima_store_measurement(iint, file, filename); 150 ima_store_measurement(iint, file, filename);
251out: 151out:
252 mutex_unlock(&iint->mutex); 152 mutex_unlock(&iint->mutex);
253 kref_put(&iint->refcount, iint_free);
254 return rc; 153 return rc;
255} 154}
256 155
@@ -313,6 +212,7 @@ int ima_file_check(struct file *file, int mask)
313{ 212{
314 int rc; 213 int rc;
315 214
215 ima_rdwr_violation_check(file);
316 rc = process_measurement(file, file->f_dentry->d_name.name, 216 rc = process_measurement(file, file->f_dentry->d_name.name,
317 mask & (MAY_READ | MAY_WRITE | MAY_EXEC), 217 mask & (MAY_READ | MAY_WRITE | MAY_EXEC),
318 FILE_CHECK); 218 FILE_CHECK);
diff --git a/security/integrity/ima/ima_policy.c b/security/integrity/ima/ima_policy.c
index aef8c0a923ab..d661afbe474c 100644
--- a/security/integrity/ima/ima_policy.c
+++ b/security/integrity/ima/ima_policy.c
@@ -253,6 +253,8 @@ static int ima_lsm_rule_init(struct ima_measure_rule_entry *entry,
253 result = security_filter_rule_init(entry->lsm[lsm_rule].type, 253 result = security_filter_rule_init(entry->lsm[lsm_rule].type,
254 Audit_equal, args, 254 Audit_equal, args,
255 &entry->lsm[lsm_rule].rule); 255 &entry->lsm[lsm_rule].rule);
256 if (!entry->lsm[lsm_rule].rule)
257 return -EINVAL;
256 return result; 258 return result;
257} 259}
258 260
diff --git a/security/keys/Makefile b/security/keys/Makefile
index 74d5447d7df7..1bf090a885fe 100644
--- a/security/keys/Makefile
+++ b/security/keys/Makefile
@@ -13,6 +13,8 @@ obj-y := \
13 request_key_auth.o \ 13 request_key_auth.o \
14 user_defined.o 14 user_defined.o
15 15
16obj-$(CONFIG_TRUSTED_KEYS) += trusted.o
17obj-$(CONFIG_ENCRYPTED_KEYS) += encrypted.o
16obj-$(CONFIG_KEYS_COMPAT) += compat.o 18obj-$(CONFIG_KEYS_COMPAT) += compat.o
17obj-$(CONFIG_PROC_FS) += proc.o 19obj-$(CONFIG_PROC_FS) += proc.o
18obj-$(CONFIG_SYSCTL) += sysctl.o 20obj-$(CONFIG_SYSCTL) += sysctl.o
diff --git a/security/keys/compat.c b/security/keys/compat.c
index 792c0a611a6d..338b510e9027 100644
--- a/security/keys/compat.c
+++ b/security/keys/compat.c
@@ -1,4 +1,4 @@
1/* compat.c: 32-bit compatibility syscall for 64-bit systems 1/* 32-bit compatibility syscall for 64-bit systems
2 * 2 *
3 * Copyright (C) 2004-5 Red Hat, Inc. All Rights Reserved. 3 * Copyright (C) 2004-5 Red Hat, Inc. All Rights Reserved.
4 * Written by David Howells (dhowells@redhat.com) 4 * Written by David Howells (dhowells@redhat.com)
@@ -12,15 +12,58 @@
12#include <linux/syscalls.h> 12#include <linux/syscalls.h>
13#include <linux/keyctl.h> 13#include <linux/keyctl.h>
14#include <linux/compat.h> 14#include <linux/compat.h>
15#include <linux/slab.h>
15#include "internal.h" 16#include "internal.h"
16 17
17/*****************************************************************************/
18/* 18/*
19 * the key control system call, 32-bit compatibility version for 64-bit archs 19 * Instantiate a key with the specified compatibility multipart payload and
20 * - this should only be called if the 64-bit arch uses weird pointers in 20 * link the key into the destination keyring if one is given.
21 * 32-bit mode or doesn't guarantee that the top 32-bits of the argument 21 *
22 * registers on taking a 32-bit syscall are zero 22 * The caller must have the appropriate instantiation permit set for this to
23 * - if you can, you should call sys_keyctl directly 23 * work (see keyctl_assume_authority). No other permissions are required.
24 *
25 * If successful, 0 will be returned.
26 */
27long compat_keyctl_instantiate_key_iov(
28 key_serial_t id,
29 const struct compat_iovec __user *_payload_iov,
30 unsigned ioc,
31 key_serial_t ringid)
32{
33 struct iovec iovstack[UIO_FASTIOV], *iov = iovstack;
34 long ret;
35
36 if (_payload_iov == 0 || ioc == 0)
37 goto no_payload;
38
39 ret = compat_rw_copy_check_uvector(WRITE, _payload_iov, ioc,
40 ARRAY_SIZE(iovstack),
41 iovstack, &iov);
42 if (ret < 0)
43 return ret;
44 if (ret == 0)
45 goto no_payload_free;
46
47 ret = keyctl_instantiate_key_common(id, iov, ioc, ret, ringid);
48
49 if (iov != iovstack)
50 kfree(iov);
51 return ret;
52
53no_payload_free:
54 if (iov != iovstack)
55 kfree(iov);
56no_payload:
57 return keyctl_instantiate_key_common(id, NULL, 0, 0, ringid);
58}
59
60/*
61 * The key control system call, 32-bit compatibility version for 64-bit archs
62 *
63 * This should only be called if the 64-bit arch uses weird pointers in 32-bit
64 * mode or doesn't guarantee that the top 32-bits of the argument registers on
65 * taking a 32-bit syscall are zero. If you can, you should call sys_keyctl()
66 * directly.
24 */ 67 */
25asmlinkage long compat_sys_keyctl(u32 option, 68asmlinkage long compat_sys_keyctl(u32 option,
26 u32 arg2, u32 arg3, u32 arg4, u32 arg5) 69 u32 arg2, u32 arg3, u32 arg4, u32 arg5)
@@ -85,8 +128,14 @@ asmlinkage long compat_sys_keyctl(u32 option,
85 case KEYCTL_SESSION_TO_PARENT: 128 case KEYCTL_SESSION_TO_PARENT:
86 return keyctl_session_to_parent(); 129 return keyctl_session_to_parent();
87 130
131 case KEYCTL_REJECT:
132 return keyctl_reject_key(arg2, arg3, arg4, arg5);
133
134 case KEYCTL_INSTANTIATE_IOV:
135 return compat_keyctl_instantiate_key_iov(
136 arg2, compat_ptr(arg3), arg4, arg5);
137
88 default: 138 default:
89 return -EOPNOTSUPP; 139 return -EOPNOTSUPP;
90 } 140 }
91 141}
92} /* end compat_sys_keyctl() */
diff --git a/security/keys/encrypted.c b/security/keys/encrypted.c
new file mode 100644
index 000000000000..b1cba5bf0a5e
--- /dev/null
+++ b/security/keys/encrypted.c
@@ -0,0 +1,902 @@
1/*
2 * Copyright (C) 2010 IBM Corporation
3 *
4 * Author:
5 * Mimi Zohar <zohar@us.ibm.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, version 2 of the License.
10 *
11 * See Documentation/security/keys-trusted-encrypted.txt
12 */
13
14#include <linux/uaccess.h>
15#include <linux/module.h>
16#include <linux/init.h>
17#include <linux/slab.h>
18#include <linux/parser.h>
19#include <linux/string.h>
20#include <linux/err.h>
21#include <keys/user-type.h>
22#include <keys/trusted-type.h>
23#include <keys/encrypted-type.h>
24#include <linux/key-type.h>
25#include <linux/random.h>
26#include <linux/rcupdate.h>
27#include <linux/scatterlist.h>
28#include <linux/crypto.h>
29#include <crypto/hash.h>
30#include <crypto/sha.h>
31#include <crypto/aes.h>
32
33#include "encrypted.h"
34
35static const char KEY_TRUSTED_PREFIX[] = "trusted:";
36static const char KEY_USER_PREFIX[] = "user:";
37static const char hash_alg[] = "sha256";
38static const char hmac_alg[] = "hmac(sha256)";
39static const char blkcipher_alg[] = "cbc(aes)";
40static unsigned int ivsize;
41static int blksize;
42
43#define KEY_TRUSTED_PREFIX_LEN (sizeof (KEY_TRUSTED_PREFIX) - 1)
44#define KEY_USER_PREFIX_LEN (sizeof (KEY_USER_PREFIX) - 1)
45#define HASH_SIZE SHA256_DIGEST_SIZE
46#define MAX_DATA_SIZE 4096
47#define MIN_DATA_SIZE 20
48
49struct sdesc {
50 struct shash_desc shash;
51 char ctx[];
52};
53
54static struct crypto_shash *hashalg;
55static struct crypto_shash *hmacalg;
56
57enum {
58 Opt_err = -1, Opt_new, Opt_load, Opt_update
59};
60
61static const match_table_t key_tokens = {
62 {Opt_new, "new"},
63 {Opt_load, "load"},
64 {Opt_update, "update"},
65 {Opt_err, NULL}
66};
67
68static int aes_get_sizes(void)
69{
70 struct crypto_blkcipher *tfm;
71
72 tfm = crypto_alloc_blkcipher(blkcipher_alg, 0, CRYPTO_ALG_ASYNC);
73 if (IS_ERR(tfm)) {
74 pr_err("encrypted_key: failed to alloc_cipher (%ld)\n",
75 PTR_ERR(tfm));
76 return PTR_ERR(tfm);
77 }
78 ivsize = crypto_blkcipher_ivsize(tfm);
79 blksize = crypto_blkcipher_blocksize(tfm);
80 crypto_free_blkcipher(tfm);
81 return 0;
82}
83
84/*
85 * valid_master_desc - verify the 'key-type:desc' of a new/updated master-key
86 *
87 * key-type:= "trusted:" | "encrypted:"
88 * desc:= master-key description
89 *
90 * Verify that 'key-type' is valid and that 'desc' exists. On key update,
91 * only the master key description is permitted to change, not the key-type.
92 * The key-type remains constant.
93 *
94 * On success returns 0, otherwise -EINVAL.
95 */
96static int valid_master_desc(const char *new_desc, const char *orig_desc)
97{
98 if (!memcmp(new_desc, KEY_TRUSTED_PREFIX, KEY_TRUSTED_PREFIX_LEN)) {
99 if (strlen(new_desc) == KEY_TRUSTED_PREFIX_LEN)
100 goto out;
101 if (orig_desc)
102 if (memcmp(new_desc, orig_desc, KEY_TRUSTED_PREFIX_LEN))
103 goto out;
104 } else if (!memcmp(new_desc, KEY_USER_PREFIX, KEY_USER_PREFIX_LEN)) {
105 if (strlen(new_desc) == KEY_USER_PREFIX_LEN)
106 goto out;
107 if (orig_desc)
108 if (memcmp(new_desc, orig_desc, KEY_USER_PREFIX_LEN))
109 goto out;
110 } else
111 goto out;
112 return 0;
113out:
114 return -EINVAL;
115}
116
117/*
118 * datablob_parse - parse the keyctl data
119 *
120 * datablob format:
121 * new <master-key name> <decrypted data length>
122 * load <master-key name> <decrypted data length> <encrypted iv + data>
123 * update <new-master-key name>
124 *
125 * Tokenizes a copy of the keyctl data, returning a pointer to each token,
126 * which is null terminated.
127 *
128 * On success returns 0, otherwise -EINVAL.
129 */
130static int datablob_parse(char *datablob, char **master_desc,
131 char **decrypted_datalen, char **hex_encoded_iv)
132{
133 substring_t args[MAX_OPT_ARGS];
134 int ret = -EINVAL;
135 int key_cmd;
136 char *p;
137
138 p = strsep(&datablob, " \t");
139 if (!p)
140 return ret;
141 key_cmd = match_token(p, key_tokens, args);
142
143 *master_desc = strsep(&datablob, " \t");
144 if (!*master_desc)
145 goto out;
146
147 if (valid_master_desc(*master_desc, NULL) < 0)
148 goto out;
149
150 if (decrypted_datalen) {
151 *decrypted_datalen = strsep(&datablob, " \t");
152 if (!*decrypted_datalen)
153 goto out;
154 }
155
156 switch (key_cmd) {
157 case Opt_new:
158 if (!decrypted_datalen)
159 break;
160 ret = 0;
161 break;
162 case Opt_load:
163 if (!decrypted_datalen)
164 break;
165 *hex_encoded_iv = strsep(&datablob, " \t");
166 if (!*hex_encoded_iv)
167 break;
168 ret = 0;
169 break;
170 case Opt_update:
171 if (decrypted_datalen)
172 break;
173 ret = 0;
174 break;
175 case Opt_err:
176 break;
177 }
178out:
179 return ret;
180}
181
182/*
183 * datablob_format - format as an ascii string, before copying to userspace
184 */
185static char *datablob_format(struct encrypted_key_payload *epayload,
186 size_t asciiblob_len)
187{
188 char *ascii_buf, *bufp;
189 u8 *iv = epayload->iv;
190 int len;
191 int i;
192
193 ascii_buf = kmalloc(asciiblob_len + 1, GFP_KERNEL);
194 if (!ascii_buf)
195 goto out;
196
197 ascii_buf[asciiblob_len] = '\0';
198
199 /* copy datablob master_desc and datalen strings */
200 len = sprintf(ascii_buf, "%s %s ", epayload->master_desc,
201 epayload->datalen);
202
203 /* convert the hex encoded iv, encrypted-data and HMAC to ascii */
204 bufp = &ascii_buf[len];
205 for (i = 0; i < (asciiblob_len - len) / 2; i++)
206 bufp = pack_hex_byte(bufp, iv[i]);
207out:
208 return ascii_buf;
209}
210
211/*
212 * request_trusted_key - request the trusted key
213 *
214 * Trusted keys are sealed to PCRs and other metadata. Although userspace
215 * manages both trusted/encrypted key-types, like the encrypted key type
216 * data, trusted key type data is not visible decrypted from userspace.
217 */
218static struct key *request_trusted_key(const char *trusted_desc,
219 u8 **master_key, size_t *master_keylen)
220{
221 struct trusted_key_payload *tpayload;
222 struct key *tkey;
223
224 tkey = request_key(&key_type_trusted, trusted_desc, NULL);
225 if (IS_ERR(tkey))
226 goto error;
227
228 down_read(&tkey->sem);
229 tpayload = rcu_dereference(tkey->payload.data);
230 *master_key = tpayload->key;
231 *master_keylen = tpayload->key_len;
232error:
233 return tkey;
234}
235
236/*
237 * request_user_key - request the user key
238 *
239 * Use a user provided key to encrypt/decrypt an encrypted-key.
240 */
241static struct key *request_user_key(const char *master_desc, u8 **master_key,
242 size_t *master_keylen)
243{
244 struct user_key_payload *upayload;
245 struct key *ukey;
246
247 ukey = request_key(&key_type_user, master_desc, NULL);
248 if (IS_ERR(ukey))
249 goto error;
250
251 down_read(&ukey->sem);
252 upayload = rcu_dereference(ukey->payload.data);
253 *master_key = upayload->data;
254 *master_keylen = upayload->datalen;
255error:
256 return ukey;
257}
258
259static struct sdesc *alloc_sdesc(struct crypto_shash *alg)
260{
261 struct sdesc *sdesc;
262 int size;
263
264 size = sizeof(struct shash_desc) + crypto_shash_descsize(alg);
265 sdesc = kmalloc(size, GFP_KERNEL);
266 if (!sdesc)
267 return ERR_PTR(-ENOMEM);
268 sdesc->shash.tfm = alg;
269 sdesc->shash.flags = 0x0;
270 return sdesc;
271}
272
273static int calc_hmac(u8 *digest, const u8 *key, unsigned int keylen,
274 const u8 *buf, unsigned int buflen)
275{
276 struct sdesc *sdesc;
277 int ret;
278
279 sdesc = alloc_sdesc(hmacalg);
280 if (IS_ERR(sdesc)) {
281 pr_info("encrypted_key: can't alloc %s\n", hmac_alg);
282 return PTR_ERR(sdesc);
283 }
284
285 ret = crypto_shash_setkey(hmacalg, key, keylen);
286 if (!ret)
287 ret = crypto_shash_digest(&sdesc->shash, buf, buflen, digest);
288 kfree(sdesc);
289 return ret;
290}
291
292static int calc_hash(u8 *digest, const u8 *buf, unsigned int buflen)
293{
294 struct sdesc *sdesc;
295 int ret;
296
297 sdesc = alloc_sdesc(hashalg);
298 if (IS_ERR(sdesc)) {
299 pr_info("encrypted_key: can't alloc %s\n", hash_alg);
300 return PTR_ERR(sdesc);
301 }
302
303 ret = crypto_shash_digest(&sdesc->shash, buf, buflen, digest);
304 kfree(sdesc);
305 return ret;
306}
307
308enum derived_key_type { ENC_KEY, AUTH_KEY };
309
310/* Derive authentication/encryption key from trusted key */
311static int get_derived_key(u8 *derived_key, enum derived_key_type key_type,
312 const u8 *master_key, size_t master_keylen)
313{
314 u8 *derived_buf;
315 unsigned int derived_buf_len;
316 int ret;
317
318 derived_buf_len = strlen("AUTH_KEY") + 1 + master_keylen;
319 if (derived_buf_len < HASH_SIZE)
320 derived_buf_len = HASH_SIZE;
321
322 derived_buf = kzalloc(derived_buf_len, GFP_KERNEL);
323 if (!derived_buf) {
324 pr_err("encrypted_key: out of memory\n");
325 return -ENOMEM;
326 }
327 if (key_type)
328 strcpy(derived_buf, "AUTH_KEY");
329 else
330 strcpy(derived_buf, "ENC_KEY");
331
332 memcpy(derived_buf + strlen(derived_buf) + 1, master_key,
333 master_keylen);
334 ret = calc_hash(derived_key, derived_buf, derived_buf_len);
335 kfree(derived_buf);
336 return ret;
337}
338
339static int init_blkcipher_desc(struct blkcipher_desc *desc, const u8 *key,
340 unsigned int key_len, const u8 *iv,
341 unsigned int ivsize)
342{
343 int ret;
344
345 desc->tfm = crypto_alloc_blkcipher(blkcipher_alg, 0, CRYPTO_ALG_ASYNC);
346 if (IS_ERR(desc->tfm)) {
347 pr_err("encrypted_key: failed to load %s transform (%ld)\n",
348 blkcipher_alg, PTR_ERR(desc->tfm));
349 return PTR_ERR(desc->tfm);
350 }
351 desc->flags = 0;
352
353 ret = crypto_blkcipher_setkey(desc->tfm, key, key_len);
354 if (ret < 0) {
355 pr_err("encrypted_key: failed to setkey (%d)\n", ret);
356 crypto_free_blkcipher(desc->tfm);
357 return ret;
358 }
359 crypto_blkcipher_set_iv(desc->tfm, iv, ivsize);
360 return 0;
361}
362
363static struct key *request_master_key(struct encrypted_key_payload *epayload,
364 u8 **master_key, size_t *master_keylen)
365{
366 struct key *mkey = NULL;
367
368 if (!strncmp(epayload->master_desc, KEY_TRUSTED_PREFIX,
369 KEY_TRUSTED_PREFIX_LEN)) {
370 mkey = request_trusted_key(epayload->master_desc +
371 KEY_TRUSTED_PREFIX_LEN,
372 master_key, master_keylen);
373 } else if (!strncmp(epayload->master_desc, KEY_USER_PREFIX,
374 KEY_USER_PREFIX_LEN)) {
375 mkey = request_user_key(epayload->master_desc +
376 KEY_USER_PREFIX_LEN,
377 master_key, master_keylen);
378 } else
379 goto out;
380
381 if (IS_ERR(mkey))
382 pr_info("encrypted_key: key %s not found",
383 epayload->master_desc);
384 if (mkey)
385 dump_master_key(*master_key, *master_keylen);
386out:
387 return mkey;
388}
389
390/* Before returning data to userspace, encrypt decrypted data. */
391static int derived_key_encrypt(struct encrypted_key_payload *epayload,
392 const u8 *derived_key,
393 unsigned int derived_keylen)
394{
395 struct scatterlist sg_in[2];
396 struct scatterlist sg_out[1];
397 struct blkcipher_desc desc;
398 unsigned int encrypted_datalen;
399 unsigned int padlen;
400 char pad[16];
401 int ret;
402
403 encrypted_datalen = roundup(epayload->decrypted_datalen, blksize);
404 padlen = encrypted_datalen - epayload->decrypted_datalen;
405
406 ret = init_blkcipher_desc(&desc, derived_key, derived_keylen,
407 epayload->iv, ivsize);
408 if (ret < 0)
409 goto out;
410 dump_decrypted_data(epayload);
411
412 memset(pad, 0, sizeof pad);
413 sg_init_table(sg_in, 2);
414 sg_set_buf(&sg_in[0], epayload->decrypted_data,
415 epayload->decrypted_datalen);
416 sg_set_buf(&sg_in[1], pad, padlen);
417
418 sg_init_table(sg_out, 1);
419 sg_set_buf(sg_out, epayload->encrypted_data, encrypted_datalen);
420
421 ret = crypto_blkcipher_encrypt(&desc, sg_out, sg_in, encrypted_datalen);
422 crypto_free_blkcipher(desc.tfm);
423 if (ret < 0)
424 pr_err("encrypted_key: failed to encrypt (%d)\n", ret);
425 else
426 dump_encrypted_data(epayload, encrypted_datalen);
427out:
428 return ret;
429}
430
431static int datablob_hmac_append(struct encrypted_key_payload *epayload,
432 const u8 *master_key, size_t master_keylen)
433{
434 u8 derived_key[HASH_SIZE];
435 u8 *digest;
436 int ret;
437
438 ret = get_derived_key(derived_key, AUTH_KEY, master_key, master_keylen);
439 if (ret < 0)
440 goto out;
441
442 digest = epayload->master_desc + epayload->datablob_len;
443 ret = calc_hmac(digest, derived_key, sizeof derived_key,
444 epayload->master_desc, epayload->datablob_len);
445 if (!ret)
446 dump_hmac(NULL, digest, HASH_SIZE);
447out:
448 return ret;
449}
450
451/* verify HMAC before decrypting encrypted key */
452static int datablob_hmac_verify(struct encrypted_key_payload *epayload,
453 const u8 *master_key, size_t master_keylen)
454{
455 u8 derived_key[HASH_SIZE];
456 u8 digest[HASH_SIZE];
457 int ret;
458
459 ret = get_derived_key(derived_key, AUTH_KEY, master_key, master_keylen);
460 if (ret < 0)
461 goto out;
462
463 ret = calc_hmac(digest, derived_key, sizeof derived_key,
464 epayload->master_desc, epayload->datablob_len);
465 if (ret < 0)
466 goto out;
467 ret = memcmp(digest, epayload->master_desc + epayload->datablob_len,
468 sizeof digest);
469 if (ret) {
470 ret = -EINVAL;
471 dump_hmac("datablob",
472 epayload->master_desc + epayload->datablob_len,
473 HASH_SIZE);
474 dump_hmac("calc", digest, HASH_SIZE);
475 }
476out:
477 return ret;
478}
479
480static int derived_key_decrypt(struct encrypted_key_payload *epayload,
481 const u8 *derived_key,
482 unsigned int derived_keylen)
483{
484 struct scatterlist sg_in[1];
485 struct scatterlist sg_out[2];
486 struct blkcipher_desc desc;
487 unsigned int encrypted_datalen;
488 char pad[16];
489 int ret;
490
491 encrypted_datalen = roundup(epayload->decrypted_datalen, blksize);
492 ret = init_blkcipher_desc(&desc, derived_key, derived_keylen,
493 epayload->iv, ivsize);
494 if (ret < 0)
495 goto out;
496 dump_encrypted_data(epayload, encrypted_datalen);
497
498 memset(pad, 0, sizeof pad);
499 sg_init_table(sg_in, 1);
500 sg_init_table(sg_out, 2);
501 sg_set_buf(sg_in, epayload->encrypted_data, encrypted_datalen);
502 sg_set_buf(&sg_out[0], epayload->decrypted_data,
503 epayload->decrypted_datalen);
504 sg_set_buf(&sg_out[1], pad, sizeof pad);
505
506 ret = crypto_blkcipher_decrypt(&desc, sg_out, sg_in, encrypted_datalen);
507 crypto_free_blkcipher(desc.tfm);
508 if (ret < 0)
509 goto out;
510 dump_decrypted_data(epayload);
511out:
512 return ret;
513}
514
515/* Allocate memory for decrypted key and datablob. */
516static struct encrypted_key_payload *encrypted_key_alloc(struct key *key,
517 const char *master_desc,
518 const char *datalen)
519{
520 struct encrypted_key_payload *epayload = NULL;
521 unsigned short datablob_len;
522 unsigned short decrypted_datalen;
523 unsigned int encrypted_datalen;
524 long dlen;
525 int ret;
526
527 ret = strict_strtol(datalen, 10, &dlen);
528 if (ret < 0 || dlen < MIN_DATA_SIZE || dlen > MAX_DATA_SIZE)
529 return ERR_PTR(-EINVAL);
530
531 decrypted_datalen = dlen;
532 encrypted_datalen = roundup(decrypted_datalen, blksize);
533
534 datablob_len = strlen(master_desc) + 1 + strlen(datalen) + 1
535 + ivsize + 1 + encrypted_datalen;
536
537 ret = key_payload_reserve(key, decrypted_datalen + datablob_len
538 + HASH_SIZE + 1);
539 if (ret < 0)
540 return ERR_PTR(ret);
541
542 epayload = kzalloc(sizeof(*epayload) + decrypted_datalen +
543 datablob_len + HASH_SIZE + 1, GFP_KERNEL);
544 if (!epayload)
545 return ERR_PTR(-ENOMEM);
546
547 epayload->decrypted_datalen = decrypted_datalen;
548 epayload->datablob_len = datablob_len;
549 return epayload;
550}
551
552static int encrypted_key_decrypt(struct encrypted_key_payload *epayload,
553 const char *hex_encoded_iv)
554{
555 struct key *mkey;
556 u8 derived_key[HASH_SIZE];
557 u8 *master_key;
558 u8 *hmac;
559 const char *hex_encoded_data;
560 unsigned int encrypted_datalen;
561 size_t master_keylen;
562 size_t asciilen;
563 int ret;
564
565 encrypted_datalen = roundup(epayload->decrypted_datalen, blksize);
566 asciilen = (ivsize + 1 + encrypted_datalen + HASH_SIZE) * 2;
567 if (strlen(hex_encoded_iv) != asciilen)
568 return -EINVAL;
569
570 hex_encoded_data = hex_encoded_iv + (2 * ivsize) + 2;
571 hex2bin(epayload->iv, hex_encoded_iv, ivsize);
572 hex2bin(epayload->encrypted_data, hex_encoded_data, encrypted_datalen);
573
574 hmac = epayload->master_desc + epayload->datablob_len;
575 hex2bin(hmac, hex_encoded_data + (encrypted_datalen * 2), HASH_SIZE);
576
577 mkey = request_master_key(epayload, &master_key, &master_keylen);
578 if (IS_ERR(mkey))
579 return PTR_ERR(mkey);
580
581 ret = datablob_hmac_verify(epayload, master_key, master_keylen);
582 if (ret < 0) {
583 pr_err("encrypted_key: bad hmac (%d)\n", ret);
584 goto out;
585 }
586
587 ret = get_derived_key(derived_key, ENC_KEY, master_key, master_keylen);
588 if (ret < 0)
589 goto out;
590
591 ret = derived_key_decrypt(epayload, derived_key, sizeof derived_key);
592 if (ret < 0)
593 pr_err("encrypted_key: failed to decrypt key (%d)\n", ret);
594out:
595 up_read(&mkey->sem);
596 key_put(mkey);
597 return ret;
598}
599
600static void __ekey_init(struct encrypted_key_payload *epayload,
601 const char *master_desc, const char *datalen)
602{
603 epayload->master_desc = epayload->decrypted_data
604 + epayload->decrypted_datalen;
605 epayload->datalen = epayload->master_desc + strlen(master_desc) + 1;
606 epayload->iv = epayload->datalen + strlen(datalen) + 1;
607 epayload->encrypted_data = epayload->iv + ivsize + 1;
608
609 memcpy(epayload->master_desc, master_desc, strlen(master_desc));
610 memcpy(epayload->datalen, datalen, strlen(datalen));
611}
612
613/*
614 * encrypted_init - initialize an encrypted key
615 *
616 * For a new key, use a random number for both the iv and data
617 * itself. For an old key, decrypt the hex encoded data.
618 */
619static int encrypted_init(struct encrypted_key_payload *epayload,
620 const char *master_desc, const char *datalen,
621 const char *hex_encoded_iv)
622{
623 int ret = 0;
624
625 __ekey_init(epayload, master_desc, datalen);
626 if (!hex_encoded_iv) {
627 get_random_bytes(epayload->iv, ivsize);
628
629 get_random_bytes(epayload->decrypted_data,
630 epayload->decrypted_datalen);
631 } else
632 ret = encrypted_key_decrypt(epayload, hex_encoded_iv);
633 return ret;
634}
635
636/*
637 * encrypted_instantiate - instantiate an encrypted key
638 *
639 * Decrypt an existing encrypted datablob or create a new encrypted key
640 * based on a kernel random number.
641 *
642 * On success, return 0. Otherwise return errno.
643 */
644static int encrypted_instantiate(struct key *key, const void *data,
645 size_t datalen)
646{
647 struct encrypted_key_payload *epayload = NULL;
648 char *datablob = NULL;
649 char *master_desc = NULL;
650 char *decrypted_datalen = NULL;
651 char *hex_encoded_iv = NULL;
652 int ret;
653
654 if (datalen <= 0 || datalen > 32767 || !data)
655 return -EINVAL;
656
657 datablob = kmalloc(datalen + 1, GFP_KERNEL);
658 if (!datablob)
659 return -ENOMEM;
660 datablob[datalen] = 0;
661 memcpy(datablob, data, datalen);
662 ret = datablob_parse(datablob, &master_desc, &decrypted_datalen,
663 &hex_encoded_iv);
664 if (ret < 0)
665 goto out;
666
667 epayload = encrypted_key_alloc(key, master_desc, decrypted_datalen);
668 if (IS_ERR(epayload)) {
669 ret = PTR_ERR(epayload);
670 goto out;
671 }
672 ret = encrypted_init(epayload, master_desc, decrypted_datalen,
673 hex_encoded_iv);
674 if (ret < 0) {
675 kfree(epayload);
676 goto out;
677 }
678
679 rcu_assign_pointer(key->payload.data, epayload);
680out:
681 kfree(datablob);
682 return ret;
683}
684
685static void encrypted_rcu_free(struct rcu_head *rcu)
686{
687 struct encrypted_key_payload *epayload;
688
689 epayload = container_of(rcu, struct encrypted_key_payload, rcu);
690 memset(epayload->decrypted_data, 0, epayload->decrypted_datalen);
691 kfree(epayload);
692}
693
694/*
695 * encrypted_update - update the master key description
696 *
697 * Change the master key description for an existing encrypted key.
698 * The next read will return an encrypted datablob using the new
699 * master key description.
700 *
701 * On success, return 0. Otherwise return errno.
702 */
703static int encrypted_update(struct key *key, const void *data, size_t datalen)
704{
705 struct encrypted_key_payload *epayload = key->payload.data;
706 struct encrypted_key_payload *new_epayload;
707 char *buf;
708 char *new_master_desc = NULL;
709 int ret = 0;
710
711 if (datalen <= 0 || datalen > 32767 || !data)
712 return -EINVAL;
713
714 buf = kmalloc(datalen + 1, GFP_KERNEL);
715 if (!buf)
716 return -ENOMEM;
717
718 buf[datalen] = 0;
719 memcpy(buf, data, datalen);
720 ret = datablob_parse(buf, &new_master_desc, NULL, NULL);
721 if (ret < 0)
722 goto out;
723
724 ret = valid_master_desc(new_master_desc, epayload->master_desc);
725 if (ret < 0)
726 goto out;
727
728 new_epayload = encrypted_key_alloc(key, new_master_desc,
729 epayload->datalen);
730 if (IS_ERR(new_epayload)) {
731 ret = PTR_ERR(new_epayload);
732 goto out;
733 }
734
735 __ekey_init(new_epayload, new_master_desc, epayload->datalen);
736
737 memcpy(new_epayload->iv, epayload->iv, ivsize);
738 memcpy(new_epayload->decrypted_data, epayload->decrypted_data,
739 epayload->decrypted_datalen);
740
741 rcu_assign_pointer(key->payload.data, new_epayload);
742 call_rcu(&epayload->rcu, encrypted_rcu_free);
743out:
744 kfree(buf);
745 return ret;
746}
747
748/*
749 * encrypted_read - format and copy the encrypted data to userspace
750 *
751 * The resulting datablob format is:
752 * <master-key name> <decrypted data length> <encrypted iv> <encrypted data>
753 *
754 * On success, return to userspace the encrypted key datablob size.
755 */
756static long encrypted_read(const struct key *key, char __user *buffer,
757 size_t buflen)
758{
759 struct encrypted_key_payload *epayload;
760 struct key *mkey;
761 u8 *master_key;
762 size_t master_keylen;
763 char derived_key[HASH_SIZE];
764 char *ascii_buf;
765 size_t asciiblob_len;
766 int ret;
767
768 epayload = rcu_dereference_key(key);
769
770 /* returns the hex encoded iv, encrypted-data, and hmac as ascii */
771 asciiblob_len = epayload->datablob_len + ivsize + 1
772 + roundup(epayload->decrypted_datalen, blksize)
773 + (HASH_SIZE * 2);
774
775 if (!buffer || buflen < asciiblob_len)
776 return asciiblob_len;
777
778 mkey = request_master_key(epayload, &master_key, &master_keylen);
779 if (IS_ERR(mkey))
780 return PTR_ERR(mkey);
781
782 ret = get_derived_key(derived_key, ENC_KEY, master_key, master_keylen);
783 if (ret < 0)
784 goto out;
785
786 ret = derived_key_encrypt(epayload, derived_key, sizeof derived_key);
787 if (ret < 0)
788 goto out;
789
790 ret = datablob_hmac_append(epayload, master_key, master_keylen);
791 if (ret < 0)
792 goto out;
793
794 ascii_buf = datablob_format(epayload, asciiblob_len);
795 if (!ascii_buf) {
796 ret = -ENOMEM;
797 goto out;
798 }
799
800 up_read(&mkey->sem);
801 key_put(mkey);
802
803 if (copy_to_user(buffer, ascii_buf, asciiblob_len) != 0)
804 ret = -EFAULT;
805 kfree(ascii_buf);
806
807 return asciiblob_len;
808out:
809 up_read(&mkey->sem);
810 key_put(mkey);
811 return ret;
812}
813
814/*
815 * encrypted_destroy - before freeing the key, clear the decrypted data
816 *
817 * Before freeing the key, clear the memory containing the decrypted
818 * key data.
819 */
820static void encrypted_destroy(struct key *key)
821{
822 struct encrypted_key_payload *epayload = key->payload.data;
823
824 if (!epayload)
825 return;
826
827 memset(epayload->decrypted_data, 0, epayload->decrypted_datalen);
828 kfree(key->payload.data);
829}
830
831struct key_type key_type_encrypted = {
832 .name = "encrypted",
833 .instantiate = encrypted_instantiate,
834 .update = encrypted_update,
835 .match = user_match,
836 .destroy = encrypted_destroy,
837 .describe = user_describe,
838 .read = encrypted_read,
839};
840EXPORT_SYMBOL_GPL(key_type_encrypted);
841
842static void encrypted_shash_release(void)
843{
844 if (hashalg)
845 crypto_free_shash(hashalg);
846 if (hmacalg)
847 crypto_free_shash(hmacalg);
848}
849
850static int __init encrypted_shash_alloc(void)
851{
852 int ret;
853
854 hmacalg = crypto_alloc_shash(hmac_alg, 0, CRYPTO_ALG_ASYNC);
855 if (IS_ERR(hmacalg)) {
856 pr_info("encrypted_key: could not allocate crypto %s\n",
857 hmac_alg);
858 return PTR_ERR(hmacalg);
859 }
860
861 hashalg = crypto_alloc_shash(hash_alg, 0, CRYPTO_ALG_ASYNC);
862 if (IS_ERR(hashalg)) {
863 pr_info("encrypted_key: could not allocate crypto %s\n",
864 hash_alg);
865 ret = PTR_ERR(hashalg);
866 goto hashalg_fail;
867 }
868
869 return 0;
870
871hashalg_fail:
872 crypto_free_shash(hmacalg);
873 return ret;
874}
875
876static int __init init_encrypted(void)
877{
878 int ret;
879
880 ret = encrypted_shash_alloc();
881 if (ret < 0)
882 return ret;
883 ret = register_key_type(&key_type_encrypted);
884 if (ret < 0)
885 goto out;
886 return aes_get_sizes();
887out:
888 encrypted_shash_release();
889 return ret;
890
891}
892
893static void __exit cleanup_encrypted(void)
894{
895 encrypted_shash_release();
896 unregister_key_type(&key_type_encrypted);
897}
898
899late_initcall(init_encrypted);
900module_exit(cleanup_encrypted);
901
902MODULE_LICENSE("GPL");
diff --git a/security/keys/encrypted.h b/security/keys/encrypted.h
new file mode 100644
index 000000000000..cef5e2f2b7d1
--- /dev/null
+++ b/security/keys/encrypted.h
@@ -0,0 +1,54 @@
1#ifndef __ENCRYPTED_KEY_H
2#define __ENCRYPTED_KEY_H
3
4#define ENCRYPTED_DEBUG 0
5
6#if ENCRYPTED_DEBUG
7static inline void dump_master_key(const u8 *master_key, size_t master_keylen)
8{
9 print_hex_dump(KERN_ERR, "master key: ", DUMP_PREFIX_NONE, 32, 1,
10 master_key, master_keylen, 0);
11}
12
13static inline void dump_decrypted_data(struct encrypted_key_payload *epayload)
14{
15 print_hex_dump(KERN_ERR, "decrypted data: ", DUMP_PREFIX_NONE, 32, 1,
16 epayload->decrypted_data,
17 epayload->decrypted_datalen, 0);
18}
19
20static inline void dump_encrypted_data(struct encrypted_key_payload *epayload,
21 unsigned int encrypted_datalen)
22{
23 print_hex_dump(KERN_ERR, "encrypted data: ", DUMP_PREFIX_NONE, 32, 1,
24 epayload->encrypted_data, encrypted_datalen, 0);
25}
26
27static inline void dump_hmac(const char *str, const u8 *digest,
28 unsigned int hmac_size)
29{
30 if (str)
31 pr_info("encrypted_key: %s", str);
32 print_hex_dump(KERN_ERR, "hmac: ", DUMP_PREFIX_NONE, 32, 1, digest,
33 hmac_size, 0);
34}
35#else
36static inline void dump_master_key(const u8 *master_key, size_t master_keylen)
37{
38}
39
40static inline void dump_decrypted_data(struct encrypted_key_payload *epayload)
41{
42}
43
44static inline void dump_encrypted_data(struct encrypted_key_payload *epayload,
45 unsigned int encrypted_datalen)
46{
47}
48
49static inline void dump_hmac(const char *str, const u8 *digest,
50 unsigned int hmac_size)
51{
52}
53#endif
54#endif
diff --git a/security/keys/gc.c b/security/keys/gc.c
index a46e825cbf02..89df6b5f203c 100644
--- a/security/keys/gc.c
+++ b/security/keys/gc.c
@@ -32,8 +32,8 @@ static time_t key_gc_next_run = LONG_MAX;
32static time_t key_gc_new_timer; 32static time_t key_gc_new_timer;
33 33
34/* 34/*
35 * Schedule a garbage collection run 35 * Schedule a garbage collection run.
36 * - precision isn't particularly important 36 * - time precision isn't particularly important
37 */ 37 */
38void key_schedule_gc(time_t gc_at) 38void key_schedule_gc(time_t gc_at)
39{ 39{
@@ -61,8 +61,9 @@ static void key_gc_timer_func(unsigned long data)
61} 61}
62 62
63/* 63/*
64 * Garbage collect pointers from a keyring 64 * Garbage collect pointers from a keyring.
65 * - return true if we altered the keyring 65 *
66 * Return true if we altered the keyring.
66 */ 67 */
67static bool key_gc_keyring(struct key *keyring, time_t limit) 68static bool key_gc_keyring(struct key *keyring, time_t limit)
68 __releases(key_serial_lock) 69 __releases(key_serial_lock)
@@ -107,9 +108,8 @@ do_gc:
107} 108}
108 109
109/* 110/*
110 * Garbage collector for keys 111 * Garbage collector for keys. This involves scanning the keyrings for dead,
111 * - this involves scanning the keyrings for dead, expired and revoked keys 112 * expired and revoked keys that have overstayed their welcome
112 * that have overstayed their welcome
113 */ 113 */
114static void key_garbage_collector(struct work_struct *work) 114static void key_garbage_collector(struct work_struct *work)
115{ 115{
diff --git a/security/keys/internal.h b/security/keys/internal.h
index 56a133d8f37d..f375152a2500 100644
--- a/security/keys/internal.h
+++ b/security/keys/internal.h
@@ -1,4 +1,4 @@
1/* internal.h: authentication token and access key management internal defs 1/* Authentication token and access key management internal defs
2 * 2 *
3 * Copyright (C) 2003-5, 2007 Red Hat, Inc. All Rights Reserved. 3 * Copyright (C) 2003-5, 2007 Red Hat, Inc. All Rights Reserved.
4 * Written by David Howells (dhowells@redhat.com) 4 * Written by David Howells (dhowells@redhat.com)
@@ -35,10 +35,12 @@ extern struct key_type key_type_user;
35 35
36/*****************************************************************************/ 36/*****************************************************************************/
37/* 37/*
38 * keep track of keys for a user 38 * Keep track of keys for a user.
39 * - this needs to be separate to user_struct to avoid a refcount-loop 39 *
40 * (user_struct pins some keyrings which pin this struct) 40 * This needs to be separate to user_struct to avoid a refcount-loop
41 * - this also keeps track of keys under request from userspace for this UID 41 * (user_struct pins some keyrings which pin this struct).
42 *
43 * We also keep track of keys under request from userspace for this UID here.
42 */ 44 */
43struct key_user { 45struct key_user {
44 struct rb_node node; 46 struct rb_node node;
@@ -62,7 +64,7 @@ extern struct key_user *key_user_lookup(uid_t uid,
62extern void key_user_put(struct key_user *user); 64extern void key_user_put(struct key_user *user);
63 65
64/* 66/*
65 * key quota limits 67 * Key quota limits.
66 * - root has its own separate limits to everyone else 68 * - root has its own separate limits to everyone else
67 */ 69 */
68extern unsigned key_quota_root_maxkeys; 70extern unsigned key_quota_root_maxkeys;
@@ -85,13 +87,13 @@ extern void key_type_put(struct key_type *ktype);
85extern int __key_link_begin(struct key *keyring, 87extern int __key_link_begin(struct key *keyring,
86 const struct key_type *type, 88 const struct key_type *type,
87 const char *description, 89 const char *description,
88 struct keyring_list **_prealloc); 90 unsigned long *_prealloc);
89extern int __key_link_check_live_key(struct key *keyring, struct key *key); 91extern int __key_link_check_live_key(struct key *keyring, struct key *key);
90extern void __key_link(struct key *keyring, struct key *key, 92extern void __key_link(struct key *keyring, struct key *key,
91 struct keyring_list **_prealloc); 93 unsigned long *_prealloc);
92extern void __key_link_end(struct key *keyring, 94extern void __key_link_end(struct key *keyring,
93 struct key_type *type, 95 struct key_type *type,
94 struct keyring_list *prealloc); 96 unsigned long prealloc);
95 97
96extern key_ref_t __keyring_search_one(key_ref_t keyring_ref, 98extern key_ref_t __keyring_search_one(key_ref_t keyring_ref,
97 const struct key_type *type, 99 const struct key_type *type,
@@ -107,11 +109,13 @@ extern key_ref_t keyring_search_aux(key_ref_t keyring_ref,
107 const struct cred *cred, 109 const struct cred *cred,
108 struct key_type *type, 110 struct key_type *type,
109 const void *description, 111 const void *description,
110 key_match_func_t match); 112 key_match_func_t match,
113 bool no_state_check);
111 114
112extern key_ref_t search_my_process_keyrings(struct key_type *type, 115extern key_ref_t search_my_process_keyrings(struct key_type *type,
113 const void *description, 116 const void *description,
114 key_match_func_t match, 117 key_match_func_t match,
118 bool no_state_check,
115 const struct cred *cred); 119 const struct cred *cred);
116extern key_ref_t search_process_keyrings(struct key_type *type, 120extern key_ref_t search_process_keyrings(struct key_type *type,
117 const void *description, 121 const void *description,
@@ -146,13 +150,13 @@ extern unsigned key_gc_delay;
146extern void keyring_gc(struct key *keyring, time_t limit); 150extern void keyring_gc(struct key *keyring, time_t limit);
147extern void key_schedule_gc(time_t expiry_at); 151extern void key_schedule_gc(time_t expiry_at);
148 152
149/*
150 * check to see whether permission is granted to use a key in the desired way
151 */
152extern int key_task_permission(const key_ref_t key_ref, 153extern int key_task_permission(const key_ref_t key_ref,
153 const struct cred *cred, 154 const struct cred *cred,
154 key_perm_t perm); 155 key_perm_t perm);
155 156
157/*
158 * Check to see whether permission is granted to use a key in the desired way.
159 */
156static inline int key_permission(const key_ref_t key_ref, key_perm_t perm) 160static inline int key_permission(const key_ref_t key_ref, key_perm_t perm)
157{ 161{
158 return key_task_permission(key_ref, current_cred(), perm); 162 return key_task_permission(key_ref, current_cred(), perm);
@@ -168,7 +172,7 @@ static inline int key_permission(const key_ref_t key_ref, key_perm_t perm)
168#define KEY_ALL 0x3f /* all the above permissions */ 172#define KEY_ALL 0x3f /* all the above permissions */
169 173
170/* 174/*
171 * request_key authorisation 175 * Authorisation record for request_key().
172 */ 176 */
173struct request_key_auth { 177struct request_key_auth {
174 struct key *target_key; 178 struct key *target_key;
@@ -188,7 +192,7 @@ extern struct key *request_key_auth_new(struct key *target,
188extern struct key *key_get_instantiation_authkey(key_serial_t target_id); 192extern struct key *key_get_instantiation_authkey(key_serial_t target_id);
189 193
190/* 194/*
191 * keyctl functions 195 * keyctl() functions
192 */ 196 */
193extern long keyctl_get_keyring_ID(key_serial_t, int); 197extern long keyctl_get_keyring_ID(key_serial_t, int);
194extern long keyctl_join_session_keyring(const char __user *); 198extern long keyctl_join_session_keyring(const char __user *);
@@ -212,9 +216,17 @@ extern long keyctl_assume_authority(key_serial_t);
212extern long keyctl_get_security(key_serial_t keyid, char __user *buffer, 216extern long keyctl_get_security(key_serial_t keyid, char __user *buffer,
213 size_t buflen); 217 size_t buflen);
214extern long keyctl_session_to_parent(void); 218extern long keyctl_session_to_parent(void);
219extern long keyctl_reject_key(key_serial_t, unsigned, unsigned, key_serial_t);
220extern long keyctl_instantiate_key_iov(key_serial_t,
221 const struct iovec __user *,
222 unsigned, key_serial_t);
223
224extern long keyctl_instantiate_key_common(key_serial_t,
225 const struct iovec __user *,
226 unsigned, size_t, key_serial_t);
215 227
216/* 228/*
217 * debugging key validation 229 * Debugging key validation
218 */ 230 */
219#ifdef KEY_DEBUGGING 231#ifdef KEY_DEBUGGING
220extern void __key_check(const struct key *); 232extern void __key_check(const struct key *);
diff --git a/security/keys/key.c b/security/keys/key.c
index c1eac8084ade..f7f9d93f08d9 100644
--- a/security/keys/key.c
+++ b/security/keys/key.c
@@ -39,10 +39,10 @@ static DECLARE_RWSEM(key_types_sem);
39static void key_cleanup(struct work_struct *work); 39static void key_cleanup(struct work_struct *work);
40static DECLARE_WORK(key_cleanup_task, key_cleanup); 40static DECLARE_WORK(key_cleanup_task, key_cleanup);
41 41
42/* we serialise key instantiation and link */ 42/* We serialise key instantiation and link */
43DEFINE_MUTEX(key_construction_mutex); 43DEFINE_MUTEX(key_construction_mutex);
44 44
45/* any key who's type gets unegistered will be re-typed to this */ 45/* Any key who's type gets unegistered will be re-typed to this */
46static struct key_type key_type_dead = { 46static struct key_type key_type_dead = {
47 .name = "dead", 47 .name = "dead",
48}; 48};
@@ -56,10 +56,9 @@ void __key_check(const struct key *key)
56} 56}
57#endif 57#endif
58 58
59/*****************************************************************************/
60/* 59/*
61 * get the key quota record for a user, allocating a new record if one doesn't 60 * Get the key quota record for a user, allocating a new record if one doesn't
62 * already exist 61 * already exist.
63 */ 62 */
64struct key_user *key_user_lookup(uid_t uid, struct user_namespace *user_ns) 63struct key_user *key_user_lookup(uid_t uid, struct user_namespace *user_ns)
65{ 64{
@@ -67,7 +66,7 @@ struct key_user *key_user_lookup(uid_t uid, struct user_namespace *user_ns)
67 struct rb_node *parent = NULL; 66 struct rb_node *parent = NULL;
68 struct rb_node **p; 67 struct rb_node **p;
69 68
70 try_again: 69try_again:
71 p = &key_user_tree.rb_node; 70 p = &key_user_tree.rb_node;
72 spin_lock(&key_user_lock); 71 spin_lock(&key_user_lock);
73 72
@@ -124,18 +123,16 @@ struct key_user *key_user_lookup(uid_t uid, struct user_namespace *user_ns)
124 goto out; 123 goto out;
125 124
126 /* okay - we found a user record for this UID */ 125 /* okay - we found a user record for this UID */
127 found: 126found:
128 atomic_inc(&user->usage); 127 atomic_inc(&user->usage);
129 spin_unlock(&key_user_lock); 128 spin_unlock(&key_user_lock);
130 kfree(candidate); 129 kfree(candidate);
131 out: 130out:
132 return user; 131 return user;
132}
133 133
134} /* end key_user_lookup() */
135
136/*****************************************************************************/
137/* 134/*
138 * dispose of a user structure 135 * Dispose of a user structure
139 */ 136 */
140void key_user_put(struct key_user *user) 137void key_user_put(struct key_user *user)
141{ 138{
@@ -146,14 +143,11 @@ void key_user_put(struct key_user *user)
146 143
147 kfree(user); 144 kfree(user);
148 } 145 }
146}
149 147
150} /* end key_user_put() */
151
152/*****************************************************************************/
153/* 148/*
154 * assign a key the next unique serial number 149 * Allocate a serial number for a key. These are assigned randomly to avoid
155 * - these are assigned randomly to avoid security issues through covert 150 * security issues through covert channel problems.
156 * channel problems
157 */ 151 */
158static inline void key_alloc_serial(struct key *key) 152static inline void key_alloc_serial(struct key *key)
159{ 153{
@@ -211,18 +205,36 @@ serial_exists:
211 if (key->serial < xkey->serial) 205 if (key->serial < xkey->serial)
212 goto attempt_insertion; 206 goto attempt_insertion;
213 } 207 }
208}
214 209
215} /* end key_alloc_serial() */ 210/**
216 211 * key_alloc - Allocate a key of the specified type.
217/*****************************************************************************/ 212 * @type: The type of key to allocate.
218/* 213 * @desc: The key description to allow the key to be searched out.
219 * allocate a key of the specified type 214 * @uid: The owner of the new key.
220 * - update the user's quota to reflect the existence of the key 215 * @gid: The group ID for the new key's group permissions.
221 * - called from a key-type operation with key_types_sem read-locked by 216 * @cred: The credentials specifying UID namespace.
222 * key_create_or_update() 217 * @perm: The permissions mask of the new key.
223 * - this prevents unregistration of the key type 218 * @flags: Flags specifying quota properties.
224 * - upon return the key is as yet uninstantiated; the caller needs to either 219 *
225 * instantiate the key or discard it before returning 220 * Allocate a key of the specified type with the attributes given. The key is
221 * returned in an uninstantiated state and the caller needs to instantiate the
222 * key before returning.
223 *
224 * The user's key count quota is updated to reflect the creation of the key and
225 * the user's key data quota has the default for the key type reserved. The
226 * instantiation function should amend this as necessary. If insufficient
227 * quota is available, -EDQUOT will be returned.
228 *
229 * The LSM security modules can prevent a key being created, in which case
230 * -EACCES will be returned.
231 *
232 * Returns a pointer to the new key if successful and an error code otherwise.
233 *
234 * Note that the caller needs to ensure the key type isn't uninstantiated.
235 * Internally this can be done by locking key_types_sem. Externally, this can
236 * be done by either never unregistering the key type, or making sure
237 * key_alloc() calls don't race with module unloading.
226 */ 238 */
227struct key *key_alloc(struct key_type *type, const char *desc, 239struct key *key_alloc(struct key_type *type, const char *desc,
228 uid_t uid, gid_t gid, const struct cred *cred, 240 uid_t uid, gid_t gid, const struct cred *cred,
@@ -237,6 +249,14 @@ struct key *key_alloc(struct key_type *type, const char *desc,
237 if (!desc || !*desc) 249 if (!desc || !*desc)
238 goto error; 250 goto error;
239 251
252 if (type->vet_description) {
253 ret = type->vet_description(desc);
254 if (ret < 0) {
255 key = ERR_PTR(ret);
256 goto error;
257 }
258 }
259
240 desclen = strlen(desc) + 1; 260 desclen = strlen(desc) + 1;
241 quotalen = desclen + type->def_datalen; 261 quotalen = desclen + type->def_datalen;
242 262
@@ -344,14 +364,19 @@ no_quota:
344 key_user_put(user); 364 key_user_put(user);
345 key = ERR_PTR(-EDQUOT); 365 key = ERR_PTR(-EDQUOT);
346 goto error; 366 goto error;
347 367}
348} /* end key_alloc() */
349
350EXPORT_SYMBOL(key_alloc); 368EXPORT_SYMBOL(key_alloc);
351 369
352/*****************************************************************************/ 370/**
353/* 371 * key_payload_reserve - Adjust data quota reservation for the key's payload
354 * reserve an amount of quota for the key's payload 372 * @key: The key to make the reservation for.
373 * @datalen: The amount of data payload the caller now wants.
374 *
375 * Adjust the amount of the owning user's key data quota that a key reserves.
376 * If the amount is increased, then -EDQUOT may be returned if there isn't
377 * enough free quota available.
378 *
379 * If successful, 0 is returned.
355 */ 380 */
356int key_payload_reserve(struct key *key, size_t datalen) 381int key_payload_reserve(struct key *key, size_t datalen)
357{ 382{
@@ -384,22 +409,21 @@ int key_payload_reserve(struct key *key, size_t datalen)
384 key->datalen = datalen; 409 key->datalen = datalen;
385 410
386 return ret; 411 return ret;
387 412}
388} /* end key_payload_reserve() */
389
390EXPORT_SYMBOL(key_payload_reserve); 413EXPORT_SYMBOL(key_payload_reserve);
391 414
392/*****************************************************************************/
393/* 415/*
394 * instantiate a key and link it into the target keyring atomically 416 * Instantiate a key and link it into the target keyring atomically. Must be
395 * - called with the target keyring's semaphore writelocked 417 * called with the target keyring's semaphore writelocked. The target key's
418 * semaphore need not be locked as instantiation is serialised by
419 * key_construction_mutex.
396 */ 420 */
397static int __key_instantiate_and_link(struct key *key, 421static int __key_instantiate_and_link(struct key *key,
398 const void *data, 422 const void *data,
399 size_t datalen, 423 size_t datalen,
400 struct key *keyring, 424 struct key *keyring,
401 struct key *authkey, 425 struct key *authkey,
402 struct keyring_list **_prealloc) 426 unsigned long *_prealloc)
403{ 427{
404 int ret, awaken; 428 int ret, awaken;
405 429
@@ -441,12 +465,23 @@ static int __key_instantiate_and_link(struct key *key,
441 wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT); 465 wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
442 466
443 return ret; 467 return ret;
468}
444 469
445} /* end __key_instantiate_and_link() */ 470/**
446 471 * key_instantiate_and_link - Instantiate a key and link it into the keyring.
447/*****************************************************************************/ 472 * @key: The key to instantiate.
448/* 473 * @data: The data to use to instantiate the keyring.
449 * instantiate a key and link it into the target keyring atomically 474 * @datalen: The length of @data.
475 * @keyring: Keyring to create a link in on success (or NULL).
476 * @authkey: The authorisation token permitting instantiation.
477 *
478 * Instantiate a key that's in the uninstantiated state using the provided data
479 * and, if successful, link it in to the destination keyring if one is
480 * supplied.
481 *
482 * If successful, 0 is returned, the authorisation token is revoked and anyone
483 * waiting for the key is woken up. If the key was already instantiated,
484 * -EBUSY will be returned.
450 */ 485 */
451int key_instantiate_and_link(struct key *key, 486int key_instantiate_and_link(struct key *key,
452 const void *data, 487 const void *data,
@@ -454,7 +489,7 @@ int key_instantiate_and_link(struct key *key,
454 struct key *keyring, 489 struct key *keyring,
455 struct key *authkey) 490 struct key *authkey)
456{ 491{
457 struct keyring_list *prealloc; 492 unsigned long prealloc;
458 int ret; 493 int ret;
459 494
460 if (keyring) { 495 if (keyring) {
@@ -471,21 +506,38 @@ int key_instantiate_and_link(struct key *key,
471 __key_link_end(keyring, key->type, prealloc); 506 __key_link_end(keyring, key->type, prealloc);
472 507
473 return ret; 508 return ret;
474 509}
475} /* end key_instantiate_and_link() */
476 510
477EXPORT_SYMBOL(key_instantiate_and_link); 511EXPORT_SYMBOL(key_instantiate_and_link);
478 512
479/*****************************************************************************/ 513/**
480/* 514 * key_reject_and_link - Negatively instantiate a key and link it into the keyring.
481 * negatively instantiate a key and link it into the target keyring atomically 515 * @key: The key to instantiate.
516 * @timeout: The timeout on the negative key.
517 * @error: The error to return when the key is hit.
518 * @keyring: Keyring to create a link in on success (or NULL).
519 * @authkey: The authorisation token permitting instantiation.
520 *
521 * Negatively instantiate a key that's in the uninstantiated state and, if
522 * successful, set its timeout and stored error and link it in to the
523 * destination keyring if one is supplied. The key and any links to the key
524 * will be automatically garbage collected after the timeout expires.
525 *
526 * Negative keys are used to rate limit repeated request_key() calls by causing
527 * them to return the stored error code (typically ENOKEY) until the negative
528 * key expires.
529 *
530 * If successful, 0 is returned, the authorisation token is revoked and anyone
531 * waiting for the key is woken up. If the key was already instantiated,
532 * -EBUSY will be returned.
482 */ 533 */
483int key_negate_and_link(struct key *key, 534int key_reject_and_link(struct key *key,
484 unsigned timeout, 535 unsigned timeout,
536 unsigned error,
485 struct key *keyring, 537 struct key *keyring,
486 struct key *authkey) 538 struct key *authkey)
487{ 539{
488 struct keyring_list *prealloc; 540 unsigned long prealloc;
489 struct timespec now; 541 struct timespec now;
490 int ret, awaken, link_ret = 0; 542 int ret, awaken, link_ret = 0;
491 543
@@ -507,6 +559,7 @@ int key_negate_and_link(struct key *key,
507 atomic_inc(&key->user->nikeys); 559 atomic_inc(&key->user->nikeys);
508 set_bit(KEY_FLAG_NEGATIVE, &key->flags); 560 set_bit(KEY_FLAG_NEGATIVE, &key->flags);
509 set_bit(KEY_FLAG_INSTANTIATED, &key->flags); 561 set_bit(KEY_FLAG_INSTANTIATED, &key->flags);
562 key->type_data.reject_error = -error;
510 now = current_kernel_time(); 563 now = current_kernel_time();
511 key->expiry = now.tv_sec + timeout; 564 key->expiry = now.tv_sec + timeout;
512 key_schedule_gc(key->expiry + key_gc_delay); 565 key_schedule_gc(key->expiry + key_gc_delay);
@@ -535,22 +588,22 @@ int key_negate_and_link(struct key *key,
535 wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT); 588 wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
536 589
537 return ret == 0 ? link_ret : ret; 590 return ret == 0 ? link_ret : ret;
591}
592EXPORT_SYMBOL(key_reject_and_link);
538 593
539} /* end key_negate_and_link() */
540
541EXPORT_SYMBOL(key_negate_and_link);
542
543/*****************************************************************************/
544/* 594/*
545 * do cleaning up in process context so that we don't have to disable 595 * Garbage collect keys in process context so that we don't have to disable
546 * interrupts all over the place 596 * interrupts all over the place.
597 *
598 * key_put() schedules this rather than trying to do the cleanup itself, which
599 * means key_put() doesn't have to sleep.
547 */ 600 */
548static void key_cleanup(struct work_struct *work) 601static void key_cleanup(struct work_struct *work)
549{ 602{
550 struct rb_node *_n; 603 struct rb_node *_n;
551 struct key *key; 604 struct key *key;
552 605
553 go_again: 606go_again:
554 /* look for a dead key in the tree */ 607 /* look for a dead key in the tree */
555 spin_lock(&key_serial_lock); 608 spin_lock(&key_serial_lock);
556 609
@@ -564,7 +617,7 @@ static void key_cleanup(struct work_struct *work)
564 spin_unlock(&key_serial_lock); 617 spin_unlock(&key_serial_lock);
565 return; 618 return;
566 619
567 found_dead_key: 620found_dead_key:
568 /* we found a dead key - once we've removed it from the tree, we can 621 /* we found a dead key - once we've removed it from the tree, we can
569 * drop the lock */ 622 * drop the lock */
570 rb_erase(&key->serial_node, &key_serial_tree); 623 rb_erase(&key->serial_node, &key_serial_tree);
@@ -601,14 +654,15 @@ static void key_cleanup(struct work_struct *work)
601 654
602 /* there may, of course, be more than one key to destroy */ 655 /* there may, of course, be more than one key to destroy */
603 goto go_again; 656 goto go_again;
657}
604 658
605} /* end key_cleanup() */ 659/**
606 660 * key_put - Discard a reference to a key.
607/*****************************************************************************/ 661 * @key: The key to discard a reference from.
608/* 662 *
609 * dispose of a reference to a key 663 * Discard a reference to a key, and when all the references are gone, we
610 * - when all the references are gone, we schedule the cleanup task to come and 664 * schedule the cleanup task to come and pull it out of the tree in process
611 * pull it out of the tree in definite process context 665 * context at some later time.
612 */ 666 */
613void key_put(struct key *key) 667void key_put(struct key *key)
614{ 668{
@@ -618,14 +672,11 @@ void key_put(struct key *key)
618 if (atomic_dec_and_test(&key->usage)) 672 if (atomic_dec_and_test(&key->usage))
619 schedule_work(&key_cleanup_task); 673 schedule_work(&key_cleanup_task);
620 } 674 }
621 675}
622} /* end key_put() */
623
624EXPORT_SYMBOL(key_put); 676EXPORT_SYMBOL(key_put);
625 677
626/*****************************************************************************/
627/* 678/*
628 * find a key by its serial number 679 * Find a key by its serial number.
629 */ 680 */
630struct key *key_lookup(key_serial_t id) 681struct key *key_lookup(key_serial_t id)
631{ 682{
@@ -647,11 +698,11 @@ struct key *key_lookup(key_serial_t id)
647 goto found; 698 goto found;
648 } 699 }
649 700
650 not_found: 701not_found:
651 key = ERR_PTR(-ENOKEY); 702 key = ERR_PTR(-ENOKEY);
652 goto error; 703 goto error;
653 704
654 found: 705found:
655 /* pretend it doesn't exist if it is awaiting deletion */ 706 /* pretend it doesn't exist if it is awaiting deletion */
656 if (atomic_read(&key->usage) == 0) 707 if (atomic_read(&key->usage) == 0)
657 goto not_found; 708 goto not_found;
@@ -661,16 +712,16 @@ struct key *key_lookup(key_serial_t id)
661 */ 712 */
662 atomic_inc(&key->usage); 713 atomic_inc(&key->usage);
663 714
664 error: 715error:
665 spin_unlock(&key_serial_lock); 716 spin_unlock(&key_serial_lock);
666 return key; 717 return key;
718}
667 719
668} /* end key_lookup() */
669
670/*****************************************************************************/
671/* 720/*
672 * find and lock the specified key type against removal 721 * Find and lock the specified key type against removal.
673 * - we return with the sem readlocked 722 *
723 * We return with the sem read-locked if successful. If the type wasn't
724 * available -ENOKEY is returned instead.
674 */ 725 */
675struct key_type *key_type_lookup(const char *type) 726struct key_type *key_type_lookup(const char *type)
676{ 727{
@@ -688,26 +739,23 @@ struct key_type *key_type_lookup(const char *type)
688 up_read(&key_types_sem); 739 up_read(&key_types_sem);
689 ktype = ERR_PTR(-ENOKEY); 740 ktype = ERR_PTR(-ENOKEY);
690 741
691 found_kernel_type: 742found_kernel_type:
692 return ktype; 743 return ktype;
744}
693 745
694} /* end key_type_lookup() */
695
696/*****************************************************************************/
697/* 746/*
698 * unlock a key type 747 * Unlock a key type locked by key_type_lookup().
699 */ 748 */
700void key_type_put(struct key_type *ktype) 749void key_type_put(struct key_type *ktype)
701{ 750{
702 up_read(&key_types_sem); 751 up_read(&key_types_sem);
752}
703 753
704} /* end key_type_put() */
705
706/*****************************************************************************/
707/* 754/*
708 * attempt to update an existing key 755 * Attempt to update an existing key.
709 * - the key has an incremented refcount 756 *
710 * - we need to put the key if we get an error 757 * The key is given to us with an incremented refcount that we need to discard
758 * if we get an error.
711 */ 759 */
712static inline key_ref_t __key_update(key_ref_t key_ref, 760static inline key_ref_t __key_update(key_ref_t key_ref,
713 const void *payload, size_t plen) 761 const void *payload, size_t plen)
@@ -742,13 +790,32 @@ error:
742 key_put(key); 790 key_put(key);
743 key_ref = ERR_PTR(ret); 791 key_ref = ERR_PTR(ret);
744 goto out; 792 goto out;
793}
745 794
746} /* end __key_update() */ 795/**
747 796 * key_create_or_update - Update or create and instantiate a key.
748/*****************************************************************************/ 797 * @keyring_ref: A pointer to the destination keyring with possession flag.
749/* 798 * @type: The type of key.
750 * search the specified keyring for a key of the same description; if one is 799 * @description: The searchable description for the key.
751 * found, update it, otherwise add a new one 800 * @payload: The data to use to instantiate or update the key.
801 * @plen: The length of @payload.
802 * @perm: The permissions mask for a new key.
803 * @flags: The quota flags for a new key.
804 *
805 * Search the destination keyring for a key of the same description and if one
806 * is found, update it, otherwise create and instantiate a new one and create a
807 * link to it from that keyring.
808 *
809 * If perm is KEY_PERM_UNDEF then an appropriate key permissions mask will be
810 * concocted.
811 *
812 * Returns a pointer to the new key if successful, -ENODEV if the key type
813 * wasn't available, -ENOTDIR if the keyring wasn't a keyring, -EACCES if the
814 * caller isn't permitted to modify the keyring or the LSM did not permit
815 * creation of the key.
816 *
817 * On success, the possession flag from the keyring ref will be tacked on to
818 * the key ref before it is returned.
752 */ 819 */
753key_ref_t key_create_or_update(key_ref_t keyring_ref, 820key_ref_t key_create_or_update(key_ref_t keyring_ref,
754 const char *type, 821 const char *type,
@@ -758,7 +825,7 @@ key_ref_t key_create_or_update(key_ref_t keyring_ref,
758 key_perm_t perm, 825 key_perm_t perm,
759 unsigned long flags) 826 unsigned long flags)
760{ 827{
761 struct keyring_list *prealloc; 828 unsigned long prealloc;
762 const struct cred *cred = current_cred(); 829 const struct cred *cred = current_cred();
763 struct key_type *ktype; 830 struct key_type *ktype;
764 struct key *keyring, *key = NULL; 831 struct key *keyring, *key = NULL;
@@ -855,14 +922,21 @@ key_ref_t key_create_or_update(key_ref_t keyring_ref,
855 922
856 key_ref = __key_update(key_ref, payload, plen); 923 key_ref = __key_update(key_ref, payload, plen);
857 goto error; 924 goto error;
858 925}
859} /* end key_create_or_update() */
860
861EXPORT_SYMBOL(key_create_or_update); 926EXPORT_SYMBOL(key_create_or_update);
862 927
863/*****************************************************************************/ 928/**
864/* 929 * key_update - Update a key's contents.
865 * update a key 930 * @key_ref: The pointer (plus possession flag) to the key.
931 * @payload: The data to be used to update the key.
932 * @plen: The length of @payload.
933 *
934 * Attempt to update the contents of a key with the given payload data. The
935 * caller must be granted Write permission on the key. Negative keys can be
936 * instantiated by this method.
937 *
938 * Returns 0 on success, -EACCES if not permitted and -EOPNOTSUPP if the key
939 * type does not support updating. The key type may return other errors.
866 */ 940 */
867int key_update(key_ref_t key_ref, const void *payload, size_t plen) 941int key_update(key_ref_t key_ref, const void *payload, size_t plen)
868{ 942{
@@ -891,14 +965,17 @@ int key_update(key_ref_t key_ref, const void *payload, size_t plen)
891 965
892 error: 966 error:
893 return ret; 967 return ret;
894 968}
895} /* end key_update() */
896
897EXPORT_SYMBOL(key_update); 969EXPORT_SYMBOL(key_update);
898 970
899/*****************************************************************************/ 971/**
900/* 972 * key_revoke - Revoke a key.
901 * revoke a key 973 * @key: The key to be revoked.
974 *
975 * Mark a key as being revoked and ask the type to free up its resources. The
976 * revocation timeout is set and the key and all its links will be
977 * automatically garbage collected after key_gc_delay amount of time if they
978 * are not manually dealt with first.
902 */ 979 */
903void key_revoke(struct key *key) 980void key_revoke(struct key *key)
904{ 981{
@@ -926,14 +1003,16 @@ void key_revoke(struct key *key)
926 } 1003 }
927 1004
928 up_write(&key->sem); 1005 up_write(&key->sem);
929 1006}
930} /* end key_revoke() */
931
932EXPORT_SYMBOL(key_revoke); 1007EXPORT_SYMBOL(key_revoke);
933 1008
934/*****************************************************************************/ 1009/**
935/* 1010 * register_key_type - Register a type of key.
936 * register a type of key 1011 * @ktype: The new key type.
1012 *
1013 * Register a new key type.
1014 *
1015 * Returns 0 on success or -EEXIST if a type of this name already exists.
937 */ 1016 */
938int register_key_type(struct key_type *ktype) 1017int register_key_type(struct key_type *ktype)
939{ 1018{
@@ -953,17 +1032,19 @@ int register_key_type(struct key_type *ktype)
953 list_add(&ktype->link, &key_types_list); 1032 list_add(&ktype->link, &key_types_list);
954 ret = 0; 1033 ret = 0;
955 1034
956 out: 1035out:
957 up_write(&key_types_sem); 1036 up_write(&key_types_sem);
958 return ret; 1037 return ret;
959 1038}
960} /* end register_key_type() */
961
962EXPORT_SYMBOL(register_key_type); 1039EXPORT_SYMBOL(register_key_type);
963 1040
964/*****************************************************************************/ 1041/**
965/* 1042 * unregister_key_type - Unregister a type of key.
966 * unregister a type of key 1043 * @ktype: The key type.
1044 *
1045 * Unregister a key type and mark all the extant keys of this type as dead.
1046 * Those keys of this type are then destroyed to get rid of their payloads and
1047 * they and their links will be garbage collected as soon as possible.
967 */ 1048 */
968void unregister_key_type(struct key_type *ktype) 1049void unregister_key_type(struct key_type *ktype)
969{ 1050{
@@ -1010,14 +1091,11 @@ void unregister_key_type(struct key_type *ktype)
1010 up_write(&key_types_sem); 1091 up_write(&key_types_sem);
1011 1092
1012 key_schedule_gc(0); 1093 key_schedule_gc(0);
1013 1094}
1014} /* end unregister_key_type() */
1015
1016EXPORT_SYMBOL(unregister_key_type); 1095EXPORT_SYMBOL(unregister_key_type);
1017 1096
1018/*****************************************************************************/
1019/* 1097/*
1020 * initialise the key management stuff 1098 * Initialise the key management state.
1021 */ 1099 */
1022void __init key_init(void) 1100void __init key_init(void)
1023{ 1101{
@@ -1037,5 +1115,4 @@ void __init key_init(void)
1037 1115
1038 rb_insert_color(&root_key_user.node, 1116 rb_insert_color(&root_key_user.node,
1039 &key_user_tree); 1117 &key_user_tree);
1040 1118}
1041} /* end key_init() */
diff --git a/security/keys/keyctl.c b/security/keys/keyctl.c
index 60924f6a52db..eca51918c951 100644
--- a/security/keys/keyctl.c
+++ b/security/keys/keyctl.c
@@ -1,4 +1,4 @@
1/* keyctl.c: userspace keyctl operations 1/* Userspace key control operations
2 * 2 *
3 * Copyright (C) 2004-5 Red Hat, Inc. All Rights Reserved. 3 * Copyright (C) 2004-5 Red Hat, Inc. All Rights Reserved.
4 * Written by David Howells (dhowells@redhat.com) 4 * Written by David Howells (dhowells@redhat.com)
@@ -31,28 +31,24 @@ static int key_get_type_from_user(char *type,
31 int ret; 31 int ret;
32 32
33 ret = strncpy_from_user(type, _type, len); 33 ret = strncpy_from_user(type, _type, len);
34
35 if (ret < 0) 34 if (ret < 0)
36 return ret; 35 return ret;
37
38 if (ret == 0 || ret >= len) 36 if (ret == 0 || ret >= len)
39 return -EINVAL; 37 return -EINVAL;
40
41 if (type[0] == '.') 38 if (type[0] == '.')
42 return -EPERM; 39 return -EPERM;
43
44 type[len - 1] = '\0'; 40 type[len - 1] = '\0';
45
46 return 0; 41 return 0;
47} 42}
48 43
49/*****************************************************************************/
50/* 44/*
51 * extract the description of a new key from userspace and either add it as a 45 * Extract the description of a new key from userspace and either add it as a
52 * new key to the specified keyring or update a matching key in that keyring 46 * new key to the specified keyring or update a matching key in that keyring.
53 * - the keyring must be writable 47 *
54 * - returns the new key's serial number 48 * The keyring must be writable so that we can attach the key to it.
55 * - implements add_key() 49 *
50 * If successful, the new key's serial number is returned, otherwise an error
51 * code is returned.
56 */ 52 */
57SYSCALL_DEFINE5(add_key, const char __user *, _type, 53SYSCALL_DEFINE5(add_key, const char __user *, _type,
58 const char __user *, _description, 54 const char __user *, _description,
@@ -132,19 +128,20 @@ SYSCALL_DEFINE5(add_key, const char __user *, _type,
132 kfree(description); 128 kfree(description);
133 error: 129 error:
134 return ret; 130 return ret;
131}
135 132
136} /* end sys_add_key() */
137
138/*****************************************************************************/
139/* 133/*
140 * search the process keyrings for a matching key 134 * Search the process keyrings and keyring trees linked from those for a
141 * - nested keyrings may also be searched if they have Search permission 135 * matching key. Keyrings must have appropriate Search permission to be
142 * - if a key is found, it will be attached to the destination keyring if 136 * searched.
143 * there's one specified 137 *
144 * - /sbin/request-key will be invoked if _callout_info is non-NULL 138 * If a key is found, it will be attached to the destination keyring if there's
145 * - the _callout_info string will be passed to /sbin/request-key 139 * one specified and the serial number of the key will be returned.
146 * - if the _callout_info string is empty, it will be rendered as "-" 140 *
147 * - implements request_key() 141 * If no key is found, /sbin/request-key will be invoked if _callout_info is
142 * non-NULL in an attempt to create a key. The _callout_info string will be
143 * passed to /sbin/request-key to aid with completing the request. If the
144 * _callout_info string is "" then it will be changed to "-".
148 */ 145 */
149SYSCALL_DEFINE4(request_key, const char __user *, _type, 146SYSCALL_DEFINE4(request_key, const char __user *, _type,
150 const char __user *, _description, 147 const char __user *, _description,
@@ -209,8 +206,14 @@ SYSCALL_DEFINE4(request_key, const char __user *, _type,
209 goto error5; 206 goto error5;
210 } 207 }
211 208
209 /* wait for the key to finish being constructed */
210 ret = wait_for_key_construction(key, 1);
211 if (ret < 0)
212 goto error6;
213
212 ret = key->serial; 214 ret = key->serial;
213 215
216error6:
214 key_put(key); 217 key_put(key);
215error5: 218error5:
216 key_type_put(ktype); 219 key_type_put(ktype);
@@ -222,14 +225,14 @@ error2:
222 kfree(description); 225 kfree(description);
223error: 226error:
224 return ret; 227 return ret;
228}
225 229
226} /* end sys_request_key() */
227
228/*****************************************************************************/
229/* 230/*
230 * get the ID of the specified process keyring 231 * Get the ID of the specified process keyring.
231 * - the keyring must have search permission to be found 232 *
232 * - implements keyctl(KEYCTL_GET_KEYRING_ID) 233 * The requested keyring must have search permission to be found.
234 *
235 * If successful, the ID of the requested keyring will be returned.
233 */ 236 */
234long keyctl_get_keyring_ID(key_serial_t id, int create) 237long keyctl_get_keyring_ID(key_serial_t id, int create)
235{ 238{
@@ -248,13 +251,17 @@ long keyctl_get_keyring_ID(key_serial_t id, int create)
248 key_ref_put(key_ref); 251 key_ref_put(key_ref);
249error: 252error:
250 return ret; 253 return ret;
254}
251 255
252} /* end keyctl_get_keyring_ID() */
253
254/*****************************************************************************/
255/* 256/*
256 * join the session keyring 257 * Join a (named) session keyring.
257 * - implements keyctl(KEYCTL_JOIN_SESSION_KEYRING) 258 *
259 * Create and join an anonymous session keyring or join a named session
260 * keyring, creating it if necessary. A named session keyring must have Search
261 * permission for it to be joined. Session keyrings without this permit will
262 * be skipped over.
263 *
264 * If successful, the ID of the joined session keyring will be returned.
258 */ 265 */
259long keyctl_join_session_keyring(const char __user *_name) 266long keyctl_join_session_keyring(const char __user *_name)
260{ 267{
@@ -277,14 +284,17 @@ long keyctl_join_session_keyring(const char __user *_name)
277 284
278error: 285error:
279 return ret; 286 return ret;
287}
280 288
281} /* end keyctl_join_session_keyring() */
282
283/*****************************************************************************/
284/* 289/*
285 * update a key's data payload 290 * Update a key's data payload from the given data.
286 * - the key must be writable 291 *
287 * - implements keyctl(KEYCTL_UPDATE) 292 * The key must grant the caller Write permission and the key type must support
293 * updating for this to work. A negative key can be positively instantiated
294 * with this call.
295 *
296 * If successful, 0 will be returned. If the key type does not support
297 * updating, then -EOPNOTSUPP will be returned.
288 */ 298 */
289long keyctl_update_key(key_serial_t id, 299long keyctl_update_key(key_serial_t id,
290 const void __user *_payload, 300 const void __user *_payload,
@@ -326,14 +336,17 @@ error2:
326 kfree(payload); 336 kfree(payload);
327error: 337error:
328 return ret; 338 return ret;
339}
329 340
330} /* end keyctl_update_key() */
331
332/*****************************************************************************/
333/* 341/*
334 * revoke a key 342 * Revoke a key.
335 * - the key must be writable 343 *
336 * - implements keyctl(KEYCTL_REVOKE) 344 * The key must be grant the caller Write or Setattr permission for this to
345 * work. The key type should give up its quota claim when revoked. The key
346 * and any links to the key will be automatically garbage collected after a
347 * certain amount of time (/proc/sys/kernel/keys/gc_delay).
348 *
349 * If successful, 0 is returned.
337 */ 350 */
338long keyctl_revoke_key(key_serial_t id) 351long keyctl_revoke_key(key_serial_t id)
339{ 352{
@@ -358,14 +371,14 @@ long keyctl_revoke_key(key_serial_t id)
358 key_ref_put(key_ref); 371 key_ref_put(key_ref);
359error: 372error:
360 return ret; 373 return ret;
374}
361 375
362} /* end keyctl_revoke_key() */
363
364/*****************************************************************************/
365/* 376/*
366 * clear the specified process keyring 377 * Clear the specified keyring, creating an empty process keyring if one of the
367 * - the keyring must be writable 378 * special keyring IDs is used.
368 * - implements keyctl(KEYCTL_CLEAR) 379 *
380 * The keyring must grant the caller Write permission for this to work. If
381 * successful, 0 will be returned.
369 */ 382 */
370long keyctl_keyring_clear(key_serial_t ringid) 383long keyctl_keyring_clear(key_serial_t ringid)
371{ 384{
@@ -383,15 +396,18 @@ long keyctl_keyring_clear(key_serial_t ringid)
383 key_ref_put(keyring_ref); 396 key_ref_put(keyring_ref);
384error: 397error:
385 return ret; 398 return ret;
399}
386 400
387} /* end keyctl_keyring_clear() */
388
389/*****************************************************************************/
390/* 401/*
391 * link a key into a keyring 402 * Create a link from a keyring to a key if there's no matching key in the
392 * - the keyring must be writable 403 * keyring, otherwise replace the link to the matching key with a link to the
393 * - the key must be linkable 404 * new key.
394 * - implements keyctl(KEYCTL_LINK) 405 *
406 * The key must grant the caller Link permission and the the keyring must grant
407 * the caller Write permission. Furthermore, if an additional link is created,
408 * the keyring's quota will be extended.
409 *
410 * If successful, 0 will be returned.
395 */ 411 */
396long keyctl_keyring_link(key_serial_t id, key_serial_t ringid) 412long keyctl_keyring_link(key_serial_t id, key_serial_t ringid)
397{ 413{
@@ -417,15 +433,16 @@ error2:
417 key_ref_put(keyring_ref); 433 key_ref_put(keyring_ref);
418error: 434error:
419 return ret; 435 return ret;
436}
420 437
421} /* end keyctl_keyring_link() */
422
423/*****************************************************************************/
424/* 438/*
425 * unlink the first attachment of a key from a keyring 439 * Unlink a key from a keyring.
426 * - the keyring must be writable 440 *
427 * - we don't need any permissions on the key 441 * The keyring must grant the caller Write permission for this to work; the key
428 * - implements keyctl(KEYCTL_UNLINK) 442 * itself need not grant the caller anything. If the last link to a key is
443 * removed then that key will be scheduled for destruction.
444 *
445 * If successful, 0 will be returned.
429 */ 446 */
430long keyctl_keyring_unlink(key_serial_t id, key_serial_t ringid) 447long keyctl_keyring_unlink(key_serial_t id, key_serial_t ringid)
431{ 448{
@@ -451,19 +468,20 @@ error2:
451 key_ref_put(keyring_ref); 468 key_ref_put(keyring_ref);
452error: 469error:
453 return ret; 470 return ret;
471}
454 472
455} /* end keyctl_keyring_unlink() */
456
457/*****************************************************************************/
458/* 473/*
459 * describe a user key 474 * Return a description of a key to userspace.
460 * - the key must have view permission 475 *
461 * - if there's a buffer, we place up to buflen bytes of data into it 476 * The key must grant the caller View permission for this to work.
462 * - unless there's an error, we return the amount of description available, 477 *
463 * irrespective of how much we may have copied 478 * If there's a buffer, we place up to buflen bytes of data into it formatted
464 * - the description is formatted thus: 479 * in the following way:
480 *
465 * type;uid;gid;perm;description<NUL> 481 * type;uid;gid;perm;description<NUL>
466 * - implements keyctl(KEYCTL_DESCRIBE) 482 *
483 * If successful, we return the amount of description available, irrespective
484 * of how much we may have copied into the buffer.
467 */ 485 */
468long keyctl_describe_key(key_serial_t keyid, 486long keyctl_describe_key(key_serial_t keyid,
469 char __user *buffer, 487 char __user *buffer,
@@ -531,18 +549,17 @@ error2:
531 key_ref_put(key_ref); 549 key_ref_put(key_ref);
532error: 550error:
533 return ret; 551 return ret;
552}
534 553
535} /* end keyctl_describe_key() */
536
537/*****************************************************************************/
538/* 554/*
539 * search the specified keyring for a matching key 555 * Search the specified keyring and any keyrings it links to for a matching
540 * - the start keyring must be searchable 556 * key. Only keyrings that grant the caller Search permission will be searched
541 * - nested keyrings may also be searched if they are searchable 557 * (this includes the starting keyring). Only keys with Search permission can
542 * - only keys with search permission may be found 558 * be found.
543 * - if a key is found, it will be attached to the destination keyring if 559 *
544 * there's one specified 560 * If successful, the found key will be linked to the destination keyring if
545 * - implements keyctl(KEYCTL_SEARCH) 561 * supplied and the key has Link permission, and the found key ID will be
562 * returned.
546 */ 563 */
547long keyctl_keyring_search(key_serial_t ringid, 564long keyctl_keyring_search(key_serial_t ringid,
548 const char __user *_type, 565 const char __user *_type,
@@ -626,18 +643,17 @@ error2:
626 kfree(description); 643 kfree(description);
627error: 644error:
628 return ret; 645 return ret;
646}
629 647
630} /* end keyctl_keyring_search() */
631
632/*****************************************************************************/
633/* 648/*
634 * read a user key's payload 649 * Read a key's payload.
635 * - the keyring must be readable or the key must be searchable from the 650 *
636 * process's keyrings 651 * The key must either grant the caller Read permission, or it must grant the
637 * - if there's a buffer, we place up to buflen bytes of data into it 652 * caller Search permission when searched for from the process keyrings.
638 * - unless there's an error, we return the amount of data in the key, 653 *
639 * irrespective of how much we may have copied 654 * If successful, we place up to buflen bytes of data into the buffer, if one
640 * - implements keyctl(KEYCTL_READ) 655 * is provided, and return the amount of data that is available in the key,
656 * irrespective of how much we copied into the buffer.
641 */ 657 */
642long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen) 658long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen)
643{ 659{
@@ -688,15 +704,22 @@ error2:
688 key_put(key); 704 key_put(key);
689error: 705error:
690 return ret; 706 return ret;
707}
691 708
692} /* end keyctl_read_key() */
693
694/*****************************************************************************/
695/* 709/*
696 * change the ownership of a key 710 * Change the ownership of a key
697 * - the keyring owned by the changer 711 *
698 * - if the uid or gid is -1, then that parameter is not changed 712 * The key must grant the caller Setattr permission for this to work, though
699 * - implements keyctl(KEYCTL_CHOWN) 713 * the key need not be fully instantiated yet. For the UID to be changed, or
714 * for the GID to be changed to a group the caller is not a member of, the
715 * caller must have sysadmin capability. If either uid or gid is -1 then that
716 * attribute is not changed.
717 *
718 * If the UID is to be changed, the new user must have sufficient quota to
719 * accept the key. The quota deduction will be removed from the old user to
720 * the new user should the attribute be changed.
721 *
722 * If successful, 0 will be returned.
700 */ 723 */
701long keyctl_chown_key(key_serial_t id, uid_t uid, gid_t gid) 724long keyctl_chown_key(key_serial_t id, uid_t uid, gid_t gid)
702{ 725{
@@ -796,14 +819,14 @@ quota_overrun:
796 zapowner = newowner; 819 zapowner = newowner;
797 ret = -EDQUOT; 820 ret = -EDQUOT;
798 goto error_put; 821 goto error_put;
822}
799 823
800} /* end keyctl_chown_key() */
801
802/*****************************************************************************/
803/* 824/*
804 * change the permission mask on a key 825 * Change the permission mask on a key.
805 * - the keyring owned by the changer 826 *
806 * - implements keyctl(KEYCTL_SETPERM) 827 * The key must grant the caller Setattr permission for this to work, though
828 * the key need not be fully instantiated yet. If the caller does not have
829 * sysadmin capability, it may only change the permission on keys that it owns.
807 */ 830 */
808long keyctl_setperm_key(key_serial_t id, key_perm_t perm) 831long keyctl_setperm_key(key_serial_t id, key_perm_t perm)
809{ 832{
@@ -838,11 +861,11 @@ long keyctl_setperm_key(key_serial_t id, key_perm_t perm)
838 key_put(key); 861 key_put(key);
839error: 862error:
840 return ret; 863 return ret;
841 864}
842} /* end keyctl_setperm_key() */
843 865
844/* 866/*
845 * get the destination keyring for instantiation 867 * Get the destination keyring for instantiation and check that the caller has
868 * Write permission on it.
846 */ 869 */
847static long get_instantiation_keyring(key_serial_t ringid, 870static long get_instantiation_keyring(key_serial_t ringid,
848 struct request_key_auth *rka, 871 struct request_key_auth *rka,
@@ -879,7 +902,7 @@ static long get_instantiation_keyring(key_serial_t ringid,
879} 902}
880 903
881/* 904/*
882 * change the request_key authorisation key on the current process 905 * Change the request_key authorisation key on the current process.
883 */ 906 */
884static int keyctl_change_reqkey_auth(struct key *key) 907static int keyctl_change_reqkey_auth(struct key *key)
885{ 908{
@@ -895,15 +918,35 @@ static int keyctl_change_reqkey_auth(struct key *key)
895 return commit_creds(new); 918 return commit_creds(new);
896} 919}
897 920
898/*****************************************************************************/
899/* 921/*
900 * instantiate the key with the specified payload, and, if one is given, link 922 * Copy the iovec data from userspace
901 * the key into the keyring
902 */ 923 */
903long keyctl_instantiate_key(key_serial_t id, 924static long copy_from_user_iovec(void *buffer, const struct iovec *iov,
904 const void __user *_payload, 925 unsigned ioc)
905 size_t plen, 926{
906 key_serial_t ringid) 927 for (; ioc > 0; ioc--) {
928 if (copy_from_user(buffer, iov->iov_base, iov->iov_len) != 0)
929 return -EFAULT;
930 buffer += iov->iov_len;
931 iov++;
932 }
933 return 0;
934}
935
936/*
937 * Instantiate a key with the specified payload and link the key into the
938 * destination keyring if one is given.
939 *
940 * The caller must have the appropriate instantiation permit set for this to
941 * work (see keyctl_assume_authority). No other permissions are required.
942 *
943 * If successful, 0 will be returned.
944 */
945long keyctl_instantiate_key_common(key_serial_t id,
946 const struct iovec *payload_iov,
947 unsigned ioc,
948 size_t plen,
949 key_serial_t ringid)
907{ 950{
908 const struct cred *cred = current_cred(); 951 const struct cred *cred = current_cred();
909 struct request_key_auth *rka; 952 struct request_key_auth *rka;
@@ -932,7 +975,7 @@ long keyctl_instantiate_key(key_serial_t id,
932 /* pull the payload in if one was supplied */ 975 /* pull the payload in if one was supplied */
933 payload = NULL; 976 payload = NULL;
934 977
935 if (_payload) { 978 if (payload_iov) {
936 ret = -ENOMEM; 979 ret = -ENOMEM;
937 payload = kmalloc(plen, GFP_KERNEL); 980 payload = kmalloc(plen, GFP_KERNEL);
938 if (!payload) { 981 if (!payload) {
@@ -944,8 +987,8 @@ long keyctl_instantiate_key(key_serial_t id,
944 goto error; 987 goto error;
945 } 988 }
946 989
947 ret = -EFAULT; 990 ret = copy_from_user_iovec(payload, payload_iov, ioc);
948 if (copy_from_user(payload, _payload, plen) != 0) 991 if (ret < 0)
949 goto error2; 992 goto error2;
950 } 993 }
951 994
@@ -973,22 +1016,127 @@ error2:
973 vfree(payload); 1016 vfree(payload);
974error: 1017error:
975 return ret; 1018 return ret;
1019}
1020
1021/*
1022 * Instantiate a key with the specified payload and link the key into the
1023 * destination keyring if one is given.
1024 *
1025 * The caller must have the appropriate instantiation permit set for this to
1026 * work (see keyctl_assume_authority). No other permissions are required.
1027 *
1028 * If successful, 0 will be returned.
1029 */
1030long keyctl_instantiate_key(key_serial_t id,
1031 const void __user *_payload,
1032 size_t plen,
1033 key_serial_t ringid)
1034{
1035 if (_payload && plen) {
1036 struct iovec iov[1] = {
1037 [0].iov_base = (void __user *)_payload,
1038 [0].iov_len = plen
1039 };
976 1040
977} /* end keyctl_instantiate_key() */ 1041 return keyctl_instantiate_key_common(id, iov, 1, plen, ringid);
1042 }
1043
1044 return keyctl_instantiate_key_common(id, NULL, 0, 0, ringid);
1045}
978 1046
979/*****************************************************************************/
980/* 1047/*
981 * negatively instantiate the key with the given timeout (in seconds), and, if 1048 * Instantiate a key with the specified multipart payload and link the key into
982 * one is given, link the key into the keyring 1049 * the destination keyring if one is given.
1050 *
1051 * The caller must have the appropriate instantiation permit set for this to
1052 * work (see keyctl_assume_authority). No other permissions are required.
1053 *
1054 * If successful, 0 will be returned.
1055 */
1056long keyctl_instantiate_key_iov(key_serial_t id,
1057 const struct iovec __user *_payload_iov,
1058 unsigned ioc,
1059 key_serial_t ringid)
1060{
1061 struct iovec iovstack[UIO_FASTIOV], *iov = iovstack;
1062 long ret;
1063
1064 if (_payload_iov == 0 || ioc == 0)
1065 goto no_payload;
1066
1067 ret = rw_copy_check_uvector(WRITE, _payload_iov, ioc,
1068 ARRAY_SIZE(iovstack), iovstack, &iov);
1069 if (ret < 0)
1070 return ret;
1071 if (ret == 0)
1072 goto no_payload_free;
1073
1074 ret = keyctl_instantiate_key_common(id, iov, ioc, ret, ringid);
1075
1076 if (iov != iovstack)
1077 kfree(iov);
1078 return ret;
1079
1080no_payload_free:
1081 if (iov != iovstack)
1082 kfree(iov);
1083no_payload:
1084 return keyctl_instantiate_key_common(id, NULL, 0, 0, ringid);
1085}
1086
1087/*
1088 * Negatively instantiate the key with the given timeout (in seconds) and link
1089 * the key into the destination keyring if one is given.
1090 *
1091 * The caller must have the appropriate instantiation permit set for this to
1092 * work (see keyctl_assume_authority). No other permissions are required.
1093 *
1094 * The key and any links to the key will be automatically garbage collected
1095 * after the timeout expires.
1096 *
1097 * Negative keys are used to rate limit repeated request_key() calls by causing
1098 * them to return -ENOKEY until the negative key expires.
1099 *
1100 * If successful, 0 will be returned.
983 */ 1101 */
984long keyctl_negate_key(key_serial_t id, unsigned timeout, key_serial_t ringid) 1102long keyctl_negate_key(key_serial_t id, unsigned timeout, key_serial_t ringid)
985{ 1103{
1104 return keyctl_reject_key(id, timeout, ENOKEY, ringid);
1105}
1106
1107/*
1108 * Negatively instantiate the key with the given timeout (in seconds) and error
1109 * code and link the key into the destination keyring if one is given.
1110 *
1111 * The caller must have the appropriate instantiation permit set for this to
1112 * work (see keyctl_assume_authority). No other permissions are required.
1113 *
1114 * The key and any links to the key will be automatically garbage collected
1115 * after the timeout expires.
1116 *
1117 * Negative keys are used to rate limit repeated request_key() calls by causing
1118 * them to return the specified error code until the negative key expires.
1119 *
1120 * If successful, 0 will be returned.
1121 */
1122long keyctl_reject_key(key_serial_t id, unsigned timeout, unsigned error,
1123 key_serial_t ringid)
1124{
986 const struct cred *cred = current_cred(); 1125 const struct cred *cred = current_cred();
987 struct request_key_auth *rka; 1126 struct request_key_auth *rka;
988 struct key *instkey, *dest_keyring; 1127 struct key *instkey, *dest_keyring;
989 long ret; 1128 long ret;
990 1129
991 kenter("%d,%u,%d", id, timeout, ringid); 1130 kenter("%d,%u,%u,%d", id, timeout, error, ringid);
1131
1132 /* must be a valid error code and mustn't be a kernel special */
1133 if (error <= 0 ||
1134 error >= MAX_ERRNO ||
1135 error == ERESTARTSYS ||
1136 error == ERESTARTNOINTR ||
1137 error == ERESTARTNOHAND ||
1138 error == ERESTART_RESTARTBLOCK)
1139 return -EINVAL;
992 1140
993 /* the appropriate instantiation authorisation key must have been 1141 /* the appropriate instantiation authorisation key must have been
994 * assumed before calling this */ 1142 * assumed before calling this */
@@ -1008,7 +1156,7 @@ long keyctl_negate_key(key_serial_t id, unsigned timeout, key_serial_t ringid)
1008 goto error; 1156 goto error;
1009 1157
1010 /* instantiate the key and link it into a keyring */ 1158 /* instantiate the key and link it into a keyring */
1011 ret = key_negate_and_link(rka->target_key, timeout, 1159 ret = key_reject_and_link(rka->target_key, timeout, error,
1012 dest_keyring, instkey); 1160 dest_keyring, instkey);
1013 1161
1014 key_put(dest_keyring); 1162 key_put(dest_keyring);
@@ -1020,13 +1168,14 @@ long keyctl_negate_key(key_serial_t id, unsigned timeout, key_serial_t ringid)
1020 1168
1021error: 1169error:
1022 return ret; 1170 return ret;
1171}
1023 1172
1024} /* end keyctl_negate_key() */
1025
1026/*****************************************************************************/
1027/* 1173/*
1028 * set the default keyring in which request_key() will cache keys 1174 * Read or set the default keyring in which request_key() will cache keys and
1029 * - return the old setting 1175 * return the old setting.
1176 *
1177 * If a process keyring is specified then this will be created if it doesn't
1178 * yet exist. The old setting will be returned if successful.
1030 */ 1179 */
1031long keyctl_set_reqkey_keyring(int reqkey_defl) 1180long keyctl_set_reqkey_keyring(int reqkey_defl)
1032{ 1181{
@@ -1079,12 +1228,19 @@ set:
1079error: 1228error:
1080 abort_creds(new); 1229 abort_creds(new);
1081 return ret; 1230 return ret;
1231}
1082 1232
1083} /* end keyctl_set_reqkey_keyring() */
1084
1085/*****************************************************************************/
1086/* 1233/*
1087 * set or clear the timeout for a key 1234 * Set or clear the timeout on a key.
1235 *
1236 * Either the key must grant the caller Setattr permission or else the caller
1237 * must hold an instantiation authorisation token for the key.
1238 *
1239 * The timeout is either 0 to clear the timeout, or a number of seconds from
1240 * the current time. The key and any links to the key will be automatically
1241 * garbage collected after the timeout expires.
1242 *
1243 * If successful, 0 is returned.
1088 */ 1244 */
1089long keyctl_set_timeout(key_serial_t id, unsigned timeout) 1245long keyctl_set_timeout(key_serial_t id, unsigned timeout)
1090{ 1246{
@@ -1136,12 +1292,24 @@ okay:
1136 ret = 0; 1292 ret = 0;
1137error: 1293error:
1138 return ret; 1294 return ret;
1295}
1139 1296
1140} /* end keyctl_set_timeout() */
1141
1142/*****************************************************************************/
1143/* 1297/*
1144 * assume the authority to instantiate the specified key 1298 * Assume (or clear) the authority to instantiate the specified key.
1299 *
1300 * This sets the authoritative token currently in force for key instantiation.
1301 * This must be done for a key to be instantiated. It has the effect of making
1302 * available all the keys from the caller of the request_key() that created a
1303 * key to request_key() calls made by the caller of this function.
1304 *
1305 * The caller must have the instantiation key in their process keyrings with a
1306 * Search permission grant available to the caller.
1307 *
1308 * If the ID given is 0, then the setting will be cleared and 0 returned.
1309 *
1310 * If the ID given has a matching an authorisation key, then that key will be
1311 * set and its ID will be returned. The authorisation key can be read to get
1312 * the callout information passed to request_key().
1145 */ 1313 */
1146long keyctl_assume_authority(key_serial_t id) 1314long keyctl_assume_authority(key_serial_t id)
1147{ 1315{
@@ -1178,16 +1346,17 @@ long keyctl_assume_authority(key_serial_t id)
1178 ret = authkey->serial; 1346 ret = authkey->serial;
1179error: 1347error:
1180 return ret; 1348 return ret;
1181 1349}
1182} /* end keyctl_assume_authority() */
1183 1350
1184/* 1351/*
1185 * get the security label of a key 1352 * Get a key's the LSM security label.
1186 * - the key must grant us view permission 1353 *
1187 * - if there's a buffer, we place up to buflen bytes of data into it 1354 * The key must grant the caller View permission for this to work.
1188 * - unless there's an error, we return the amount of information available, 1355 *
1189 * irrespective of how much we may have copied (including the terminal NUL) 1356 * If there's a buffer, then up to buflen bytes of data will be placed into it.
1190 * - implements keyctl(KEYCTL_GET_SECURITY) 1357 *
1358 * If successful, the amount of information available will be returned,
1359 * irrespective of how much was copied (including the terminal NUL).
1191 */ 1360 */
1192long keyctl_get_security(key_serial_t keyid, 1361long keyctl_get_security(key_serial_t keyid,
1193 char __user *buffer, 1362 char __user *buffer,
@@ -1242,10 +1411,16 @@ long keyctl_get_security(key_serial_t keyid,
1242} 1411}
1243 1412
1244/* 1413/*
1245 * attempt to install the calling process's session keyring on the process's 1414 * Attempt to install the calling process's session keyring on the process's
1246 * parent process 1415 * parent process.
1247 * - the keyring must exist and must grant us LINK permission 1416 *
1248 * - implements keyctl(KEYCTL_SESSION_TO_PARENT) 1417 * The keyring must exist and must grant the caller LINK permission, and the
1418 * parent process must be single-threaded and must have the same effective
1419 * ownership as this process and mustn't be SUID/SGID.
1420 *
1421 * The keyring will be emplaced on the parent when it next resumes userspace.
1422 *
1423 * If successful, 0 will be returned.
1249 */ 1424 */
1250long keyctl_session_to_parent(void) 1425long keyctl_session_to_parent(void)
1251{ 1426{
@@ -1348,9 +1523,8 @@ error_keyring:
1348#endif /* !TIF_NOTIFY_RESUME */ 1523#endif /* !TIF_NOTIFY_RESUME */
1349} 1524}
1350 1525
1351/*****************************************************************************/
1352/* 1526/*
1353 * the key control system call 1527 * The key control system call
1354 */ 1528 */
1355SYSCALL_DEFINE5(keyctl, int, option, unsigned long, arg2, unsigned long, arg3, 1529SYSCALL_DEFINE5(keyctl, int, option, unsigned long, arg2, unsigned long, arg3,
1356 unsigned long, arg4, unsigned long, arg5) 1530 unsigned long, arg4, unsigned long, arg5)
@@ -1436,8 +1610,20 @@ SYSCALL_DEFINE5(keyctl, int, option, unsigned long, arg2, unsigned long, arg3,
1436 case KEYCTL_SESSION_TO_PARENT: 1610 case KEYCTL_SESSION_TO_PARENT:
1437 return keyctl_session_to_parent(); 1611 return keyctl_session_to_parent();
1438 1612
1613 case KEYCTL_REJECT:
1614 return keyctl_reject_key((key_serial_t) arg2,
1615 (unsigned) arg3,
1616 (unsigned) arg4,
1617 (key_serial_t) arg5);
1618
1619 case KEYCTL_INSTANTIATE_IOV:
1620 return keyctl_instantiate_key_iov(
1621 (key_serial_t) arg2,
1622 (const struct iovec __user *) arg3,
1623 (unsigned) arg4,
1624 (key_serial_t) arg5);
1625
1439 default: 1626 default:
1440 return -EOPNOTSUPP; 1627 return -EOPNOTSUPP;
1441 } 1628 }
1442 1629}
1443} /* end sys_keyctl() */
diff --git a/security/keys/keyring.c b/security/keys/keyring.c
index d37f713e73ce..a06ffab38568 100644
--- a/security/keys/keyring.c
+++ b/security/keys/keyring.c
@@ -25,14 +25,16 @@
25 (keyring)->payload.subscriptions, \ 25 (keyring)->payload.subscriptions, \
26 rwsem_is_locked((struct rw_semaphore *)&(keyring)->sem))) 26 rwsem_is_locked((struct rw_semaphore *)&(keyring)->sem)))
27 27
28#define KEY_LINK_FIXQUOTA 1UL
29
28/* 30/*
29 * when plumbing the depths of the key tree, this sets a hard limit set on how 31 * When plumbing the depths of the key tree, this sets a hard limit
30 * deep we're willing to go 32 * set on how deep we're willing to go.
31 */ 33 */
32#define KEYRING_SEARCH_MAX_DEPTH 6 34#define KEYRING_SEARCH_MAX_DEPTH 6
33 35
34/* 36/*
35 * we keep all named keyrings in a hash to speed looking them up 37 * We keep all named keyrings in a hash to speed looking them up.
36 */ 38 */
37#define KEYRING_NAME_HASH_SIZE (1 << 5) 39#define KEYRING_NAME_HASH_SIZE (1 << 5)
38 40
@@ -50,7 +52,9 @@ static inline unsigned keyring_hash(const char *desc)
50} 52}
51 53
52/* 54/*
53 * the keyring type definition 55 * The keyring key type definition. Keyrings are simply keys of this type and
56 * can be treated as ordinary keys in addition to having their own special
57 * operations.
54 */ 58 */
55static int keyring_instantiate(struct key *keyring, 59static int keyring_instantiate(struct key *keyring,
56 const void *data, size_t datalen); 60 const void *data, size_t datalen);
@@ -71,19 +75,17 @@ struct key_type key_type_keyring = {
71 .describe = keyring_describe, 75 .describe = keyring_describe,
72 .read = keyring_read, 76 .read = keyring_read,
73}; 77};
74
75EXPORT_SYMBOL(key_type_keyring); 78EXPORT_SYMBOL(key_type_keyring);
76 79
77/* 80/*
78 * semaphore to serialise link/link calls to prevent two link calls in parallel 81 * Semaphore to serialise link/link calls to prevent two link calls in parallel
79 * introducing a cycle 82 * introducing a cycle.
80 */ 83 */
81static DECLARE_RWSEM(keyring_serialise_link_sem); 84static DECLARE_RWSEM(keyring_serialise_link_sem);
82 85
83/*****************************************************************************/
84/* 86/*
85 * publish the name of a keyring so that it can be found by name (if it has 87 * Publish the name of a keyring so that it can be found by name (if it has
86 * one) 88 * one).
87 */ 89 */
88static void keyring_publish_name(struct key *keyring) 90static void keyring_publish_name(struct key *keyring)
89{ 91{
@@ -102,13 +104,12 @@ static void keyring_publish_name(struct key *keyring)
102 104
103 write_unlock(&keyring_name_lock); 105 write_unlock(&keyring_name_lock);
104 } 106 }
107}
105 108
106} /* end keyring_publish_name() */
107
108/*****************************************************************************/
109/* 109/*
110 * initialise a keyring 110 * Initialise a keyring.
111 * - we object if we were given any data 111 *
112 * Returns 0 on success, -EINVAL if given any data.
112 */ 113 */
113static int keyring_instantiate(struct key *keyring, 114static int keyring_instantiate(struct key *keyring,
114 const void *data, size_t datalen) 115 const void *data, size_t datalen)
@@ -123,23 +124,20 @@ static int keyring_instantiate(struct key *keyring,
123 } 124 }
124 125
125 return ret; 126 return ret;
127}
126 128
127} /* end keyring_instantiate() */
128
129/*****************************************************************************/
130/* 129/*
131 * match keyrings on their name 130 * Match keyrings on their name
132 */ 131 */
133static int keyring_match(const struct key *keyring, const void *description) 132static int keyring_match(const struct key *keyring, const void *description)
134{ 133{
135 return keyring->description && 134 return keyring->description &&
136 strcmp(keyring->description, description) == 0; 135 strcmp(keyring->description, description) == 0;
136}
137 137
138} /* end keyring_match() */
139
140/*****************************************************************************/
141/* 138/*
142 * dispose of the data dangling from the corpse of a keyring 139 * Clean up a keyring when it is destroyed. Unpublish its name if it had one
140 * and dispose of its data.
143 */ 141 */
144static void keyring_destroy(struct key *keyring) 142static void keyring_destroy(struct key *keyring)
145{ 143{
@@ -164,12 +162,10 @@ static void keyring_destroy(struct key *keyring)
164 key_put(klist->keys[loop]); 162 key_put(klist->keys[loop]);
165 kfree(klist); 163 kfree(klist);
166 } 164 }
165}
167 166
168} /* end keyring_destroy() */
169
170/*****************************************************************************/
171/* 167/*
172 * describe the keyring 168 * Describe a keyring for /proc.
173 */ 169 */
174static void keyring_describe(const struct key *keyring, struct seq_file *m) 170static void keyring_describe(const struct key *keyring, struct seq_file *m)
175{ 171{
@@ -180,20 +176,21 @@ static void keyring_describe(const struct key *keyring, struct seq_file *m)
180 else 176 else
181 seq_puts(m, "[anon]"); 177 seq_puts(m, "[anon]");
182 178
183 rcu_read_lock(); 179 if (key_is_instantiated(keyring)) {
184 klist = rcu_dereference(keyring->payload.subscriptions); 180 rcu_read_lock();
185 if (klist) 181 klist = rcu_dereference(keyring->payload.subscriptions);
186 seq_printf(m, ": %u/%u", klist->nkeys, klist->maxkeys); 182 if (klist)
187 else 183 seq_printf(m, ": %u/%u", klist->nkeys, klist->maxkeys);
188 seq_puts(m, ": empty"); 184 else
189 rcu_read_unlock(); 185 seq_puts(m, ": empty");
190 186 rcu_read_unlock();
191} /* end keyring_describe() */ 187 }
188}
192 189
193/*****************************************************************************/
194/* 190/*
195 * read a list of key IDs from the keyring's contents 191 * Read a list of key IDs from the keyring's contents in binary form
196 * - the keyring's semaphore is read-locked 192 *
193 * The keyring's semaphore is read-locked by the caller.
197 */ 194 */
198static long keyring_read(const struct key *keyring, 195static long keyring_read(const struct key *keyring,
199 char __user *buffer, size_t buflen) 196 char __user *buffer, size_t buflen)
@@ -241,12 +238,10 @@ static long keyring_read(const struct key *keyring,
241 238
242error: 239error:
243 return ret; 240 return ret;
241}
244 242
245} /* end keyring_read() */
246
247/*****************************************************************************/
248/* 243/*
249 * allocate a keyring and link into the destination keyring 244 * Allocate a keyring and link into the destination keyring.
250 */ 245 */
251struct key *keyring_alloc(const char *description, uid_t uid, gid_t gid, 246struct key *keyring_alloc(const char *description, uid_t uid, gid_t gid,
252 const struct cred *cred, unsigned long flags, 247 const struct cred *cred, unsigned long flags,
@@ -269,26 +264,50 @@ struct key *keyring_alloc(const char *description, uid_t uid, gid_t gid,
269 } 264 }
270 265
271 return keyring; 266 return keyring;
267}
272 268
273} /* end keyring_alloc() */ 269/**
274 270 * keyring_search_aux - Search a keyring tree for a key matching some criteria
275/*****************************************************************************/ 271 * @keyring_ref: A pointer to the keyring with possession indicator.
276/* 272 * @cred: The credentials to use for permissions checks.
277 * search the supplied keyring tree for a key that matches the criterion 273 * @type: The type of key to search for.
278 * - perform a breadth-then-depth search up to the prescribed limit 274 * @description: Parameter for @match.
279 * - we only find keys on which we have search permission 275 * @match: Function to rule on whether or not a key is the one required.
280 * - we use the supplied match function to see if the description (or other 276 * @no_state_check: Don't check if a matching key is bad
281 * feature of interest) matches 277 *
282 * - we rely on RCU to prevent the keyring lists from disappearing on us 278 * Search the supplied keyring tree for a key that matches the criteria given.
283 * - we return -EAGAIN if we didn't find any matching key 279 * The root keyring and any linked keyrings must grant Search permission to the
284 * - we return -ENOKEY if we only found negative matching keys 280 * caller to be searchable and keys can only be found if they too grant Search
285 * - we propagate the possession attribute from the keyring ref to the key ref 281 * to the caller. The possession flag on the root keyring pointer controls use
282 * of the possessor bits in permissions checking of the entire tree. In
283 * addition, the LSM gets to forbid keyring searches and key matches.
284 *
285 * The search is performed as a breadth-then-depth search up to the prescribed
286 * limit (KEYRING_SEARCH_MAX_DEPTH).
287 *
288 * Keys are matched to the type provided and are then filtered by the match
289 * function, which is given the description to use in any way it sees fit. The
290 * match function may use any attributes of a key that it wishes to to
291 * determine the match. Normally the match function from the key type would be
292 * used.
293 *
294 * RCU is used to prevent the keyring key lists from disappearing without the
295 * need to take lots of locks.
296 *
297 * Returns a pointer to the found key and increments the key usage count if
298 * successful; -EAGAIN if no matching keys were found, or if expired or revoked
299 * keys were found; -ENOKEY if only negative keys were found; -ENOTDIR if the
300 * specified keyring wasn't a keyring.
301 *
302 * In the case of a successful return, the possession attribute from
303 * @keyring_ref is propagated to the returned key reference.
286 */ 304 */
287key_ref_t keyring_search_aux(key_ref_t keyring_ref, 305key_ref_t keyring_search_aux(key_ref_t keyring_ref,
288 const struct cred *cred, 306 const struct cred *cred,
289 struct key_type *type, 307 struct key_type *type,
290 const void *description, 308 const void *description,
291 key_match_func_t match) 309 key_match_func_t match,
310 bool no_state_check)
292{ 311{
293 struct { 312 struct {
294 struct keyring_list *keylist; 313 struct keyring_list *keylist;
@@ -330,6 +349,8 @@ key_ref_t keyring_search_aux(key_ref_t keyring_ref,
330 kflags = keyring->flags; 349 kflags = keyring->flags;
331 if (keyring->type == type && match(keyring, description)) { 350 if (keyring->type == type && match(keyring, description)) {
332 key = keyring; 351 key = keyring;
352 if (no_state_check)
353 goto found;
333 354
334 /* check it isn't negative and hasn't expired or been 355 /* check it isn't negative and hasn't expired or been
335 * revoked */ 356 * revoked */
@@ -337,7 +358,7 @@ key_ref_t keyring_search_aux(key_ref_t keyring_ref,
337 goto error_2; 358 goto error_2;
338 if (key->expiry && now.tv_sec >= key->expiry) 359 if (key->expiry && now.tv_sec >= key->expiry)
339 goto error_2; 360 goto error_2;
340 key_ref = ERR_PTR(-ENOKEY); 361 key_ref = ERR_PTR(key->type_data.reject_error);
341 if (kflags & (1 << KEY_FLAG_NEGATIVE)) 362 if (kflags & (1 << KEY_FLAG_NEGATIVE))
342 goto error_2; 363 goto error_2;
343 goto found; 364 goto found;
@@ -369,11 +390,13 @@ descend:
369 continue; 390 continue;
370 391
371 /* skip revoked keys and expired keys */ 392 /* skip revoked keys and expired keys */
372 if (kflags & (1 << KEY_FLAG_REVOKED)) 393 if (!no_state_check) {
373 continue; 394 if (kflags & (1 << KEY_FLAG_REVOKED))
395 continue;
374 396
375 if (key->expiry && now.tv_sec >= key->expiry) 397 if (key->expiry && now.tv_sec >= key->expiry)
376 continue; 398 continue;
399 }
377 400
378 /* keys that don't match */ 401 /* keys that don't match */
379 if (!match(key, description)) 402 if (!match(key, description))
@@ -384,9 +407,12 @@ descend:
384 cred, KEY_SEARCH) < 0) 407 cred, KEY_SEARCH) < 0)
385 continue; 408 continue;
386 409
410 if (no_state_check)
411 goto found;
412
387 /* we set a different error code if we pass a negative key */ 413 /* we set a different error code if we pass a negative key */
388 if (kflags & (1 << KEY_FLAG_NEGATIVE)) { 414 if (kflags & (1 << KEY_FLAG_NEGATIVE)) {
389 err = -ENOKEY; 415 err = key->type_data.reject_error;
390 continue; 416 continue;
391 } 417 }
392 418
@@ -444,17 +470,16 @@ error_2:
444 rcu_read_unlock(); 470 rcu_read_unlock();
445error: 471error:
446 return key_ref; 472 return key_ref;
473}
447 474
448} /* end keyring_search_aux() */ 475/**
449 476 * keyring_search - Search the supplied keyring tree for a matching key
450/*****************************************************************************/ 477 * @keyring: The root of the keyring tree to be searched.
451/* 478 * @type: The type of keyring we want to find.
452 * search the supplied keyring tree for a key that matches the criterion 479 * @description: The name of the keyring we want to find.
453 * - perform a breadth-then-depth search up to the prescribed limit 480 *
454 * - we only find keys on which we have search permission 481 * As keyring_search_aux() above, but using the current task's credentials and
455 * - we readlock the keyrings as we search down the tree 482 * type's default matching function.
456 * - we return -EAGAIN if we didn't find any matching key
457 * - we return -ENOKEY if we only found negative matching keys
458 */ 483 */
459key_ref_t keyring_search(key_ref_t keyring, 484key_ref_t keyring_search(key_ref_t keyring,
460 struct key_type *type, 485 struct key_type *type,
@@ -464,17 +489,24 @@ key_ref_t keyring_search(key_ref_t keyring,
464 return ERR_PTR(-ENOKEY); 489 return ERR_PTR(-ENOKEY);
465 490
466 return keyring_search_aux(keyring, current->cred, 491 return keyring_search_aux(keyring, current->cred,
467 type, description, type->match); 492 type, description, type->match, false);
468 493}
469} /* end keyring_search() */
470
471EXPORT_SYMBOL(keyring_search); 494EXPORT_SYMBOL(keyring_search);
472 495
473/*****************************************************************************/
474/* 496/*
475 * search the given keyring only (no recursion) 497 * Search the given keyring only (no recursion).
476 * - keyring must be locked by caller 498 *
477 * - caller must guarantee that the keyring is a keyring 499 * The caller must guarantee that the keyring is a keyring and that the
500 * permission is granted to search the keyring as no check is made here.
501 *
502 * RCU is used to make it unnecessary to lock the keyring key list here.
503 *
504 * Returns a pointer to the found key with usage count incremented if
505 * successful and returns -ENOKEY if not found. Revoked keys and keys not
506 * providing the requested permission are skipped over.
507 *
508 * If successful, the possession indicator is propagated from the keyring ref
509 * to the returned key reference.
478 */ 510 */
479key_ref_t __keyring_search_one(key_ref_t keyring_ref, 511key_ref_t __keyring_search_one(key_ref_t keyring_ref,
480 const struct key_type *ktype, 512 const struct key_type *ktype,
@@ -514,14 +546,18 @@ found:
514 atomic_inc(&key->usage); 546 atomic_inc(&key->usage);
515 rcu_read_unlock(); 547 rcu_read_unlock();
516 return make_key_ref(key, possessed); 548 return make_key_ref(key, possessed);
549}
517 550
518} /* end __keyring_search_one() */
519
520/*****************************************************************************/
521/* 551/*
522 * find a keyring with the specified name 552 * Find a keyring with the specified name.
523 * - all named keyrings are searched 553 *
524 * - normally only finds keyrings with search permission for the current process 554 * All named keyrings in the current user namespace are searched, provided they
555 * grant Search permission directly to the caller (unless this check is
556 * skipped). Keyrings whose usage points have reached zero or who have been
557 * revoked are skipped.
558 *
559 * Returns a pointer to the keyring with the keyring's refcount having being
560 * incremented on success. -ENOKEY is returned if a key could not be found.
525 */ 561 */
526struct key *find_keyring_by_name(const char *name, bool skip_perm_check) 562struct key *find_keyring_by_name(const char *name, bool skip_perm_check)
527{ 563{
@@ -569,15 +605,14 @@ struct key *find_keyring_by_name(const char *name, bool skip_perm_check)
569out: 605out:
570 read_unlock(&keyring_name_lock); 606 read_unlock(&keyring_name_lock);
571 return keyring; 607 return keyring;
608}
572 609
573} /* end find_keyring_by_name() */
574
575/*****************************************************************************/
576/* 610/*
577 * see if a cycle will will be created by inserting acyclic tree B in acyclic 611 * See if a cycle will will be created by inserting acyclic tree B in acyclic
578 * tree A at the topmost level (ie: as a direct child of A) 612 * tree A at the topmost level (ie: as a direct child of A).
579 * - since we are adding B to A at the top level, checking for cycles should 613 *
580 * just be a matter of seeing if node A is somewhere in tree B 614 * Since we are adding B to A at the top level, checking for cycles should just
615 * be a matter of seeing if node A is somewhere in tree B.
581 */ 616 */
582static int keyring_detect_cycle(struct key *A, struct key *B) 617static int keyring_detect_cycle(struct key *A, struct key *B)
583{ 618{
@@ -657,11 +692,10 @@ too_deep:
657cycle_detected: 692cycle_detected:
658 ret = -EDEADLK; 693 ret = -EDEADLK;
659 goto error; 694 goto error;
660 695}
661} /* end keyring_detect_cycle() */
662 696
663/* 697/*
664 * dispose of a keyring list after the RCU grace period, freeing the unlinked 698 * Dispose of a keyring list after the RCU grace period, freeing the unlinked
665 * key 699 * key
666 */ 700 */
667static void keyring_unlink_rcu_disposal(struct rcu_head *rcu) 701static void keyring_unlink_rcu_disposal(struct rcu_head *rcu)
@@ -675,14 +709,14 @@ static void keyring_unlink_rcu_disposal(struct rcu_head *rcu)
675} 709}
676 710
677/* 711/*
678 * preallocate memory so that a key can be linked into to a keyring 712 * Preallocate memory so that a key can be linked into to a keyring.
679 */ 713 */
680int __key_link_begin(struct key *keyring, const struct key_type *type, 714int __key_link_begin(struct key *keyring, const struct key_type *type,
681 const char *description, 715 const char *description, unsigned long *_prealloc)
682 struct keyring_list **_prealloc)
683 __acquires(&keyring->sem) 716 __acquires(&keyring->sem)
684{ 717{
685 struct keyring_list *klist, *nklist; 718 struct keyring_list *klist, *nklist;
719 unsigned long prealloc;
686 unsigned max; 720 unsigned max;
687 size_t size; 721 size_t size;
688 int loop, ret; 722 int loop, ret;
@@ -725,6 +759,7 @@ int __key_link_begin(struct key *keyring, const struct key_type *type,
725 759
726 /* note replacement slot */ 760 /* note replacement slot */
727 klist->delkey = nklist->delkey = loop; 761 klist->delkey = nklist->delkey = loop;
762 prealloc = (unsigned long)nklist;
728 goto done; 763 goto done;
729 } 764 }
730 } 765 }
@@ -739,6 +774,7 @@ int __key_link_begin(struct key *keyring, const struct key_type *type,
739 if (klist && klist->nkeys < klist->maxkeys) { 774 if (klist && klist->nkeys < klist->maxkeys) {
740 /* there's sufficient slack space to append directly */ 775 /* there's sufficient slack space to append directly */
741 nklist = NULL; 776 nklist = NULL;
777 prealloc = KEY_LINK_FIXQUOTA;
742 } else { 778 } else {
743 /* grow the key list */ 779 /* grow the key list */
744 max = 4; 780 max = 4;
@@ -773,8 +809,9 @@ int __key_link_begin(struct key *keyring, const struct key_type *type,
773 nklist->keys[nklist->delkey] = NULL; 809 nklist->keys[nklist->delkey] = NULL;
774 } 810 }
775 811
812 prealloc = (unsigned long)nklist | KEY_LINK_FIXQUOTA;
776done: 813done:
777 *_prealloc = nklist; 814 *_prealloc = prealloc;
778 kleave(" = 0"); 815 kleave(" = 0");
779 return 0; 816 return 0;
780 817
@@ -792,10 +829,10 @@ error_krsem:
792} 829}
793 830
794/* 831/*
795 * check already instantiated keys aren't going to be a problem 832 * Check already instantiated keys aren't going to be a problem.
796 * - the caller must have called __key_link_begin() 833 *
797 * - don't need to call this for keys that were created since __key_link_begin() 834 * The caller must have called __key_link_begin(). Don't need to call this for
798 * was called 835 * keys that were created since __key_link_begin() was called.
799 */ 836 */
800int __key_link_check_live_key(struct key *keyring, struct key *key) 837int __key_link_check_live_key(struct key *keyring, struct key *key)
801{ 838{
@@ -807,17 +844,20 @@ int __key_link_check_live_key(struct key *keyring, struct key *key)
807} 844}
808 845
809/* 846/*
810 * link a key into to a keyring 847 * Link a key into to a keyring.
811 * - must be called with __key_link_begin() having being called 848 *
812 * - discard already extant link to matching key if there is one 849 * Must be called with __key_link_begin() having being called. Discards any
850 * already extant link to matching key if there is one, so that each keyring
851 * holds at most one link to any given key of a particular type+description
852 * combination.
813 */ 853 */
814void __key_link(struct key *keyring, struct key *key, 854void __key_link(struct key *keyring, struct key *key,
815 struct keyring_list **_prealloc) 855 unsigned long *_prealloc)
816{ 856{
817 struct keyring_list *klist, *nklist; 857 struct keyring_list *klist, *nklist;
818 858
819 nklist = *_prealloc; 859 nklist = (struct keyring_list *)(*_prealloc & ~KEY_LINK_FIXQUOTA);
820 *_prealloc = NULL; 860 *_prealloc = 0;
821 861
822 kenter("%d,%d,%p", keyring->serial, key->serial, nklist); 862 kenter("%d,%d,%p", keyring->serial, key->serial, nklist);
823 863
@@ -852,34 +892,54 @@ void __key_link(struct key *keyring, struct key *key,
852} 892}
853 893
854/* 894/*
855 * finish linking a key into to a keyring 895 * Finish linking a key into to a keyring.
856 * - must be called with __key_link_begin() having being called 896 *
897 * Must be called with __key_link_begin() having being called.
857 */ 898 */
858void __key_link_end(struct key *keyring, struct key_type *type, 899void __key_link_end(struct key *keyring, struct key_type *type,
859 struct keyring_list *prealloc) 900 unsigned long prealloc)
860 __releases(&keyring->sem) 901 __releases(&keyring->sem)
861{ 902{
862 BUG_ON(type == NULL); 903 BUG_ON(type == NULL);
863 BUG_ON(type->name == NULL); 904 BUG_ON(type->name == NULL);
864 kenter("%d,%s,%p", keyring->serial, type->name, prealloc); 905 kenter("%d,%s,%lx", keyring->serial, type->name, prealloc);
865 906
866 if (type == &key_type_keyring) 907 if (type == &key_type_keyring)
867 up_write(&keyring_serialise_link_sem); 908 up_write(&keyring_serialise_link_sem);
868 909
869 if (prealloc) { 910 if (prealloc) {
870 kfree(prealloc); 911 if (prealloc & KEY_LINK_FIXQUOTA)
871 key_payload_reserve(keyring, 912 key_payload_reserve(keyring,
872 keyring->datalen - KEYQUOTA_LINK_BYTES); 913 keyring->datalen -
914 KEYQUOTA_LINK_BYTES);
915 kfree((struct keyring_list *)(prealloc & ~KEY_LINK_FIXQUOTA));
873 } 916 }
874 up_write(&keyring->sem); 917 up_write(&keyring->sem);
875} 918}
876 919
877/* 920/**
878 * link a key to a keyring 921 * key_link - Link a key to a keyring
922 * @keyring: The keyring to make the link in.
923 * @key: The key to link to.
924 *
925 * Make a link in a keyring to a key, such that the keyring holds a reference
926 * on that key and the key can potentially be found by searching that keyring.
927 *
928 * This function will write-lock the keyring's semaphore and will consume some
929 * of the user's key data quota to hold the link.
930 *
931 * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring,
932 * -EKEYREVOKED if the keyring has been revoked, -ENFILE if the keyring is
933 * full, -EDQUOT if there is insufficient key data quota remaining to add
934 * another link or -ENOMEM if there's insufficient memory.
935 *
936 * It is assumed that the caller has checked that it is permitted for a link to
937 * be made (the keyring should have Write permission and the key Link
938 * permission).
879 */ 939 */
880int key_link(struct key *keyring, struct key *key) 940int key_link(struct key *keyring, struct key *key)
881{ 941{
882 struct keyring_list *prealloc; 942 unsigned long prealloc;
883 int ret; 943 int ret;
884 944
885 key_check(keyring); 945 key_check(keyring);
@@ -895,12 +955,24 @@ int key_link(struct key *keyring, struct key *key)
895 955
896 return ret; 956 return ret;
897} 957}
898
899EXPORT_SYMBOL(key_link); 958EXPORT_SYMBOL(key_link);
900 959
901/*****************************************************************************/ 960/**
902/* 961 * key_unlink - Unlink the first link to a key from a keyring.
903 * unlink the first link to a key from a keyring 962 * @keyring: The keyring to remove the link from.
963 * @key: The key the link is to.
964 *
965 * Remove a link from a keyring to a key.
966 *
967 * This function will write-lock the keyring's semaphore.
968 *
969 * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring, -ENOENT if
970 * the key isn't linked to by the keyring or -ENOMEM if there's insufficient
971 * memory.
972 *
973 * It is assumed that the caller has checked that it is permitted for a link to
974 * be removed (the keyring should have Write permission; no permissions are
975 * required on the key).
904 */ 976 */
905int key_unlink(struct key *keyring, struct key *key) 977int key_unlink(struct key *keyring, struct key *key)
906{ 978{
@@ -968,15 +1040,12 @@ nomem:
968 ret = -ENOMEM; 1040 ret = -ENOMEM;
969 up_write(&keyring->sem); 1041 up_write(&keyring->sem);
970 goto error; 1042 goto error;
971 1043}
972} /* end key_unlink() */
973
974EXPORT_SYMBOL(key_unlink); 1044EXPORT_SYMBOL(key_unlink);
975 1045
976/*****************************************************************************/
977/* 1046/*
978 * dispose of a keyring list after the RCU grace period, releasing the keys it 1047 * Dispose of a keyring list after the RCU grace period, releasing the keys it
979 * links to 1048 * links to.
980 */ 1049 */
981static void keyring_clear_rcu_disposal(struct rcu_head *rcu) 1050static void keyring_clear_rcu_disposal(struct rcu_head *rcu)
982{ 1051{
@@ -989,13 +1058,15 @@ static void keyring_clear_rcu_disposal(struct rcu_head *rcu)
989 key_put(klist->keys[loop]); 1058 key_put(klist->keys[loop]);
990 1059
991 kfree(klist); 1060 kfree(klist);
1061}
992 1062
993} /* end keyring_clear_rcu_disposal() */ 1063/**
994 1064 * keyring_clear - Clear a keyring
995/*****************************************************************************/ 1065 * @keyring: The keyring to clear.
996/* 1066 *
997 * clear the specified process keyring 1067 * Clear the contents of the specified keyring.
998 * - implements keyctl(KEYCTL_CLEAR) 1068 *
1069 * Returns 0 if successful or -ENOTDIR if the keyring isn't a keyring.
999 */ 1070 */
1000int keyring_clear(struct key *keyring) 1071int keyring_clear(struct key *keyring)
1001{ 1072{
@@ -1027,15 +1098,13 @@ int keyring_clear(struct key *keyring)
1027 } 1098 }
1028 1099
1029 return ret; 1100 return ret;
1030 1101}
1031} /* end keyring_clear() */
1032
1033EXPORT_SYMBOL(keyring_clear); 1102EXPORT_SYMBOL(keyring_clear);
1034 1103
1035/*****************************************************************************/
1036/* 1104/*
1037 * dispose of the links from a revoked keyring 1105 * Dispose of the links from a revoked keyring.
1038 * - called with the key sem write-locked 1106 *
1107 * This is called with the key sem write-locked.
1039 */ 1108 */
1040static void keyring_revoke(struct key *keyring) 1109static void keyring_revoke(struct key *keyring)
1041{ 1110{
@@ -1050,11 +1119,10 @@ static void keyring_revoke(struct key *keyring)
1050 rcu_assign_pointer(keyring->payload.subscriptions, NULL); 1119 rcu_assign_pointer(keyring->payload.subscriptions, NULL);
1051 call_rcu(&klist->rcu, keyring_clear_rcu_disposal); 1120 call_rcu(&klist->rcu, keyring_clear_rcu_disposal);
1052 } 1121 }
1053 1122}
1054} /* end keyring_revoke() */
1055 1123
1056/* 1124/*
1057 * Determine whether a key is dead 1125 * Determine whether a key is dead.
1058 */ 1126 */
1059static bool key_is_dead(struct key *key, time_t limit) 1127static bool key_is_dead(struct key *key, time_t limit)
1060{ 1128{
@@ -1063,7 +1131,12 @@ static bool key_is_dead(struct key *key, time_t limit)
1063} 1131}
1064 1132
1065/* 1133/*
1066 * Collect garbage from the contents of a keyring 1134 * Collect garbage from the contents of a keyring, replacing the old list with
1135 * a new one with the pointers all shuffled down.
1136 *
1137 * Dead keys are classed as oned that are flagged as being dead or are revoked,
1138 * expired or negative keys that were revoked or expired before the specified
1139 * limit.
1067 */ 1140 */
1068void keyring_gc(struct key *keyring, time_t limit) 1141void keyring_gc(struct key *keyring, time_t limit)
1069{ 1142{
diff --git a/security/keys/permission.c b/security/keys/permission.c
index 28645502cd0d..c35b5229e3cd 100644
--- a/security/keys/permission.c
+++ b/security/keys/permission.c
@@ -1,4 +1,4 @@
1/* permission.c: key permission determination 1/* Key permission checking
2 * 2 *
3 * Copyright (C) 2005 Red Hat, Inc. All Rights Reserved. 3 * Copyright (C) 2005 Red Hat, Inc. All Rights Reserved.
4 * Written by David Howells (dhowells@redhat.com) 4 * Written by David Howells (dhowells@redhat.com)
@@ -13,18 +13,19 @@
13#include <linux/security.h> 13#include <linux/security.h>
14#include "internal.h" 14#include "internal.h"
15 15
16/*****************************************************************************/
17/** 16/**
18 * key_task_permission - Check a key can be used 17 * key_task_permission - Check a key can be used
19 * @key_ref: The key to check 18 * @key_ref: The key to check.
20 * @cred: The credentials to use 19 * @cred: The credentials to use.
21 * @perm: The permissions to check for 20 * @perm: The permissions to check for.
22 * 21 *
23 * Check to see whether permission is granted to use a key in the desired way, 22 * Check to see whether permission is granted to use a key in the desired way,
24 * but permit the security modules to override. 23 * but permit the security modules to override.
25 * 24 *
26 * The caller must hold either a ref on cred or must hold the RCU readlock or a 25 * The caller must hold either a ref on cred or must hold the RCU readlock.
27 * spinlock. 26 *
27 * Returns 0 if successful, -EACCES if access is denied based on the
28 * permissions bits or the LSM check.
28 */ 29 */
29int key_task_permission(const key_ref_t key_ref, const struct cred *cred, 30int key_task_permission(const key_ref_t key_ref, const struct cred *cred,
30 key_perm_t perm) 31 key_perm_t perm)
@@ -79,14 +80,16 @@ use_these_perms:
79 80
80 /* let LSM be the final arbiter */ 81 /* let LSM be the final arbiter */
81 return security_key_permission(key_ref, cred, perm); 82 return security_key_permission(key_ref, cred, perm);
82 83}
83} /* end key_task_permission() */
84
85EXPORT_SYMBOL(key_task_permission); 84EXPORT_SYMBOL(key_task_permission);
86 85
87/*****************************************************************************/ 86/**
88/* 87 * key_validate - Validate a key.
89 * validate a key 88 * @key: The key to be validated.
89 *
90 * Check that a key is valid, returning 0 if the key is okay, -EKEYREVOKED if
91 * the key's type has been removed or if the key has been revoked or
92 * -EKEYEXPIRED if the key has expired.
90 */ 93 */
91int key_validate(struct key *key) 94int key_validate(struct key *key)
92{ 95{
@@ -111,7 +114,5 @@ int key_validate(struct key *key)
111 114
112error: 115error:
113 return ret; 116 return ret;
114 117}
115} /* end key_validate() */
116
117EXPORT_SYMBOL(key_validate); 118EXPORT_SYMBOL(key_validate);
diff --git a/security/keys/proc.c b/security/keys/proc.c
index 70373966816e..49bbc97943ad 100644
--- a/security/keys/proc.c
+++ b/security/keys/proc.c
@@ -1,4 +1,4 @@
1/* proc.c: proc files for key database enumeration 1/* procfs files for key database enumeration
2 * 2 *
3 * Copyright (C) 2004 Red Hat, Inc. All Rights Reserved. 3 * Copyright (C) 2004 Red Hat, Inc. All Rights Reserved.
4 * Written by David Howells (dhowells@redhat.com) 4 * Written by David Howells (dhowells@redhat.com)
@@ -60,9 +60,8 @@ static const struct file_operations proc_key_users_fops = {
60 .release = seq_release, 60 .release = seq_release,
61}; 61};
62 62
63/*****************************************************************************/
64/* 63/*
65 * declare the /proc files 64 * Declare the /proc files.
66 */ 65 */
67static int __init key_proc_init(void) 66static int __init key_proc_init(void)
68{ 67{
@@ -79,14 +78,13 @@ static int __init key_proc_init(void)
79 panic("Cannot create /proc/key-users\n"); 78 panic("Cannot create /proc/key-users\n");
80 79
81 return 0; 80 return 0;
82 81}
83} /* end key_proc_init() */
84 82
85__initcall(key_proc_init); 83__initcall(key_proc_init);
86 84
87/*****************************************************************************/
88/* 85/*
89 * implement "/proc/keys" to provides a list of the keys on the system 86 * Implement "/proc/keys" to provide a list of the keys on the system that
87 * grant View permission to the caller.
90 */ 88 */
91#ifdef CONFIG_KEYS_DEBUG_PROC_KEYS 89#ifdef CONFIG_KEYS_DEBUG_PROC_KEYS
92 90
@@ -201,7 +199,7 @@ static int proc_keys_show(struct seq_file *m, void *v)
201 if (key->perm & KEY_POS_VIEW) { 199 if (key->perm & KEY_POS_VIEW) {
202 skey_ref = search_my_process_keyrings(key->type, key, 200 skey_ref = search_my_process_keyrings(key->type, key,
203 lookup_user_key_possessed, 201 lookup_user_key_possessed,
204 cred); 202 true, cred);
205 if (!IS_ERR(skey_ref)) { 203 if (!IS_ERR(skey_ref)) {
206 key_ref_put(skey_ref); 204 key_ref_put(skey_ref);
207 key_ref = make_key_ref(key, 1); 205 key_ref = make_key_ref(key, 1);
@@ -293,9 +291,9 @@ static struct rb_node *key_user_first(struct rb_root *r)
293 return __key_user_next(n); 291 return __key_user_next(n);
294} 292}
295 293
296/*****************************************************************************/
297/* 294/*
298 * implement "/proc/key-users" to provides a list of the key users 295 * Implement "/proc/key-users" to provides a list of the key users and their
296 * quotas.
299 */ 297 */
300static int proc_key_users_open(struct inode *inode, struct file *file) 298static int proc_key_users_open(struct inode *inode, struct file *file)
301{ 299{
@@ -351,5 +349,4 @@ static int proc_key_users_show(struct seq_file *m, void *v)
351 maxbytes); 349 maxbytes);
352 350
353 return 0; 351 return 0;
354
355} 352}
diff --git a/security/keys/process_keys.c b/security/keys/process_keys.c
index f8e7251ae2c8..a3063eb3dc23 100644
--- a/security/keys/process_keys.c
+++ b/security/keys/process_keys.c
@@ -1,4 +1,4 @@
1/* Management of a process's keyrings 1/* Manage a process's keyrings
2 * 2 *
3 * Copyright (C) 2004-2005, 2008 Red Hat, Inc. All Rights Reserved. 3 * Copyright (C) 2004-2005, 2008 Red Hat, Inc. All Rights Reserved.
4 * Written by David Howells (dhowells@redhat.com) 4 * Written by David Howells (dhowells@redhat.com)
@@ -21,13 +21,13 @@
21#include <asm/uaccess.h> 21#include <asm/uaccess.h>
22#include "internal.h" 22#include "internal.h"
23 23
24/* session keyring create vs join semaphore */ 24/* Session keyring create vs join semaphore */
25static DEFINE_MUTEX(key_session_mutex); 25static DEFINE_MUTEX(key_session_mutex);
26 26
27/* user keyring creation semaphore */ 27/* User keyring creation semaphore */
28static DEFINE_MUTEX(key_user_keyring_mutex); 28static DEFINE_MUTEX(key_user_keyring_mutex);
29 29
30/* the root user's tracking struct */ 30/* The root user's tracking struct */
31struct key_user root_key_user = { 31struct key_user root_key_user = {
32 .usage = ATOMIC_INIT(3), 32 .usage = ATOMIC_INIT(3),
33 .cons_lock = __MUTEX_INITIALIZER(root_key_user.cons_lock), 33 .cons_lock = __MUTEX_INITIALIZER(root_key_user.cons_lock),
@@ -38,9 +38,8 @@ struct key_user root_key_user = {
38 .user_ns = &init_user_ns, 38 .user_ns = &init_user_ns,
39}; 39};
40 40
41/*****************************************************************************/
42/* 41/*
43 * install user and user session keyrings for a particular UID 42 * Install the user and user session keyrings for the current process's UID.
44 */ 43 */
45int install_user_keyrings(void) 44int install_user_keyrings(void)
46{ 45{
@@ -122,7 +121,8 @@ error:
122} 121}
123 122
124/* 123/*
125 * install a fresh thread keyring directly to new credentials 124 * Install a fresh thread keyring directly to new credentials. This keyring is
125 * allowed to overrun the quota.
126 */ 126 */
127int install_thread_keyring_to_cred(struct cred *new) 127int install_thread_keyring_to_cred(struct cred *new)
128{ 128{
@@ -138,7 +138,7 @@ int install_thread_keyring_to_cred(struct cred *new)
138} 138}
139 139
140/* 140/*
141 * install a fresh thread keyring, discarding the old one 141 * Install a fresh thread keyring, discarding the old one.
142 */ 142 */
143static int install_thread_keyring(void) 143static int install_thread_keyring(void)
144{ 144{
@@ -161,9 +161,10 @@ static int install_thread_keyring(void)
161} 161}
162 162
163/* 163/*
164 * install a process keyring directly to a credentials struct 164 * Install a process keyring directly to a credentials struct.
165 * - returns -EEXIST if there was already a process keyring, 0 if one installed, 165 *
166 * and other -ve on any other error 166 * Returns -EEXIST if there was already a process keyring, 0 if one installed,
167 * and other value on any other error
167 */ 168 */
168int install_process_keyring_to_cred(struct cred *new) 169int install_process_keyring_to_cred(struct cred *new)
169{ 170{
@@ -192,8 +193,11 @@ int install_process_keyring_to_cred(struct cred *new)
192} 193}
193 194
194/* 195/*
195 * make sure a process keyring is installed 196 * Make sure a process keyring is installed for the current process. The
196 * - we 197 * existing process keyring is not replaced.
198 *
199 * Returns 0 if there is a process keyring by the end of this function, some
200 * error otherwise.
197 */ 201 */
198static int install_process_keyring(void) 202static int install_process_keyring(void)
199{ 203{
@@ -207,14 +211,14 @@ static int install_process_keyring(void)
207 ret = install_process_keyring_to_cred(new); 211 ret = install_process_keyring_to_cred(new);
208 if (ret < 0) { 212 if (ret < 0) {
209 abort_creds(new); 213 abort_creds(new);
210 return ret != -EEXIST ?: 0; 214 return ret != -EEXIST ? ret : 0;
211 } 215 }
212 216
213 return commit_creds(new); 217 return commit_creds(new);
214} 218}
215 219
216/* 220/*
217 * install a session keyring directly to a credentials struct 221 * Install a session keyring directly to a credentials struct.
218 */ 222 */
219int install_session_keyring_to_cred(struct cred *cred, struct key *keyring) 223int install_session_keyring_to_cred(struct cred *cred, struct key *keyring)
220{ 224{
@@ -254,8 +258,8 @@ int install_session_keyring_to_cred(struct cred *cred, struct key *keyring)
254} 258}
255 259
256/* 260/*
257 * install a session keyring, discarding the old one 261 * Install a session keyring, discarding the old one. If a keyring is not
258 * - if a keyring is not supplied, an empty one is invented 262 * supplied, an empty one is invented.
259 */ 263 */
260static int install_session_keyring(struct key *keyring) 264static int install_session_keyring(struct key *keyring)
261{ 265{
@@ -275,9 +279,8 @@ static int install_session_keyring(struct key *keyring)
275 return commit_creds(new); 279 return commit_creds(new);
276} 280}
277 281
278/*****************************************************************************/
279/* 282/*
280 * the filesystem user ID changed 283 * Handle the fsuid changing.
281 */ 284 */
282void key_fsuid_changed(struct task_struct *tsk) 285void key_fsuid_changed(struct task_struct *tsk)
283{ 286{
@@ -288,12 +291,10 @@ void key_fsuid_changed(struct task_struct *tsk)
288 tsk->cred->thread_keyring->uid = tsk->cred->fsuid; 291 tsk->cred->thread_keyring->uid = tsk->cred->fsuid;
289 up_write(&tsk->cred->thread_keyring->sem); 292 up_write(&tsk->cred->thread_keyring->sem);
290 } 293 }
294}
291 295
292} /* end key_fsuid_changed() */
293
294/*****************************************************************************/
295/* 296/*
296 * the filesystem group ID changed 297 * Handle the fsgid changing.
297 */ 298 */
298void key_fsgid_changed(struct task_struct *tsk) 299void key_fsgid_changed(struct task_struct *tsk)
299{ 300{
@@ -304,20 +305,33 @@ void key_fsgid_changed(struct task_struct *tsk)
304 tsk->cred->thread_keyring->gid = tsk->cred->fsgid; 305 tsk->cred->thread_keyring->gid = tsk->cred->fsgid;
305 up_write(&tsk->cred->thread_keyring->sem); 306 up_write(&tsk->cred->thread_keyring->sem);
306 } 307 }
308}
307 309
308} /* end key_fsgid_changed() */
309
310/*****************************************************************************/
311/* 310/*
312 * search only my process keyrings for the first matching key 311 * Search the process keyrings attached to the supplied cred for the first
313 * - we use the supplied match function to see if the description (or other 312 * matching key.
314 * feature of interest) matches 313 *
315 * - we return -EAGAIN if we didn't find any matching key 314 * The search criteria are the type and the match function. The description is
316 * - we return -ENOKEY if we found only negative matching keys 315 * given to the match function as a parameter, but doesn't otherwise influence
316 * the search. Typically the match function will compare the description
317 * parameter to the key's description.
318 *
319 * This can only search keyrings that grant Search permission to the supplied
320 * credentials. Keyrings linked to searched keyrings will also be searched if
321 * they grant Search permission too. Keys can only be found if they grant
322 * Search permission to the credentials.
323 *
324 * Returns a pointer to the key with the key usage count incremented if
325 * successful, -EAGAIN if we didn't find any matching key or -ENOKEY if we only
326 * matched negative keys.
327 *
328 * In the case of a successful return, the possession attribute is set on the
329 * returned key reference.
317 */ 330 */
318key_ref_t search_my_process_keyrings(struct key_type *type, 331key_ref_t search_my_process_keyrings(struct key_type *type,
319 const void *description, 332 const void *description,
320 key_match_func_t match, 333 key_match_func_t match,
334 bool no_state_check,
321 const struct cred *cred) 335 const struct cred *cred)
322{ 336{
323 key_ref_t key_ref, ret, err; 337 key_ref_t key_ref, ret, err;
@@ -337,7 +351,7 @@ key_ref_t search_my_process_keyrings(struct key_type *type,
337 if (cred->thread_keyring) { 351 if (cred->thread_keyring) {
338 key_ref = keyring_search_aux( 352 key_ref = keyring_search_aux(
339 make_key_ref(cred->thread_keyring, 1), 353 make_key_ref(cred->thread_keyring, 1),
340 cred, type, description, match); 354 cred, type, description, match, no_state_check);
341 if (!IS_ERR(key_ref)) 355 if (!IS_ERR(key_ref))
342 goto found; 356 goto found;
343 357
@@ -358,7 +372,7 @@ key_ref_t search_my_process_keyrings(struct key_type *type,
358 if (cred->tgcred->process_keyring) { 372 if (cred->tgcred->process_keyring) {
359 key_ref = keyring_search_aux( 373 key_ref = keyring_search_aux(
360 make_key_ref(cred->tgcred->process_keyring, 1), 374 make_key_ref(cred->tgcred->process_keyring, 1),
361 cred, type, description, match); 375 cred, type, description, match, no_state_check);
362 if (!IS_ERR(key_ref)) 376 if (!IS_ERR(key_ref))
363 goto found; 377 goto found;
364 378
@@ -382,7 +396,7 @@ key_ref_t search_my_process_keyrings(struct key_type *type,
382 make_key_ref(rcu_dereference( 396 make_key_ref(rcu_dereference(
383 cred->tgcred->session_keyring), 397 cred->tgcred->session_keyring),
384 1), 398 1),
385 cred, type, description, match); 399 cred, type, description, match, no_state_check);
386 rcu_read_unlock(); 400 rcu_read_unlock();
387 401
388 if (!IS_ERR(key_ref)) 402 if (!IS_ERR(key_ref))
@@ -404,7 +418,7 @@ key_ref_t search_my_process_keyrings(struct key_type *type,
404 else if (cred->user->session_keyring) { 418 else if (cred->user->session_keyring) {
405 key_ref = keyring_search_aux( 419 key_ref = keyring_search_aux(
406 make_key_ref(cred->user->session_keyring, 1), 420 make_key_ref(cred->user->session_keyring, 1),
407 cred, type, description, match); 421 cred, type, description, match, no_state_check);
408 if (!IS_ERR(key_ref)) 422 if (!IS_ERR(key_ref))
409 goto found; 423 goto found;
410 424
@@ -428,13 +442,13 @@ found:
428 return key_ref; 442 return key_ref;
429} 443}
430 444
431/*****************************************************************************/
432/* 445/*
433 * search the process keyrings for the first matching key 446 * Search the process keyrings attached to the supplied cred for the first
434 * - we use the supplied match function to see if the description (or other 447 * matching key in the manner of search_my_process_keyrings(), but also search
435 * feature of interest) matches 448 * the keys attached to the assumed authorisation key using its credentials if
436 * - we return -EAGAIN if we didn't find any matching key 449 * one is available.
437 * - we return -ENOKEY if we found only negative matching keys 450 *
451 * Return same as search_my_process_keyrings().
438 */ 452 */
439key_ref_t search_process_keyrings(struct key_type *type, 453key_ref_t search_process_keyrings(struct key_type *type,
440 const void *description, 454 const void *description,
@@ -446,7 +460,8 @@ key_ref_t search_process_keyrings(struct key_type *type,
446 460
447 might_sleep(); 461 might_sleep();
448 462
449 key_ref = search_my_process_keyrings(type, description, match, cred); 463 key_ref = search_my_process_keyrings(type, description, match,
464 false, cred);
450 if (!IS_ERR(key_ref)) 465 if (!IS_ERR(key_ref))
451 goto found; 466 goto found;
452 err = key_ref; 467 err = key_ref;
@@ -489,24 +504,33 @@ key_ref_t search_process_keyrings(struct key_type *type,
489 504
490found: 505found:
491 return key_ref; 506 return key_ref;
507}
492 508
493} /* end search_process_keyrings() */
494
495/*****************************************************************************/
496/* 509/*
497 * see if the key we're looking at is the target key 510 * See if the key we're looking at is the target key.
498 */ 511 */
499int lookup_user_key_possessed(const struct key *key, const void *target) 512int lookup_user_key_possessed(const struct key *key, const void *target)
500{ 513{
501 return key == target; 514 return key == target;
515}
502 516
503} /* end lookup_user_key_possessed() */
504
505/*****************************************************************************/
506/* 517/*
507 * lookup a key given a key ID from userspace with a given permissions mask 518 * Look up a key ID given us by userspace with a given permissions mask to get
508 * - don't create special keyrings unless so requested 519 * the key it refers to.
509 * - partially constructed keys aren't found unless requested 520 *
521 * Flags can be passed to request that special keyrings be created if referred
522 * to directly, to permit partially constructed keys to be found and to skip
523 * validity and permission checks on the found key.
524 *
525 * Returns a pointer to the key with an incremented usage count if successful;
526 * -EINVAL if the key ID is invalid; -ENOKEY if the key ID does not correspond
527 * to a key or the best found key was a negative key; -EKEYREVOKED or
528 * -EKEYEXPIRED if the best found key was revoked or expired; -EACCES if the
529 * found key doesn't grant the requested permit or the LSM denied access to it;
530 * or -ENOMEM if a special keyring couldn't be created.
531 *
532 * In the case of a successful return, the possession attribute is set on the
533 * returned key reference.
510 */ 534 */
511key_ref_t lookup_user_key(key_serial_t id, unsigned long lflags, 535key_ref_t lookup_user_key(key_serial_t id, unsigned long lflags,
512 key_perm_t perm) 536 key_perm_t perm)
@@ -711,15 +735,18 @@ invalid_key:
711reget_creds: 735reget_creds:
712 put_cred(cred); 736 put_cred(cred);
713 goto try_again; 737 goto try_again;
738}
714 739
715} /* end lookup_user_key() */
716
717/*****************************************************************************/
718/* 740/*
719 * join the named keyring as the session keyring if possible, or attempt to 741 * Join the named keyring as the session keyring if possible else attempt to
720 * create a new one of that name if not 742 * create a new one of that name and join that.
721 * - if the name is NULL, an empty anonymous keyring is installed instead 743 *
722 * - named session keyring joining is done with a semaphore held 744 * If the name is NULL, an empty anonymous keyring will be installed as the
745 * session keyring.
746 *
747 * Named session keyrings are joined with a semaphore held to prevent the
748 * keyrings from going away whilst the attempt is made to going them and also
749 * to prevent a race in creating compatible session keyrings.
723 */ 750 */
724long join_session_keyring(const char *name) 751long join_session_keyring(const char *name)
725{ 752{
@@ -791,8 +818,8 @@ error:
791} 818}
792 819
793/* 820/*
794 * Replace a process's session keyring when that process resumes userspace on 821 * Replace a process's session keyring on behalf of one of its children when
795 * behalf of one of its children 822 * the target process is about to resume userspace execution.
796 */ 823 */
797void key_replace_session_keyring(void) 824void key_replace_session_keyring(void)
798{ 825{
@@ -820,6 +847,7 @@ void key_replace_session_keyring(void)
820 new-> sgid = old-> sgid; 847 new-> sgid = old-> sgid;
821 new->fsgid = old->fsgid; 848 new->fsgid = old->fsgid;
822 new->user = get_uid(old->user); 849 new->user = get_uid(old->user);
850 new->user_ns = new->user->user_ns;
823 new->group_info = get_group_info(old->group_info); 851 new->group_info = get_group_info(old->group_info);
824 852
825 new->securebits = old->securebits; 853 new->securebits = old->securebits;
diff --git a/security/keys/request_key.c b/security/keys/request_key.c
index 0088dd8bf68a..82465328c39b 100644
--- a/security/keys/request_key.c
+++ b/security/keys/request_key.c
@@ -8,7 +8,7 @@
8 * as published by the Free Software Foundation; either version 8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version. 9 * 2 of the License, or (at your option) any later version.
10 * 10 *
11 * See Documentation/keys-request-key.txt 11 * See Documentation/security/keys-request-key.txt
12 */ 12 */
13 13
14#include <linux/module.h> 14#include <linux/module.h>
@@ -39,8 +39,14 @@ static int key_wait_bit_intr(void *flags)
39 return signal_pending(current) ? -ERESTARTSYS : 0; 39 return signal_pending(current) ? -ERESTARTSYS : 0;
40} 40}
41 41
42/* 42/**
43 * call to complete the construction of a key 43 * complete_request_key - Complete the construction of a key.
44 * @cons: The key construction record.
45 * @error: The success or failute of the construction.
46 *
47 * Complete the attempt to construct a key. The key will be negated
48 * if an error is indicated. The authorisation key will be revoked
49 * unconditionally.
44 */ 50 */
45void complete_request_key(struct key_construction *cons, int error) 51void complete_request_key(struct key_construction *cons, int error)
46{ 52{
@@ -58,23 +64,32 @@ void complete_request_key(struct key_construction *cons, int error)
58} 64}
59EXPORT_SYMBOL(complete_request_key); 65EXPORT_SYMBOL(complete_request_key);
60 66
61static int umh_keys_init(struct subprocess_info *info) 67/*
68 * Initialise a usermode helper that is going to have a specific session
69 * keyring.
70 *
71 * This is called in context of freshly forked kthread before kernel_execve(),
72 * so we can simply install the desired session_keyring at this point.
73 */
74static int umh_keys_init(struct subprocess_info *info, struct cred *cred)
62{ 75{
63 struct cred *cred = (struct cred*)current_cred();
64 struct key *keyring = info->data; 76 struct key *keyring = info->data;
65 /* 77
66 * This is called in context of freshly forked kthread before
67 * kernel_execve(), we can just change our ->session_keyring.
68 */
69 return install_session_keyring_to_cred(cred, keyring); 78 return install_session_keyring_to_cred(cred, keyring);
70} 79}
71 80
81/*
82 * Clean up a usermode helper with session keyring.
83 */
72static void umh_keys_cleanup(struct subprocess_info *info) 84static void umh_keys_cleanup(struct subprocess_info *info)
73{ 85{
74 struct key *keyring = info->data; 86 struct key *keyring = info->data;
75 key_put(keyring); 87 key_put(keyring);
76} 88}
77 89
90/*
91 * Call a usermode helper with a specific session keyring.
92 */
78static int call_usermodehelper_keys(char *path, char **argv, char **envp, 93static int call_usermodehelper_keys(char *path, char **argv, char **envp,
79 struct key *session_keyring, enum umh_wait wait) 94 struct key *session_keyring, enum umh_wait wait)
80{ 95{
@@ -91,7 +106,7 @@ static int call_usermodehelper_keys(char *path, char **argv, char **envp,
91} 106}
92 107
93/* 108/*
94 * request userspace finish the construction of a key 109 * Request userspace finish the construction of a key
95 * - execute "/sbin/request-key <op> <key> <uid> <gid> <keyring> <keyring> <keyring>" 110 * - execute "/sbin/request-key <op> <key> <uid> <gid> <keyring> <keyring> <keyring>"
96 */ 111 */
97static int call_sbin_request_key(struct key_construction *cons, 112static int call_sbin_request_key(struct key_construction *cons,
@@ -198,8 +213,9 @@ error_alloc:
198} 213}
199 214
200/* 215/*
201 * call out to userspace for key construction 216 * Call out to userspace for key construction.
202 * - we ignore program failure and go on key status instead 217 *
218 * Program failure is ignored in favour of key status.
203 */ 219 */
204static int construct_key(struct key *key, const void *callout_info, 220static int construct_key(struct key *key, const void *callout_info,
205 size_t callout_len, void *aux, 221 size_t callout_len, void *aux,
@@ -246,9 +262,10 @@ static int construct_key(struct key *key, const void *callout_info,
246} 262}
247 263
248/* 264/*
249 * get the appropriate destination keyring for the request 265 * Get the appropriate destination keyring for the request.
250 * - we return whatever keyring we select with an extra reference upon it which 266 *
251 * the caller must release 267 * The keyring selected is returned with an extra reference upon it which the
268 * caller must release.
252 */ 269 */
253static void construct_get_dest_keyring(struct key **_dest_keyring) 270static void construct_get_dest_keyring(struct key **_dest_keyring)
254{ 271{
@@ -321,9 +338,11 @@ static void construct_get_dest_keyring(struct key **_dest_keyring)
321} 338}
322 339
323/* 340/*
324 * allocate a new key in under-construction state and attempt to link it in to 341 * Allocate a new key in under-construction state and attempt to link it in to
325 * the requested place 342 * the requested keyring.
326 * - may return a key that's already under construction instead 343 *
344 * May return a key that's already under construction instead if there was a
345 * race between two thread calling request_key().
327 */ 346 */
328static int construct_alloc_key(struct key_type *type, 347static int construct_alloc_key(struct key_type *type,
329 const char *description, 348 const char *description,
@@ -332,8 +351,8 @@ static int construct_alloc_key(struct key_type *type,
332 struct key_user *user, 351 struct key_user *user,
333 struct key **_key) 352 struct key **_key)
334{ 353{
335 struct keyring_list *prealloc;
336 const struct cred *cred = current_cred(); 354 const struct cred *cred = current_cred();
355 unsigned long prealloc;
337 struct key *key; 356 struct key *key;
338 key_ref_t key_ref; 357 key_ref_t key_ref;
339 int ret; 358 int ret;
@@ -403,7 +422,6 @@ link_check_failed:
403 return ret; 422 return ret;
404 423
405link_prealloc_failed: 424link_prealloc_failed:
406 up_write(&dest_keyring->sem);
407 mutex_unlock(&user->cons_lock); 425 mutex_unlock(&user->cons_lock);
408 kleave(" = %d [prelink]", ret); 426 kleave(" = %d [prelink]", ret);
409 return ret; 427 return ret;
@@ -415,7 +433,7 @@ alloc_failed:
415} 433}
416 434
417/* 435/*
418 * commence key construction 436 * Commence key construction.
419 */ 437 */
420static struct key *construct_key_and_link(struct key_type *type, 438static struct key *construct_key_and_link(struct key_type *type,
421 const char *description, 439 const char *description,
@@ -451,7 +469,7 @@ static struct key *construct_key_and_link(struct key_type *type,
451 } else if (ret == -EINPROGRESS) { 469 } else if (ret == -EINPROGRESS) {
452 ret = 0; 470 ret = 0;
453 } else { 471 } else {
454 key = ERR_PTR(ret); 472 goto couldnt_alloc_key;
455 } 473 }
456 474
457 key_put(dest_keyring); 475 key_put(dest_keyring);
@@ -461,17 +479,38 @@ static struct key *construct_key_and_link(struct key_type *type,
461construction_failed: 479construction_failed:
462 key_negate_and_link(key, key_negative_timeout, NULL, NULL); 480 key_negate_and_link(key, key_negative_timeout, NULL, NULL);
463 key_put(key); 481 key_put(key);
482couldnt_alloc_key:
464 key_put(dest_keyring); 483 key_put(dest_keyring);
465 kleave(" = %d", ret); 484 kleave(" = %d", ret);
466 return ERR_PTR(ret); 485 return ERR_PTR(ret);
467} 486}
468 487
469/* 488/**
470 * request a key 489 * request_key_and_link - Request a key and cache it in a keyring.
471 * - search the process's keyrings 490 * @type: The type of key we want.
472 * - check the list of keys being created or updated 491 * @description: The searchable description of the key.
473 * - call out to userspace for a key if supplementary info was provided 492 * @callout_info: The data to pass to the instantiation upcall (or NULL).
474 * - cache the key in an appropriate keyring 493 * @callout_len: The length of callout_info.
494 * @aux: Auxiliary data for the upcall.
495 * @dest_keyring: Where to cache the key.
496 * @flags: Flags to key_alloc().
497 *
498 * A key matching the specified criteria is searched for in the process's
499 * keyrings and returned with its usage count incremented if found. Otherwise,
500 * if callout_info is not NULL, a key will be allocated and some service
501 * (probably in userspace) will be asked to instantiate it.
502 *
503 * If successfully found or created, the key will be linked to the destination
504 * keyring if one is provided.
505 *
506 * Returns a pointer to the key if successful; -EACCES, -ENOKEY, -EKEYREVOKED
507 * or -EKEYEXPIRED if an inaccessible, negative, revoked or expired key was
508 * found; -ENOKEY if no key was found and no @callout_info was given; -EDQUOT
509 * if insufficient key quota was available to create a new key; or -ENOMEM if
510 * insufficient memory was available.
511 *
512 * If the returned key was created, then it may still be under construction,
513 * and wait_for_key_construction() should be used to wait for that to complete.
475 */ 514 */
476struct key *request_key_and_link(struct key_type *type, 515struct key *request_key_and_link(struct key_type *type,
477 const char *description, 516 const char *description,
@@ -491,8 +530,7 @@ struct key *request_key_and_link(struct key_type *type,
491 dest_keyring, flags); 530 dest_keyring, flags);
492 531
493 /* search all the process keyrings for a key */ 532 /* search all the process keyrings for a key */
494 key_ref = search_process_keyrings(type, description, type->match, 533 key_ref = search_process_keyrings(type, description, type->match, cred);
495 cred);
496 534
497 if (!IS_ERR(key_ref)) { 535 if (!IS_ERR(key_ref)) {
498 key = key_ref_to_ptr(key_ref); 536 key = key_ref_to_ptr(key_ref);
@@ -525,8 +563,16 @@ error:
525 return key; 563 return key;
526} 564}
527 565
528/* 566/**
529 * wait for construction of a key to complete 567 * wait_for_key_construction - Wait for construction of a key to complete
568 * @key: The key being waited for.
569 * @intr: Whether to wait interruptibly.
570 *
571 * Wait for a key to finish being constructed.
572 *
573 * Returns 0 if successful; -ERESTARTSYS if the wait was interrupted; -ENOKEY
574 * if the key was negated; or -EKEYREVOKED or -EKEYEXPIRED if the key was
575 * revoked or expired.
530 */ 576 */
531int wait_for_key_construction(struct key *key, bool intr) 577int wait_for_key_construction(struct key *key, bool intr)
532{ 578{
@@ -538,17 +584,24 @@ int wait_for_key_construction(struct key *key, bool intr)
538 if (ret < 0) 584 if (ret < 0)
539 return ret; 585 return ret;
540 if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) 586 if (test_bit(KEY_FLAG_NEGATIVE, &key->flags))
541 return -ENOKEY; 587 return key->type_data.reject_error;
542 return key_validate(key); 588 return key_validate(key);
543} 589}
544EXPORT_SYMBOL(wait_for_key_construction); 590EXPORT_SYMBOL(wait_for_key_construction);
545 591
546/* 592/**
547 * request a key 593 * request_key - Request a key and wait for construction
548 * - search the process's keyrings 594 * @type: Type of key.
549 * - check the list of keys being created or updated 595 * @description: The searchable description of the key.
550 * - call out to userspace for a key if supplementary info was provided 596 * @callout_info: The data to pass to the instantiation upcall (or NULL).
551 * - waits uninterruptible for creation to complete 597 *
598 * As for request_key_and_link() except that it does not add the returned key
599 * to a keyring if found, new keys are always allocated in the user's quota,
600 * the callout_info must be a NUL-terminated string and no auxiliary data can
601 * be passed.
602 *
603 * Furthermore, it then works as wait_for_key_construction() to wait for the
604 * completion of keys undergoing construction with a non-interruptible wait.
552 */ 605 */
553struct key *request_key(struct key_type *type, 606struct key *request_key(struct key_type *type,
554 const char *description, 607 const char *description,
@@ -573,12 +626,19 @@ struct key *request_key(struct key_type *type,
573} 626}
574EXPORT_SYMBOL(request_key); 627EXPORT_SYMBOL(request_key);
575 628
576/* 629/**
577 * request a key with auxiliary data for the upcaller 630 * request_key_with_auxdata - Request a key with auxiliary data for the upcaller
578 * - search the process's keyrings 631 * @type: The type of key we want.
579 * - check the list of keys being created or updated 632 * @description: The searchable description of the key.
580 * - call out to userspace for a key if supplementary info was provided 633 * @callout_info: The data to pass to the instantiation upcall (or NULL).
581 * - waits uninterruptible for creation to complete 634 * @callout_len: The length of callout_info.
635 * @aux: Auxiliary data for the upcall.
636 *
637 * As for request_key_and_link() except that it does not add the returned key
638 * to a keyring if found and new keys are always allocated in the user's quota.
639 *
640 * Furthermore, it then works as wait_for_key_construction() to wait for the
641 * completion of keys undergoing construction with a non-interruptible wait.
582 */ 642 */
583struct key *request_key_with_auxdata(struct key_type *type, 643struct key *request_key_with_auxdata(struct key_type *type,
584 const char *description, 644 const char *description,
@@ -603,10 +663,18 @@ struct key *request_key_with_auxdata(struct key_type *type,
603EXPORT_SYMBOL(request_key_with_auxdata); 663EXPORT_SYMBOL(request_key_with_auxdata);
604 664
605/* 665/*
606 * request a key (allow async construction) 666 * request_key_async - Request a key (allow async construction)
607 * - search the process's keyrings 667 * @type: Type of key.
608 * - check the list of keys being created or updated 668 * @description: The searchable description of the key.
609 * - call out to userspace for a key if supplementary info was provided 669 * @callout_info: The data to pass to the instantiation upcall (or NULL).
670 * @callout_len: The length of callout_info.
671 *
672 * As for request_key_and_link() except that it does not add the returned key
673 * to a keyring if found, new keys are always allocated in the user's quota and
674 * no auxiliary data can be passed.
675 *
676 * The caller should call wait_for_key_construction() to wait for the
677 * completion of the returned key if it is still undergoing construction.
610 */ 678 */
611struct key *request_key_async(struct key_type *type, 679struct key *request_key_async(struct key_type *type,
612 const char *description, 680 const char *description,
@@ -621,9 +689,17 @@ EXPORT_SYMBOL(request_key_async);
621 689
622/* 690/*
623 * request a key with auxiliary data for the upcaller (allow async construction) 691 * request a key with auxiliary data for the upcaller (allow async construction)
624 * - search the process's keyrings 692 * @type: Type of key.
625 * - check the list of keys being created or updated 693 * @description: The searchable description of the key.
626 * - call out to userspace for a key if supplementary info was provided 694 * @callout_info: The data to pass to the instantiation upcall (or NULL).
695 * @callout_len: The length of callout_info.
696 * @aux: Auxiliary data for the upcall.
697 *
698 * As for request_key_and_link() except that it does not add the returned key
699 * to a keyring if found and new keys are always allocated in the user's quota.
700 *
701 * The caller should call wait_for_key_construction() to wait for the
702 * completion of the returned key if it is still undergoing construction.
627 */ 703 */
628struct key *request_key_async_with_auxdata(struct key_type *type, 704struct key *request_key_async_with_auxdata(struct key_type *type,
629 const char *description, 705 const char *description,
diff --git a/security/keys/request_key_auth.c b/security/keys/request_key_auth.c
index 86747151ee5b..6cff37529b80 100644
--- a/security/keys/request_key_auth.c
+++ b/security/keys/request_key_auth.c
@@ -1,4 +1,4 @@
1/* request_key_auth.c: request key authorisation controlling key def 1/* Request key authorisation token key definition.
2 * 2 *
3 * Copyright (C) 2005 Red Hat, Inc. All Rights Reserved. 3 * Copyright (C) 2005 Red Hat, Inc. All Rights Reserved.
4 * Written by David Howells (dhowells@redhat.com) 4 * Written by David Howells (dhowells@redhat.com)
@@ -8,7 +8,7 @@
8 * as published by the Free Software Foundation; either version 8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version. 9 * 2 of the License, or (at your option) any later version.
10 * 10 *
11 * See Documentation/keys-request-key.txt 11 * See Documentation/security/keys-request-key.txt
12 */ 12 */
13 13
14#include <linux/module.h> 14#include <linux/module.h>
@@ -26,7 +26,7 @@ static void request_key_auth_destroy(struct key *);
26static long request_key_auth_read(const struct key *, char __user *, size_t); 26static long request_key_auth_read(const struct key *, char __user *, size_t);
27 27
28/* 28/*
29 * the request-key authorisation key type definition 29 * The request-key authorisation key type definition.
30 */ 30 */
31struct key_type key_type_request_key_auth = { 31struct key_type key_type_request_key_auth = {
32 .name = ".request_key_auth", 32 .name = ".request_key_auth",
@@ -38,9 +38,8 @@ struct key_type key_type_request_key_auth = {
38 .read = request_key_auth_read, 38 .read = request_key_auth_read,
39}; 39};
40 40
41/*****************************************************************************/
42/* 41/*
43 * instantiate a request-key authorisation key 42 * Instantiate a request-key authorisation key.
44 */ 43 */
45static int request_key_auth_instantiate(struct key *key, 44static int request_key_auth_instantiate(struct key *key,
46 const void *data, 45 const void *data,
@@ -48,12 +47,10 @@ static int request_key_auth_instantiate(struct key *key,
48{ 47{
49 key->payload.data = (struct request_key_auth *) data; 48 key->payload.data = (struct request_key_auth *) data;
50 return 0; 49 return 0;
50}
51 51
52} /* end request_key_auth_instantiate() */
53
54/*****************************************************************************/
55/* 52/*
56 * reading a request-key authorisation key retrieves the callout information 53 * Describe an authorisation token.
57 */ 54 */
58static void request_key_auth_describe(const struct key *key, 55static void request_key_auth_describe(const struct key *key,
59 struct seq_file *m) 56 struct seq_file *m)
@@ -62,13 +59,12 @@ static void request_key_auth_describe(const struct key *key,
62 59
63 seq_puts(m, "key:"); 60 seq_puts(m, "key:");
64 seq_puts(m, key->description); 61 seq_puts(m, key->description);
65 seq_printf(m, " pid:%d ci:%zu", rka->pid, rka->callout_len); 62 if (key_is_instantiated(key))
66 63 seq_printf(m, " pid:%d ci:%zu", rka->pid, rka->callout_len);
67} /* end request_key_auth_describe() */ 64}
68 65
69/*****************************************************************************/
70/* 66/*
71 * read the callout_info data 67 * Read the callout_info data (retrieves the callout information).
72 * - the key's semaphore is read-locked 68 * - the key's semaphore is read-locked
73 */ 69 */
74static long request_key_auth_read(const struct key *key, 70static long request_key_auth_read(const struct key *key,
@@ -91,13 +87,12 @@ static long request_key_auth_read(const struct key *key,
91 } 87 }
92 88
93 return ret; 89 return ret;
90}
94 91
95} /* end request_key_auth_read() */
96
97/*****************************************************************************/
98/* 92/*
99 * handle revocation of an authorisation token key 93 * Handle revocation of an authorisation token key.
100 * - called with the key sem write-locked 94 *
95 * Called with the key sem write-locked.
101 */ 96 */
102static void request_key_auth_revoke(struct key *key) 97static void request_key_auth_revoke(struct key *key)
103{ 98{
@@ -109,12 +104,10 @@ static void request_key_auth_revoke(struct key *key)
109 put_cred(rka->cred); 104 put_cred(rka->cred);
110 rka->cred = NULL; 105 rka->cred = NULL;
111 } 106 }
107}
112 108
113} /* end request_key_auth_revoke() */
114
115/*****************************************************************************/
116/* 109/*
117 * destroy an instantiation authorisation token key 110 * Destroy an instantiation authorisation token key.
118 */ 111 */
119static void request_key_auth_destroy(struct key *key) 112static void request_key_auth_destroy(struct key *key)
120{ 113{
@@ -131,13 +124,11 @@ static void request_key_auth_destroy(struct key *key)
131 key_put(rka->dest_keyring); 124 key_put(rka->dest_keyring);
132 kfree(rka->callout_info); 125 kfree(rka->callout_info);
133 kfree(rka); 126 kfree(rka);
127}
134 128
135} /* end request_key_auth_destroy() */
136
137/*****************************************************************************/
138/* 129/*
139 * create an authorisation token for /sbin/request-key or whoever to gain 130 * Create an authorisation token for /sbin/request-key or whoever to gain
140 * access to the caller's security data 131 * access to the caller's security data.
141 */ 132 */
142struct key *request_key_auth_new(struct key *target, const void *callout_info, 133struct key *request_key_auth_new(struct key *target, const void *callout_info,
143 size_t callout_len, struct key *dest_keyring) 134 size_t callout_len, struct key *dest_keyring)
@@ -228,12 +219,10 @@ error_alloc:
228 kfree(rka); 219 kfree(rka);
229 kleave("= %d", ret); 220 kleave("= %d", ret);
230 return ERR_PTR(ret); 221 return ERR_PTR(ret);
222}
231 223
232} /* end request_key_auth_new() */
233
234/*****************************************************************************/
235/* 224/*
236 * see if an authorisation key is associated with a particular key 225 * See if an authorisation key is associated with a particular key.
237 */ 226 */
238static int key_get_instantiation_authkey_match(const struct key *key, 227static int key_get_instantiation_authkey_match(const struct key *key,
239 const void *_id) 228 const void *_id)
@@ -242,16 +231,11 @@ static int key_get_instantiation_authkey_match(const struct key *key,
242 key_serial_t id = (key_serial_t)(unsigned long) _id; 231 key_serial_t id = (key_serial_t)(unsigned long) _id;
243 232
244 return rka->target_key->serial == id; 233 return rka->target_key->serial == id;
234}
245 235
246} /* end key_get_instantiation_authkey_match() */
247
248/*****************************************************************************/
249/* 236/*
250 * get the authorisation key for instantiation of a specific key if attached to 237 * Search the current process's keyrings for the authorisation key for
251 * the current process's keyrings 238 * instantiation of a key.
252 * - this key is inserted into a keyring and that is set as /sbin/request-key's
253 * session keyring
254 * - a target_id of zero specifies any valid token
255 */ 239 */
256struct key *key_get_instantiation_authkey(key_serial_t target_id) 240struct key *key_get_instantiation_authkey(key_serial_t target_id)
257{ 241{
@@ -278,5 +262,4 @@ struct key *key_get_instantiation_authkey(key_serial_t target_id)
278 262
279error: 263error:
280 return authkey; 264 return authkey;
281 265}
282} /* end key_get_instantiation_authkey() */
diff --git a/security/keys/trusted.c b/security/keys/trusted.c
new file mode 100644
index 000000000000..0c33e2ea1f3c
--- /dev/null
+++ b/security/keys/trusted.c
@@ -0,0 +1,1180 @@
1/*
2 * Copyright (C) 2010 IBM Corporation
3 *
4 * Author:
5 * David Safford <safford@us.ibm.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, version 2 of the License.
10 *
11 * See Documentation/security/keys-trusted-encrypted.txt
12 */
13
14#include <linux/uaccess.h>
15#include <linux/module.h>
16#include <linux/init.h>
17#include <linux/slab.h>
18#include <linux/parser.h>
19#include <linux/string.h>
20#include <linux/err.h>
21#include <keys/user-type.h>
22#include <keys/trusted-type.h>
23#include <linux/key-type.h>
24#include <linux/rcupdate.h>
25#include <linux/crypto.h>
26#include <crypto/hash.h>
27#include <crypto/sha.h>
28#include <linux/capability.h>
29#include <linux/tpm.h>
30#include <linux/tpm_command.h>
31
32#include "trusted.h"
33
34static const char hmac_alg[] = "hmac(sha1)";
35static const char hash_alg[] = "sha1";
36
37struct sdesc {
38 struct shash_desc shash;
39 char ctx[];
40};
41
42static struct crypto_shash *hashalg;
43static struct crypto_shash *hmacalg;
44
45static struct sdesc *init_sdesc(struct crypto_shash *alg)
46{
47 struct sdesc *sdesc;
48 int size;
49
50 size = sizeof(struct shash_desc) + crypto_shash_descsize(alg);
51 sdesc = kmalloc(size, GFP_KERNEL);
52 if (!sdesc)
53 return ERR_PTR(-ENOMEM);
54 sdesc->shash.tfm = alg;
55 sdesc->shash.flags = 0x0;
56 return sdesc;
57}
58
59static int TSS_sha1(const unsigned char *data, unsigned int datalen,
60 unsigned char *digest)
61{
62 struct sdesc *sdesc;
63 int ret;
64
65 sdesc = init_sdesc(hashalg);
66 if (IS_ERR(sdesc)) {
67 pr_info("trusted_key: can't alloc %s\n", hash_alg);
68 return PTR_ERR(sdesc);
69 }
70
71 ret = crypto_shash_digest(&sdesc->shash, data, datalen, digest);
72 kfree(sdesc);
73 return ret;
74}
75
76static int TSS_rawhmac(unsigned char *digest, const unsigned char *key,
77 unsigned int keylen, ...)
78{
79 struct sdesc *sdesc;
80 va_list argp;
81 unsigned int dlen;
82 unsigned char *data;
83 int ret;
84
85 sdesc = init_sdesc(hmacalg);
86 if (IS_ERR(sdesc)) {
87 pr_info("trusted_key: can't alloc %s\n", hmac_alg);
88 return PTR_ERR(sdesc);
89 }
90
91 ret = crypto_shash_setkey(hmacalg, key, keylen);
92 if (ret < 0)
93 goto out;
94 ret = crypto_shash_init(&sdesc->shash);
95 if (ret < 0)
96 goto out;
97
98 va_start(argp, keylen);
99 for (;;) {
100 dlen = va_arg(argp, unsigned int);
101 if (dlen == 0)
102 break;
103 data = va_arg(argp, unsigned char *);
104 if (data == NULL) {
105 ret = -EINVAL;
106 break;
107 }
108 ret = crypto_shash_update(&sdesc->shash, data, dlen);
109 if (ret < 0)
110 break;
111 }
112 va_end(argp);
113 if (!ret)
114 ret = crypto_shash_final(&sdesc->shash, digest);
115out:
116 kfree(sdesc);
117 return ret;
118}
119
120/*
121 * calculate authorization info fields to send to TPM
122 */
123static int TSS_authhmac(unsigned char *digest, const unsigned char *key,
124 unsigned int keylen, unsigned char *h1,
125 unsigned char *h2, unsigned char h3, ...)
126{
127 unsigned char paramdigest[SHA1_DIGEST_SIZE];
128 struct sdesc *sdesc;
129 unsigned int dlen;
130 unsigned char *data;
131 unsigned char c;
132 int ret;
133 va_list argp;
134
135 sdesc = init_sdesc(hashalg);
136 if (IS_ERR(sdesc)) {
137 pr_info("trusted_key: can't alloc %s\n", hash_alg);
138 return PTR_ERR(sdesc);
139 }
140
141 c = h3;
142 ret = crypto_shash_init(&sdesc->shash);
143 if (ret < 0)
144 goto out;
145 va_start(argp, h3);
146 for (;;) {
147 dlen = va_arg(argp, unsigned int);
148 if (dlen == 0)
149 break;
150 data = va_arg(argp, unsigned char *);
151 if (!data) {
152 ret = -EINVAL;
153 break;
154 }
155 ret = crypto_shash_update(&sdesc->shash, data, dlen);
156 if (ret < 0)
157 break;
158 }
159 va_end(argp);
160 if (!ret)
161 ret = crypto_shash_final(&sdesc->shash, paramdigest);
162 if (!ret)
163 ret = TSS_rawhmac(digest, key, keylen, SHA1_DIGEST_SIZE,
164 paramdigest, TPM_NONCE_SIZE, h1,
165 TPM_NONCE_SIZE, h2, 1, &c, 0, 0);
166out:
167 kfree(sdesc);
168 return ret;
169}
170
171/*
172 * verify the AUTH1_COMMAND (Seal) result from TPM
173 */
174static int TSS_checkhmac1(unsigned char *buffer,
175 const uint32_t command,
176 const unsigned char *ononce,
177 const unsigned char *key,
178 unsigned int keylen, ...)
179{
180 uint32_t bufsize;
181 uint16_t tag;
182 uint32_t ordinal;
183 uint32_t result;
184 unsigned char *enonce;
185 unsigned char *continueflag;
186 unsigned char *authdata;
187 unsigned char testhmac[SHA1_DIGEST_SIZE];
188 unsigned char paramdigest[SHA1_DIGEST_SIZE];
189 struct sdesc *sdesc;
190 unsigned int dlen;
191 unsigned int dpos;
192 va_list argp;
193 int ret;
194
195 bufsize = LOAD32(buffer, TPM_SIZE_OFFSET);
196 tag = LOAD16(buffer, 0);
197 ordinal = command;
198 result = LOAD32N(buffer, TPM_RETURN_OFFSET);
199 if (tag == TPM_TAG_RSP_COMMAND)
200 return 0;
201 if (tag != TPM_TAG_RSP_AUTH1_COMMAND)
202 return -EINVAL;
203 authdata = buffer + bufsize - SHA1_DIGEST_SIZE;
204 continueflag = authdata - 1;
205 enonce = continueflag - TPM_NONCE_SIZE;
206
207 sdesc = init_sdesc(hashalg);
208 if (IS_ERR(sdesc)) {
209 pr_info("trusted_key: can't alloc %s\n", hash_alg);
210 return PTR_ERR(sdesc);
211 }
212 ret = crypto_shash_init(&sdesc->shash);
213 if (ret < 0)
214 goto out;
215 ret = crypto_shash_update(&sdesc->shash, (const u8 *)&result,
216 sizeof result);
217 if (ret < 0)
218 goto out;
219 ret = crypto_shash_update(&sdesc->shash, (const u8 *)&ordinal,
220 sizeof ordinal);
221 if (ret < 0)
222 goto out;
223 va_start(argp, keylen);
224 for (;;) {
225 dlen = va_arg(argp, unsigned int);
226 if (dlen == 0)
227 break;
228 dpos = va_arg(argp, unsigned int);
229 ret = crypto_shash_update(&sdesc->shash, buffer + dpos, dlen);
230 if (ret < 0)
231 break;
232 }
233 va_end(argp);
234 if (!ret)
235 ret = crypto_shash_final(&sdesc->shash, paramdigest);
236 if (ret < 0)
237 goto out;
238
239 ret = TSS_rawhmac(testhmac, key, keylen, SHA1_DIGEST_SIZE, paramdigest,
240 TPM_NONCE_SIZE, enonce, TPM_NONCE_SIZE, ononce,
241 1, continueflag, 0, 0);
242 if (ret < 0)
243 goto out;
244
245 if (memcmp(testhmac, authdata, SHA1_DIGEST_SIZE))
246 ret = -EINVAL;
247out:
248 kfree(sdesc);
249 return ret;
250}
251
252/*
253 * verify the AUTH2_COMMAND (unseal) result from TPM
254 */
255static int TSS_checkhmac2(unsigned char *buffer,
256 const uint32_t command,
257 const unsigned char *ononce,
258 const unsigned char *key1,
259 unsigned int keylen1,
260 const unsigned char *key2,
261 unsigned int keylen2, ...)
262{
263 uint32_t bufsize;
264 uint16_t tag;
265 uint32_t ordinal;
266 uint32_t result;
267 unsigned char *enonce1;
268 unsigned char *continueflag1;
269 unsigned char *authdata1;
270 unsigned char *enonce2;
271 unsigned char *continueflag2;
272 unsigned char *authdata2;
273 unsigned char testhmac1[SHA1_DIGEST_SIZE];
274 unsigned char testhmac2[SHA1_DIGEST_SIZE];
275 unsigned char paramdigest[SHA1_DIGEST_SIZE];
276 struct sdesc *sdesc;
277 unsigned int dlen;
278 unsigned int dpos;
279 va_list argp;
280 int ret;
281
282 bufsize = LOAD32(buffer, TPM_SIZE_OFFSET);
283 tag = LOAD16(buffer, 0);
284 ordinal = command;
285 result = LOAD32N(buffer, TPM_RETURN_OFFSET);
286
287 if (tag == TPM_TAG_RSP_COMMAND)
288 return 0;
289 if (tag != TPM_TAG_RSP_AUTH2_COMMAND)
290 return -EINVAL;
291 authdata1 = buffer + bufsize - (SHA1_DIGEST_SIZE + 1
292 + SHA1_DIGEST_SIZE + SHA1_DIGEST_SIZE);
293 authdata2 = buffer + bufsize - (SHA1_DIGEST_SIZE);
294 continueflag1 = authdata1 - 1;
295 continueflag2 = authdata2 - 1;
296 enonce1 = continueflag1 - TPM_NONCE_SIZE;
297 enonce2 = continueflag2 - TPM_NONCE_SIZE;
298
299 sdesc = init_sdesc(hashalg);
300 if (IS_ERR(sdesc)) {
301 pr_info("trusted_key: can't alloc %s\n", hash_alg);
302 return PTR_ERR(sdesc);
303 }
304 ret = crypto_shash_init(&sdesc->shash);
305 if (ret < 0)
306 goto out;
307 ret = crypto_shash_update(&sdesc->shash, (const u8 *)&result,
308 sizeof result);
309 if (ret < 0)
310 goto out;
311 ret = crypto_shash_update(&sdesc->shash, (const u8 *)&ordinal,
312 sizeof ordinal);
313 if (ret < 0)
314 goto out;
315
316 va_start(argp, keylen2);
317 for (;;) {
318 dlen = va_arg(argp, unsigned int);
319 if (dlen == 0)
320 break;
321 dpos = va_arg(argp, unsigned int);
322 ret = crypto_shash_update(&sdesc->shash, buffer + dpos, dlen);
323 if (ret < 0)
324 break;
325 }
326 va_end(argp);
327 if (!ret)
328 ret = crypto_shash_final(&sdesc->shash, paramdigest);
329 if (ret < 0)
330 goto out;
331
332 ret = TSS_rawhmac(testhmac1, key1, keylen1, SHA1_DIGEST_SIZE,
333 paramdigest, TPM_NONCE_SIZE, enonce1,
334 TPM_NONCE_SIZE, ononce, 1, continueflag1, 0, 0);
335 if (ret < 0)
336 goto out;
337 if (memcmp(testhmac1, authdata1, SHA1_DIGEST_SIZE)) {
338 ret = -EINVAL;
339 goto out;
340 }
341 ret = TSS_rawhmac(testhmac2, key2, keylen2, SHA1_DIGEST_SIZE,
342 paramdigest, TPM_NONCE_SIZE, enonce2,
343 TPM_NONCE_SIZE, ononce, 1, continueflag2, 0, 0);
344 if (ret < 0)
345 goto out;
346 if (memcmp(testhmac2, authdata2, SHA1_DIGEST_SIZE))
347 ret = -EINVAL;
348out:
349 kfree(sdesc);
350 return ret;
351}
352
353/*
354 * For key specific tpm requests, we will generate and send our
355 * own TPM command packets using the drivers send function.
356 */
357static int trusted_tpm_send(const u32 chip_num, unsigned char *cmd,
358 size_t buflen)
359{
360 int rc;
361
362 dump_tpm_buf(cmd);
363 rc = tpm_send(chip_num, cmd, buflen);
364 dump_tpm_buf(cmd);
365 if (rc > 0)
366 /* Can't return positive return codes values to keyctl */
367 rc = -EPERM;
368 return rc;
369}
370
371/*
372 * get a random value from TPM
373 */
374static int tpm_get_random(struct tpm_buf *tb, unsigned char *buf, uint32_t len)
375{
376 int ret;
377
378 INIT_BUF(tb);
379 store16(tb, TPM_TAG_RQU_COMMAND);
380 store32(tb, TPM_GETRANDOM_SIZE);
381 store32(tb, TPM_ORD_GETRANDOM);
382 store32(tb, len);
383 ret = trusted_tpm_send(TPM_ANY_NUM, tb->data, sizeof tb->data);
384 if (!ret)
385 memcpy(buf, tb->data + TPM_GETRANDOM_SIZE, len);
386 return ret;
387}
388
389static int my_get_random(unsigned char *buf, int len)
390{
391 struct tpm_buf *tb;
392 int ret;
393
394 tb = kmalloc(sizeof *tb, GFP_KERNEL);
395 if (!tb)
396 return -ENOMEM;
397 ret = tpm_get_random(tb, buf, len);
398
399 kfree(tb);
400 return ret;
401}
402
403/*
404 * Lock a trusted key, by extending a selected PCR.
405 *
406 * Prevents a trusted key that is sealed to PCRs from being accessed.
407 * This uses the tpm driver's extend function.
408 */
409static int pcrlock(const int pcrnum)
410{
411 unsigned char hash[SHA1_DIGEST_SIZE];
412 int ret;
413
414 if (!capable(CAP_SYS_ADMIN))
415 return -EPERM;
416 ret = my_get_random(hash, SHA1_DIGEST_SIZE);
417 if (ret < 0)
418 return ret;
419 return tpm_pcr_extend(TPM_ANY_NUM, pcrnum, hash) ? -EINVAL : 0;
420}
421
422/*
423 * Create an object specific authorisation protocol (OSAP) session
424 */
425static int osap(struct tpm_buf *tb, struct osapsess *s,
426 const unsigned char *key, uint16_t type, uint32_t handle)
427{
428 unsigned char enonce[TPM_NONCE_SIZE];
429 unsigned char ononce[TPM_NONCE_SIZE];
430 int ret;
431
432 ret = tpm_get_random(tb, ononce, TPM_NONCE_SIZE);
433 if (ret < 0)
434 return ret;
435
436 INIT_BUF(tb);
437 store16(tb, TPM_TAG_RQU_COMMAND);
438 store32(tb, TPM_OSAP_SIZE);
439 store32(tb, TPM_ORD_OSAP);
440 store16(tb, type);
441 store32(tb, handle);
442 storebytes(tb, ononce, TPM_NONCE_SIZE);
443
444 ret = trusted_tpm_send(TPM_ANY_NUM, tb->data, MAX_BUF_SIZE);
445 if (ret < 0)
446 return ret;
447
448 s->handle = LOAD32(tb->data, TPM_DATA_OFFSET);
449 memcpy(s->enonce, &(tb->data[TPM_DATA_OFFSET + sizeof(uint32_t)]),
450 TPM_NONCE_SIZE);
451 memcpy(enonce, &(tb->data[TPM_DATA_OFFSET + sizeof(uint32_t) +
452 TPM_NONCE_SIZE]), TPM_NONCE_SIZE);
453 return TSS_rawhmac(s->secret, key, SHA1_DIGEST_SIZE, TPM_NONCE_SIZE,
454 enonce, TPM_NONCE_SIZE, ononce, 0, 0);
455}
456
457/*
458 * Create an object independent authorisation protocol (oiap) session
459 */
460static int oiap(struct tpm_buf *tb, uint32_t *handle, unsigned char *nonce)
461{
462 int ret;
463
464 INIT_BUF(tb);
465 store16(tb, TPM_TAG_RQU_COMMAND);
466 store32(tb, TPM_OIAP_SIZE);
467 store32(tb, TPM_ORD_OIAP);
468 ret = trusted_tpm_send(TPM_ANY_NUM, tb->data, MAX_BUF_SIZE);
469 if (ret < 0)
470 return ret;
471
472 *handle = LOAD32(tb->data, TPM_DATA_OFFSET);
473 memcpy(nonce, &tb->data[TPM_DATA_OFFSET + sizeof(uint32_t)],
474 TPM_NONCE_SIZE);
475 return 0;
476}
477
478struct tpm_digests {
479 unsigned char encauth[SHA1_DIGEST_SIZE];
480 unsigned char pubauth[SHA1_DIGEST_SIZE];
481 unsigned char xorwork[SHA1_DIGEST_SIZE * 2];
482 unsigned char xorhash[SHA1_DIGEST_SIZE];
483 unsigned char nonceodd[TPM_NONCE_SIZE];
484};
485
486/*
487 * Have the TPM seal(encrypt) the trusted key, possibly based on
488 * Platform Configuration Registers (PCRs). AUTH1 for sealing key.
489 */
490static int tpm_seal(struct tpm_buf *tb, uint16_t keytype,
491 uint32_t keyhandle, const unsigned char *keyauth,
492 const unsigned char *data, uint32_t datalen,
493 unsigned char *blob, uint32_t *bloblen,
494 const unsigned char *blobauth,
495 const unsigned char *pcrinfo, uint32_t pcrinfosize)
496{
497 struct osapsess sess;
498 struct tpm_digests *td;
499 unsigned char cont;
500 uint32_t ordinal;
501 uint32_t pcrsize;
502 uint32_t datsize;
503 int sealinfosize;
504 int encdatasize;
505 int storedsize;
506 int ret;
507 int i;
508
509 /* alloc some work space for all the hashes */
510 td = kmalloc(sizeof *td, GFP_KERNEL);
511 if (!td)
512 return -ENOMEM;
513
514 /* get session for sealing key */
515 ret = osap(tb, &sess, keyauth, keytype, keyhandle);
516 if (ret < 0)
517 goto out;
518 dump_sess(&sess);
519
520 /* calculate encrypted authorization value */
521 memcpy(td->xorwork, sess.secret, SHA1_DIGEST_SIZE);
522 memcpy(td->xorwork + SHA1_DIGEST_SIZE, sess.enonce, SHA1_DIGEST_SIZE);
523 ret = TSS_sha1(td->xorwork, SHA1_DIGEST_SIZE * 2, td->xorhash);
524 if (ret < 0)
525 goto out;
526
527 ret = tpm_get_random(tb, td->nonceodd, TPM_NONCE_SIZE);
528 if (ret < 0)
529 goto out;
530 ordinal = htonl(TPM_ORD_SEAL);
531 datsize = htonl(datalen);
532 pcrsize = htonl(pcrinfosize);
533 cont = 0;
534
535 /* encrypt data authorization key */
536 for (i = 0; i < SHA1_DIGEST_SIZE; ++i)
537 td->encauth[i] = td->xorhash[i] ^ blobauth[i];
538
539 /* calculate authorization HMAC value */
540 if (pcrinfosize == 0) {
541 /* no pcr info specified */
542 ret = TSS_authhmac(td->pubauth, sess.secret, SHA1_DIGEST_SIZE,
543 sess.enonce, td->nonceodd, cont,
544 sizeof(uint32_t), &ordinal, SHA1_DIGEST_SIZE,
545 td->encauth, sizeof(uint32_t), &pcrsize,
546 sizeof(uint32_t), &datsize, datalen, data, 0,
547 0);
548 } else {
549 /* pcr info specified */
550 ret = TSS_authhmac(td->pubauth, sess.secret, SHA1_DIGEST_SIZE,
551 sess.enonce, td->nonceodd, cont,
552 sizeof(uint32_t), &ordinal, SHA1_DIGEST_SIZE,
553 td->encauth, sizeof(uint32_t), &pcrsize,
554 pcrinfosize, pcrinfo, sizeof(uint32_t),
555 &datsize, datalen, data, 0, 0);
556 }
557 if (ret < 0)
558 goto out;
559
560 /* build and send the TPM request packet */
561 INIT_BUF(tb);
562 store16(tb, TPM_TAG_RQU_AUTH1_COMMAND);
563 store32(tb, TPM_SEAL_SIZE + pcrinfosize + datalen);
564 store32(tb, TPM_ORD_SEAL);
565 store32(tb, keyhandle);
566 storebytes(tb, td->encauth, SHA1_DIGEST_SIZE);
567 store32(tb, pcrinfosize);
568 storebytes(tb, pcrinfo, pcrinfosize);
569 store32(tb, datalen);
570 storebytes(tb, data, datalen);
571 store32(tb, sess.handle);
572 storebytes(tb, td->nonceodd, TPM_NONCE_SIZE);
573 store8(tb, cont);
574 storebytes(tb, td->pubauth, SHA1_DIGEST_SIZE);
575
576 ret = trusted_tpm_send(TPM_ANY_NUM, tb->data, MAX_BUF_SIZE);
577 if (ret < 0)
578 goto out;
579
580 /* calculate the size of the returned Blob */
581 sealinfosize = LOAD32(tb->data, TPM_DATA_OFFSET + sizeof(uint32_t));
582 encdatasize = LOAD32(tb->data, TPM_DATA_OFFSET + sizeof(uint32_t) +
583 sizeof(uint32_t) + sealinfosize);
584 storedsize = sizeof(uint32_t) + sizeof(uint32_t) + sealinfosize +
585 sizeof(uint32_t) + encdatasize;
586
587 /* check the HMAC in the response */
588 ret = TSS_checkhmac1(tb->data, ordinal, td->nonceodd, sess.secret,
589 SHA1_DIGEST_SIZE, storedsize, TPM_DATA_OFFSET, 0,
590 0);
591
592 /* copy the returned blob to caller */
593 if (!ret) {
594 memcpy(blob, tb->data + TPM_DATA_OFFSET, storedsize);
595 *bloblen = storedsize;
596 }
597out:
598 kfree(td);
599 return ret;
600}
601
602/*
603 * use the AUTH2_COMMAND form of unseal, to authorize both key and blob
604 */
605static int tpm_unseal(struct tpm_buf *tb,
606 uint32_t keyhandle, const unsigned char *keyauth,
607 const unsigned char *blob, int bloblen,
608 const unsigned char *blobauth,
609 unsigned char *data, unsigned int *datalen)
610{
611 unsigned char nonceodd[TPM_NONCE_SIZE];
612 unsigned char enonce1[TPM_NONCE_SIZE];
613 unsigned char enonce2[TPM_NONCE_SIZE];
614 unsigned char authdata1[SHA1_DIGEST_SIZE];
615 unsigned char authdata2[SHA1_DIGEST_SIZE];
616 uint32_t authhandle1 = 0;
617 uint32_t authhandle2 = 0;
618 unsigned char cont = 0;
619 uint32_t ordinal;
620 uint32_t keyhndl;
621 int ret;
622
623 /* sessions for unsealing key and data */
624 ret = oiap(tb, &authhandle1, enonce1);
625 if (ret < 0) {
626 pr_info("trusted_key: oiap failed (%d)\n", ret);
627 return ret;
628 }
629 ret = oiap(tb, &authhandle2, enonce2);
630 if (ret < 0) {
631 pr_info("trusted_key: oiap failed (%d)\n", ret);
632 return ret;
633 }
634
635 ordinal = htonl(TPM_ORD_UNSEAL);
636 keyhndl = htonl(SRKHANDLE);
637 ret = tpm_get_random(tb, nonceodd, TPM_NONCE_SIZE);
638 if (ret < 0) {
639 pr_info("trusted_key: tpm_get_random failed (%d)\n", ret);
640 return ret;
641 }
642 ret = TSS_authhmac(authdata1, keyauth, TPM_NONCE_SIZE,
643 enonce1, nonceodd, cont, sizeof(uint32_t),
644 &ordinal, bloblen, blob, 0, 0);
645 if (ret < 0)
646 return ret;
647 ret = TSS_authhmac(authdata2, blobauth, TPM_NONCE_SIZE,
648 enonce2, nonceodd, cont, sizeof(uint32_t),
649 &ordinal, bloblen, blob, 0, 0);
650 if (ret < 0)
651 return ret;
652
653 /* build and send TPM request packet */
654 INIT_BUF(tb);
655 store16(tb, TPM_TAG_RQU_AUTH2_COMMAND);
656 store32(tb, TPM_UNSEAL_SIZE + bloblen);
657 store32(tb, TPM_ORD_UNSEAL);
658 store32(tb, keyhandle);
659 storebytes(tb, blob, bloblen);
660 store32(tb, authhandle1);
661 storebytes(tb, nonceodd, TPM_NONCE_SIZE);
662 store8(tb, cont);
663 storebytes(tb, authdata1, SHA1_DIGEST_SIZE);
664 store32(tb, authhandle2);
665 storebytes(tb, nonceodd, TPM_NONCE_SIZE);
666 store8(tb, cont);
667 storebytes(tb, authdata2, SHA1_DIGEST_SIZE);
668
669 ret = trusted_tpm_send(TPM_ANY_NUM, tb->data, MAX_BUF_SIZE);
670 if (ret < 0) {
671 pr_info("trusted_key: authhmac failed (%d)\n", ret);
672 return ret;
673 }
674
675 *datalen = LOAD32(tb->data, TPM_DATA_OFFSET);
676 ret = TSS_checkhmac2(tb->data, ordinal, nonceodd,
677 keyauth, SHA1_DIGEST_SIZE,
678 blobauth, SHA1_DIGEST_SIZE,
679 sizeof(uint32_t), TPM_DATA_OFFSET,
680 *datalen, TPM_DATA_OFFSET + sizeof(uint32_t), 0,
681 0);
682 if (ret < 0) {
683 pr_info("trusted_key: TSS_checkhmac2 failed (%d)\n", ret);
684 return ret;
685 }
686 memcpy(data, tb->data + TPM_DATA_OFFSET + sizeof(uint32_t), *datalen);
687 return 0;
688}
689
690/*
691 * Have the TPM seal(encrypt) the symmetric key
692 */
693static int key_seal(struct trusted_key_payload *p,
694 struct trusted_key_options *o)
695{
696 struct tpm_buf *tb;
697 int ret;
698
699 tb = kzalloc(sizeof *tb, GFP_KERNEL);
700 if (!tb)
701 return -ENOMEM;
702
703 /* include migratable flag at end of sealed key */
704 p->key[p->key_len] = p->migratable;
705
706 ret = tpm_seal(tb, o->keytype, o->keyhandle, o->keyauth,
707 p->key, p->key_len + 1, p->blob, &p->blob_len,
708 o->blobauth, o->pcrinfo, o->pcrinfo_len);
709 if (ret < 0)
710 pr_info("trusted_key: srkseal failed (%d)\n", ret);
711
712 kfree(tb);
713 return ret;
714}
715
716/*
717 * Have the TPM unseal(decrypt) the symmetric key
718 */
719static int key_unseal(struct trusted_key_payload *p,
720 struct trusted_key_options *o)
721{
722 struct tpm_buf *tb;
723 int ret;
724
725 tb = kzalloc(sizeof *tb, GFP_KERNEL);
726 if (!tb)
727 return -ENOMEM;
728
729 ret = tpm_unseal(tb, o->keyhandle, o->keyauth, p->blob, p->blob_len,
730 o->blobauth, p->key, &p->key_len);
731 if (ret < 0)
732 pr_info("trusted_key: srkunseal failed (%d)\n", ret);
733 else
734 /* pull migratable flag out of sealed key */
735 p->migratable = p->key[--p->key_len];
736
737 kfree(tb);
738 return ret;
739}
740
741enum {
742 Opt_err = -1,
743 Opt_new, Opt_load, Opt_update,
744 Opt_keyhandle, Opt_keyauth, Opt_blobauth,
745 Opt_pcrinfo, Opt_pcrlock, Opt_migratable
746};
747
748static const match_table_t key_tokens = {
749 {Opt_new, "new"},
750 {Opt_load, "load"},
751 {Opt_update, "update"},
752 {Opt_keyhandle, "keyhandle=%s"},
753 {Opt_keyauth, "keyauth=%s"},
754 {Opt_blobauth, "blobauth=%s"},
755 {Opt_pcrinfo, "pcrinfo=%s"},
756 {Opt_pcrlock, "pcrlock=%s"},
757 {Opt_migratable, "migratable=%s"},
758 {Opt_err, NULL}
759};
760
761/* can have zero or more token= options */
762static int getoptions(char *c, struct trusted_key_payload *pay,
763 struct trusted_key_options *opt)
764{
765 substring_t args[MAX_OPT_ARGS];
766 char *p = c;
767 int token;
768 int res;
769 unsigned long handle;
770 unsigned long lock;
771
772 while ((p = strsep(&c, " \t"))) {
773 if (*p == '\0' || *p == ' ' || *p == '\t')
774 continue;
775 token = match_token(p, key_tokens, args);
776
777 switch (token) {
778 case Opt_pcrinfo:
779 opt->pcrinfo_len = strlen(args[0].from) / 2;
780 if (opt->pcrinfo_len > MAX_PCRINFO_SIZE)
781 return -EINVAL;
782 hex2bin(opt->pcrinfo, args[0].from, opt->pcrinfo_len);
783 break;
784 case Opt_keyhandle:
785 res = strict_strtoul(args[0].from, 16, &handle);
786 if (res < 0)
787 return -EINVAL;
788 opt->keytype = SEAL_keytype;
789 opt->keyhandle = handle;
790 break;
791 case Opt_keyauth:
792 if (strlen(args[0].from) != 2 * SHA1_DIGEST_SIZE)
793 return -EINVAL;
794 hex2bin(opt->keyauth, args[0].from, SHA1_DIGEST_SIZE);
795 break;
796 case Opt_blobauth:
797 if (strlen(args[0].from) != 2 * SHA1_DIGEST_SIZE)
798 return -EINVAL;
799 hex2bin(opt->blobauth, args[0].from, SHA1_DIGEST_SIZE);
800 break;
801 case Opt_migratable:
802 if (*args[0].from == '0')
803 pay->migratable = 0;
804 else
805 return -EINVAL;
806 break;
807 case Opt_pcrlock:
808 res = strict_strtoul(args[0].from, 10, &lock);
809 if (res < 0)
810 return -EINVAL;
811 opt->pcrlock = lock;
812 break;
813 default:
814 return -EINVAL;
815 }
816 }
817 return 0;
818}
819
820/*
821 * datablob_parse - parse the keyctl data and fill in the
822 * payload and options structures
823 *
824 * On success returns 0, otherwise -EINVAL.
825 */
826static int datablob_parse(char *datablob, struct trusted_key_payload *p,
827 struct trusted_key_options *o)
828{
829 substring_t args[MAX_OPT_ARGS];
830 long keylen;
831 int ret = -EINVAL;
832 int key_cmd;
833 char *c;
834
835 /* main command */
836 c = strsep(&datablob, " \t");
837 if (!c)
838 return -EINVAL;
839 key_cmd = match_token(c, key_tokens, args);
840 switch (key_cmd) {
841 case Opt_new:
842 /* first argument is key size */
843 c = strsep(&datablob, " \t");
844 if (!c)
845 return -EINVAL;
846 ret = strict_strtol(c, 10, &keylen);
847 if (ret < 0 || keylen < MIN_KEY_SIZE || keylen > MAX_KEY_SIZE)
848 return -EINVAL;
849 p->key_len = keylen;
850 ret = getoptions(datablob, p, o);
851 if (ret < 0)
852 return ret;
853 ret = Opt_new;
854 break;
855 case Opt_load:
856 /* first argument is sealed blob */
857 c = strsep(&datablob, " \t");
858 if (!c)
859 return -EINVAL;
860 p->blob_len = strlen(c) / 2;
861 if (p->blob_len > MAX_BLOB_SIZE)
862 return -EINVAL;
863 hex2bin(p->blob, c, p->blob_len);
864 ret = getoptions(datablob, p, o);
865 if (ret < 0)
866 return ret;
867 ret = Opt_load;
868 break;
869 case Opt_update:
870 /* all arguments are options */
871 ret = getoptions(datablob, p, o);
872 if (ret < 0)
873 return ret;
874 ret = Opt_update;
875 break;
876 case Opt_err:
877 return -EINVAL;
878 break;
879 }
880 return ret;
881}
882
883static struct trusted_key_options *trusted_options_alloc(void)
884{
885 struct trusted_key_options *options;
886
887 options = kzalloc(sizeof *options, GFP_KERNEL);
888 if (options) {
889 /* set any non-zero defaults */
890 options->keytype = SRK_keytype;
891 options->keyhandle = SRKHANDLE;
892 }
893 return options;
894}
895
896static struct trusted_key_payload *trusted_payload_alloc(struct key *key)
897{
898 struct trusted_key_payload *p = NULL;
899 int ret;
900
901 ret = key_payload_reserve(key, sizeof *p);
902 if (ret < 0)
903 return p;
904 p = kzalloc(sizeof *p, GFP_KERNEL);
905 if (p)
906 p->migratable = 1; /* migratable by default */
907 return p;
908}
909
910/*
911 * trusted_instantiate - create a new trusted key
912 *
913 * Unseal an existing trusted blob or, for a new key, get a
914 * random key, then seal and create a trusted key-type key,
915 * adding it to the specified keyring.
916 *
917 * On success, return 0. Otherwise return errno.
918 */
919static int trusted_instantiate(struct key *key, const void *data,
920 size_t datalen)
921{
922 struct trusted_key_payload *payload = NULL;
923 struct trusted_key_options *options = NULL;
924 char *datablob;
925 int ret = 0;
926 int key_cmd;
927
928 if (datalen <= 0 || datalen > 32767 || !data)
929 return -EINVAL;
930
931 datablob = kmalloc(datalen + 1, GFP_KERNEL);
932 if (!datablob)
933 return -ENOMEM;
934 memcpy(datablob, data, datalen);
935 datablob[datalen] = '\0';
936
937 options = trusted_options_alloc();
938 if (!options) {
939 ret = -ENOMEM;
940 goto out;
941 }
942 payload = trusted_payload_alloc(key);
943 if (!payload) {
944 ret = -ENOMEM;
945 goto out;
946 }
947
948 key_cmd = datablob_parse(datablob, payload, options);
949 if (key_cmd < 0) {
950 ret = key_cmd;
951 goto out;
952 }
953
954 dump_payload(payload);
955 dump_options(options);
956
957 switch (key_cmd) {
958 case Opt_load:
959 ret = key_unseal(payload, options);
960 dump_payload(payload);
961 dump_options(options);
962 if (ret < 0)
963 pr_info("trusted_key: key_unseal failed (%d)\n", ret);
964 break;
965 case Opt_new:
966 ret = my_get_random(payload->key, payload->key_len);
967 if (ret < 0) {
968 pr_info("trusted_key: key_create failed (%d)\n", ret);
969 goto out;
970 }
971 ret = key_seal(payload, options);
972 if (ret < 0)
973 pr_info("trusted_key: key_seal failed (%d)\n", ret);
974 break;
975 default:
976 ret = -EINVAL;
977 goto out;
978 }
979 if (!ret && options->pcrlock)
980 ret = pcrlock(options->pcrlock);
981out:
982 kfree(datablob);
983 kfree(options);
984 if (!ret)
985 rcu_assign_pointer(key->payload.data, payload);
986 else
987 kfree(payload);
988 return ret;
989}
990
991static void trusted_rcu_free(struct rcu_head *rcu)
992{
993 struct trusted_key_payload *p;
994
995 p = container_of(rcu, struct trusted_key_payload, rcu);
996 memset(p->key, 0, p->key_len);
997 kfree(p);
998}
999
1000/*
1001 * trusted_update - reseal an existing key with new PCR values
1002 */
1003static int trusted_update(struct key *key, const void *data, size_t datalen)
1004{
1005 struct trusted_key_payload *p = key->payload.data;
1006 struct trusted_key_payload *new_p;
1007 struct trusted_key_options *new_o;
1008 char *datablob;
1009 int ret = 0;
1010
1011 if (!p->migratable)
1012 return -EPERM;
1013 if (datalen <= 0 || datalen > 32767 || !data)
1014 return -EINVAL;
1015
1016 datablob = kmalloc(datalen + 1, GFP_KERNEL);
1017 if (!datablob)
1018 return -ENOMEM;
1019 new_o = trusted_options_alloc();
1020 if (!new_o) {
1021 ret = -ENOMEM;
1022 goto out;
1023 }
1024 new_p = trusted_payload_alloc(key);
1025 if (!new_p) {
1026 ret = -ENOMEM;
1027 goto out;
1028 }
1029
1030 memcpy(datablob, data, datalen);
1031 datablob[datalen] = '\0';
1032 ret = datablob_parse(datablob, new_p, new_o);
1033 if (ret != Opt_update) {
1034 ret = -EINVAL;
1035 kfree(new_p);
1036 goto out;
1037 }
1038 /* copy old key values, and reseal with new pcrs */
1039 new_p->migratable = p->migratable;
1040 new_p->key_len = p->key_len;
1041 memcpy(new_p->key, p->key, p->key_len);
1042 dump_payload(p);
1043 dump_payload(new_p);
1044
1045 ret = key_seal(new_p, new_o);
1046 if (ret < 0) {
1047 pr_info("trusted_key: key_seal failed (%d)\n", ret);
1048 kfree(new_p);
1049 goto out;
1050 }
1051 if (new_o->pcrlock) {
1052 ret = pcrlock(new_o->pcrlock);
1053 if (ret < 0) {
1054 pr_info("trusted_key: pcrlock failed (%d)\n", ret);
1055 kfree(new_p);
1056 goto out;
1057 }
1058 }
1059 rcu_assign_pointer(key->payload.data, new_p);
1060 call_rcu(&p->rcu, trusted_rcu_free);
1061out:
1062 kfree(datablob);
1063 kfree(new_o);
1064 return ret;
1065}
1066
1067/*
1068 * trusted_read - copy the sealed blob data to userspace in hex.
1069 * On success, return to userspace the trusted key datablob size.
1070 */
1071static long trusted_read(const struct key *key, char __user *buffer,
1072 size_t buflen)
1073{
1074 struct trusted_key_payload *p;
1075 char *ascii_buf;
1076 char *bufp;
1077 int i;
1078
1079 p = rcu_dereference_key(key);
1080 if (!p)
1081 return -EINVAL;
1082 if (!buffer || buflen <= 0)
1083 return 2 * p->blob_len;
1084 ascii_buf = kmalloc(2 * p->blob_len, GFP_KERNEL);
1085 if (!ascii_buf)
1086 return -ENOMEM;
1087
1088 bufp = ascii_buf;
1089 for (i = 0; i < p->blob_len; i++)
1090 bufp = pack_hex_byte(bufp, p->blob[i]);
1091 if ((copy_to_user(buffer, ascii_buf, 2 * p->blob_len)) != 0) {
1092 kfree(ascii_buf);
1093 return -EFAULT;
1094 }
1095 kfree(ascii_buf);
1096 return 2 * p->blob_len;
1097}
1098
1099/*
1100 * trusted_destroy - before freeing the key, clear the decrypted data
1101 */
1102static void trusted_destroy(struct key *key)
1103{
1104 struct trusted_key_payload *p = key->payload.data;
1105
1106 if (!p)
1107 return;
1108 memset(p->key, 0, p->key_len);
1109 kfree(key->payload.data);
1110}
1111
1112struct key_type key_type_trusted = {
1113 .name = "trusted",
1114 .instantiate = trusted_instantiate,
1115 .update = trusted_update,
1116 .match = user_match,
1117 .destroy = trusted_destroy,
1118 .describe = user_describe,
1119 .read = trusted_read,
1120};
1121
1122EXPORT_SYMBOL_GPL(key_type_trusted);
1123
1124static void trusted_shash_release(void)
1125{
1126 if (hashalg)
1127 crypto_free_shash(hashalg);
1128 if (hmacalg)
1129 crypto_free_shash(hmacalg);
1130}
1131
1132static int __init trusted_shash_alloc(void)
1133{
1134 int ret;
1135
1136 hmacalg = crypto_alloc_shash(hmac_alg, 0, CRYPTO_ALG_ASYNC);
1137 if (IS_ERR(hmacalg)) {
1138 pr_info("trusted_key: could not allocate crypto %s\n",
1139 hmac_alg);
1140 return PTR_ERR(hmacalg);
1141 }
1142
1143 hashalg = crypto_alloc_shash(hash_alg, 0, CRYPTO_ALG_ASYNC);
1144 if (IS_ERR(hashalg)) {
1145 pr_info("trusted_key: could not allocate crypto %s\n",
1146 hash_alg);
1147 ret = PTR_ERR(hashalg);
1148 goto hashalg_fail;
1149 }
1150
1151 return 0;
1152
1153hashalg_fail:
1154 crypto_free_shash(hmacalg);
1155 return ret;
1156}
1157
1158static int __init init_trusted(void)
1159{
1160 int ret;
1161
1162 ret = trusted_shash_alloc();
1163 if (ret < 0)
1164 return ret;
1165 ret = register_key_type(&key_type_trusted);
1166 if (ret < 0)
1167 trusted_shash_release();
1168 return ret;
1169}
1170
1171static void __exit cleanup_trusted(void)
1172{
1173 trusted_shash_release();
1174 unregister_key_type(&key_type_trusted);
1175}
1176
1177late_initcall(init_trusted);
1178module_exit(cleanup_trusted);
1179
1180MODULE_LICENSE("GPL");
diff --git a/security/keys/trusted.h b/security/keys/trusted.h
new file mode 100644
index 000000000000..3249fbd2b653
--- /dev/null
+++ b/security/keys/trusted.h
@@ -0,0 +1,134 @@
1#ifndef __TRUSTED_KEY_H
2#define __TRUSTED_KEY_H
3
4/* implementation specific TPM constants */
5#define MAX_PCRINFO_SIZE 64
6#define MAX_BUF_SIZE 512
7#define TPM_GETRANDOM_SIZE 14
8#define TPM_OSAP_SIZE 36
9#define TPM_OIAP_SIZE 10
10#define TPM_SEAL_SIZE 87
11#define TPM_UNSEAL_SIZE 104
12#define TPM_SIZE_OFFSET 2
13#define TPM_RETURN_OFFSET 6
14#define TPM_DATA_OFFSET 10
15
16#define LOAD32(buffer, offset) (ntohl(*(uint32_t *)&buffer[offset]))
17#define LOAD32N(buffer, offset) (*(uint32_t *)&buffer[offset])
18#define LOAD16(buffer, offset) (ntohs(*(uint16_t *)&buffer[offset]))
19
20struct tpm_buf {
21 int len;
22 unsigned char data[MAX_BUF_SIZE];
23};
24
25#define INIT_BUF(tb) (tb->len = 0)
26
27struct osapsess {
28 uint32_t handle;
29 unsigned char secret[SHA1_DIGEST_SIZE];
30 unsigned char enonce[TPM_NONCE_SIZE];
31};
32
33/* discrete values, but have to store in uint16_t for TPM use */
34enum {
35 SEAL_keytype = 1,
36 SRK_keytype = 4
37};
38
39struct trusted_key_options {
40 uint16_t keytype;
41 uint32_t keyhandle;
42 unsigned char keyauth[SHA1_DIGEST_SIZE];
43 unsigned char blobauth[SHA1_DIGEST_SIZE];
44 uint32_t pcrinfo_len;
45 unsigned char pcrinfo[MAX_PCRINFO_SIZE];
46 int pcrlock;
47};
48
49#define TPM_DEBUG 0
50
51#if TPM_DEBUG
52static inline void dump_options(struct trusted_key_options *o)
53{
54 pr_info("trusted_key: sealing key type %d\n", o->keytype);
55 pr_info("trusted_key: sealing key handle %0X\n", o->keyhandle);
56 pr_info("trusted_key: pcrlock %d\n", o->pcrlock);
57 pr_info("trusted_key: pcrinfo %d\n", o->pcrinfo_len);
58 print_hex_dump(KERN_INFO, "pcrinfo ", DUMP_PREFIX_NONE,
59 16, 1, o->pcrinfo, o->pcrinfo_len, 0);
60}
61
62static inline void dump_payload(struct trusted_key_payload *p)
63{
64 pr_info("trusted_key: key_len %d\n", p->key_len);
65 print_hex_dump(KERN_INFO, "key ", DUMP_PREFIX_NONE,
66 16, 1, p->key, p->key_len, 0);
67 pr_info("trusted_key: bloblen %d\n", p->blob_len);
68 print_hex_dump(KERN_INFO, "blob ", DUMP_PREFIX_NONE,
69 16, 1, p->blob, p->blob_len, 0);
70 pr_info("trusted_key: migratable %d\n", p->migratable);
71}
72
73static inline void dump_sess(struct osapsess *s)
74{
75 print_hex_dump(KERN_INFO, "trusted-key: handle ", DUMP_PREFIX_NONE,
76 16, 1, &s->handle, 4, 0);
77 pr_info("trusted-key: secret:\n");
78 print_hex_dump(KERN_INFO, "", DUMP_PREFIX_NONE,
79 16, 1, &s->secret, SHA1_DIGEST_SIZE, 0);
80 pr_info("trusted-key: enonce:\n");
81 print_hex_dump(KERN_INFO, "", DUMP_PREFIX_NONE,
82 16, 1, &s->enonce, SHA1_DIGEST_SIZE, 0);
83}
84
85static inline void dump_tpm_buf(unsigned char *buf)
86{
87 int len;
88
89 pr_info("\ntrusted-key: tpm buffer\n");
90 len = LOAD32(buf, TPM_SIZE_OFFSET);
91 print_hex_dump(KERN_INFO, "", DUMP_PREFIX_NONE, 16, 1, buf, len, 0);
92}
93#else
94static inline void dump_options(struct trusted_key_options *o)
95{
96}
97
98static inline void dump_payload(struct trusted_key_payload *p)
99{
100}
101
102static inline void dump_sess(struct osapsess *s)
103{
104}
105
106static inline void dump_tpm_buf(unsigned char *buf)
107{
108}
109#endif
110
111static inline void store8(struct tpm_buf *buf, const unsigned char value)
112{
113 buf->data[buf->len++] = value;
114}
115
116static inline void store16(struct tpm_buf *buf, const uint16_t value)
117{
118 *(uint16_t *) & buf->data[buf->len] = htons(value);
119 buf->len += sizeof value;
120}
121
122static inline void store32(struct tpm_buf *buf, const uint32_t value)
123{
124 *(uint32_t *) & buf->data[buf->len] = htonl(value);
125 buf->len += sizeof value;
126}
127
128static inline void storebytes(struct tpm_buf *buf, const unsigned char *in,
129 const int len)
130{
131 memcpy(buf->data + buf->len, in, len);
132 buf->len += len;
133}
134#endif
diff --git a/security/keys/user_defined.c b/security/keys/user_defined.c
index e9aa07929656..5b366d7af3c4 100644
--- a/security/keys/user_defined.c
+++ b/security/keys/user_defined.c
@@ -35,7 +35,6 @@ struct key_type key_type_user = {
35 35
36EXPORT_SYMBOL_GPL(key_type_user); 36EXPORT_SYMBOL_GPL(key_type_user);
37 37
38/*****************************************************************************/
39/* 38/*
40 * instantiate a user defined key 39 * instantiate a user defined key
41 */ 40 */
@@ -65,26 +64,10 @@ int user_instantiate(struct key *key, const void *data, size_t datalen)
65 64
66error: 65error:
67 return ret; 66 return ret;
68 67}
69} /* end user_instantiate() */
70 68
71EXPORT_SYMBOL_GPL(user_instantiate); 69EXPORT_SYMBOL_GPL(user_instantiate);
72 70
73/*****************************************************************************/
74/*
75 * dispose of the old data from an updated user defined key
76 */
77static void user_update_rcu_disposal(struct rcu_head *rcu)
78{
79 struct user_key_payload *upayload;
80
81 upayload = container_of(rcu, struct user_key_payload, rcu);
82
83 kfree(upayload);
84
85} /* end user_update_rcu_disposal() */
86
87/*****************************************************************************/
88/* 71/*
89 * update a user defined key 72 * update a user defined key
90 * - the key's semaphore is write-locked 73 * - the key's semaphore is write-locked
@@ -119,28 +102,24 @@ int user_update(struct key *key, const void *data, size_t datalen)
119 key->expiry = 0; 102 key->expiry = 0;
120 } 103 }
121 104
122 call_rcu(&zap->rcu, user_update_rcu_disposal); 105 kfree_rcu(zap, rcu);
123 106
124error: 107error:
125 return ret; 108 return ret;
126 109}
127} /* end user_update() */
128 110
129EXPORT_SYMBOL_GPL(user_update); 111EXPORT_SYMBOL_GPL(user_update);
130 112
131/*****************************************************************************/
132/* 113/*
133 * match users on their name 114 * match users on their name
134 */ 115 */
135int user_match(const struct key *key, const void *description) 116int user_match(const struct key *key, const void *description)
136{ 117{
137 return strcmp(key->description, description) == 0; 118 return strcmp(key->description, description) == 0;
138 119}
139} /* end user_match() */
140 120
141EXPORT_SYMBOL_GPL(user_match); 121EXPORT_SYMBOL_GPL(user_match);
142 122
143/*****************************************************************************/
144/* 123/*
145 * dispose of the links from a revoked keyring 124 * dispose of the links from a revoked keyring
146 * - called with the key sem write-locked 125 * - called with the key sem write-locked
@@ -154,14 +133,12 @@ void user_revoke(struct key *key)
154 133
155 if (upayload) { 134 if (upayload) {
156 rcu_assign_pointer(key->payload.data, NULL); 135 rcu_assign_pointer(key->payload.data, NULL);
157 call_rcu(&upayload->rcu, user_update_rcu_disposal); 136 kfree_rcu(upayload, rcu);
158 } 137 }
159 138}
160} /* end user_revoke() */
161 139
162EXPORT_SYMBOL(user_revoke); 140EXPORT_SYMBOL(user_revoke);
163 141
164/*****************************************************************************/
165/* 142/*
166 * dispose of the data dangling from the corpse of a user key 143 * dispose of the data dangling from the corpse of a user key
167 */ 144 */
@@ -170,26 +147,22 @@ void user_destroy(struct key *key)
170 struct user_key_payload *upayload = key->payload.data; 147 struct user_key_payload *upayload = key->payload.data;
171 148
172 kfree(upayload); 149 kfree(upayload);
173 150}
174} /* end user_destroy() */
175 151
176EXPORT_SYMBOL_GPL(user_destroy); 152EXPORT_SYMBOL_GPL(user_destroy);
177 153
178/*****************************************************************************/
179/* 154/*
180 * describe the user key 155 * describe the user key
181 */ 156 */
182void user_describe(const struct key *key, struct seq_file *m) 157void user_describe(const struct key *key, struct seq_file *m)
183{ 158{
184 seq_puts(m, key->description); 159 seq_puts(m, key->description);
185 160 if (key_is_instantiated(key))
186 seq_printf(m, ": %u", key->datalen); 161 seq_printf(m, ": %u", key->datalen);
187 162}
188} /* end user_describe() */
189 163
190EXPORT_SYMBOL_GPL(user_describe); 164EXPORT_SYMBOL_GPL(user_describe);
191 165
192/*****************************************************************************/
193/* 166/*
194 * read the key data 167 * read the key data
195 * - the key's semaphore is read-locked 168 * - the key's semaphore is read-locked
@@ -199,8 +172,7 @@ long user_read(const struct key *key, char __user *buffer, size_t buflen)
199 struct user_key_payload *upayload; 172 struct user_key_payload *upayload;
200 long ret; 173 long ret;
201 174
202 upayload = rcu_dereference_protected( 175 upayload = rcu_dereference_key(key);
203 key->payload.data, rwsem_is_locked(&((struct key *)key)->sem));
204 ret = upayload->datalen; 176 ret = upayload->datalen;
205 177
206 /* we can return the data as is */ 178 /* we can return the data as is */
@@ -213,7 +185,6 @@ long user_read(const struct key *key, char __user *buffer, size_t buflen)
213 } 185 }
214 186
215 return ret; 187 return ret;
216 188}
217} /* end user_read() */
218 189
219EXPORT_SYMBOL_GPL(user_read); 190EXPORT_SYMBOL_GPL(user_read);
diff --git a/security/lsm_audit.c b/security/lsm_audit.c
index 908aa712816a..893af8a2fa1e 100644
--- a/security/lsm_audit.c
+++ b/security/lsm_audit.c
@@ -210,7 +210,6 @@ static inline void print_ipv4_addr(struct audit_buffer *ab, __be32 addr,
210static void dump_common_audit_data(struct audit_buffer *ab, 210static void dump_common_audit_data(struct audit_buffer *ab,
211 struct common_audit_data *a) 211 struct common_audit_data *a)
212{ 212{
213 struct inode *inode = NULL;
214 struct task_struct *tsk = current; 213 struct task_struct *tsk = current;
215 214
216 if (a->tsk) 215 if (a->tsk)
@@ -229,33 +228,47 @@ static void dump_common_audit_data(struct audit_buffer *ab,
229 case LSM_AUDIT_DATA_CAP: 228 case LSM_AUDIT_DATA_CAP:
230 audit_log_format(ab, " capability=%d ", a->u.cap); 229 audit_log_format(ab, " capability=%d ", a->u.cap);
231 break; 230 break;
232 case LSM_AUDIT_DATA_FS: 231 case LSM_AUDIT_DATA_PATH: {
233 if (a->u.fs.path.dentry) { 232 struct inode *inode;
234 struct dentry *dentry = a->u.fs.path.dentry; 233
235 if (a->u.fs.path.mnt) { 234 audit_log_d_path(ab, "path=", &a->u.path);
236 audit_log_d_path(ab, "path=", &a->u.fs.path); 235
237 } else { 236 inode = a->u.path.dentry->d_inode;
238 audit_log_format(ab, " name=");
239 audit_log_untrustedstring(ab,
240 dentry->d_name.name);
241 }
242 inode = dentry->d_inode;
243 } else if (a->u.fs.inode) {
244 struct dentry *dentry;
245 inode = a->u.fs.inode;
246 dentry = d_find_alias(inode);
247 if (dentry) {
248 audit_log_format(ab, " name=");
249 audit_log_untrustedstring(ab,
250 dentry->d_name.name);
251 dput(dentry);
252 }
253 }
254 if (inode) 237 if (inode)
255 audit_log_format(ab, " dev=%s ino=%lu", 238 audit_log_format(ab, " dev=%s ino=%lu",
256 inode->i_sb->s_id, 239 inode->i_sb->s_id,
257 inode->i_ino); 240 inode->i_ino);
258 break; 241 break;
242 }
243 case LSM_AUDIT_DATA_DENTRY: {
244 struct inode *inode;
245
246 audit_log_format(ab, " name=");
247 audit_log_untrustedstring(ab, a->u.dentry->d_name.name);
248
249 inode = a->u.dentry->d_inode;
250 if (inode)
251 audit_log_format(ab, " dev=%s ino=%lu",
252 inode->i_sb->s_id,
253 inode->i_ino);
254 break;
255 }
256 case LSM_AUDIT_DATA_INODE: {
257 struct dentry *dentry;
258 struct inode *inode;
259
260 inode = a->u.inode;
261 dentry = d_find_alias(inode);
262 if (dentry) {
263 audit_log_format(ab, " name=");
264 audit_log_untrustedstring(ab,
265 dentry->d_name.name);
266 dput(dentry);
267 }
268 audit_log_format(ab, " dev=%s ino=%lu", inode->i_sb->s_id,
269 inode->i_ino);
270 break;
271 }
259 case LSM_AUDIT_DATA_TASK: 272 case LSM_AUDIT_DATA_TASK:
260 tsk = a->u.tsk; 273 tsk = a->u.tsk;
261 if (tsk && tsk->pid) { 274 if (tsk && tsk->pid) {
diff --git a/security/security.c b/security/security.c
index c53949f17d9e..4ba6d4cc061f 100644
--- a/security/security.c
+++ b/security/security.c
@@ -89,20 +89,12 @@ __setup("security=", choose_lsm);
89 * Return true if: 89 * Return true if:
90 * -The passed LSM is the one chosen by user at boot time, 90 * -The passed LSM is the one chosen by user at boot time,
91 * -or the passed LSM is configured as the default and the user did not 91 * -or the passed LSM is configured as the default and the user did not
92 * choose an alternate LSM at boot time, 92 * choose an alternate LSM at boot time.
93 * -or there is no default LSM set and the user didn't specify a
94 * specific LSM and we're the first to ask for registration permission,
95 * -or the passed LSM is currently loaded.
96 * Otherwise, return false. 93 * Otherwise, return false.
97 */ 94 */
98int __init security_module_enable(struct security_operations *ops) 95int __init security_module_enable(struct security_operations *ops)
99{ 96{
100 if (!*chosen_lsm) 97 return !strcmp(ops->name, chosen_lsm);
101 strncpy(chosen_lsm, ops->name, SECURITY_NAME_MAX);
102 else if (strncmp(ops->name, chosen_lsm, SECURITY_NAME_MAX))
103 return 0;
104
105 return 1;
106} 98}
107 99
108/** 100/**
@@ -162,39 +154,37 @@ int security_capset(struct cred *new, const struct cred *old,
162 effective, inheritable, permitted); 154 effective, inheritable, permitted);
163} 155}
164 156
165int security_capable(int cap) 157int security_capable(struct user_namespace *ns, const struct cred *cred,
158 int cap)
166{ 159{
167 return security_ops->capable(current, current_cred(), cap, 160 return security_ops->capable(current, cred, ns, cap,
168 SECURITY_CAP_AUDIT); 161 SECURITY_CAP_AUDIT);
169} 162}
170 163
171int security_real_capable(struct task_struct *tsk, int cap) 164int security_real_capable(struct task_struct *tsk, struct user_namespace *ns,
165 int cap)
172{ 166{
173 const struct cred *cred; 167 const struct cred *cred;
174 int ret; 168 int ret;
175 169
176 cred = get_task_cred(tsk); 170 cred = get_task_cred(tsk);
177 ret = security_ops->capable(tsk, cred, cap, SECURITY_CAP_AUDIT); 171 ret = security_ops->capable(tsk, cred, ns, cap, SECURITY_CAP_AUDIT);
178 put_cred(cred); 172 put_cred(cred);
179 return ret; 173 return ret;
180} 174}
181 175
182int security_real_capable_noaudit(struct task_struct *tsk, int cap) 176int security_real_capable_noaudit(struct task_struct *tsk,
177 struct user_namespace *ns, int cap)
183{ 178{
184 const struct cred *cred; 179 const struct cred *cred;
185 int ret; 180 int ret;
186 181
187 cred = get_task_cred(tsk); 182 cred = get_task_cred(tsk);
188 ret = security_ops->capable(tsk, cred, cap, SECURITY_CAP_NOAUDIT); 183 ret = security_ops->capable(tsk, cred, ns, cap, SECURITY_CAP_NOAUDIT);
189 put_cred(cred); 184 put_cred(cred);
190 return ret; 185 return ret;
191} 186}
192 187
193int security_sysctl(struct ctl_table *table, int op)
194{
195 return security_ops->sysctl(table, op);
196}
197
198int security_quotactl(int cmds, int type, int id, struct super_block *sb) 188int security_quotactl(int cmds, int type, int id, struct super_block *sb)
199{ 189{
200 return security_ops->quotactl(cmds, type, id, sb); 190 return security_ops->quotactl(cmds, type, id, sb);
@@ -205,12 +195,12 @@ int security_quota_on(struct dentry *dentry)
205 return security_ops->quota_on(dentry); 195 return security_ops->quota_on(dentry);
206} 196}
207 197
208int security_syslog(int type, bool from_file) 198int security_syslog(int type)
209{ 199{
210 return security_ops->syslog(type, from_file); 200 return security_ops->syslog(type);
211} 201}
212 202
213int security_settime(struct timespec *ts, struct timezone *tz) 203int security_settime(const struct timespec *ts, const struct timezone *tz)
214{ 204{
215 return security_ops->settime(ts, tz); 205 return security_ops->settime(ts, tz);
216} 206}
@@ -280,6 +270,11 @@ int security_sb_copy_data(char *orig, char *copy)
280} 270}
281EXPORT_SYMBOL(security_sb_copy_data); 271EXPORT_SYMBOL(security_sb_copy_data);
282 272
273int security_sb_remount(struct super_block *sb, void *data)
274{
275 return security_ops->sb_remount(sb, data);
276}
277
283int security_sb_kern_mount(struct super_block *sb, int flags, void *data) 278int security_sb_kern_mount(struct super_block *sb, int flags, void *data)
284{ 279{
285 return security_ops->sb_kern_mount(sb, flags, data); 280 return security_ops->sb_kern_mount(sb, flags, data);
@@ -333,16 +328,8 @@ EXPORT_SYMBOL(security_sb_parse_opts_str);
333 328
334int security_inode_alloc(struct inode *inode) 329int security_inode_alloc(struct inode *inode)
335{ 330{
336 int ret;
337
338 inode->i_security = NULL; 331 inode->i_security = NULL;
339 ret = security_ops->inode_alloc_security(inode); 332 return security_ops->inode_alloc_security(inode);
340 if (ret)
341 return ret;
342 ret = ima_inode_alloc(inode);
343 if (ret)
344 security_inode_free(inode);
345 return ret;
346} 333}
347 334
348void security_inode_free(struct inode *inode) 335void security_inode_free(struct inode *inode)
@@ -352,11 +339,13 @@ void security_inode_free(struct inode *inode)
352} 339}
353 340
354int security_inode_init_security(struct inode *inode, struct inode *dir, 341int security_inode_init_security(struct inode *inode, struct inode *dir,
355 char **name, void **value, size_t *len) 342 const struct qstr *qstr, char **name,
343 void **value, size_t *len)
356{ 344{
357 if (unlikely(IS_PRIVATE(inode))) 345 if (unlikely(IS_PRIVATE(inode)))
358 return -EOPNOTSUPP; 346 return -EOPNOTSUPP;
359 return security_ops->inode_init_security(inode, dir, name, value, len); 347 return security_ops->inode_init_security(inode, dir, qstr, name, value,
348 len);
360} 349}
361EXPORT_SYMBOL(security_inode_init_security); 350EXPORT_SYMBOL(security_inode_init_security);
362 351
@@ -376,6 +365,7 @@ int security_path_mkdir(struct path *dir, struct dentry *dentry, int mode)
376 return 0; 365 return 0;
377 return security_ops->path_mkdir(dir, dentry, mode); 366 return security_ops->path_mkdir(dir, dentry, mode);
378} 367}
368EXPORT_SYMBOL(security_path_mkdir);
379 369
380int security_path_rmdir(struct path *dir, struct dentry *dentry) 370int security_path_rmdir(struct path *dir, struct dentry *dentry)
381{ 371{
@@ -390,6 +380,7 @@ int security_path_unlink(struct path *dir, struct dentry *dentry)
390 return 0; 380 return 0;
391 return security_ops->path_unlink(dir, dentry); 381 return security_ops->path_unlink(dir, dentry);
392} 382}
383EXPORT_SYMBOL(security_path_unlink);
393 384
394int security_path_symlink(struct path *dir, struct dentry *dentry, 385int security_path_symlink(struct path *dir, struct dentry *dentry,
395 const char *old_name) 386 const char *old_name)
@@ -416,6 +407,7 @@ int security_path_rename(struct path *old_dir, struct dentry *old_dentry,
416 return security_ops->path_rename(old_dir, old_dentry, new_dir, 407 return security_ops->path_rename(old_dir, old_dentry, new_dir,
417 new_dentry); 408 new_dentry);
418} 409}
410EXPORT_SYMBOL(security_path_rename);
419 411
420int security_path_truncate(struct path *path) 412int security_path_truncate(struct path *path)
421{ 413{
@@ -526,7 +518,14 @@ int security_inode_permission(struct inode *inode, int mask)
526{ 518{
527 if (unlikely(IS_PRIVATE(inode))) 519 if (unlikely(IS_PRIVATE(inode)))
528 return 0; 520 return 0;
529 return security_ops->inode_permission(inode, mask); 521 return security_ops->inode_permission(inode, mask, 0);
522}
523
524int security_inode_exec_permission(struct inode *inode, unsigned int flags)
525{
526 if (unlikely(IS_PRIVATE(inode)))
527 return 0;
528 return security_ops->inode_permission(inode, MAY_EXEC, flags);
530} 529}
531 530
532int security_inode_setattr(struct dentry *dentry, struct iattr *attr) 531int security_inode_setattr(struct dentry *dentry, struct iattr *attr)
@@ -786,10 +785,9 @@ int security_task_setrlimit(struct task_struct *p, unsigned int resource,
786 return security_ops->task_setrlimit(p, resource, new_rlim); 785 return security_ops->task_setrlimit(p, resource, new_rlim);
787} 786}
788 787
789int security_task_setscheduler(struct task_struct *p, 788int security_task_setscheduler(struct task_struct *p)
790 int policy, struct sched_param *lp)
791{ 789{
792 return security_ops->task_setscheduler(p, policy, lp); 790 return security_ops->task_setscheduler(p);
793} 791}
794 792
795int security_task_getscheduler(struct task_struct *p) 793int security_task_getscheduler(struct task_struct *p)
@@ -994,8 +992,7 @@ EXPORT_SYMBOL(security_inode_getsecctx);
994 992
995#ifdef CONFIG_SECURITY_NETWORK 993#ifdef CONFIG_SECURITY_NETWORK
996 994
997int security_unix_stream_connect(struct socket *sock, struct socket *other, 995int security_unix_stream_connect(struct sock *sock, struct sock *other, struct sock *newsk)
998 struct sock *newsk)
999{ 996{
1000 return security_ops->unix_stream_connect(sock, other, newsk); 997 return security_ops->unix_stream_connect(sock, other, newsk);
1001} 998}
@@ -1110,7 +1107,7 @@ void security_sk_clone(const struct sock *sk, struct sock *newsk)
1110 1107
1111void security_sk_classify_flow(struct sock *sk, struct flowi *fl) 1108void security_sk_classify_flow(struct sock *sk, struct flowi *fl)
1112{ 1109{
1113 security_ops->sk_getsecid(sk, &fl->secid); 1110 security_ops->sk_getsecid(sk, &fl->flowi_secid);
1114} 1111}
1115EXPORT_SYMBOL(security_sk_classify_flow); 1112EXPORT_SYMBOL(security_sk_classify_flow);
1116 1113
@@ -1145,6 +1142,24 @@ void security_inet_conn_established(struct sock *sk,
1145 security_ops->inet_conn_established(sk, skb); 1142 security_ops->inet_conn_established(sk, skb);
1146} 1143}
1147 1144
1145int security_secmark_relabel_packet(u32 secid)
1146{
1147 return security_ops->secmark_relabel_packet(secid);
1148}
1149EXPORT_SYMBOL(security_secmark_relabel_packet);
1150
1151void security_secmark_refcount_inc(void)
1152{
1153 security_ops->secmark_refcount_inc();
1154}
1155EXPORT_SYMBOL(security_secmark_refcount_inc);
1156
1157void security_secmark_refcount_dec(void)
1158{
1159 security_ops->secmark_refcount_dec();
1160}
1161EXPORT_SYMBOL(security_secmark_refcount_dec);
1162
1148int security_tun_dev_create(void) 1163int security_tun_dev_create(void)
1149{ 1164{
1150 return security_ops->tun_dev_create(); 1165 return security_ops->tun_dev_create();
@@ -1225,7 +1240,8 @@ int security_xfrm_policy_lookup(struct xfrm_sec_ctx *ctx, u32 fl_secid, u8 dir)
1225} 1240}
1226 1241
1227int security_xfrm_state_pol_flow_match(struct xfrm_state *x, 1242int security_xfrm_state_pol_flow_match(struct xfrm_state *x,
1228 struct xfrm_policy *xp, struct flowi *fl) 1243 struct xfrm_policy *xp,
1244 const struct flowi *fl)
1229{ 1245{
1230 return security_ops->xfrm_state_pol_flow_match(x, xp, fl); 1246 return security_ops->xfrm_state_pol_flow_match(x, xp, fl);
1231} 1247}
@@ -1237,7 +1253,7 @@ int security_xfrm_decode_session(struct sk_buff *skb, u32 *secid)
1237 1253
1238void security_skb_classify_flow(struct sk_buff *skb, struct flowi *fl) 1254void security_skb_classify_flow(struct sk_buff *skb, struct flowi *fl)
1239{ 1255{
1240 int rc = security_ops->xfrm_decode_session(skb, &fl->secid, 0); 1256 int rc = security_ops->xfrm_decode_session(skb, &fl->flowi_secid, 0);
1241 1257
1242 BUG_ON(rc); 1258 BUG_ON(rc);
1243} 1259}
diff --git a/security/selinux/Makefile b/security/selinux/Makefile
index 58d80f3bd6f6..ad5cd76ec231 100644
--- a/security/selinux/Makefile
+++ b/security/selinux/Makefile
@@ -2,25 +2,20 @@
2# Makefile for building the SELinux module as part of the kernel tree. 2# Makefile for building the SELinux module as part of the kernel tree.
3# 3#
4 4
5obj-$(CONFIG_SECURITY_SELINUX) := selinux.o ss/ 5obj-$(CONFIG_SECURITY_SELINUX) := selinux.o
6 6
7selinux-y := avc.o \ 7selinux-y := avc.o hooks.o selinuxfs.o netlink.o nlmsgtab.o netif.o \
8 hooks.o \ 8 netnode.o netport.o exports.o \
9 selinuxfs.o \ 9 ss/ebitmap.o ss/hashtab.o ss/symtab.o ss/sidtab.o ss/avtab.o \
10 netlink.o \ 10 ss/policydb.o ss/services.o ss/conditional.o ss/mls.o ss/status.o
11 nlmsgtab.o \
12 netif.o \
13 netnode.o \
14 netport.o \
15 exports.o
16 11
17selinux-$(CONFIG_SECURITY_NETWORK_XFRM) += xfrm.o 12selinux-$(CONFIG_SECURITY_NETWORK_XFRM) += xfrm.o
18 13
19selinux-$(CONFIG_NETLABEL) += netlabel.o 14selinux-$(CONFIG_NETLABEL) += netlabel.o
20 15
21EXTRA_CFLAGS += -Isecurity/selinux -Isecurity/selinux/include 16ccflags-y := -Isecurity/selinux -Isecurity/selinux/include
22 17
23$(obj)/avc.o: $(obj)/flask.h 18$(addprefix $(obj)/,$(selinux-y)): $(obj)/flask.h
24 19
25quiet_cmd_flask = GEN $(obj)/flask.h $(obj)/av_permissions.h 20quiet_cmd_flask = GEN $(obj)/flask.h $(obj)/av_permissions.h
26 cmd_flask = scripts/selinux/genheaders/genheaders $(obj)/flask.h $(obj)/av_permissions.h 21 cmd_flask = scripts/selinux/genheaders/genheaders $(obj)/flask.h $(obj)/av_permissions.h
diff --git a/security/selinux/avc.c b/security/selinux/avc.c
index 9da6420e2056..d515b2128a4e 100644
--- a/security/selinux/avc.c
+++ b/security/selinux/avc.c
@@ -38,11 +38,7 @@
38#define AVC_CACHE_RECLAIM 16 38#define AVC_CACHE_RECLAIM 16
39 39
40#ifdef CONFIG_SECURITY_SELINUX_AVC_STATS 40#ifdef CONFIG_SECURITY_SELINUX_AVC_STATS
41#define avc_cache_stats_incr(field) \ 41#define avc_cache_stats_incr(field) this_cpu_inc(avc_cache_stats.field)
42do { \
43 per_cpu(avc_cache_stats, get_cpu()).field++; \
44 put_cpu(); \
45} while (0)
46#else 42#else
47#define avc_cache_stats_incr(field) do {} while (0) 43#define avc_cache_stats_incr(field) do {} while (0)
48#endif 44#endif
@@ -347,11 +343,10 @@ static struct avc_node *avc_lookup(u32 ssid, u32 tsid, u16 tclass)
347 node = avc_search_node(ssid, tsid, tclass); 343 node = avc_search_node(ssid, tsid, tclass);
348 344
349 if (node) 345 if (node)
350 avc_cache_stats_incr(hits); 346 return node;
351 else
352 avc_cache_stats_incr(misses);
353 347
354 return node; 348 avc_cache_stats_incr(misses);
349 return NULL;
355} 350}
356 351
357static int avc_latest_notif_update(int seqno, int is_insert) 352static int avc_latest_notif_update(int seqno, int is_insert)
@@ -471,6 +466,7 @@ static void avc_audit_post_callback(struct audit_buffer *ab, void *a)
471 * @avd: access vector decisions 466 * @avd: access vector decisions
472 * @result: result from avc_has_perm_noaudit 467 * @result: result from avc_has_perm_noaudit
473 * @a: auxiliary audit data 468 * @a: auxiliary audit data
469 * @flags: VFS walk flags
474 * 470 *
475 * Audit the granting or denial of permissions in accordance 471 * Audit the granting or denial of permissions in accordance
476 * with the policy. This function is typically called by 472 * with the policy. This function is typically called by
@@ -481,9 +477,10 @@ static void avc_audit_post_callback(struct audit_buffer *ab, void *a)
481 * be performed under a lock, to allow the lock to be released 477 * be performed under a lock, to allow the lock to be released
482 * before calling the auditing code. 478 * before calling the auditing code.
483 */ 479 */
484void avc_audit(u32 ssid, u32 tsid, 480int avc_audit(u32 ssid, u32 tsid,
485 u16 tclass, u32 requested, 481 u16 tclass, u32 requested,
486 struct av_decision *avd, int result, struct common_audit_data *a) 482 struct av_decision *avd, int result, struct common_audit_data *a,
483 unsigned flags)
487{ 484{
488 struct common_audit_data stack_data; 485 struct common_audit_data stack_data;
489 u32 denied, audited; 486 u32 denied, audited;
@@ -515,11 +512,24 @@ void avc_audit(u32 ssid, u32 tsid,
515 else 512 else
516 audited = requested & avd->auditallow; 513 audited = requested & avd->auditallow;
517 if (!audited) 514 if (!audited)
518 return; 515 return 0;
516
519 if (!a) { 517 if (!a) {
520 a = &stack_data; 518 a = &stack_data;
521 COMMON_AUDIT_DATA_INIT(a, NONE); 519 COMMON_AUDIT_DATA_INIT(a, NONE);
522 } 520 }
521
522 /*
523 * When in a RCU walk do the audit on the RCU retry. This is because
524 * the collection of the dname in an inode audit message is not RCU
525 * safe. Note this may drop some audits when the situation changes
526 * during retry. However this is logically just as if the operation
527 * happened a little later.
528 */
529 if ((a->type == LSM_AUDIT_DATA_INODE) &&
530 (flags & IPERM_FLAG_RCU))
531 return -ECHILD;
532
523 a->selinux_audit_data.tclass = tclass; 533 a->selinux_audit_data.tclass = tclass;
524 a->selinux_audit_data.requested = requested; 534 a->selinux_audit_data.requested = requested;
525 a->selinux_audit_data.ssid = ssid; 535 a->selinux_audit_data.ssid = ssid;
@@ -529,6 +539,7 @@ void avc_audit(u32 ssid, u32 tsid,
529 a->lsm_pre_audit = avc_audit_pre_callback; 539 a->lsm_pre_audit = avc_audit_pre_callback;
530 a->lsm_post_audit = avc_audit_post_callback; 540 a->lsm_post_audit = avc_audit_post_callback;
531 common_lsm_audit(a); 541 common_lsm_audit(a);
542 return 0;
532} 543}
533 544
534/** 545/**
@@ -741,10 +752,9 @@ int avc_ss_reset(u32 seqno)
741int avc_has_perm_noaudit(u32 ssid, u32 tsid, 752int avc_has_perm_noaudit(u32 ssid, u32 tsid,
742 u16 tclass, u32 requested, 753 u16 tclass, u32 requested,
743 unsigned flags, 754 unsigned flags,
744 struct av_decision *in_avd) 755 struct av_decision *avd)
745{ 756{
746 struct avc_node *node; 757 struct avc_node *node;
747 struct av_decision avd_entry, *avd;
748 int rc = 0; 758 int rc = 0;
749 u32 denied; 759 u32 denied;
750 760
@@ -753,20 +763,13 @@ int avc_has_perm_noaudit(u32 ssid, u32 tsid,
753 rcu_read_lock(); 763 rcu_read_lock();
754 764
755 node = avc_lookup(ssid, tsid, tclass); 765 node = avc_lookup(ssid, tsid, tclass);
756 if (!node) { 766 if (unlikely(!node)) {
757 rcu_read_unlock(); 767 rcu_read_unlock();
758
759 if (in_avd)
760 avd = in_avd;
761 else
762 avd = &avd_entry;
763
764 security_compute_av(ssid, tsid, tclass, avd); 768 security_compute_av(ssid, tsid, tclass, avd);
765 rcu_read_lock(); 769 rcu_read_lock();
766 node = avc_insert(ssid, tsid, tclass, avd); 770 node = avc_insert(ssid, tsid, tclass, avd);
767 } else { 771 } else {
768 if (in_avd) 772 memcpy(avd, &node->ae.avd, sizeof(*avd));
769 memcpy(in_avd, &node->ae.avd, sizeof(*in_avd));
770 avd = &node->ae.avd; 773 avd = &node->ae.avd;
771 } 774 }
772 775
@@ -793,6 +796,7 @@ int avc_has_perm_noaudit(u32 ssid, u32 tsid,
793 * @tclass: target security class 796 * @tclass: target security class
794 * @requested: requested permissions, interpreted based on @tclass 797 * @requested: requested permissions, interpreted based on @tclass
795 * @auditdata: auxiliary audit data 798 * @auditdata: auxiliary audit data
799 * @flags: VFS walk flags
796 * 800 *
797 * Check the AVC to determine whether the @requested permissions are granted 801 * Check the AVC to determine whether the @requested permissions are granted
798 * for the SID pair (@ssid, @tsid), interpreting the permissions 802 * for the SID pair (@ssid, @tsid), interpreting the permissions
@@ -802,14 +806,19 @@ int avc_has_perm_noaudit(u32 ssid, u32 tsid,
802 * permissions are granted, -%EACCES if any permissions are denied, or 806 * permissions are granted, -%EACCES if any permissions are denied, or
803 * another -errno upon other errors. 807 * another -errno upon other errors.
804 */ 808 */
805int avc_has_perm(u32 ssid, u32 tsid, u16 tclass, 809int avc_has_perm_flags(u32 ssid, u32 tsid, u16 tclass,
806 u32 requested, struct common_audit_data *auditdata) 810 u32 requested, struct common_audit_data *auditdata,
811 unsigned flags)
807{ 812{
808 struct av_decision avd; 813 struct av_decision avd;
809 int rc; 814 int rc, rc2;
810 815
811 rc = avc_has_perm_noaudit(ssid, tsid, tclass, requested, 0, &avd); 816 rc = avc_has_perm_noaudit(ssid, tsid, tclass, requested, 0, &avd);
812 avc_audit(ssid, tsid, tclass, requested, &avd, rc, auditdata); 817
818 rc2 = avc_audit(ssid, tsid, tclass, requested, &avd, rc, auditdata,
819 flags);
820 if (rc2)
821 return rc2;
813 return rc; 822 return rc;
814} 823}
815 824
diff --git a/security/selinux/exports.c b/security/selinux/exports.c
index c0a454aee1e0..90664385dead 100644
--- a/security/selinux/exports.c
+++ b/security/selinux/exports.c
@@ -11,58 +11,9 @@
11 * it under the terms of the GNU General Public License version 2, 11 * it under the terms of the GNU General Public License version 2,
12 * as published by the Free Software Foundation. 12 * as published by the Free Software Foundation.
13 */ 13 */
14#include <linux/types.h>
15#include <linux/kernel.h>
16#include <linux/module.h> 14#include <linux/module.h>
17#include <linux/selinux.h>
18#include <linux/fs.h>
19#include <linux/ipc.h>
20#include <asm/atomic.h>
21 15
22#include "security.h" 16#include "security.h"
23#include "objsec.h"
24
25/* SECMARK reference count */
26extern atomic_t selinux_secmark_refcount;
27
28int selinux_string_to_sid(char *str, u32 *sid)
29{
30 if (selinux_enabled)
31 return security_context_to_sid(str, strlen(str), sid);
32 else {
33 *sid = 0;
34 return 0;
35 }
36}
37EXPORT_SYMBOL_GPL(selinux_string_to_sid);
38
39int selinux_secmark_relabel_packet_permission(u32 sid)
40{
41 if (selinux_enabled) {
42 const struct task_security_struct *__tsec;
43 u32 tsid;
44
45 __tsec = current_security();
46 tsid = __tsec->sid;
47
48 return avc_has_perm(tsid, sid, SECCLASS_PACKET,
49 PACKET__RELABELTO, NULL);
50 }
51 return 0;
52}
53EXPORT_SYMBOL_GPL(selinux_secmark_relabel_packet_permission);
54
55void selinux_secmark_refcount_inc(void)
56{
57 atomic_inc(&selinux_secmark_refcount);
58}
59EXPORT_SYMBOL_GPL(selinux_secmark_refcount_inc);
60
61void selinux_secmark_refcount_dec(void)
62{
63 atomic_dec(&selinux_secmark_refcount);
64}
65EXPORT_SYMBOL_GPL(selinux_secmark_refcount_dec);
66 17
67bool selinux_is_enabled(void) 18bool selinux_is_enabled(void)
68{ 19{
diff --git a/security/selinux/hooks.c b/security/selinux/hooks.c
index 4796ddd4e721..20219ef5439a 100644
--- a/security/selinux/hooks.c
+++ b/security/selinux/hooks.c
@@ -24,9 +24,11 @@
24 */ 24 */
25 25
26#include <linux/init.h> 26#include <linux/init.h>
27#include <linux/kd.h>
27#include <linux/kernel.h> 28#include <linux/kernel.h>
28#include <linux/tracehook.h> 29#include <linux/tracehook.h>
29#include <linux/errno.h> 30#include <linux/errno.h>
31#include <linux/ext2_fs.h>
30#include <linux/sched.h> 32#include <linux/sched.h>
31#include <linux/security.h> 33#include <linux/security.h>
32#include <linux/xattr.h> 34#include <linux/xattr.h>
@@ -36,14 +38,15 @@
36#include <linux/mman.h> 38#include <linux/mman.h>
37#include <linux/slab.h> 39#include <linux/slab.h>
38#include <linux/pagemap.h> 40#include <linux/pagemap.h>
41#include <linux/proc_fs.h>
39#include <linux/swap.h> 42#include <linux/swap.h>
40#include <linux/spinlock.h> 43#include <linux/spinlock.h>
41#include <linux/syscalls.h> 44#include <linux/syscalls.h>
45#include <linux/dcache.h>
42#include <linux/file.h> 46#include <linux/file.h>
43#include <linux/fdtable.h> 47#include <linux/fdtable.h>
44#include <linux/namei.h> 48#include <linux/namei.h>
45#include <linux/mount.h> 49#include <linux/mount.h>
46#include <linux/proc_fs.h>
47#include <linux/netfilter_ipv4.h> 50#include <linux/netfilter_ipv4.h>
48#include <linux/netfilter_ipv6.h> 51#include <linux/netfilter_ipv6.h>
49#include <linux/tty.h> 52#include <linux/tty.h>
@@ -70,13 +73,13 @@
70#include <net/ipv6.h> 73#include <net/ipv6.h>
71#include <linux/hugetlb.h> 74#include <linux/hugetlb.h>
72#include <linux/personality.h> 75#include <linux/personality.h>
73#include <linux/sysctl.h>
74#include <linux/audit.h> 76#include <linux/audit.h>
75#include <linux/string.h> 77#include <linux/string.h>
76#include <linux/selinux.h> 78#include <linux/selinux.h>
77#include <linux/mutex.h> 79#include <linux/mutex.h>
78#include <linux/posix-timers.h> 80#include <linux/posix-timers.h>
79#include <linux/syslog.h> 81#include <linux/syslog.h>
82#include <linux/user_namespace.h>
80 83
81#include "avc.h" 84#include "avc.h"
82#include "objsec.h" 85#include "objsec.h"
@@ -987,6 +990,7 @@ static void selinux_write_opts(struct seq_file *m,
987 continue; 990 continue;
988 default: 991 default:
989 BUG(); 992 BUG();
993 return;
990 }; 994 };
991 /* we need a comma before each option */ 995 /* we need a comma before each option */
992 seq_putc(m, ','); 996 seq_putc(m, ',');
@@ -1120,39 +1124,35 @@ static inline u16 socket_type_to_security_class(int family, int type, int protoc
1120} 1124}
1121 1125
1122#ifdef CONFIG_PROC_FS 1126#ifdef CONFIG_PROC_FS
1123static int selinux_proc_get_sid(struct proc_dir_entry *de, 1127static int selinux_proc_get_sid(struct dentry *dentry,
1124 u16 tclass, 1128 u16 tclass,
1125 u32 *sid) 1129 u32 *sid)
1126{ 1130{
1127 int buflen, rc; 1131 int rc;
1128 char *buffer, *path, *end; 1132 char *buffer, *path;
1129 1133
1130 buffer = (char *)__get_free_page(GFP_KERNEL); 1134 buffer = (char *)__get_free_page(GFP_KERNEL);
1131 if (!buffer) 1135 if (!buffer)
1132 return -ENOMEM; 1136 return -ENOMEM;
1133 1137
1134 buflen = PAGE_SIZE; 1138 path = dentry_path_raw(dentry, buffer, PAGE_SIZE);
1135 end = buffer+buflen; 1139 if (IS_ERR(path))
1136 *--end = '\0'; 1140 rc = PTR_ERR(path);
1137 buflen--; 1141 else {
1138 path = end-1; 1142 /* each process gets a /proc/PID/ entry. Strip off the
1139 *path = '/'; 1143 * PID part to get a valid selinux labeling.
1140 while (de && de != de->parent) { 1144 * e.g. /proc/1/net/rpc/nfs -> /net/rpc/nfs */
1141 buflen -= de->namelen + 1; 1145 while (path[1] >= '0' && path[1] <= '9') {
1142 if (buflen < 0) 1146 path[1] = '/';
1143 break; 1147 path++;
1144 end -= de->namelen; 1148 }
1145 memcpy(end, de->name, de->namelen); 1149 rc = security_genfs_sid("proc", path, tclass, sid);
1146 *--end = '/';
1147 path = end;
1148 de = de->parent;
1149 } 1150 }
1150 rc = security_genfs_sid("proc", path, tclass, sid);
1151 free_page((unsigned long)buffer); 1151 free_page((unsigned long)buffer);
1152 return rc; 1152 return rc;
1153} 1153}
1154#else 1154#else
1155static int selinux_proc_get_sid(struct proc_dir_entry *de, 1155static int selinux_proc_get_sid(struct dentry *dentry,
1156 u16 tclass, 1156 u16 tclass,
1157 u32 *sid) 1157 u32 *sid)
1158{ 1158{
@@ -1300,10 +1300,8 @@ static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dent
1300 1300
1301 /* Try to obtain a transition SID. */ 1301 /* Try to obtain a transition SID. */
1302 isec->sclass = inode_mode_to_security_class(inode->i_mode); 1302 isec->sclass = inode_mode_to_security_class(inode->i_mode);
1303 rc = security_transition_sid(isec->task_sid, 1303 rc = security_transition_sid(isec->task_sid, sbsec->sid,
1304 sbsec->sid, 1304 isec->sclass, NULL, &sid);
1305 isec->sclass,
1306 &sid);
1307 if (rc) 1305 if (rc)
1308 goto out_unlock; 1306 goto out_unlock;
1309 isec->sid = sid; 1307 isec->sid = sid;
@@ -1316,10 +1314,9 @@ static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dent
1316 isec->sid = sbsec->sid; 1314 isec->sid = sbsec->sid;
1317 1315
1318 if ((sbsec->flags & SE_SBPROC) && !S_ISLNK(inode->i_mode)) { 1316 if ((sbsec->flags & SE_SBPROC) && !S_ISLNK(inode->i_mode)) {
1319 struct proc_inode *proci = PROC_I(inode); 1317 if (opt_dentry) {
1320 if (proci->pde) {
1321 isec->sclass = inode_mode_to_security_class(inode->i_mode); 1318 isec->sclass = inode_mode_to_security_class(inode->i_mode);
1322 rc = selinux_proc_get_sid(proci->pde, 1319 rc = selinux_proc_get_sid(opt_dentry,
1323 isec->sclass, 1320 isec->sclass,
1324 &sid); 1321 &sid);
1325 if (rc) 1322 if (rc)
@@ -1447,11 +1444,15 @@ static int task_has_capability(struct task_struct *tsk,
1447 printk(KERN_ERR 1444 printk(KERN_ERR
1448 "SELinux: out of range capability %d\n", cap); 1445 "SELinux: out of range capability %d\n", cap);
1449 BUG(); 1446 BUG();
1447 return -EINVAL;
1450 } 1448 }
1451 1449
1452 rc = avc_has_perm_noaudit(sid, sid, sclass, av, 0, &avd); 1450 rc = avc_has_perm_noaudit(sid, sid, sclass, av, 0, &avd);
1453 if (audit == SECURITY_CAP_AUDIT) 1451 if (audit == SECURITY_CAP_AUDIT) {
1454 avc_audit(sid, sid, sclass, av, &avd, rc, &ad); 1452 int rc2 = avc_audit(sid, sid, sclass, av, &avd, rc, &ad, 0);
1453 if (rc2)
1454 return rc2;
1455 }
1455 return rc; 1456 return rc;
1456} 1457}
1457 1458
@@ -1471,10 +1472,10 @@ static int task_has_system(struct task_struct *tsk,
1471static int inode_has_perm(const struct cred *cred, 1472static int inode_has_perm(const struct cred *cred,
1472 struct inode *inode, 1473 struct inode *inode,
1473 u32 perms, 1474 u32 perms,
1474 struct common_audit_data *adp) 1475 struct common_audit_data *adp,
1476 unsigned flags)
1475{ 1477{
1476 struct inode_security_struct *isec; 1478 struct inode_security_struct *isec;
1477 struct common_audit_data ad;
1478 u32 sid; 1479 u32 sid;
1479 1480
1480 validate_creds(cred); 1481 validate_creds(cred);
@@ -1485,30 +1486,49 @@ static int inode_has_perm(const struct cred *cred,
1485 sid = cred_sid(cred); 1486 sid = cred_sid(cred);
1486 isec = inode->i_security; 1487 isec = inode->i_security;
1487 1488
1488 if (!adp) { 1489 return avc_has_perm_flags(sid, isec->sid, isec->sclass, perms, adp, flags);
1489 adp = &ad; 1490}
1490 COMMON_AUDIT_DATA_INIT(&ad, FS);
1491 ad.u.fs.inode = inode;
1492 }
1493 1491
1494 return avc_has_perm(sid, isec->sid, isec->sclass, perms, adp); 1492static int inode_has_perm_noadp(const struct cred *cred,
1493 struct inode *inode,
1494 u32 perms,
1495 unsigned flags)
1496{
1497 struct common_audit_data ad;
1498
1499 COMMON_AUDIT_DATA_INIT(&ad, INODE);
1500 ad.u.inode = inode;
1501 return inode_has_perm(cred, inode, perms, &ad, flags);
1495} 1502}
1496 1503
1497/* Same as inode_has_perm, but pass explicit audit data containing 1504/* Same as inode_has_perm, but pass explicit audit data containing
1498 the dentry to help the auditing code to more easily generate the 1505 the dentry to help the auditing code to more easily generate the
1499 pathname if needed. */ 1506 pathname if needed. */
1500static inline int dentry_has_perm(const struct cred *cred, 1507static inline int dentry_has_perm(const struct cred *cred,
1501 struct vfsmount *mnt,
1502 struct dentry *dentry, 1508 struct dentry *dentry,
1503 u32 av) 1509 u32 av)
1504{ 1510{
1505 struct inode *inode = dentry->d_inode; 1511 struct inode *inode = dentry->d_inode;
1506 struct common_audit_data ad; 1512 struct common_audit_data ad;
1507 1513
1508 COMMON_AUDIT_DATA_INIT(&ad, FS); 1514 COMMON_AUDIT_DATA_INIT(&ad, DENTRY);
1509 ad.u.fs.path.mnt = mnt; 1515 ad.u.dentry = dentry;
1510 ad.u.fs.path.dentry = dentry; 1516 return inode_has_perm(cred, inode, av, &ad, 0);
1511 return inode_has_perm(cred, inode, av, &ad); 1517}
1518
1519/* Same as inode_has_perm, but pass explicit audit data containing
1520 the path to help the auditing code to more easily generate the
1521 pathname if needed. */
1522static inline int path_has_perm(const struct cred *cred,
1523 struct path *path,
1524 u32 av)
1525{
1526 struct inode *inode = path->dentry->d_inode;
1527 struct common_audit_data ad;
1528
1529 COMMON_AUDIT_DATA_INIT(&ad, PATH);
1530 ad.u.path = *path;
1531 return inode_has_perm(cred, inode, av, &ad, 0);
1512} 1532}
1513 1533
1514/* Check whether a task can use an open file descriptor to 1534/* Check whether a task can use an open file descriptor to
@@ -1529,8 +1549,8 @@ static int file_has_perm(const struct cred *cred,
1529 u32 sid = cred_sid(cred); 1549 u32 sid = cred_sid(cred);
1530 int rc; 1550 int rc;
1531 1551
1532 COMMON_AUDIT_DATA_INIT(&ad, FS); 1552 COMMON_AUDIT_DATA_INIT(&ad, PATH);
1533 ad.u.fs.path = file->f_path; 1553 ad.u.path = file->f_path;
1534 1554
1535 if (sid != fsec->sid) { 1555 if (sid != fsec->sid) {
1536 rc = avc_has_perm(sid, fsec->sid, 1556 rc = avc_has_perm(sid, fsec->sid,
@@ -1544,7 +1564,7 @@ static int file_has_perm(const struct cred *cred,
1544 /* av is zero if only checking access to the descriptor. */ 1564 /* av is zero if only checking access to the descriptor. */
1545 rc = 0; 1565 rc = 0;
1546 if (av) 1566 if (av)
1547 rc = inode_has_perm(cred, inode, av, &ad); 1567 rc = inode_has_perm(cred, inode, av, &ad, 0);
1548 1568
1549out: 1569out:
1550 return rc; 1570 return rc;
@@ -1568,8 +1588,8 @@ static int may_create(struct inode *dir,
1568 sid = tsec->sid; 1588 sid = tsec->sid;
1569 newsid = tsec->create_sid; 1589 newsid = tsec->create_sid;
1570 1590
1571 COMMON_AUDIT_DATA_INIT(&ad, FS); 1591 COMMON_AUDIT_DATA_INIT(&ad, DENTRY);
1572 ad.u.fs.path.dentry = dentry; 1592 ad.u.dentry = dentry;
1573 1593
1574 rc = avc_has_perm(sid, dsec->sid, SECCLASS_DIR, 1594 rc = avc_has_perm(sid, dsec->sid, SECCLASS_DIR,
1575 DIR__ADD_NAME | DIR__SEARCH, 1595 DIR__ADD_NAME | DIR__SEARCH,
@@ -1578,7 +1598,8 @@ static int may_create(struct inode *dir,
1578 return rc; 1598 return rc;
1579 1599
1580 if (!newsid || !(sbsec->flags & SE_SBLABELSUPP)) { 1600 if (!newsid || !(sbsec->flags & SE_SBLABELSUPP)) {
1581 rc = security_transition_sid(sid, dsec->sid, tclass, &newsid); 1601 rc = security_transition_sid(sid, dsec->sid, tclass,
1602 &dentry->d_name, &newsid);
1582 if (rc) 1603 if (rc)
1583 return rc; 1604 return rc;
1584 } 1605 }
@@ -1620,8 +1641,8 @@ static int may_link(struct inode *dir,
1620 dsec = dir->i_security; 1641 dsec = dir->i_security;
1621 isec = dentry->d_inode->i_security; 1642 isec = dentry->d_inode->i_security;
1622 1643
1623 COMMON_AUDIT_DATA_INIT(&ad, FS); 1644 COMMON_AUDIT_DATA_INIT(&ad, DENTRY);
1624 ad.u.fs.path.dentry = dentry; 1645 ad.u.dentry = dentry;
1625 1646
1626 av = DIR__SEARCH; 1647 av = DIR__SEARCH;
1627 av |= (kind ? DIR__REMOVE_NAME : DIR__ADD_NAME); 1648 av |= (kind ? DIR__REMOVE_NAME : DIR__ADD_NAME);
@@ -1666,9 +1687,9 @@ static inline int may_rename(struct inode *old_dir,
1666 old_is_dir = S_ISDIR(old_dentry->d_inode->i_mode); 1687 old_is_dir = S_ISDIR(old_dentry->d_inode->i_mode);
1667 new_dsec = new_dir->i_security; 1688 new_dsec = new_dir->i_security;
1668 1689
1669 COMMON_AUDIT_DATA_INIT(&ad, FS); 1690 COMMON_AUDIT_DATA_INIT(&ad, DENTRY);
1670 1691
1671 ad.u.fs.path.dentry = old_dentry; 1692 ad.u.dentry = old_dentry;
1672 rc = avc_has_perm(sid, old_dsec->sid, SECCLASS_DIR, 1693 rc = avc_has_perm(sid, old_dsec->sid, SECCLASS_DIR,
1673 DIR__REMOVE_NAME | DIR__SEARCH, &ad); 1694 DIR__REMOVE_NAME | DIR__SEARCH, &ad);
1674 if (rc) 1695 if (rc)
@@ -1684,7 +1705,7 @@ static inline int may_rename(struct inode *old_dir,
1684 return rc; 1705 return rc;
1685 } 1706 }
1686 1707
1687 ad.u.fs.path.dentry = new_dentry; 1708 ad.u.dentry = new_dentry;
1688 av = DIR__ADD_NAME | DIR__SEARCH; 1709 av = DIR__ADD_NAME | DIR__SEARCH;
1689 if (new_dentry->d_inode) 1710 if (new_dentry->d_inode)
1690 av |= DIR__REMOVE_NAME; 1711 av |= DIR__REMOVE_NAME;
@@ -1851,93 +1872,17 @@ static int selinux_capset(struct cred *new, const struct cred *old,
1851 */ 1872 */
1852 1873
1853static int selinux_capable(struct task_struct *tsk, const struct cred *cred, 1874static int selinux_capable(struct task_struct *tsk, const struct cred *cred,
1854 int cap, int audit) 1875 struct user_namespace *ns, int cap, int audit)
1855{ 1876{
1856 int rc; 1877 int rc;
1857 1878
1858 rc = cap_capable(tsk, cred, cap, audit); 1879 rc = cap_capable(tsk, cred, ns, cap, audit);
1859 if (rc) 1880 if (rc)
1860 return rc; 1881 return rc;
1861 1882
1862 return task_has_capability(tsk, cred, cap, audit); 1883 return task_has_capability(tsk, cred, cap, audit);
1863} 1884}
1864 1885
1865static int selinux_sysctl_get_sid(ctl_table *table, u16 tclass, u32 *sid)
1866{
1867 int buflen, rc;
1868 char *buffer, *path, *end;
1869
1870 rc = -ENOMEM;
1871 buffer = (char *)__get_free_page(GFP_KERNEL);
1872 if (!buffer)
1873 goto out;
1874
1875 buflen = PAGE_SIZE;
1876 end = buffer+buflen;
1877 *--end = '\0';
1878 buflen--;
1879 path = end-1;
1880 *path = '/';
1881 while (table) {
1882 const char *name = table->procname;
1883 size_t namelen = strlen(name);
1884 buflen -= namelen + 1;
1885 if (buflen < 0)
1886 goto out_free;
1887 end -= namelen;
1888 memcpy(end, name, namelen);
1889 *--end = '/';
1890 path = end;
1891 table = table->parent;
1892 }
1893 buflen -= 4;
1894 if (buflen < 0)
1895 goto out_free;
1896 end -= 4;
1897 memcpy(end, "/sys", 4);
1898 path = end;
1899 rc = security_genfs_sid("proc", path, tclass, sid);
1900out_free:
1901 free_page((unsigned long)buffer);
1902out:
1903 return rc;
1904}
1905
1906static int selinux_sysctl(ctl_table *table, int op)
1907{
1908 int error = 0;
1909 u32 av;
1910 u32 tsid, sid;
1911 int rc;
1912
1913 sid = current_sid();
1914
1915 rc = selinux_sysctl_get_sid(table, (op == 0001) ?
1916 SECCLASS_DIR : SECCLASS_FILE, &tsid);
1917 if (rc) {
1918 /* Default to the well-defined sysctl SID. */
1919 tsid = SECINITSID_SYSCTL;
1920 }
1921
1922 /* The op values are "defined" in sysctl.c, thereby creating
1923 * a bad coupling between this module and sysctl.c */
1924 if (op == 001) {
1925 error = avc_has_perm(sid, tsid,
1926 SECCLASS_DIR, DIR__SEARCH, NULL);
1927 } else {
1928 av = 0;
1929 if (op & 004)
1930 av |= FILE__READ;
1931 if (op & 002)
1932 av |= FILE__WRITE;
1933 if (av)
1934 error = avc_has_perm(sid, tsid,
1935 SECCLASS_FILE, av, NULL);
1936 }
1937
1938 return error;
1939}
1940
1941static int selinux_quotactl(int cmds, int type, int id, struct super_block *sb) 1886static int selinux_quotactl(int cmds, int type, int id, struct super_block *sb)
1942{ 1887{
1943 const struct cred *cred = current_cred(); 1888 const struct cred *cred = current_cred();
@@ -1970,17 +1915,13 @@ static int selinux_quota_on(struct dentry *dentry)
1970{ 1915{
1971 const struct cred *cred = current_cred(); 1916 const struct cred *cred = current_cred();
1972 1917
1973 return dentry_has_perm(cred, NULL, dentry, FILE__QUOTAON); 1918 return dentry_has_perm(cred, dentry, FILE__QUOTAON);
1974} 1919}
1975 1920
1976static int selinux_syslog(int type, bool from_file) 1921static int selinux_syslog(int type)
1977{ 1922{
1978 int rc; 1923 int rc;
1979 1924
1980 rc = cap_syslog(type, from_file);
1981 if (rc)
1982 return rc;
1983
1984 switch (type) { 1925 switch (type) {
1985 case SYSLOG_ACTION_READ_ALL: /* Read last kernel messages */ 1926 case SYSLOG_ACTION_READ_ALL: /* Read last kernel messages */
1986 case SYSLOG_ACTION_SIZE_BUFFER: /* Return size of the log buffer */ 1927 case SYSLOG_ACTION_SIZE_BUFFER: /* Return size of the log buffer */
@@ -2016,7 +1957,8 @@ static int selinux_vm_enough_memory(struct mm_struct *mm, long pages)
2016{ 1957{
2017 int rc, cap_sys_admin = 0; 1958 int rc, cap_sys_admin = 0;
2018 1959
2019 rc = selinux_capable(current, current_cred(), CAP_SYS_ADMIN, 1960 rc = selinux_capable(current, current_cred(),
1961 &init_user_ns, CAP_SYS_ADMIN,
2020 SECURITY_CAP_NOAUDIT); 1962 SECURITY_CAP_NOAUDIT);
2021 if (rc == 0) 1963 if (rc == 0)
2022 cap_sys_admin = 1; 1964 cap_sys_admin = 1;
@@ -2064,13 +2006,14 @@ static int selinux_bprm_set_creds(struct linux_binprm *bprm)
2064 } else { 2006 } else {
2065 /* Check for a default transition on this program. */ 2007 /* Check for a default transition on this program. */
2066 rc = security_transition_sid(old_tsec->sid, isec->sid, 2008 rc = security_transition_sid(old_tsec->sid, isec->sid,
2067 SECCLASS_PROCESS, &new_tsec->sid); 2009 SECCLASS_PROCESS, NULL,
2010 &new_tsec->sid);
2068 if (rc) 2011 if (rc)
2069 return rc; 2012 return rc;
2070 } 2013 }
2071 2014
2072 COMMON_AUDIT_DATA_INIT(&ad, FS); 2015 COMMON_AUDIT_DATA_INIT(&ad, PATH);
2073 ad.u.fs.path = bprm->file->f_path; 2016 ad.u.path = bprm->file->f_path;
2074 2017
2075 if (bprm->file->f_path.mnt->mnt_flags & MNT_NOSUID) 2018 if (bprm->file->f_path.mnt->mnt_flags & MNT_NOSUID)
2076 new_tsec->sid = old_tsec->sid; 2019 new_tsec->sid = old_tsec->sid;
@@ -2184,8 +2127,8 @@ static inline void flush_unauthorized_files(const struct cred *cred,
2184 struct tty_file_private, list); 2127 struct tty_file_private, list);
2185 file = file_priv->file; 2128 file = file_priv->file;
2186 inode = file->f_path.dentry->d_inode; 2129 inode = file->f_path.dentry->d_inode;
2187 if (inode_has_perm(cred, inode, 2130 if (inode_has_perm_noadp(cred, inode,
2188 FILE__READ | FILE__WRITE, NULL)) { 2131 FILE__READ | FILE__WRITE, 0)) {
2189 drop_tty = 1; 2132 drop_tty = 1;
2190 } 2133 }
2191 } 2134 }
@@ -2198,7 +2141,7 @@ static inline void flush_unauthorized_files(const struct cred *cred,
2198 2141
2199 /* Revalidate access to inherited open files. */ 2142 /* Revalidate access to inherited open files. */
2200 2143
2201 COMMON_AUDIT_DATA_INIT(&ad, FS); 2144 COMMON_AUDIT_DATA_INIT(&ad, INODE);
2202 2145
2203 spin_lock(&files->file_lock); 2146 spin_lock(&files->file_lock);
2204 for (;;) { 2147 for (;;) {
@@ -2447,6 +2390,91 @@ out:
2447 return rc; 2390 return rc;
2448} 2391}
2449 2392
2393static int selinux_sb_remount(struct super_block *sb, void *data)
2394{
2395 int rc, i, *flags;
2396 struct security_mnt_opts opts;
2397 char *secdata, **mount_options;
2398 struct superblock_security_struct *sbsec = sb->s_security;
2399
2400 if (!(sbsec->flags & SE_SBINITIALIZED))
2401 return 0;
2402
2403 if (!data)
2404 return 0;
2405
2406 if (sb->s_type->fs_flags & FS_BINARY_MOUNTDATA)
2407 return 0;
2408
2409 security_init_mnt_opts(&opts);
2410 secdata = alloc_secdata();
2411 if (!secdata)
2412 return -ENOMEM;
2413 rc = selinux_sb_copy_data(data, secdata);
2414 if (rc)
2415 goto out_free_secdata;
2416
2417 rc = selinux_parse_opts_str(secdata, &opts);
2418 if (rc)
2419 goto out_free_secdata;
2420
2421 mount_options = opts.mnt_opts;
2422 flags = opts.mnt_opts_flags;
2423
2424 for (i = 0; i < opts.num_mnt_opts; i++) {
2425 u32 sid;
2426 size_t len;
2427
2428 if (flags[i] == SE_SBLABELSUPP)
2429 continue;
2430 len = strlen(mount_options[i]);
2431 rc = security_context_to_sid(mount_options[i], len, &sid);
2432 if (rc) {
2433 printk(KERN_WARNING "SELinux: security_context_to_sid"
2434 "(%s) failed for (dev %s, type %s) errno=%d\n",
2435 mount_options[i], sb->s_id, sb->s_type->name, rc);
2436 goto out_free_opts;
2437 }
2438 rc = -EINVAL;
2439 switch (flags[i]) {
2440 case FSCONTEXT_MNT:
2441 if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid, sid))
2442 goto out_bad_option;
2443 break;
2444 case CONTEXT_MNT:
2445 if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid, sid))
2446 goto out_bad_option;
2447 break;
2448 case ROOTCONTEXT_MNT: {
2449 struct inode_security_struct *root_isec;
2450 root_isec = sb->s_root->d_inode->i_security;
2451
2452 if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid, sid))
2453 goto out_bad_option;
2454 break;
2455 }
2456 case DEFCONTEXT_MNT:
2457 if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid, sid))
2458 goto out_bad_option;
2459 break;
2460 default:
2461 goto out_free_opts;
2462 }
2463 }
2464
2465 rc = 0;
2466out_free_opts:
2467 security_free_mnt_opts(&opts);
2468out_free_secdata:
2469 free_secdata(secdata);
2470 return rc;
2471out_bad_option:
2472 printk(KERN_WARNING "SELinux: unable to change security options "
2473 "during remount (dev %s, type=%s)\n", sb->s_id,
2474 sb->s_type->name);
2475 goto out_free_opts;
2476}
2477
2450static int selinux_sb_kern_mount(struct super_block *sb, int flags, void *data) 2478static int selinux_sb_kern_mount(struct super_block *sb, int flags, void *data)
2451{ 2479{
2452 const struct cred *cred = current_cred(); 2480 const struct cred *cred = current_cred();
@@ -2461,8 +2489,8 @@ static int selinux_sb_kern_mount(struct super_block *sb, int flags, void *data)
2461 if (flags & MS_KERNMOUNT) 2489 if (flags & MS_KERNMOUNT)
2462 return 0; 2490 return 0;
2463 2491
2464 COMMON_AUDIT_DATA_INIT(&ad, FS); 2492 COMMON_AUDIT_DATA_INIT(&ad, DENTRY);
2465 ad.u.fs.path.dentry = sb->s_root; 2493 ad.u.dentry = sb->s_root;
2466 return superblock_has_perm(cred, sb, FILESYSTEM__MOUNT, &ad); 2494 return superblock_has_perm(cred, sb, FILESYSTEM__MOUNT, &ad);
2467} 2495}
2468 2496
@@ -2471,8 +2499,8 @@ static int selinux_sb_statfs(struct dentry *dentry)
2471 const struct cred *cred = current_cred(); 2499 const struct cred *cred = current_cred();
2472 struct common_audit_data ad; 2500 struct common_audit_data ad;
2473 2501
2474 COMMON_AUDIT_DATA_INIT(&ad, FS); 2502 COMMON_AUDIT_DATA_INIT(&ad, DENTRY);
2475 ad.u.fs.path.dentry = dentry->d_sb->s_root; 2503 ad.u.dentry = dentry->d_sb->s_root;
2476 return superblock_has_perm(cred, dentry->d_sb, FILESYSTEM__GETATTR, &ad); 2504 return superblock_has_perm(cred, dentry->d_sb, FILESYSTEM__GETATTR, &ad);
2477} 2505}
2478 2506
@@ -2488,8 +2516,7 @@ static int selinux_mount(char *dev_name,
2488 return superblock_has_perm(cred, path->mnt->mnt_sb, 2516 return superblock_has_perm(cred, path->mnt->mnt_sb,
2489 FILESYSTEM__REMOUNT, NULL); 2517 FILESYSTEM__REMOUNT, NULL);
2490 else 2518 else
2491 return dentry_has_perm(cred, path->mnt, path->dentry, 2519 return path_has_perm(cred, path, FILE__MOUNTON);
2492 FILE__MOUNTON);
2493} 2520}
2494 2521
2495static int selinux_umount(struct vfsmount *mnt, int flags) 2522static int selinux_umount(struct vfsmount *mnt, int flags)
@@ -2513,8 +2540,8 @@ static void selinux_inode_free_security(struct inode *inode)
2513} 2540}
2514 2541
2515static int selinux_inode_init_security(struct inode *inode, struct inode *dir, 2542static int selinux_inode_init_security(struct inode *inode, struct inode *dir,
2516 char **name, void **value, 2543 const struct qstr *qstr, char **name,
2517 size_t *len) 2544 void **value, size_t *len)
2518{ 2545{
2519 const struct task_security_struct *tsec = current_security(); 2546 const struct task_security_struct *tsec = current_security();
2520 struct inode_security_struct *dsec; 2547 struct inode_security_struct *dsec;
@@ -2529,10 +2556,13 @@ static int selinux_inode_init_security(struct inode *inode, struct inode *dir,
2529 sid = tsec->sid; 2556 sid = tsec->sid;
2530 newsid = tsec->create_sid; 2557 newsid = tsec->create_sid;
2531 2558
2532 if (!newsid || !(sbsec->flags & SE_SBLABELSUPP)) { 2559 if ((sbsec->flags & SE_SBINITIALIZED) &&
2560 (sbsec->behavior == SECURITY_FS_USE_MNTPOINT))
2561 newsid = sbsec->mntpoint_sid;
2562 else if (!newsid || !(sbsec->flags & SE_SBLABELSUPP)) {
2533 rc = security_transition_sid(sid, dsec->sid, 2563 rc = security_transition_sid(sid, dsec->sid,
2534 inode_mode_to_security_class(inode->i_mode), 2564 inode_mode_to_security_class(inode->i_mode),
2535 &newsid); 2565 qstr, &newsid);
2536 if (rc) { 2566 if (rc) {
2537 printk(KERN_WARNING "%s: " 2567 printk(KERN_WARNING "%s: "
2538 "security_transition_sid failed, rc=%d (dev=%s " 2568 "security_transition_sid failed, rc=%d (dev=%s "
@@ -2619,17 +2649,17 @@ static int selinux_inode_readlink(struct dentry *dentry)
2619{ 2649{
2620 const struct cred *cred = current_cred(); 2650 const struct cred *cred = current_cred();
2621 2651
2622 return dentry_has_perm(cred, NULL, dentry, FILE__READ); 2652 return dentry_has_perm(cred, dentry, FILE__READ);
2623} 2653}
2624 2654
2625static int selinux_inode_follow_link(struct dentry *dentry, struct nameidata *nameidata) 2655static int selinux_inode_follow_link(struct dentry *dentry, struct nameidata *nameidata)
2626{ 2656{
2627 const struct cred *cred = current_cred(); 2657 const struct cred *cred = current_cred();
2628 2658
2629 return dentry_has_perm(cred, NULL, dentry, FILE__READ); 2659 return dentry_has_perm(cred, dentry, FILE__READ);
2630} 2660}
2631 2661
2632static int selinux_inode_permission(struct inode *inode, int mask) 2662static int selinux_inode_permission(struct inode *inode, int mask, unsigned flags)
2633{ 2663{
2634 const struct cred *cred = current_cred(); 2664 const struct cred *cred = current_cred();
2635 struct common_audit_data ad; 2665 struct common_audit_data ad;
@@ -2643,15 +2673,15 @@ static int selinux_inode_permission(struct inode *inode, int mask)
2643 if (!mask) 2673 if (!mask)
2644 return 0; 2674 return 0;
2645 2675
2646 COMMON_AUDIT_DATA_INIT(&ad, FS); 2676 COMMON_AUDIT_DATA_INIT(&ad, INODE);
2647 ad.u.fs.inode = inode; 2677 ad.u.inode = inode;
2648 2678
2649 if (from_access) 2679 if (from_access)
2650 ad.selinux_audit_data.auditdeny |= FILE__AUDIT_ACCESS; 2680 ad.selinux_audit_data.auditdeny |= FILE__AUDIT_ACCESS;
2651 2681
2652 perms = file_mask_to_av(inode->i_mode, mask); 2682 perms = file_mask_to_av(inode->i_mode, mask);
2653 2683
2654 return inode_has_perm(cred, inode, perms, &ad); 2684 return inode_has_perm(cred, inode, perms, &ad, flags);
2655} 2685}
2656 2686
2657static int selinux_inode_setattr(struct dentry *dentry, struct iattr *iattr) 2687static int selinux_inode_setattr(struct dentry *dentry, struct iattr *iattr)
@@ -2669,16 +2699,20 @@ static int selinux_inode_setattr(struct dentry *dentry, struct iattr *iattr)
2669 2699
2670 if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID | 2700 if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID |
2671 ATTR_ATIME_SET | ATTR_MTIME_SET | ATTR_TIMES_SET)) 2701 ATTR_ATIME_SET | ATTR_MTIME_SET | ATTR_TIMES_SET))
2672 return dentry_has_perm(cred, NULL, dentry, FILE__SETATTR); 2702 return dentry_has_perm(cred, dentry, FILE__SETATTR);
2673 2703
2674 return dentry_has_perm(cred, NULL, dentry, FILE__WRITE); 2704 return dentry_has_perm(cred, dentry, FILE__WRITE);
2675} 2705}
2676 2706
2677static int selinux_inode_getattr(struct vfsmount *mnt, struct dentry *dentry) 2707static int selinux_inode_getattr(struct vfsmount *mnt, struct dentry *dentry)
2678{ 2708{
2679 const struct cred *cred = current_cred(); 2709 const struct cred *cred = current_cred();
2710 struct path path;
2711
2712 path.dentry = dentry;
2713 path.mnt = mnt;
2680 2714
2681 return dentry_has_perm(cred, mnt, dentry, FILE__GETATTR); 2715 return path_has_perm(cred, &path, FILE__GETATTR);
2682} 2716}
2683 2717
2684static int selinux_inode_setotherxattr(struct dentry *dentry, const char *name) 2718static int selinux_inode_setotherxattr(struct dentry *dentry, const char *name)
@@ -2699,7 +2733,7 @@ static int selinux_inode_setotherxattr(struct dentry *dentry, const char *name)
2699 2733
2700 /* Not an attribute we recognize, so just check the 2734 /* Not an attribute we recognize, so just check the
2701 ordinary setattr permission. */ 2735 ordinary setattr permission. */
2702 return dentry_has_perm(cred, NULL, dentry, FILE__SETATTR); 2736 return dentry_has_perm(cred, dentry, FILE__SETATTR);
2703} 2737}
2704 2738
2705static int selinux_inode_setxattr(struct dentry *dentry, const char *name, 2739static int selinux_inode_setxattr(struct dentry *dentry, const char *name,
@@ -2719,11 +2753,11 @@ static int selinux_inode_setxattr(struct dentry *dentry, const char *name,
2719 if (!(sbsec->flags & SE_SBLABELSUPP)) 2753 if (!(sbsec->flags & SE_SBLABELSUPP))
2720 return -EOPNOTSUPP; 2754 return -EOPNOTSUPP;
2721 2755
2722 if (!is_owner_or_cap(inode)) 2756 if (!inode_owner_or_capable(inode))
2723 return -EPERM; 2757 return -EPERM;
2724 2758
2725 COMMON_AUDIT_DATA_INIT(&ad, FS); 2759 COMMON_AUDIT_DATA_INIT(&ad, DENTRY);
2726 ad.u.fs.path.dentry = dentry; 2760 ad.u.dentry = dentry;
2727 2761
2728 rc = avc_has_perm(sid, isec->sid, isec->sclass, 2762 rc = avc_has_perm(sid, isec->sid, isec->sclass,
2729 FILE__RELABELFROM, &ad); 2763 FILE__RELABELFROM, &ad);
@@ -2786,14 +2820,14 @@ static int selinux_inode_getxattr(struct dentry *dentry, const char *name)
2786{ 2820{
2787 const struct cred *cred = current_cred(); 2821 const struct cred *cred = current_cred();
2788 2822
2789 return dentry_has_perm(cred, NULL, dentry, FILE__GETATTR); 2823 return dentry_has_perm(cred, dentry, FILE__GETATTR);
2790} 2824}
2791 2825
2792static int selinux_inode_listxattr(struct dentry *dentry) 2826static int selinux_inode_listxattr(struct dentry *dentry)
2793{ 2827{
2794 const struct cred *cred = current_cred(); 2828 const struct cred *cred = current_cred();
2795 2829
2796 return dentry_has_perm(cred, NULL, dentry, FILE__GETATTR); 2830 return dentry_has_perm(cred, dentry, FILE__GETATTR);
2797} 2831}
2798 2832
2799static int selinux_inode_removexattr(struct dentry *dentry, const char *name) 2833static int selinux_inode_removexattr(struct dentry *dentry, const char *name)
@@ -2830,7 +2864,8 @@ static int selinux_inode_getsecurity(const struct inode *inode, const char *name
2830 * and lack of permission just means that we fall back to the 2864 * and lack of permission just means that we fall back to the
2831 * in-core context value, not a denial. 2865 * in-core context value, not a denial.
2832 */ 2866 */
2833 error = selinux_capable(current, current_cred(), CAP_MAC_ADMIN, 2867 error = selinux_capable(current, current_cred(),
2868 &init_user_ns, CAP_MAC_ADMIN,
2834 SECURITY_CAP_NOAUDIT); 2869 SECURITY_CAP_NOAUDIT);
2835 if (!error) 2870 if (!error)
2836 error = security_sid_to_context_force(isec->sid, &context, 2871 error = security_sid_to_context_force(isec->sid, &context,
@@ -2933,16 +2968,47 @@ static int selinux_file_ioctl(struct file *file, unsigned int cmd,
2933 unsigned long arg) 2968 unsigned long arg)
2934{ 2969{
2935 const struct cred *cred = current_cred(); 2970 const struct cred *cred = current_cred();
2936 u32 av = 0; 2971 int error = 0;
2937 2972
2938 if (_IOC_DIR(cmd) & _IOC_WRITE) 2973 switch (cmd) {
2939 av |= FILE__WRITE; 2974 case FIONREAD:
2940 if (_IOC_DIR(cmd) & _IOC_READ) 2975 /* fall through */
2941 av |= FILE__READ; 2976 case FIBMAP:
2942 if (!av) 2977 /* fall through */
2943 av = FILE__IOCTL; 2978 case FIGETBSZ:
2979 /* fall through */
2980 case EXT2_IOC_GETFLAGS:
2981 /* fall through */
2982 case EXT2_IOC_GETVERSION:
2983 error = file_has_perm(cred, file, FILE__GETATTR);
2984 break;
2944 2985
2945 return file_has_perm(cred, file, av); 2986 case EXT2_IOC_SETFLAGS:
2987 /* fall through */
2988 case EXT2_IOC_SETVERSION:
2989 error = file_has_perm(cred, file, FILE__SETATTR);
2990 break;
2991
2992 /* sys_ioctl() checks */
2993 case FIONBIO:
2994 /* fall through */
2995 case FIOASYNC:
2996 error = file_has_perm(cred, file, 0);
2997 break;
2998
2999 case KDSKBENT:
3000 case KDSKBSENT:
3001 error = task_has_capability(current, cred, CAP_SYS_TTY_CONFIG,
3002 SECURITY_CAP_AUDIT);
3003 break;
3004
3005 /* default case assumes that the command will go
3006 * to the file's ioctl() function.
3007 */
3008 default:
3009 error = file_has_perm(cred, file, FILE__IOCTL);
3010 }
3011 return error;
2946} 3012}
2947 3013
2948static int default_noexec; 3014static int default_noexec;
@@ -3167,7 +3233,7 @@ static int selinux_dentry_open(struct file *file, const struct cred *cred)
3167 * new inode label or new policy. 3233 * new inode label or new policy.
3168 * This check is not redundant - do not remove. 3234 * This check is not redundant - do not remove.
3169 */ 3235 */
3170 return inode_has_perm(cred, inode, open_file_to_av(file), NULL); 3236 return inode_has_perm_noadp(cred, inode, open_file_to_av(file), 0);
3171} 3237}
3172 3238
3173/* task security operations */ 3239/* task security operations */
@@ -3199,7 +3265,11 @@ static void selinux_cred_free(struct cred *cred)
3199{ 3265{
3200 struct task_security_struct *tsec = cred->security; 3266 struct task_security_struct *tsec = cred->security;
3201 3267
3202 BUG_ON((unsigned long) cred->security < PAGE_SIZE); 3268 /*
3269 * cred->security == NULL if security_cred_alloc_blank() or
3270 * security_prepare_creds() returned an error.
3271 */
3272 BUG_ON(cred->security && (unsigned long) cred->security < PAGE_SIZE);
3203 cred->security = (void *) 0x7UL; 3273 cred->security = (void *) 0x7UL;
3204 kfree(tsec); 3274 kfree(tsec);
3205} 3275}
@@ -3354,11 +3424,11 @@ static int selinux_task_setrlimit(struct task_struct *p, unsigned int resource,
3354 return 0; 3424 return 0;
3355} 3425}
3356 3426
3357static int selinux_task_setscheduler(struct task_struct *p, int policy, struct sched_param *lp) 3427static int selinux_task_setscheduler(struct task_struct *p)
3358{ 3428{
3359 int rc; 3429 int rc;
3360 3430
3361 rc = cap_task_setscheduler(p, policy, lp); 3431 rc = cap_task_setscheduler(p);
3362 if (rc) 3432 if (rc)
3363 return rc; 3433 return rc;
3364 3434
@@ -3641,9 +3711,16 @@ static int selinux_skb_peerlbl_sid(struct sk_buff *skb, u16 family, u32 *sid)
3641 3711
3642/* socket security operations */ 3712/* socket security operations */
3643 3713
3644static u32 socket_sockcreate_sid(const struct task_security_struct *tsec) 3714static int socket_sockcreate_sid(const struct task_security_struct *tsec,
3715 u16 secclass, u32 *socksid)
3645{ 3716{
3646 return tsec->sockcreate_sid ? : tsec->sid; 3717 if (tsec->sockcreate_sid > SECSID_NULL) {
3718 *socksid = tsec->sockcreate_sid;
3719 return 0;
3720 }
3721
3722 return security_transition_sid(tsec->sid, tsec->sid, secclass, NULL,
3723 socksid);
3647} 3724}
3648 3725
3649static int sock_has_perm(struct task_struct *task, struct sock *sk, u32 perms) 3726static int sock_has_perm(struct task_struct *task, struct sock *sk, u32 perms)
@@ -3667,12 +3744,16 @@ static int selinux_socket_create(int family, int type,
3667 const struct task_security_struct *tsec = current_security(); 3744 const struct task_security_struct *tsec = current_security();
3668 u32 newsid; 3745 u32 newsid;
3669 u16 secclass; 3746 u16 secclass;
3747 int rc;
3670 3748
3671 if (kern) 3749 if (kern)
3672 return 0; 3750 return 0;
3673 3751
3674 newsid = socket_sockcreate_sid(tsec);
3675 secclass = socket_type_to_security_class(family, type, protocol); 3752 secclass = socket_type_to_security_class(family, type, protocol);
3753 rc = socket_sockcreate_sid(tsec, secclass, &newsid);
3754 if (rc)
3755 return rc;
3756
3676 return avc_has_perm(tsec->sid, newsid, secclass, SOCKET__CREATE, NULL); 3757 return avc_has_perm(tsec->sid, newsid, secclass, SOCKET__CREATE, NULL);
3677} 3758}
3678 3759
@@ -3684,12 +3765,16 @@ static int selinux_socket_post_create(struct socket *sock, int family,
3684 struct sk_security_struct *sksec; 3765 struct sk_security_struct *sksec;
3685 int err = 0; 3766 int err = 0;
3686 3767
3768 isec->sclass = socket_type_to_security_class(family, type, protocol);
3769
3687 if (kern) 3770 if (kern)
3688 isec->sid = SECINITSID_KERNEL; 3771 isec->sid = SECINITSID_KERNEL;
3689 else 3772 else {
3690 isec->sid = socket_sockcreate_sid(tsec); 3773 err = socket_sockcreate_sid(tsec, isec->sclass, &(isec->sid));
3774 if (err)
3775 return err;
3776 }
3691 3777
3692 isec->sclass = socket_type_to_security_class(family, type, protocol);
3693 isec->initialized = 1; 3778 isec->initialized = 1;
3694 3779
3695 if (sock->sk) { 3780 if (sock->sk) {
@@ -3925,18 +4010,18 @@ static int selinux_socket_shutdown(struct socket *sock, int how)
3925 return sock_has_perm(current, sock->sk, SOCKET__SHUTDOWN); 4010 return sock_has_perm(current, sock->sk, SOCKET__SHUTDOWN);
3926} 4011}
3927 4012
3928static int selinux_socket_unix_stream_connect(struct socket *sock, 4013static int selinux_socket_unix_stream_connect(struct sock *sock,
3929 struct socket *other, 4014 struct sock *other,
3930 struct sock *newsk) 4015 struct sock *newsk)
3931{ 4016{
3932 struct sk_security_struct *sksec_sock = sock->sk->sk_security; 4017 struct sk_security_struct *sksec_sock = sock->sk_security;
3933 struct sk_security_struct *sksec_other = other->sk->sk_security; 4018 struct sk_security_struct *sksec_other = other->sk_security;
3934 struct sk_security_struct *sksec_new = newsk->sk_security; 4019 struct sk_security_struct *sksec_new = newsk->sk_security;
3935 struct common_audit_data ad; 4020 struct common_audit_data ad;
3936 int err; 4021 int err;
3937 4022
3938 COMMON_AUDIT_DATA_INIT(&ad, NET); 4023 COMMON_AUDIT_DATA_INIT(&ad, NET);
3939 ad.u.net.sk = other->sk; 4024 ad.u.net.sk = other;
3940 4025
3941 err = avc_has_perm(sksec_sock->sid, sksec_other->sid, 4026 err = avc_has_perm(sksec_sock->sid, sksec_other->sid,
3942 sksec_other->sclass, 4027 sksec_other->sclass,
@@ -3999,7 +4084,6 @@ static int selinux_sock_rcv_skb_compat(struct sock *sk, struct sk_buff *skb,
3999{ 4084{
4000 int err = 0; 4085 int err = 0;
4001 struct sk_security_struct *sksec = sk->sk_security; 4086 struct sk_security_struct *sksec = sk->sk_security;
4002 u32 peer_sid;
4003 u32 sk_sid = sksec->sid; 4087 u32 sk_sid = sksec->sid;
4004 struct common_audit_data ad; 4088 struct common_audit_data ad;
4005 char *addrp; 4089 char *addrp;
@@ -4018,20 +4102,10 @@ static int selinux_sock_rcv_skb_compat(struct sock *sk, struct sk_buff *skb,
4018 return err; 4102 return err;
4019 } 4103 }
4020 4104
4021 if (selinux_policycap_netpeer) { 4105 err = selinux_netlbl_sock_rcv_skb(sksec, skb, family, &ad);
4022 err = selinux_skb_peerlbl_sid(skb, family, &peer_sid); 4106 if (err)
4023 if (err) 4107 return err;
4024 return err; 4108 err = selinux_xfrm_sock_rcv_skb(sksec->sid, skb, &ad);
4025 err = avc_has_perm(sk_sid, peer_sid,
4026 SECCLASS_PEER, PEER__RECV, &ad);
4027 if (err)
4028 selinux_netlbl_err(skb, err, 0);
4029 } else {
4030 err = selinux_netlbl_sock_rcv_skb(sksec, skb, family, &ad);
4031 if (err)
4032 return err;
4033 err = selinux_xfrm_sock_rcv_skb(sksec->sid, skb, &ad);
4034 }
4035 4109
4036 return err; 4110 return err;
4037} 4111}
@@ -4279,10 +4353,31 @@ static void selinux_inet_conn_established(struct sock *sk, struct sk_buff *skb)
4279 selinux_skb_peerlbl_sid(skb, family, &sksec->peer_sid); 4353 selinux_skb_peerlbl_sid(skb, family, &sksec->peer_sid);
4280} 4354}
4281 4355
4356static int selinux_secmark_relabel_packet(u32 sid)
4357{
4358 const struct task_security_struct *__tsec;
4359 u32 tsid;
4360
4361 __tsec = current_security();
4362 tsid = __tsec->sid;
4363
4364 return avc_has_perm(tsid, sid, SECCLASS_PACKET, PACKET__RELABELTO, NULL);
4365}
4366
4367static void selinux_secmark_refcount_inc(void)
4368{
4369 atomic_inc(&selinux_secmark_refcount);
4370}
4371
4372static void selinux_secmark_refcount_dec(void)
4373{
4374 atomic_dec(&selinux_secmark_refcount);
4375}
4376
4282static void selinux_req_classify_flow(const struct request_sock *req, 4377static void selinux_req_classify_flow(const struct request_sock *req,
4283 struct flowi *fl) 4378 struct flowi *fl)
4284{ 4379{
4285 fl->secid = req->secid; 4380 fl->flowi_secid = req->secid;
4286} 4381}
4287 4382
4288static int selinux_tun_dev_create(void) 4383static int selinux_tun_dev_create(void)
@@ -4503,11 +4598,10 @@ static unsigned int selinux_ip_postroute_compat(struct sk_buff *skb,
4503 if (selinux_secmark_enabled()) 4598 if (selinux_secmark_enabled())
4504 if (avc_has_perm(sksec->sid, skb->secmark, 4599 if (avc_has_perm(sksec->sid, skb->secmark,
4505 SECCLASS_PACKET, PACKET__SEND, &ad)) 4600 SECCLASS_PACKET, PACKET__SEND, &ad))
4506 return NF_DROP; 4601 return NF_DROP_ERR(-ECONNREFUSED);
4507 4602
4508 if (selinux_policycap_netpeer) 4603 if (selinux_xfrm_postroute_last(sksec->sid, skb, &ad, proto))
4509 if (selinux_xfrm_postroute_last(sksec->sid, skb, &ad, proto)) 4604 return NF_DROP_ERR(-ECONNREFUSED);
4510 return NF_DROP;
4511 4605
4512 return NF_ACCEPT; 4606 return NF_ACCEPT;
4513} 4607}
@@ -4550,27 +4644,14 @@ static unsigned int selinux_ip_postroute(struct sk_buff *skb, int ifindex,
4550 * from the sending socket, otherwise use the kernel's sid */ 4644 * from the sending socket, otherwise use the kernel's sid */
4551 sk = skb->sk; 4645 sk = skb->sk;
4552 if (sk == NULL) { 4646 if (sk == NULL) {
4553 switch (family) { 4647 if (skb->skb_iif) {
4554 case PF_INET: 4648 secmark_perm = PACKET__FORWARD_OUT;
4555 if (IPCB(skb)->flags & IPSKB_FORWARDED)
4556 secmark_perm = PACKET__FORWARD_OUT;
4557 else
4558 secmark_perm = PACKET__SEND;
4559 break;
4560 case PF_INET6:
4561 if (IP6CB(skb)->flags & IP6SKB_FORWARDED)
4562 secmark_perm = PACKET__FORWARD_OUT;
4563 else
4564 secmark_perm = PACKET__SEND;
4565 break;
4566 default:
4567 return NF_DROP;
4568 }
4569 if (secmark_perm == PACKET__FORWARD_OUT) {
4570 if (selinux_skb_peerlbl_sid(skb, family, &peer_sid)) 4649 if (selinux_skb_peerlbl_sid(skb, family, &peer_sid))
4571 return NF_DROP; 4650 return NF_DROP;
4572 } else 4651 } else {
4652 secmark_perm = PACKET__SEND;
4573 peer_sid = SECINITSID_KERNEL; 4653 peer_sid = SECINITSID_KERNEL;
4654 }
4574 } else { 4655 } else {
4575 struct sk_security_struct *sksec = sk->sk_security; 4656 struct sk_security_struct *sksec = sk->sk_security;
4576 peer_sid = sksec->sid; 4657 peer_sid = sksec->sid;
@@ -4586,7 +4667,7 @@ static unsigned int selinux_ip_postroute(struct sk_buff *skb, int ifindex,
4586 if (secmark_active) 4667 if (secmark_active)
4587 if (avc_has_perm(peer_sid, skb->secmark, 4668 if (avc_has_perm(peer_sid, skb->secmark,
4588 SECCLASS_PACKET, secmark_perm, &ad)) 4669 SECCLASS_PACKET, secmark_perm, &ad))
4589 return NF_DROP; 4670 return NF_DROP_ERR(-ECONNREFUSED);
4590 4671
4591 if (peerlbl_active) { 4672 if (peerlbl_active) {
4592 u32 if_sid; 4673 u32 if_sid;
@@ -4596,13 +4677,13 @@ static unsigned int selinux_ip_postroute(struct sk_buff *skb, int ifindex,
4596 return NF_DROP; 4677 return NF_DROP;
4597 if (avc_has_perm(peer_sid, if_sid, 4678 if (avc_has_perm(peer_sid, if_sid,
4598 SECCLASS_NETIF, NETIF__EGRESS, &ad)) 4679 SECCLASS_NETIF, NETIF__EGRESS, &ad))
4599 return NF_DROP; 4680 return NF_DROP_ERR(-ECONNREFUSED);
4600 4681
4601 if (sel_netnode_sid(addrp, family, &node_sid)) 4682 if (sel_netnode_sid(addrp, family, &node_sid))
4602 return NF_DROP; 4683 return NF_DROP;
4603 if (avc_has_perm(peer_sid, node_sid, 4684 if (avc_has_perm(peer_sid, node_sid,
4604 SECCLASS_NODE, NODE__SENDTO, &ad)) 4685 SECCLASS_NODE, NODE__SENDTO, &ad))
4605 return NF_DROP; 4686 return NF_DROP_ERR(-ECONNREFUSED);
4606 } 4687 }
4607 4688
4608 return NF_ACCEPT; 4689 return NF_ACCEPT;
@@ -4645,6 +4726,7 @@ static int selinux_netlink_recv(struct sk_buff *skb, int capability)
4645{ 4726{
4646 int err; 4727 int err;
4647 struct common_audit_data ad; 4728 struct common_audit_data ad;
4729 u32 sid;
4648 4730
4649 err = cap_netlink_recv(skb, capability); 4731 err = cap_netlink_recv(skb, capability);
4650 if (err) 4732 if (err)
@@ -4653,8 +4735,9 @@ static int selinux_netlink_recv(struct sk_buff *skb, int capability)
4653 COMMON_AUDIT_DATA_INIT(&ad, CAP); 4735 COMMON_AUDIT_DATA_INIT(&ad, CAP);
4654 ad.u.cap = capability; 4736 ad.u.cap = capability;
4655 4737
4656 return avc_has_perm(NETLINK_CB(skb).sid, NETLINK_CB(skb).sid, 4738 security_task_getsecid(current, &sid);
4657 SECCLASS_CAPABILITY, CAP_TO_MASK(capability), &ad); 4739 return avc_has_perm(sid, sid, SECCLASS_CAPABILITY,
4740 CAP_TO_MASK(capability), &ad);
4658} 4741}
4659 4742
4660static int ipc_alloc_security(struct task_struct *task, 4743static int ipc_alloc_security(struct task_struct *task,
@@ -4824,7 +4907,7 @@ static int selinux_msg_queue_msgsnd(struct msg_queue *msq, struct msg_msg *msg,
4824 * message queue this message will be stored in 4907 * message queue this message will be stored in
4825 */ 4908 */
4826 rc = security_transition_sid(sid, isec->sid, SECCLASS_MSG, 4909 rc = security_transition_sid(sid, isec->sid, SECCLASS_MSG,
4827 &msec->sid); 4910 NULL, &msec->sid);
4828 if (rc) 4911 if (rc)
4829 return rc; 4912 return rc;
4830 } 4913 }
@@ -5378,7 +5461,6 @@ static struct security_operations selinux_ops = {
5378 .ptrace_traceme = selinux_ptrace_traceme, 5461 .ptrace_traceme = selinux_ptrace_traceme,
5379 .capget = selinux_capget, 5462 .capget = selinux_capget,
5380 .capset = selinux_capset, 5463 .capset = selinux_capset,
5381 .sysctl = selinux_sysctl,
5382 .capable = selinux_capable, 5464 .capable = selinux_capable,
5383 .quotactl = selinux_quotactl, 5465 .quotactl = selinux_quotactl,
5384 .quota_on = selinux_quota_on, 5466 .quota_on = selinux_quota_on,
@@ -5396,6 +5478,7 @@ static struct security_operations selinux_ops = {
5396 .sb_alloc_security = selinux_sb_alloc_security, 5478 .sb_alloc_security = selinux_sb_alloc_security,
5397 .sb_free_security = selinux_sb_free_security, 5479 .sb_free_security = selinux_sb_free_security,
5398 .sb_copy_data = selinux_sb_copy_data, 5480 .sb_copy_data = selinux_sb_copy_data,
5481 .sb_remount = selinux_sb_remount,
5399 .sb_kern_mount = selinux_sb_kern_mount, 5482 .sb_kern_mount = selinux_sb_kern_mount,
5400 .sb_show_options = selinux_sb_show_options, 5483 .sb_show_options = selinux_sb_show_options,
5401 .sb_statfs = selinux_sb_statfs, 5484 .sb_statfs = selinux_sb_statfs,
@@ -5533,6 +5616,9 @@ static struct security_operations selinux_ops = {
5533 .inet_conn_request = selinux_inet_conn_request, 5616 .inet_conn_request = selinux_inet_conn_request,
5534 .inet_csk_clone = selinux_inet_csk_clone, 5617 .inet_csk_clone = selinux_inet_csk_clone,
5535 .inet_conn_established = selinux_inet_conn_established, 5618 .inet_conn_established = selinux_inet_conn_established,
5619 .secmark_relabel_packet = selinux_secmark_relabel_packet,
5620 .secmark_refcount_inc = selinux_secmark_refcount_inc,
5621 .secmark_refcount_dec = selinux_secmark_refcount_dec,
5536 .req_classify_flow = selinux_req_classify_flow, 5622 .req_classify_flow = selinux_req_classify_flow,
5537 .tun_dev_create = selinux_tun_dev_create, 5623 .tun_dev_create = selinux_tun_dev_create,
5538 .tun_dev_post_create = selinux_tun_dev_post_create, 5624 .tun_dev_post_create = selinux_tun_dev_post_create,
diff --git a/security/selinux/include/avc.h b/security/selinux/include/avc.h
index e94e82f73818..47fda963495d 100644
--- a/security/selinux/include/avc.h
+++ b/security/selinux/include/avc.h
@@ -15,7 +15,6 @@
15#include <linux/audit.h> 15#include <linux/audit.h>
16#include <linux/lsm_audit.h> 16#include <linux/lsm_audit.h>
17#include <linux/in6.h> 17#include <linux/in6.h>
18#include <linux/path.h>
19#include <asm/system.h> 18#include <asm/system.h>
20#include "flask.h" 19#include "flask.h"
21#include "av_permissions.h" 20#include "av_permissions.h"
@@ -42,7 +41,6 @@ struct sk_buff;
42 */ 41 */
43struct avc_cache_stats { 42struct avc_cache_stats {
44 unsigned int lookups; 43 unsigned int lookups;
45 unsigned int hits;
46 unsigned int misses; 44 unsigned int misses;
47 unsigned int allocations; 45 unsigned int allocations;
48 unsigned int reclaims; 46 unsigned int reclaims;
@@ -55,11 +53,11 @@ struct avc_cache_stats {
55 53
56void __init avc_init(void); 54void __init avc_init(void);
57 55
58void avc_audit(u32 ssid, u32 tsid, 56int avc_audit(u32 ssid, u32 tsid,
59 u16 tclass, u32 requested, 57 u16 tclass, u32 requested,
60 struct av_decision *avd, 58 struct av_decision *avd,
61 int result, 59 int result,
62 struct common_audit_data *a); 60 struct common_audit_data *a, unsigned flags);
63 61
64#define AVC_STRICT 1 /* Ignore permissive mode. */ 62#define AVC_STRICT 1 /* Ignore permissive mode. */
65int avc_has_perm_noaudit(u32 ssid, u32 tsid, 63int avc_has_perm_noaudit(u32 ssid, u32 tsid,
@@ -67,9 +65,17 @@ int avc_has_perm_noaudit(u32 ssid, u32 tsid,
67 unsigned flags, 65 unsigned flags,
68 struct av_decision *avd); 66 struct av_decision *avd);
69 67
70int avc_has_perm(u32 ssid, u32 tsid, 68int avc_has_perm_flags(u32 ssid, u32 tsid,
71 u16 tclass, u32 requested, 69 u16 tclass, u32 requested,
72 struct common_audit_data *auditdata); 70 struct common_audit_data *auditdata,
71 unsigned);
72
73static inline int avc_has_perm(u32 ssid, u32 tsid,
74 u16 tclass, u32 requested,
75 struct common_audit_data *auditdata)
76{
77 return avc_has_perm_flags(ssid, tsid, tclass, requested, auditdata, 0);
78}
73 79
74u32 avc_policy_seqno(void); 80u32 avc_policy_seqno(void);
75 81
diff --git a/security/selinux/include/classmap.h b/security/selinux/include/classmap.h
index b4c9eb4bd6f9..b8c53723e09b 100644
--- a/security/selinux/include/classmap.h
+++ b/security/selinux/include/classmap.h
@@ -12,12 +12,16 @@
12#define COMMON_IPC_PERMS "create", "destroy", "getattr", "setattr", "read", \ 12#define COMMON_IPC_PERMS "create", "destroy", "getattr", "setattr", "read", \
13 "write", "associate", "unix_read", "unix_write" 13 "write", "associate", "unix_read", "unix_write"
14 14
15/*
16 * Note: The name for any socket class should be suffixed by "socket",
17 * and doesn't contain more than one substr of "socket".
18 */
15struct security_class_mapping secclass_map[] = { 19struct security_class_mapping secclass_map[] = {
16 { "security", 20 { "security",
17 { "compute_av", "compute_create", "compute_member", 21 { "compute_av", "compute_create", "compute_member",
18 "check_context", "load_policy", "compute_relabel", 22 "check_context", "load_policy", "compute_relabel",
19 "compute_user", "setenforce", "setbool", "setsecparam", 23 "compute_user", "setenforce", "setbool", "setsecparam",
20 "setcheckreqprot", NULL } }, 24 "setcheckreqprot", "read_policy", NULL } },
21 { "process", 25 { "process",
22 { "fork", "transition", "sigchld", "sigkill", 26 { "fork", "transition", "sigchld", "sigkill",
23 "sigstop", "signull", "signal", "ptrace", "getsched", "setsched", 27 "sigstop", "signull", "signal", "ptrace", "getsched", "setsched",
@@ -132,8 +136,7 @@ struct security_class_mapping secclass_map[] = {
132 { "appletalk_socket", 136 { "appletalk_socket",
133 { COMMON_SOCK_PERMS, NULL } }, 137 { COMMON_SOCK_PERMS, NULL } },
134 { "packet", 138 { "packet",
135 { "send", "recv", "relabelto", "flow_in", "flow_out", 139 { "send", "recv", "relabelto", "forward_in", "forward_out", NULL } },
136 "forward_in", "forward_out", NULL } },
137 { "key", 140 { "key",
138 { "view", "read", "write", "search", "link", "setattr", "create", 141 { "view", "read", "write", "search", "link", "setattr", "create",
139 NULL } }, 142 NULL } },
@@ -142,7 +145,7 @@ struct security_class_mapping secclass_map[] = {
142 "node_bind", "name_connect", NULL } }, 145 "node_bind", "name_connect", NULL } },
143 { "memprotect", { "mmap_zero", NULL } }, 146 { "memprotect", { "mmap_zero", NULL } },
144 { "peer", { "recv", NULL } }, 147 { "peer", { "recv", NULL } },
145 { "capability2", { "mac_override", "mac_admin", NULL } }, 148 { "capability2", { "mac_override", "mac_admin", "syslog", NULL } },
146 { "kernel_service", { "use_as_override", "create_files_as", NULL } }, 149 { "kernel_service", { "use_as_override", "create_files_as", NULL } },
147 { "tun_socket", 150 { "tun_socket",
148 { COMMON_SOCK_PERMS, NULL } }, 151 { COMMON_SOCK_PERMS, NULL } },
diff --git a/security/selinux/include/security.h b/security/selinux/include/security.h
index 1f7c2491d3dc..3ba4feba048a 100644
--- a/security/selinux/include/security.h
+++ b/security/selinux/include/security.h
@@ -8,7 +8,9 @@
8#ifndef _SELINUX_SECURITY_H_ 8#ifndef _SELINUX_SECURITY_H_
9#define _SELINUX_SECURITY_H_ 9#define _SELINUX_SECURITY_H_
10 10
11#include <linux/dcache.h>
11#include <linux/magic.h> 12#include <linux/magic.h>
13#include <linux/types.h>
12#include "flask.h" 14#include "flask.h"
13 15
14#define SECSID_NULL 0x00000000 /* unspecified SID */ 16#define SECSID_NULL 0x00000000 /* unspecified SID */
@@ -27,13 +29,15 @@
27#define POLICYDB_VERSION_POLCAP 22 29#define POLICYDB_VERSION_POLCAP 22
28#define POLICYDB_VERSION_PERMISSIVE 23 30#define POLICYDB_VERSION_PERMISSIVE 23
29#define POLICYDB_VERSION_BOUNDARY 24 31#define POLICYDB_VERSION_BOUNDARY 24
32#define POLICYDB_VERSION_FILENAME_TRANS 25
33#define POLICYDB_VERSION_ROLETRANS 26
30 34
31/* Range of policy versions we understand*/ 35/* Range of policy versions we understand*/
32#define POLICYDB_VERSION_MIN POLICYDB_VERSION_BASE 36#define POLICYDB_VERSION_MIN POLICYDB_VERSION_BASE
33#ifdef CONFIG_SECURITY_SELINUX_POLICYDB_VERSION_MAX 37#ifdef CONFIG_SECURITY_SELINUX_POLICYDB_VERSION_MAX
34#define POLICYDB_VERSION_MAX CONFIG_SECURITY_SELINUX_POLICYDB_VERSION_MAX_VALUE 38#define POLICYDB_VERSION_MAX CONFIG_SECURITY_SELINUX_POLICYDB_VERSION_MAX_VALUE
35#else 39#else
36#define POLICYDB_VERSION_MAX POLICYDB_VERSION_BOUNDARY 40#define POLICYDB_VERSION_MAX POLICYDB_VERSION_ROLETRANS
37#endif 41#endif
38 42
39/* Mask for just the mount related flags */ 43/* Mask for just the mount related flags */
@@ -82,6 +86,8 @@ extern int selinux_policycap_openperm;
82int security_mls_enabled(void); 86int security_mls_enabled(void);
83 87
84int security_load_policy(void *data, size_t len); 88int security_load_policy(void *data, size_t len);
89int security_read_policy(void **data, size_t *len);
90size_t security_policydb_len(void);
85 91
86int security_policycap_supported(unsigned int req_cap); 92int security_policycap_supported(unsigned int req_cap);
87 93
@@ -103,11 +109,11 @@ void security_compute_av(u32 ssid, u32 tsid,
103void security_compute_av_user(u32 ssid, u32 tsid, 109void security_compute_av_user(u32 ssid, u32 tsid,
104 u16 tclass, struct av_decision *avd); 110 u16 tclass, struct av_decision *avd);
105 111
106int security_transition_sid(u32 ssid, u32 tsid, 112int security_transition_sid(u32 ssid, u32 tsid, u16 tclass,
107 u16 tclass, u32 *out_sid); 113 const struct qstr *qstr, u32 *out_sid);
108 114
109int security_transition_sid_user(u32 ssid, u32 tsid, 115int security_transition_sid_user(u32 ssid, u32 tsid, u16 tclass,
110 u16 tclass, u32 *out_sid); 116 const char *objname, u32 *out_sid);
111 117
112int security_member_sid(u32 ssid, u32 tsid, 118int security_member_sid(u32 ssid, u32 tsid,
113 u16 tclass, u32 *out_sid); 119 u16 tclass, u32 *out_sid);
@@ -191,5 +197,25 @@ static inline int security_netlbl_sid_to_secattr(u32 sid,
191 197
192const char *security_get_initial_sid_context(u32 sid); 198const char *security_get_initial_sid_context(u32 sid);
193 199
200/*
201 * status notifier using mmap interface
202 */
203extern struct page *selinux_kernel_status_page(void);
204
205#define SELINUX_KERNEL_STATUS_VERSION 1
206struct selinux_kernel_status {
207 u32 version; /* version number of thie structure */
208 u32 sequence; /* sequence number of seqlock logic */
209 u32 enforcing; /* current setting of enforcing mode */
210 u32 policyload; /* times of policy reloaded */
211 u32 deny_unknown; /* current setting of deny_unknown */
212 /*
213 * The version > 0 supports above members.
214 */
215} __attribute__((packed));
216
217extern void selinux_status_update_setenforce(int enforcing);
218extern void selinux_status_update_policyload(int seqno);
219
194#endif /* _SELINUX_SECURITY_H_ */ 220#endif /* _SELINUX_SECURITY_H_ */
195 221
diff --git a/security/selinux/include/xfrm.h b/security/selinux/include/xfrm.h
index 13128f9a3e5a..b43813c9e049 100644
--- a/security/selinux/include/xfrm.h
+++ b/security/selinux/include/xfrm.h
@@ -19,7 +19,7 @@ void selinux_xfrm_state_free(struct xfrm_state *x);
19int selinux_xfrm_state_delete(struct xfrm_state *x); 19int selinux_xfrm_state_delete(struct xfrm_state *x);
20int selinux_xfrm_policy_lookup(struct xfrm_sec_ctx *ctx, u32 fl_secid, u8 dir); 20int selinux_xfrm_policy_lookup(struct xfrm_sec_ctx *ctx, u32 fl_secid, u8 dir);
21int selinux_xfrm_state_pol_flow_match(struct xfrm_state *x, 21int selinux_xfrm_state_pol_flow_match(struct xfrm_state *x,
22 struct xfrm_policy *xp, struct flowi *fl); 22 struct xfrm_policy *xp, const struct flowi *fl);
23 23
24/* 24/*
25 * Extract the security blob from the sock (it's actually on the socket) 25 * Extract the security blob from the sock (it's actually on the socket)
diff --git a/security/selinux/netif.c b/security/selinux/netif.c
index d6095d63d831..58cc481c93d5 100644
--- a/security/selinux/netif.c
+++ b/security/selinux/netif.c
@@ -104,22 +104,6 @@ static int sel_netif_insert(struct sel_netif *netif)
104} 104}
105 105
106/** 106/**
107 * sel_netif_free - Frees an interface entry
108 * @p: the entry's RCU field
109 *
110 * Description:
111 * This function is designed to be used as a callback to the call_rcu()
112 * function so that memory allocated to a hash table interface entry can be
113 * released safely.
114 *
115 */
116static void sel_netif_free(struct rcu_head *p)
117{
118 struct sel_netif *netif = container_of(p, struct sel_netif, rcu_head);
119 kfree(netif);
120}
121
122/**
123 * sel_netif_destroy - Remove an interface record from the table 107 * sel_netif_destroy - Remove an interface record from the table
124 * @netif: the existing interface record 108 * @netif: the existing interface record
125 * 109 *
@@ -131,7 +115,7 @@ static void sel_netif_destroy(struct sel_netif *netif)
131{ 115{
132 list_del_rcu(&netif->list); 116 list_del_rcu(&netif->list);
133 sel_netif_total--; 117 sel_netif_total--;
134 call_rcu(&netif->rcu_head, sel_netif_free); 118 kfree_rcu(netif, rcu_head);
135} 119}
136 120
137/** 121/**
diff --git a/security/selinux/netlabel.c b/security/selinux/netlabel.c
index 1c2fc46544bf..c3bf3ed07b06 100644
--- a/security/selinux/netlabel.c
+++ b/security/selinux/netlabel.c
@@ -151,7 +151,7 @@ void selinux_netlbl_sk_security_free(struct sk_security_struct *sksec)
151 * 151 *
152 * Description: 152 * Description:
153 * Called when the NetLabel state of a sk_security_struct needs to be reset. 153 * Called when the NetLabel state of a sk_security_struct needs to be reset.
154 * The caller is responsibile for all the NetLabel sk_security_struct locking. 154 * The caller is responsible for all the NetLabel sk_security_struct locking.
155 * 155 *
156 */ 156 */
157void selinux_netlbl_sk_security_reset(struct sk_security_struct *sksec) 157void selinux_netlbl_sk_security_reset(struct sk_security_struct *sksec)
diff --git a/security/selinux/netnode.c b/security/selinux/netnode.c
index 65ebfe954f85..3618251d0fdb 100644
--- a/security/selinux/netnode.c
+++ b/security/selinux/netnode.c
@@ -141,6 +141,7 @@ static struct sel_netnode *sel_netnode_find(const void *addr, u16 family)
141 break; 141 break;
142 default: 142 default:
143 BUG(); 143 BUG();
144 return NULL;
144 } 145 }
145 146
146 list_for_each_entry_rcu(node, &sel_netnode_hash[idx].list, list) 147 list_for_each_entry_rcu(node, &sel_netnode_hash[idx].list, list)
diff --git a/security/selinux/nlmsgtab.c b/security/selinux/nlmsgtab.c
index 75ec0c6ebacd..8b02b2137da2 100644
--- a/security/selinux/nlmsgtab.c
+++ b/security/selinux/nlmsgtab.c
@@ -65,6 +65,8 @@ static struct nlmsg_perm nlmsg_route_perms[] =
65 { RTM_NEWADDRLABEL, NETLINK_ROUTE_SOCKET__NLMSG_WRITE }, 65 { RTM_NEWADDRLABEL, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
66 { RTM_DELADDRLABEL, NETLINK_ROUTE_SOCKET__NLMSG_WRITE }, 66 { RTM_DELADDRLABEL, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
67 { RTM_GETADDRLABEL, NETLINK_ROUTE_SOCKET__NLMSG_READ }, 67 { RTM_GETADDRLABEL, NETLINK_ROUTE_SOCKET__NLMSG_READ },
68 { RTM_GETDCB, NETLINK_ROUTE_SOCKET__NLMSG_READ },
69 { RTM_SETDCB, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
68}; 70};
69 71
70static struct nlmsg_perm nlmsg_firewall_perms[] = 72static struct nlmsg_perm nlmsg_firewall_perms[] =
diff --git a/security/selinux/selinuxfs.c b/security/selinux/selinuxfs.c
index 79a1bb635662..35459340019e 100644
--- a/security/selinux/selinuxfs.c
+++ b/security/selinux/selinuxfs.c
@@ -28,6 +28,8 @@
28#include <linux/percpu.h> 28#include <linux/percpu.h>
29#include <linux/audit.h> 29#include <linux/audit.h>
30#include <linux/uaccess.h> 30#include <linux/uaccess.h>
31#include <linux/kobject.h>
32#include <linux/ctype.h>
31 33
32/* selinuxfs pseudo filesystem for exporting the security policy API. 34/* selinuxfs pseudo filesystem for exporting the security policy API.
33 Based on the proc code and the fs/nfsd/nfsctl.c code. */ 35 Based on the proc code and the fs/nfsd/nfsctl.c code. */
@@ -68,6 +70,8 @@ static int *bool_pending_values;
68static struct dentry *class_dir; 70static struct dentry *class_dir;
69static unsigned long last_class_ino; 71static unsigned long last_class_ino;
70 72
73static char policy_opened;
74
71/* global data for policy capabilities */ 75/* global data for policy capabilities */
72static struct dentry *policycap_dir; 76static struct dentry *policycap_dir;
73 77
@@ -110,6 +114,8 @@ enum sel_inos {
110 SEL_COMPAT_NET, /* whether to use old compat network packet controls */ 114 SEL_COMPAT_NET, /* whether to use old compat network packet controls */
111 SEL_REJECT_UNKNOWN, /* export unknown reject handling to userspace */ 115 SEL_REJECT_UNKNOWN, /* export unknown reject handling to userspace */
112 SEL_DENY_UNKNOWN, /* export unknown deny handling to userspace */ 116 SEL_DENY_UNKNOWN, /* export unknown deny handling to userspace */
117 SEL_STATUS, /* export current status using mmap() */
118 SEL_POLICY, /* allow userspace to read the in kernel policy */
113 SEL_INO_NEXT, /* The next inode number to use */ 119 SEL_INO_NEXT, /* The next inode number to use */
114}; 120};
115 121
@@ -137,19 +143,24 @@ static ssize_t sel_write_enforce(struct file *file, const char __user *buf,
137 size_t count, loff_t *ppos) 143 size_t count, loff_t *ppos)
138 144
139{ 145{
140 char *page; 146 char *page = NULL;
141 ssize_t length; 147 ssize_t length;
142 int new_value; 148 int new_value;
143 149
150 length = -ENOMEM;
144 if (count >= PAGE_SIZE) 151 if (count >= PAGE_SIZE)
145 return -ENOMEM; 152 goto out;
146 if (*ppos != 0) { 153
147 /* No partial writes. */ 154 /* No partial writes. */
148 return -EINVAL; 155 length = EINVAL;
149 } 156 if (*ppos != 0)
157 goto out;
158
159 length = -ENOMEM;
150 page = (char *)get_zeroed_page(GFP_KERNEL); 160 page = (char *)get_zeroed_page(GFP_KERNEL);
151 if (!page) 161 if (!page)
152 return -ENOMEM; 162 goto out;
163
153 length = -EFAULT; 164 length = -EFAULT;
154 if (copy_from_user(page, buf, count)) 165 if (copy_from_user(page, buf, count))
155 goto out; 166 goto out;
@@ -171,6 +182,7 @@ static ssize_t sel_write_enforce(struct file *file, const char __user *buf,
171 if (selinux_enforcing) 182 if (selinux_enforcing)
172 avc_ss_reset(0); 183 avc_ss_reset(0);
173 selnl_notify_setenforce(selinux_enforcing); 184 selnl_notify_setenforce(selinux_enforcing);
185 selinux_status_update_setenforce(selinux_enforcing);
174 } 186 }
175 length = count; 187 length = count;
176out: 188out:
@@ -205,25 +217,83 @@ static const struct file_operations sel_handle_unknown_ops = {
205 .llseek = generic_file_llseek, 217 .llseek = generic_file_llseek,
206}; 218};
207 219
220static int sel_open_handle_status(struct inode *inode, struct file *filp)
221{
222 struct page *status = selinux_kernel_status_page();
223
224 if (!status)
225 return -ENOMEM;
226
227 filp->private_data = status;
228
229 return 0;
230}
231
232static ssize_t sel_read_handle_status(struct file *filp, char __user *buf,
233 size_t count, loff_t *ppos)
234{
235 struct page *status = filp->private_data;
236
237 BUG_ON(!status);
238
239 return simple_read_from_buffer(buf, count, ppos,
240 page_address(status),
241 sizeof(struct selinux_kernel_status));
242}
243
244static int sel_mmap_handle_status(struct file *filp,
245 struct vm_area_struct *vma)
246{
247 struct page *status = filp->private_data;
248 unsigned long size = vma->vm_end - vma->vm_start;
249
250 BUG_ON(!status);
251
252 /* only allows one page from the head */
253 if (vma->vm_pgoff > 0 || size != PAGE_SIZE)
254 return -EIO;
255 /* disallow writable mapping */
256 if (vma->vm_flags & VM_WRITE)
257 return -EPERM;
258 /* disallow mprotect() turns it into writable */
259 vma->vm_flags &= ~VM_MAYWRITE;
260
261 return remap_pfn_range(vma, vma->vm_start,
262 page_to_pfn(status),
263 size, vma->vm_page_prot);
264}
265
266static const struct file_operations sel_handle_status_ops = {
267 .open = sel_open_handle_status,
268 .read = sel_read_handle_status,
269 .mmap = sel_mmap_handle_status,
270 .llseek = generic_file_llseek,
271};
272
208#ifdef CONFIG_SECURITY_SELINUX_DISABLE 273#ifdef CONFIG_SECURITY_SELINUX_DISABLE
209static ssize_t sel_write_disable(struct file *file, const char __user *buf, 274static ssize_t sel_write_disable(struct file *file, const char __user *buf,
210 size_t count, loff_t *ppos) 275 size_t count, loff_t *ppos)
211 276
212{ 277{
213 char *page; 278 char *page = NULL;
214 ssize_t length; 279 ssize_t length;
215 int new_value; 280 int new_value;
216 extern int selinux_disable(void); 281 extern int selinux_disable(void);
217 282
283 length = -ENOMEM;
218 if (count >= PAGE_SIZE) 284 if (count >= PAGE_SIZE)
219 return -ENOMEM; 285 goto out;
220 if (*ppos != 0) { 286
221 /* No partial writes. */ 287 /* No partial writes. */
222 return -EINVAL; 288 length = -EINVAL;
223 } 289 if (*ppos != 0)
290 goto out;
291
292 length = -ENOMEM;
224 page = (char *)get_zeroed_page(GFP_KERNEL); 293 page = (char *)get_zeroed_page(GFP_KERNEL);
225 if (!page) 294 if (!page)
226 return -ENOMEM; 295 goto out;
296
227 length = -EFAULT; 297 length = -EFAULT;
228 if (copy_from_user(page, buf, count)) 298 if (copy_from_user(page, buf, count))
229 goto out; 299 goto out;
@@ -234,7 +304,7 @@ static ssize_t sel_write_disable(struct file *file, const char __user *buf,
234 304
235 if (new_value) { 305 if (new_value) {
236 length = selinux_disable(); 306 length = selinux_disable();
237 if (length < 0) 307 if (length)
238 goto out; 308 goto out;
239 audit_log(current->audit_context, GFP_KERNEL, AUDIT_MAC_STATUS, 309 audit_log(current->audit_context, GFP_KERNEL, AUDIT_MAC_STATUS,
240 "selinux=0 auid=%u ses=%u", 310 "selinux=0 auid=%u ses=%u",
@@ -296,11 +366,145 @@ static const struct file_operations sel_mls_ops = {
296 .llseek = generic_file_llseek, 366 .llseek = generic_file_llseek,
297}; 367};
298 368
369struct policy_load_memory {
370 size_t len;
371 void *data;
372};
373
374static int sel_open_policy(struct inode *inode, struct file *filp)
375{
376 struct policy_load_memory *plm = NULL;
377 int rc;
378
379 BUG_ON(filp->private_data);
380
381 mutex_lock(&sel_mutex);
382
383 rc = task_has_security(current, SECURITY__READ_POLICY);
384 if (rc)
385 goto err;
386
387 rc = -EBUSY;
388 if (policy_opened)
389 goto err;
390
391 rc = -ENOMEM;
392 plm = kzalloc(sizeof(*plm), GFP_KERNEL);
393 if (!plm)
394 goto err;
395
396 if (i_size_read(inode) != security_policydb_len()) {
397 mutex_lock(&inode->i_mutex);
398 i_size_write(inode, security_policydb_len());
399 mutex_unlock(&inode->i_mutex);
400 }
401
402 rc = security_read_policy(&plm->data, &plm->len);
403 if (rc)
404 goto err;
405
406 policy_opened = 1;
407
408 filp->private_data = plm;
409
410 mutex_unlock(&sel_mutex);
411
412 return 0;
413err:
414 mutex_unlock(&sel_mutex);
415
416 if (plm)
417 vfree(plm->data);
418 kfree(plm);
419 return rc;
420}
421
422static int sel_release_policy(struct inode *inode, struct file *filp)
423{
424 struct policy_load_memory *plm = filp->private_data;
425
426 BUG_ON(!plm);
427
428 policy_opened = 0;
429
430 vfree(plm->data);
431 kfree(plm);
432
433 return 0;
434}
435
436static ssize_t sel_read_policy(struct file *filp, char __user *buf,
437 size_t count, loff_t *ppos)
438{
439 struct policy_load_memory *plm = filp->private_data;
440 int ret;
441
442 mutex_lock(&sel_mutex);
443
444 ret = task_has_security(current, SECURITY__READ_POLICY);
445 if (ret)
446 goto out;
447
448 ret = simple_read_from_buffer(buf, count, ppos, plm->data, plm->len);
449out:
450 mutex_unlock(&sel_mutex);
451 return ret;
452}
453
454static int sel_mmap_policy_fault(struct vm_area_struct *vma,
455 struct vm_fault *vmf)
456{
457 struct policy_load_memory *plm = vma->vm_file->private_data;
458 unsigned long offset;
459 struct page *page;
460
461 if (vmf->flags & (FAULT_FLAG_MKWRITE | FAULT_FLAG_WRITE))
462 return VM_FAULT_SIGBUS;
463
464 offset = vmf->pgoff << PAGE_SHIFT;
465 if (offset >= roundup(plm->len, PAGE_SIZE))
466 return VM_FAULT_SIGBUS;
467
468 page = vmalloc_to_page(plm->data + offset);
469 get_page(page);
470
471 vmf->page = page;
472
473 return 0;
474}
475
476static struct vm_operations_struct sel_mmap_policy_ops = {
477 .fault = sel_mmap_policy_fault,
478 .page_mkwrite = sel_mmap_policy_fault,
479};
480
481int sel_mmap_policy(struct file *filp, struct vm_area_struct *vma)
482{
483 if (vma->vm_flags & VM_SHARED) {
484 /* do not allow mprotect to make mapping writable */
485 vma->vm_flags &= ~VM_MAYWRITE;
486
487 if (vma->vm_flags & VM_WRITE)
488 return -EACCES;
489 }
490
491 vma->vm_flags |= VM_RESERVED;
492 vma->vm_ops = &sel_mmap_policy_ops;
493
494 return 0;
495}
496
497static const struct file_operations sel_policy_ops = {
498 .open = sel_open_policy,
499 .read = sel_read_policy,
500 .mmap = sel_mmap_policy,
501 .release = sel_release_policy,
502};
503
299static ssize_t sel_write_load(struct file *file, const char __user *buf, 504static ssize_t sel_write_load(struct file *file, const char __user *buf,
300 size_t count, loff_t *ppos) 505 size_t count, loff_t *ppos)
301 506
302{ 507{
303 int ret;
304 ssize_t length; 508 ssize_t length;
305 void *data = NULL; 509 void *data = NULL;
306 510
@@ -310,17 +514,19 @@ static ssize_t sel_write_load(struct file *file, const char __user *buf,
310 if (length) 514 if (length)
311 goto out; 515 goto out;
312 516
313 if (*ppos != 0) { 517 /* No partial writes. */
314 /* No partial writes. */ 518 length = -EINVAL;
315 length = -EINVAL; 519 if (*ppos != 0)
316 goto out; 520 goto out;
317 }
318 521
319 if ((count > 64 * 1024 * 1024) 522 length = -EFBIG;
320 || (data = vmalloc(count)) == NULL) { 523 if (count > 64 * 1024 * 1024)
321 length = -ENOMEM; 524 goto out;
525
526 length = -ENOMEM;
527 data = vmalloc(count);
528 if (!data)
322 goto out; 529 goto out;
323 }
324 530
325 length = -EFAULT; 531 length = -EFAULT;
326 if (copy_from_user(data, buf, count) != 0) 532 if (copy_from_user(data, buf, count) != 0)
@@ -330,23 +536,19 @@ static ssize_t sel_write_load(struct file *file, const char __user *buf,
330 if (length) 536 if (length)
331 goto out; 537 goto out;
332 538
333 ret = sel_make_bools(); 539 length = sel_make_bools();
334 if (ret) { 540 if (length)
335 length = ret;
336 goto out1; 541 goto out1;
337 }
338 542
339 ret = sel_make_classes(); 543 length = sel_make_classes();
340 if (ret) { 544 if (length)
341 length = ret;
342 goto out1; 545 goto out1;
343 }
344 546
345 ret = sel_make_policycap(); 547 length = sel_make_policycap();
346 if (ret) 548 if (length)
347 length = ret; 549 goto out1;
348 else 550
349 length = count; 551 length = count;
350 552
351out1: 553out1:
352 audit_log(current->audit_context, GFP_KERNEL, AUDIT_MAC_POLICY_LOAD, 554 audit_log(current->audit_context, GFP_KERNEL, AUDIT_MAC_POLICY_LOAD,
@@ -366,26 +568,26 @@ static const struct file_operations sel_load_ops = {
366 568
367static ssize_t sel_write_context(struct file *file, char *buf, size_t size) 569static ssize_t sel_write_context(struct file *file, char *buf, size_t size)
368{ 570{
369 char *canon; 571 char *canon = NULL;
370 u32 sid, len; 572 u32 sid, len;
371 ssize_t length; 573 ssize_t length;
372 574
373 length = task_has_security(current, SECURITY__CHECK_CONTEXT); 575 length = task_has_security(current, SECURITY__CHECK_CONTEXT);
374 if (length) 576 if (length)
375 return length; 577 goto out;
376 578
377 length = security_context_to_sid(buf, size, &sid); 579 length = security_context_to_sid(buf, size, &sid);
378 if (length < 0) 580 if (length)
379 return length; 581 goto out;
380 582
381 length = security_sid_to_context(sid, &canon, &len); 583 length = security_sid_to_context(sid, &canon, &len);
382 if (length < 0) 584 if (length)
383 return length; 585 goto out;
384 586
587 length = -ERANGE;
385 if (len > SIMPLE_TRANSACTION_LIMIT) { 588 if (len > SIMPLE_TRANSACTION_LIMIT) {
386 printk(KERN_ERR "SELinux: %s: context size (%u) exceeds " 589 printk(KERN_ERR "SELinux: %s: context size (%u) exceeds "
387 "payload max\n", __func__, len); 590 "payload max\n", __func__, len);
388 length = -ERANGE;
389 goto out; 591 goto out;
390 } 592 }
391 593
@@ -409,23 +611,28 @@ static ssize_t sel_read_checkreqprot(struct file *filp, char __user *buf,
409static ssize_t sel_write_checkreqprot(struct file *file, const char __user *buf, 611static ssize_t sel_write_checkreqprot(struct file *file, const char __user *buf,
410 size_t count, loff_t *ppos) 612 size_t count, loff_t *ppos)
411{ 613{
412 char *page; 614 char *page = NULL;
413 ssize_t length; 615 ssize_t length;
414 unsigned int new_value; 616 unsigned int new_value;
415 617
416 length = task_has_security(current, SECURITY__SETCHECKREQPROT); 618 length = task_has_security(current, SECURITY__SETCHECKREQPROT);
417 if (length) 619 if (length)
418 return length; 620 goto out;
419 621
622 length = -ENOMEM;
420 if (count >= PAGE_SIZE) 623 if (count >= PAGE_SIZE)
421 return -ENOMEM; 624 goto out;
422 if (*ppos != 0) { 625
423 /* No partial writes. */ 626 /* No partial writes. */
424 return -EINVAL; 627 length = -EINVAL;
425 } 628 if (*ppos != 0)
629 goto out;
630
631 length = -ENOMEM;
426 page = (char *)get_zeroed_page(GFP_KERNEL); 632 page = (char *)get_zeroed_page(GFP_KERNEL);
427 if (!page) 633 if (!page)
428 return -ENOMEM; 634 goto out;
635
429 length = -EFAULT; 636 length = -EFAULT;
430 if (copy_from_user(page, buf, count)) 637 if (copy_from_user(page, buf, count))
431 goto out; 638 goto out;
@@ -500,7 +707,7 @@ static const struct file_operations transaction_ops = {
500 707
501static ssize_t sel_write_access(struct file *file, char *buf, size_t size) 708static ssize_t sel_write_access(struct file *file, char *buf, size_t size)
502{ 709{
503 char *scon, *tcon; 710 char *scon = NULL, *tcon = NULL;
504 u32 ssid, tsid; 711 u32 ssid, tsid;
505 u16 tclass; 712 u16 tclass;
506 struct av_decision avd; 713 struct av_decision avd;
@@ -508,27 +715,29 @@ static ssize_t sel_write_access(struct file *file, char *buf, size_t size)
508 715
509 length = task_has_security(current, SECURITY__COMPUTE_AV); 716 length = task_has_security(current, SECURITY__COMPUTE_AV);
510 if (length) 717 if (length)
511 return length; 718 goto out;
512 719
513 length = -ENOMEM; 720 length = -ENOMEM;
514 scon = kzalloc(size + 1, GFP_KERNEL); 721 scon = kzalloc(size + 1, GFP_KERNEL);
515 if (!scon) 722 if (!scon)
516 return length; 723 goto out;
517 724
725 length = -ENOMEM;
518 tcon = kzalloc(size + 1, GFP_KERNEL); 726 tcon = kzalloc(size + 1, GFP_KERNEL);
519 if (!tcon) 727 if (!tcon)
520 goto out; 728 goto out;
521 729
522 length = -EINVAL; 730 length = -EINVAL;
523 if (sscanf(buf, "%s %s %hu", scon, tcon, &tclass) != 3) 731 if (sscanf(buf, "%s %s %hu", scon, tcon, &tclass) != 3)
524 goto out2; 732 goto out;
525 733
526 length = security_context_to_sid(scon, strlen(scon) + 1, &ssid); 734 length = security_context_to_sid(scon, strlen(scon) + 1, &ssid);
527 if (length < 0) 735 if (length)
528 goto out2; 736 goto out;
737
529 length = security_context_to_sid(tcon, strlen(tcon) + 1, &tsid); 738 length = security_context_to_sid(tcon, strlen(tcon) + 1, &tsid);
530 if (length < 0) 739 if (length)
531 goto out2; 740 goto out;
532 741
533 security_compute_av_user(ssid, tsid, tclass, &avd); 742 security_compute_av_user(ssid, tsid, tclass, &avd);
534 743
@@ -537,133 +746,177 @@ static ssize_t sel_write_access(struct file *file, char *buf, size_t size)
537 avd.allowed, 0xffffffff, 746 avd.allowed, 0xffffffff,
538 avd.auditallow, avd.auditdeny, 747 avd.auditallow, avd.auditdeny,
539 avd.seqno, avd.flags); 748 avd.seqno, avd.flags);
540out2:
541 kfree(tcon);
542out: 749out:
750 kfree(tcon);
543 kfree(scon); 751 kfree(scon);
544 return length; 752 return length;
545} 753}
546 754
755static inline int hexcode_to_int(int code) {
756 if (code == '\0' || !isxdigit(code))
757 return -1;
758 if (isdigit(code))
759 return code - '0';
760 return tolower(code) - 'a' + 10;
761}
762
547static ssize_t sel_write_create(struct file *file, char *buf, size_t size) 763static ssize_t sel_write_create(struct file *file, char *buf, size_t size)
548{ 764{
549 char *scon, *tcon; 765 char *scon = NULL, *tcon = NULL;
766 char *namebuf = NULL, *objname = NULL;
550 u32 ssid, tsid, newsid; 767 u32 ssid, tsid, newsid;
551 u16 tclass; 768 u16 tclass;
552 ssize_t length; 769 ssize_t length;
553 char *newcon; 770 char *newcon = NULL;
554 u32 len; 771 u32 len;
772 int nargs;
555 773
556 length = task_has_security(current, SECURITY__COMPUTE_CREATE); 774 length = task_has_security(current, SECURITY__COMPUTE_CREATE);
557 if (length) 775 if (length)
558 return length; 776 goto out;
559 777
560 length = -ENOMEM; 778 length = -ENOMEM;
561 scon = kzalloc(size + 1, GFP_KERNEL); 779 scon = kzalloc(size + 1, GFP_KERNEL);
562 if (!scon) 780 if (!scon)
563 return length; 781 goto out;
564 782
783 length = -ENOMEM;
565 tcon = kzalloc(size + 1, GFP_KERNEL); 784 tcon = kzalloc(size + 1, GFP_KERNEL);
566 if (!tcon) 785 if (!tcon)
567 goto out; 786 goto out;
568 787
788 length = -ENOMEM;
789 namebuf = kzalloc(size + 1, GFP_KERNEL);
790 if (!namebuf)
791 goto out;
792
569 length = -EINVAL; 793 length = -EINVAL;
570 if (sscanf(buf, "%s %s %hu", scon, tcon, &tclass) != 3) 794 nargs = sscanf(buf, "%s %s %hu %s", scon, tcon, &tclass, namebuf);
571 goto out2; 795 if (nargs < 3 || nargs > 4)
796 goto out;
797 if (nargs == 4) {
798 /*
799 * If and when the name of new object to be queried contains
800 * either whitespace or multibyte characters, they shall be
801 * encoded based on the percentage-encoding rule.
802 * If not encoded, the sscanf logic picks up only left-half
803 * of the supplied name; splitted by a whitespace unexpectedly.
804 */
805 char *r, *w;
806 int c1, c2;
807
808 r = w = namebuf;
809 do {
810 c1 = *r++;
811 if (c1 == '+')
812 c1 = ' ';
813 else if (c1 == '%') {
814 if ((c1 = hexcode_to_int(*r++)) < 0)
815 goto out;
816 if ((c2 = hexcode_to_int(*r++)) < 0)
817 goto out;
818 c1 = (c1 << 4) | c2;
819 }
820 *w++ = c1;
821 } while (c1 != '\0');
822
823 objname = namebuf;
824 }
572 825
573 length = security_context_to_sid(scon, strlen(scon) + 1, &ssid); 826 length = security_context_to_sid(scon, strlen(scon) + 1, &ssid);
574 if (length < 0) 827 if (length)
575 goto out2; 828 goto out;
829
576 length = security_context_to_sid(tcon, strlen(tcon) + 1, &tsid); 830 length = security_context_to_sid(tcon, strlen(tcon) + 1, &tsid);
577 if (length < 0) 831 if (length)
578 goto out2; 832 goto out;
579 833
580 length = security_transition_sid_user(ssid, tsid, tclass, &newsid); 834 length = security_transition_sid_user(ssid, tsid, tclass,
581 if (length < 0) 835 objname, &newsid);
582 goto out2; 836 if (length)
837 goto out;
583 838
584 length = security_sid_to_context(newsid, &newcon, &len); 839 length = security_sid_to_context(newsid, &newcon, &len);
585 if (length < 0) 840 if (length)
586 goto out2; 841 goto out;
587 842
843 length = -ERANGE;
588 if (len > SIMPLE_TRANSACTION_LIMIT) { 844 if (len > SIMPLE_TRANSACTION_LIMIT) {
589 printk(KERN_ERR "SELinux: %s: context size (%u) exceeds " 845 printk(KERN_ERR "SELinux: %s: context size (%u) exceeds "
590 "payload max\n", __func__, len); 846 "payload max\n", __func__, len);
591 length = -ERANGE; 847 goto out;
592 goto out3;
593 } 848 }
594 849
595 memcpy(buf, newcon, len); 850 memcpy(buf, newcon, len);
596 length = len; 851 length = len;
597out3: 852out:
598 kfree(newcon); 853 kfree(newcon);
599out2: 854 kfree(namebuf);
600 kfree(tcon); 855 kfree(tcon);
601out:
602 kfree(scon); 856 kfree(scon);
603 return length; 857 return length;
604} 858}
605 859
606static ssize_t sel_write_relabel(struct file *file, char *buf, size_t size) 860static ssize_t sel_write_relabel(struct file *file, char *buf, size_t size)
607{ 861{
608 char *scon, *tcon; 862 char *scon = NULL, *tcon = NULL;
609 u32 ssid, tsid, newsid; 863 u32 ssid, tsid, newsid;
610 u16 tclass; 864 u16 tclass;
611 ssize_t length; 865 ssize_t length;
612 char *newcon; 866 char *newcon = NULL;
613 u32 len; 867 u32 len;
614 868
615 length = task_has_security(current, SECURITY__COMPUTE_RELABEL); 869 length = task_has_security(current, SECURITY__COMPUTE_RELABEL);
616 if (length) 870 if (length)
617 return length; 871 goto out;
618 872
619 length = -ENOMEM; 873 length = -ENOMEM;
620 scon = kzalloc(size + 1, GFP_KERNEL); 874 scon = kzalloc(size + 1, GFP_KERNEL);
621 if (!scon) 875 if (!scon)
622 return length; 876 goto out;
623 877
878 length = -ENOMEM;
624 tcon = kzalloc(size + 1, GFP_KERNEL); 879 tcon = kzalloc(size + 1, GFP_KERNEL);
625 if (!tcon) 880 if (!tcon)
626 goto out; 881 goto out;
627 882
628 length = -EINVAL; 883 length = -EINVAL;
629 if (sscanf(buf, "%s %s %hu", scon, tcon, &tclass) != 3) 884 if (sscanf(buf, "%s %s %hu", scon, tcon, &tclass) != 3)
630 goto out2; 885 goto out;
631 886
632 length = security_context_to_sid(scon, strlen(scon) + 1, &ssid); 887 length = security_context_to_sid(scon, strlen(scon) + 1, &ssid);
633 if (length < 0) 888 if (length)
634 goto out2; 889 goto out;
890
635 length = security_context_to_sid(tcon, strlen(tcon) + 1, &tsid); 891 length = security_context_to_sid(tcon, strlen(tcon) + 1, &tsid);
636 if (length < 0) 892 if (length)
637 goto out2; 893 goto out;
638 894
639 length = security_change_sid(ssid, tsid, tclass, &newsid); 895 length = security_change_sid(ssid, tsid, tclass, &newsid);
640 if (length < 0) 896 if (length)
641 goto out2; 897 goto out;
642 898
643 length = security_sid_to_context(newsid, &newcon, &len); 899 length = security_sid_to_context(newsid, &newcon, &len);
644 if (length < 0) 900 if (length)
645 goto out2; 901 goto out;
646 902
647 if (len > SIMPLE_TRANSACTION_LIMIT) { 903 length = -ERANGE;
648 length = -ERANGE; 904 if (len > SIMPLE_TRANSACTION_LIMIT)
649 goto out3; 905 goto out;
650 }
651 906
652 memcpy(buf, newcon, len); 907 memcpy(buf, newcon, len);
653 length = len; 908 length = len;
654out3: 909out:
655 kfree(newcon); 910 kfree(newcon);
656out2:
657 kfree(tcon); 911 kfree(tcon);
658out:
659 kfree(scon); 912 kfree(scon);
660 return length; 913 return length;
661} 914}
662 915
663static ssize_t sel_write_user(struct file *file, char *buf, size_t size) 916static ssize_t sel_write_user(struct file *file, char *buf, size_t size)
664{ 917{
665 char *con, *user, *ptr; 918 char *con = NULL, *user = NULL, *ptr;
666 u32 sid, *sids; 919 u32 sid, *sids = NULL;
667 ssize_t length; 920 ssize_t length;
668 char *newcon; 921 char *newcon;
669 int i, rc; 922 int i, rc;
@@ -671,28 +924,29 @@ static ssize_t sel_write_user(struct file *file, char *buf, size_t size)
671 924
672 length = task_has_security(current, SECURITY__COMPUTE_USER); 925 length = task_has_security(current, SECURITY__COMPUTE_USER);
673 if (length) 926 if (length)
674 return length; 927 goto out;
675 928
676 length = -ENOMEM; 929 length = -ENOMEM;
677 con = kzalloc(size + 1, GFP_KERNEL); 930 con = kzalloc(size + 1, GFP_KERNEL);
678 if (!con) 931 if (!con)
679 return length; 932 goto out;
680 933
934 length = -ENOMEM;
681 user = kzalloc(size + 1, GFP_KERNEL); 935 user = kzalloc(size + 1, GFP_KERNEL);
682 if (!user) 936 if (!user)
683 goto out; 937 goto out;
684 938
685 length = -EINVAL; 939 length = -EINVAL;
686 if (sscanf(buf, "%s %s", con, user) != 2) 940 if (sscanf(buf, "%s %s", con, user) != 2)
687 goto out2; 941 goto out;
688 942
689 length = security_context_to_sid(con, strlen(con) + 1, &sid); 943 length = security_context_to_sid(con, strlen(con) + 1, &sid);
690 if (length < 0) 944 if (length)
691 goto out2; 945 goto out;
692 946
693 length = security_get_user_sids(sid, user, &sids, &nsids); 947 length = security_get_user_sids(sid, user, &sids, &nsids);
694 if (length < 0) 948 if (length)
695 goto out2; 949 goto out;
696 950
697 length = sprintf(buf, "%u", nsids) + 1; 951 length = sprintf(buf, "%u", nsids) + 1;
698 ptr = buf + length; 952 ptr = buf + length;
@@ -700,82 +954,80 @@ static ssize_t sel_write_user(struct file *file, char *buf, size_t size)
700 rc = security_sid_to_context(sids[i], &newcon, &len); 954 rc = security_sid_to_context(sids[i], &newcon, &len);
701 if (rc) { 955 if (rc) {
702 length = rc; 956 length = rc;
703 goto out3; 957 goto out;
704 } 958 }
705 if ((length + len) >= SIMPLE_TRANSACTION_LIMIT) { 959 if ((length + len) >= SIMPLE_TRANSACTION_LIMIT) {
706 kfree(newcon); 960 kfree(newcon);
707 length = -ERANGE; 961 length = -ERANGE;
708 goto out3; 962 goto out;
709 } 963 }
710 memcpy(ptr, newcon, len); 964 memcpy(ptr, newcon, len);
711 kfree(newcon); 965 kfree(newcon);
712 ptr += len; 966 ptr += len;
713 length += len; 967 length += len;
714 } 968 }
715out3: 969out:
716 kfree(sids); 970 kfree(sids);
717out2:
718 kfree(user); 971 kfree(user);
719out:
720 kfree(con); 972 kfree(con);
721 return length; 973 return length;
722} 974}
723 975
724static ssize_t sel_write_member(struct file *file, char *buf, size_t size) 976static ssize_t sel_write_member(struct file *file, char *buf, size_t size)
725{ 977{
726 char *scon, *tcon; 978 char *scon = NULL, *tcon = NULL;
727 u32 ssid, tsid, newsid; 979 u32 ssid, tsid, newsid;
728 u16 tclass; 980 u16 tclass;
729 ssize_t length; 981 ssize_t length;
730 char *newcon; 982 char *newcon = NULL;
731 u32 len; 983 u32 len;
732 984
733 length = task_has_security(current, SECURITY__COMPUTE_MEMBER); 985 length = task_has_security(current, SECURITY__COMPUTE_MEMBER);
734 if (length) 986 if (length)
735 return length; 987 goto out;
736 988
737 length = -ENOMEM; 989 length = -ENOMEM;
738 scon = kzalloc(size + 1, GFP_KERNEL); 990 scon = kzalloc(size + 1, GFP_KERNEL);
739 if (!scon) 991 if (!scon)
740 return length; 992 goto out;
741 993
994 length = -ENOMEM;
742 tcon = kzalloc(size + 1, GFP_KERNEL); 995 tcon = kzalloc(size + 1, GFP_KERNEL);
743 if (!tcon) 996 if (!tcon)
744 goto out; 997 goto out;
745 998
746 length = -EINVAL; 999 length = -EINVAL;
747 if (sscanf(buf, "%s %s %hu", scon, tcon, &tclass) != 3) 1000 if (sscanf(buf, "%s %s %hu", scon, tcon, &tclass) != 3)
748 goto out2; 1001 goto out;
749 1002
750 length = security_context_to_sid(scon, strlen(scon) + 1, &ssid); 1003 length = security_context_to_sid(scon, strlen(scon) + 1, &ssid);
751 if (length < 0) 1004 if (length)
752 goto out2; 1005 goto out;
1006
753 length = security_context_to_sid(tcon, strlen(tcon) + 1, &tsid); 1007 length = security_context_to_sid(tcon, strlen(tcon) + 1, &tsid);
754 if (length < 0) 1008 if (length)
755 goto out2; 1009 goto out;
756 1010
757 length = security_member_sid(ssid, tsid, tclass, &newsid); 1011 length = security_member_sid(ssid, tsid, tclass, &newsid);
758 if (length < 0) 1012 if (length)
759 goto out2; 1013 goto out;
760 1014
761 length = security_sid_to_context(newsid, &newcon, &len); 1015 length = security_sid_to_context(newsid, &newcon, &len);
762 if (length < 0) 1016 if (length)
763 goto out2; 1017 goto out;
764 1018
1019 length = -ERANGE;
765 if (len > SIMPLE_TRANSACTION_LIMIT) { 1020 if (len > SIMPLE_TRANSACTION_LIMIT) {
766 printk(KERN_ERR "SELinux: %s: context size (%u) exceeds " 1021 printk(KERN_ERR "SELinux: %s: context size (%u) exceeds "
767 "payload max\n", __func__, len); 1022 "payload max\n", __func__, len);
768 length = -ERANGE; 1023 goto out;
769 goto out3;
770 } 1024 }
771 1025
772 memcpy(buf, newcon, len); 1026 memcpy(buf, newcon, len);
773 length = len; 1027 length = len;
774out3: 1028out:
775 kfree(newcon); 1029 kfree(newcon);
776out2:
777 kfree(tcon); 1030 kfree(tcon);
778out:
779 kfree(scon); 1031 kfree(scon);
780 return length; 1032 return length;
781} 1033}
@@ -804,16 +1056,14 @@ static ssize_t sel_read_bool(struct file *filep, char __user *buf,
804 1056
805 mutex_lock(&sel_mutex); 1057 mutex_lock(&sel_mutex);
806 1058
807 if (index >= bool_num || strcmp(name, bool_pending_names[index])) { 1059 ret = -EINVAL;
808 ret = -EINVAL; 1060 if (index >= bool_num || strcmp(name, bool_pending_names[index]))
809 goto out; 1061 goto out;
810 }
811 1062
1063 ret = -ENOMEM;
812 page = (char *)get_zeroed_page(GFP_KERNEL); 1064 page = (char *)get_zeroed_page(GFP_KERNEL);
813 if (!page) { 1065 if (!page)
814 ret = -ENOMEM;
815 goto out; 1066 goto out;
816 }
817 1067
818 cur_enforcing = security_get_bool_value(index); 1068 cur_enforcing = security_get_bool_value(index);
819 if (cur_enforcing < 0) { 1069 if (cur_enforcing < 0) {
@@ -825,8 +1075,7 @@ static ssize_t sel_read_bool(struct file *filep, char __user *buf,
825 ret = simple_read_from_buffer(buf, count, ppos, page, length); 1075 ret = simple_read_from_buffer(buf, count, ppos, page, length);
826out: 1076out:
827 mutex_unlock(&sel_mutex); 1077 mutex_unlock(&sel_mutex);
828 if (page) 1078 free_page((unsigned long)page);
829 free_page((unsigned long)page);
830 return ret; 1079 return ret;
831} 1080}
832 1081
@@ -846,26 +1095,23 @@ static ssize_t sel_write_bool(struct file *filep, const char __user *buf,
846 if (length) 1095 if (length)
847 goto out; 1096 goto out;
848 1097
849 if (index >= bool_num || strcmp(name, bool_pending_names[index])) { 1098 length = -EINVAL;
850 length = -EINVAL; 1099 if (index >= bool_num || strcmp(name, bool_pending_names[index]))
851 goto out; 1100 goto out;
852 }
853 1101
854 if (count >= PAGE_SIZE) { 1102 length = -ENOMEM;
855 length = -ENOMEM; 1103 if (count >= PAGE_SIZE)
856 goto out; 1104 goto out;
857 }
858 1105
859 if (*ppos != 0) { 1106 /* No partial writes. */
860 /* No partial writes. */ 1107 length = -EINVAL;
861 length = -EINVAL; 1108 if (*ppos != 0)
862 goto out; 1109 goto out;
863 } 1110
1111 length = -ENOMEM;
864 page = (char *)get_zeroed_page(GFP_KERNEL); 1112 page = (char *)get_zeroed_page(GFP_KERNEL);
865 if (!page) { 1113 if (!page)
866 length = -ENOMEM;
867 goto out; 1114 goto out;
868 }
869 1115
870 length = -EFAULT; 1116 length = -EFAULT;
871 if (copy_from_user(page, buf, count)) 1117 if (copy_from_user(page, buf, count))
@@ -883,8 +1129,7 @@ static ssize_t sel_write_bool(struct file *filep, const char __user *buf,
883 1129
884out: 1130out:
885 mutex_unlock(&sel_mutex); 1131 mutex_unlock(&sel_mutex);
886 if (page) 1132 free_page((unsigned long) page);
887 free_page((unsigned long) page);
888 return length; 1133 return length;
889} 1134}
890 1135
@@ -908,19 +1153,19 @@ static ssize_t sel_commit_bools_write(struct file *filep,
908 if (length) 1153 if (length)
909 goto out; 1154 goto out;
910 1155
911 if (count >= PAGE_SIZE) { 1156 length = -ENOMEM;
912 length = -ENOMEM; 1157 if (count >= PAGE_SIZE)
913 goto out; 1158 goto out;
914 } 1159
915 if (*ppos != 0) { 1160 /* No partial writes. */
916 /* No partial writes. */ 1161 length = -EINVAL;
1162 if (*ppos != 0)
917 goto out; 1163 goto out;
918 } 1164
1165 length = -ENOMEM;
919 page = (char *)get_zeroed_page(GFP_KERNEL); 1166 page = (char *)get_zeroed_page(GFP_KERNEL);
920 if (!page) { 1167 if (!page)
921 length = -ENOMEM;
922 goto out; 1168 goto out;
923 }
924 1169
925 length = -EFAULT; 1170 length = -EFAULT;
926 if (copy_from_user(page, buf, count)) 1171 if (copy_from_user(page, buf, count))
@@ -930,15 +1175,16 @@ static ssize_t sel_commit_bools_write(struct file *filep,
930 if (sscanf(page, "%d", &new_value) != 1) 1175 if (sscanf(page, "%d", &new_value) != 1)
931 goto out; 1176 goto out;
932 1177
1178 length = 0;
933 if (new_value && bool_pending_values) 1179 if (new_value && bool_pending_values)
934 security_set_bools(bool_num, bool_pending_values); 1180 length = security_set_bools(bool_num, bool_pending_values);
935 1181
936 length = count; 1182 if (!length)
1183 length = count;
937 1184
938out: 1185out:
939 mutex_unlock(&sel_mutex); 1186 mutex_unlock(&sel_mutex);
940 if (page) 1187 free_page((unsigned long) page);
941 free_page((unsigned long) page);
942 return length; 1188 return length;
943} 1189}
944 1190
@@ -951,31 +1197,35 @@ static void sel_remove_entries(struct dentry *de)
951{ 1197{
952 struct list_head *node; 1198 struct list_head *node;
953 1199
954 spin_lock(&dcache_lock); 1200 spin_lock(&de->d_lock);
955 node = de->d_subdirs.next; 1201 node = de->d_subdirs.next;
956 while (node != &de->d_subdirs) { 1202 while (node != &de->d_subdirs) {
957 struct dentry *d = list_entry(node, struct dentry, d_u.d_child); 1203 struct dentry *d = list_entry(node, struct dentry, d_u.d_child);
1204
1205 spin_lock_nested(&d->d_lock, DENTRY_D_LOCK_NESTED);
958 list_del_init(node); 1206 list_del_init(node);
959 1207
960 if (d->d_inode) { 1208 if (d->d_inode) {
961 d = dget_locked(d); 1209 dget_dlock(d);
962 spin_unlock(&dcache_lock); 1210 spin_unlock(&de->d_lock);
1211 spin_unlock(&d->d_lock);
963 d_delete(d); 1212 d_delete(d);
964 simple_unlink(de->d_inode, d); 1213 simple_unlink(de->d_inode, d);
965 dput(d); 1214 dput(d);
966 spin_lock(&dcache_lock); 1215 spin_lock(&de->d_lock);
967 } 1216 } else
1217 spin_unlock(&d->d_lock);
968 node = de->d_subdirs.next; 1218 node = de->d_subdirs.next;
969 } 1219 }
970 1220
971 spin_unlock(&dcache_lock); 1221 spin_unlock(&de->d_lock);
972} 1222}
973 1223
974#define BOOL_DIR_NAME "booleans" 1224#define BOOL_DIR_NAME "booleans"
975 1225
976static int sel_make_bools(void) 1226static int sel_make_bools(void)
977{ 1227{
978 int i, ret = 0; 1228 int i, ret;
979 ssize_t len; 1229 ssize_t len;
980 struct dentry *dentry = NULL; 1230 struct dentry *dentry = NULL;
981 struct dentry *dir = bool_dir; 1231 struct dentry *dir = bool_dir;
@@ -996,38 +1246,40 @@ static int sel_make_bools(void)
996 1246
997 sel_remove_entries(dir); 1247 sel_remove_entries(dir);
998 1248
1249 ret = -ENOMEM;
999 page = (char *)get_zeroed_page(GFP_KERNEL); 1250 page = (char *)get_zeroed_page(GFP_KERNEL);
1000 if (!page) 1251 if (!page)
1001 return -ENOMEM; 1252 goto out;
1002 1253
1003 ret = security_get_bools(&num, &names, &values); 1254 ret = security_get_bools(&num, &names, &values);
1004 if (ret != 0) 1255 if (ret)
1005 goto out; 1256 goto out;
1006 1257
1007 for (i = 0; i < num; i++) { 1258 for (i = 0; i < num; i++) {
1259 ret = -ENOMEM;
1008 dentry = d_alloc_name(dir, names[i]); 1260 dentry = d_alloc_name(dir, names[i]);
1009 if (!dentry) { 1261 if (!dentry)
1010 ret = -ENOMEM; 1262 goto out;
1011 goto err; 1263
1012 } 1264 ret = -ENOMEM;
1013 inode = sel_make_inode(dir->d_sb, S_IFREG | S_IRUGO | S_IWUSR); 1265 inode = sel_make_inode(dir->d_sb, S_IFREG | S_IRUGO | S_IWUSR);
1014 if (!inode) { 1266 if (!inode)
1015 ret = -ENOMEM; 1267 goto out;
1016 goto err;
1017 }
1018 1268
1269 ret = -EINVAL;
1019 len = snprintf(page, PAGE_SIZE, "/%s/%s", BOOL_DIR_NAME, names[i]); 1270 len = snprintf(page, PAGE_SIZE, "/%s/%s", BOOL_DIR_NAME, names[i]);
1020 if (len < 0) { 1271 if (len < 0)
1021 ret = -EINVAL; 1272 goto out;
1022 goto err; 1273
1023 } else if (len >= PAGE_SIZE) { 1274 ret = -ENAMETOOLONG;
1024 ret = -ENAMETOOLONG; 1275 if (len >= PAGE_SIZE)
1025 goto err; 1276 goto out;
1026 } 1277
1027 isec = (struct inode_security_struct *)inode->i_security; 1278 isec = (struct inode_security_struct *)inode->i_security;
1028 ret = security_genfs_sid("selinuxfs", page, SECCLASS_FILE, &sid); 1279 ret = security_genfs_sid("selinuxfs", page, SECCLASS_FILE, &sid);
1029 if (ret) 1280 if (ret)
1030 goto err; 1281 goto out;
1282
1031 isec->sid = sid; 1283 isec->sid = sid;
1032 isec->initialized = 1; 1284 isec->initialized = 1;
1033 inode->i_fop = &sel_bool_ops; 1285 inode->i_fop = &sel_bool_ops;
@@ -1037,10 +1289,12 @@ static int sel_make_bools(void)
1037 bool_num = num; 1289 bool_num = num;
1038 bool_pending_names = names; 1290 bool_pending_names = names;
1039 bool_pending_values = values; 1291 bool_pending_values = values;
1292
1293 free_page((unsigned long)page);
1294 return 0;
1040out: 1295out:
1041 free_page((unsigned long)page); 1296 free_page((unsigned long)page);
1042 return ret; 1297
1043err:
1044 if (names) { 1298 if (names) {
1045 for (i = 0; i < num; i++) 1299 for (i = 0; i < num; i++)
1046 kfree(names[i]); 1300 kfree(names[i]);
@@ -1048,8 +1302,8 @@ err:
1048 } 1302 }
1049 kfree(values); 1303 kfree(values);
1050 sel_remove_entries(dir); 1304 sel_remove_entries(dir);
1051 ret = -ENOMEM; 1305
1052 goto out; 1306 return ret;
1053} 1307}
1054 1308
1055#define NULL_FILE_NAME "null" 1309#define NULL_FILE_NAME "null"
@@ -1071,47 +1325,41 @@ static ssize_t sel_write_avc_cache_threshold(struct file *file,
1071 size_t count, loff_t *ppos) 1325 size_t count, loff_t *ppos)
1072 1326
1073{ 1327{
1074 char *page; 1328 char *page = NULL;
1075 ssize_t ret; 1329 ssize_t ret;
1076 int new_value; 1330 int new_value;
1077 1331
1078 if (count >= PAGE_SIZE) { 1332 ret = task_has_security(current, SECURITY__SETSECPARAM);
1079 ret = -ENOMEM; 1333 if (ret)
1080 goto out; 1334 goto out;
1081 }
1082 1335
1083 if (*ppos != 0) { 1336 ret = -ENOMEM;
1084 /* No partial writes. */ 1337 if (count >= PAGE_SIZE)
1085 ret = -EINVAL; 1338 goto out;
1339
1340 /* No partial writes. */
1341 ret = -EINVAL;
1342 if (*ppos != 0)
1086 goto out; 1343 goto out;
1087 }
1088 1344
1345 ret = -ENOMEM;
1089 page = (char *)get_zeroed_page(GFP_KERNEL); 1346 page = (char *)get_zeroed_page(GFP_KERNEL);
1090 if (!page) { 1347 if (!page)
1091 ret = -ENOMEM;
1092 goto out; 1348 goto out;
1093 }
1094 1349
1095 if (copy_from_user(page, buf, count)) { 1350 ret = -EFAULT;
1096 ret = -EFAULT; 1351 if (copy_from_user(page, buf, count))
1097 goto out_free; 1352 goto out;
1098 }
1099 1353
1100 if (sscanf(page, "%u", &new_value) != 1) { 1354 ret = -EINVAL;
1101 ret = -EINVAL; 1355 if (sscanf(page, "%u", &new_value) != 1)
1102 goto out; 1356 goto out;
1103 }
1104 1357
1105 if (new_value != avc_cache_threshold) { 1358 avc_cache_threshold = new_value;
1106 ret = task_has_security(current, SECURITY__SETSECPARAM); 1359
1107 if (ret)
1108 goto out_free;
1109 avc_cache_threshold = new_value;
1110 }
1111 ret = count; 1360 ret = count;
1112out_free:
1113 free_page((unsigned long)page);
1114out: 1361out:
1362 free_page((unsigned long)page);
1115 return ret; 1363 return ret;
1116} 1364}
1117 1365
@@ -1119,19 +1367,18 @@ static ssize_t sel_read_avc_hash_stats(struct file *filp, char __user *buf,
1119 size_t count, loff_t *ppos) 1367 size_t count, loff_t *ppos)
1120{ 1368{
1121 char *page; 1369 char *page;
1122 ssize_t ret = 0; 1370 ssize_t length;
1123 1371
1124 page = (char *)__get_free_page(GFP_KERNEL); 1372 page = (char *)__get_free_page(GFP_KERNEL);
1125 if (!page) { 1373 if (!page)
1126 ret = -ENOMEM; 1374 return -ENOMEM;
1127 goto out; 1375
1128 } 1376 length = avc_get_hash_stats(page);
1129 ret = avc_get_hash_stats(page); 1377 if (length >= 0)
1130 if (ret >= 0) 1378 length = simple_read_from_buffer(buf, count, ppos, page, length);
1131 ret = simple_read_from_buffer(buf, count, ppos, page, ret);
1132 free_page((unsigned long)page); 1379 free_page((unsigned long)page);
1133out: 1380
1134 return ret; 1381 return length;
1135} 1382}
1136 1383
1137static const struct file_operations sel_avc_cache_threshold_ops = { 1384static const struct file_operations sel_avc_cache_threshold_ops = {
@@ -1181,10 +1428,14 @@ static int sel_avc_stats_seq_show(struct seq_file *seq, void *v)
1181 if (v == SEQ_START_TOKEN) 1428 if (v == SEQ_START_TOKEN)
1182 seq_printf(seq, "lookups hits misses allocations reclaims " 1429 seq_printf(seq, "lookups hits misses allocations reclaims "
1183 "frees\n"); 1430 "frees\n");
1184 else 1431 else {
1185 seq_printf(seq, "%u %u %u %u %u %u\n", st->lookups, 1432 unsigned int lookups = st->lookups;
1186 st->hits, st->misses, st->allocations, 1433 unsigned int misses = st->misses;
1434 unsigned int hits = lookups - misses;
1435 seq_printf(seq, "%u %u %u %u %u %u\n", lookups,
1436 hits, misses, st->allocations,
1187 st->reclaims, st->frees); 1437 st->reclaims, st->frees);
1438 }
1188 return 0; 1439 return 0;
1189} 1440}
1190 1441
@@ -1213,7 +1464,7 @@ static const struct file_operations sel_avc_cache_stats_ops = {
1213 1464
1214static int sel_make_avc_files(struct dentry *dir) 1465static int sel_make_avc_files(struct dentry *dir)
1215{ 1466{
1216 int i, ret = 0; 1467 int i;
1217 static struct tree_descr files[] = { 1468 static struct tree_descr files[] = {
1218 { "cache_threshold", 1469 { "cache_threshold",
1219 &sel_avc_cache_threshold_ops, S_IRUGO|S_IWUSR }, 1470 &sel_avc_cache_threshold_ops, S_IRUGO|S_IWUSR },
@@ -1228,22 +1479,19 @@ static int sel_make_avc_files(struct dentry *dir)
1228 struct dentry *dentry; 1479 struct dentry *dentry;
1229 1480
1230 dentry = d_alloc_name(dir, files[i].name); 1481 dentry = d_alloc_name(dir, files[i].name);
1231 if (!dentry) { 1482 if (!dentry)
1232 ret = -ENOMEM; 1483 return -ENOMEM;
1233 goto out;
1234 }
1235 1484
1236 inode = sel_make_inode(dir->d_sb, S_IFREG|files[i].mode); 1485 inode = sel_make_inode(dir->d_sb, S_IFREG|files[i].mode);
1237 if (!inode) { 1486 if (!inode)
1238 ret = -ENOMEM; 1487 return -ENOMEM;
1239 goto out; 1488
1240 }
1241 inode->i_fop = files[i].ops; 1489 inode->i_fop = files[i].ops;
1242 inode->i_ino = ++sel_last_ino; 1490 inode->i_ino = ++sel_last_ino;
1243 d_add(dentry, inode); 1491 d_add(dentry, inode);
1244 } 1492 }
1245out: 1493
1246 return ret; 1494 return 0;
1247} 1495}
1248 1496
1249static ssize_t sel_read_initcon(struct file *file, char __user *buf, 1497static ssize_t sel_read_initcon(struct file *file, char __user *buf,
@@ -1257,7 +1505,7 @@ static ssize_t sel_read_initcon(struct file *file, char __user *buf,
1257 inode = file->f_path.dentry->d_inode; 1505 inode = file->f_path.dentry->d_inode;
1258 sid = inode->i_ino&SEL_INO_MASK; 1506 sid = inode->i_ino&SEL_INO_MASK;
1259 ret = security_sid_to_context(sid, &con, &len); 1507 ret = security_sid_to_context(sid, &con, &len);
1260 if (ret < 0) 1508 if (ret)
1261 return ret; 1509 return ret;
1262 1510
1263 ret = simple_read_from_buffer(buf, count, ppos, con, len); 1511 ret = simple_read_from_buffer(buf, count, ppos, con, len);
@@ -1272,28 +1520,25 @@ static const struct file_operations sel_initcon_ops = {
1272 1520
1273static int sel_make_initcon_files(struct dentry *dir) 1521static int sel_make_initcon_files(struct dentry *dir)
1274{ 1522{
1275 int i, ret = 0; 1523 int i;
1276 1524
1277 for (i = 1; i <= SECINITSID_NUM; i++) { 1525 for (i = 1; i <= SECINITSID_NUM; i++) {
1278 struct inode *inode; 1526 struct inode *inode;
1279 struct dentry *dentry; 1527 struct dentry *dentry;
1280 dentry = d_alloc_name(dir, security_get_initial_sid_context(i)); 1528 dentry = d_alloc_name(dir, security_get_initial_sid_context(i));
1281 if (!dentry) { 1529 if (!dentry)
1282 ret = -ENOMEM; 1530 return -ENOMEM;
1283 goto out;
1284 }
1285 1531
1286 inode = sel_make_inode(dir->d_sb, S_IFREG|S_IRUGO); 1532 inode = sel_make_inode(dir->d_sb, S_IFREG|S_IRUGO);
1287 if (!inode) { 1533 if (!inode)
1288 ret = -ENOMEM; 1534 return -ENOMEM;
1289 goto out; 1535
1290 }
1291 inode->i_fop = &sel_initcon_ops; 1536 inode->i_fop = &sel_initcon_ops;
1292 inode->i_ino = i|SEL_INITCON_INO_OFFSET; 1537 inode->i_ino = i|SEL_INITCON_INO_OFFSET;
1293 d_add(dentry, inode); 1538 d_add(dentry, inode);
1294 } 1539 }
1295out: 1540
1296 return ret; 1541 return 0;
1297} 1542}
1298 1543
1299static inline unsigned int sel_div(unsigned long a, unsigned long b) 1544static inline unsigned int sel_div(unsigned long a, unsigned long b)
@@ -1329,15 +1574,13 @@ static ssize_t sel_read_class(struct file *file, char __user *buf,
1329 unsigned long ino = file->f_path.dentry->d_inode->i_ino; 1574 unsigned long ino = file->f_path.dentry->d_inode->i_ino;
1330 1575
1331 page = (char *)__get_free_page(GFP_KERNEL); 1576 page = (char *)__get_free_page(GFP_KERNEL);
1332 if (!page) { 1577 if (!page)
1333 rc = -ENOMEM; 1578 return -ENOMEM;
1334 goto out;
1335 }
1336 1579
1337 len = snprintf(page, PAGE_SIZE, "%d", sel_ino_to_class(ino)); 1580 len = snprintf(page, PAGE_SIZE, "%d", sel_ino_to_class(ino));
1338 rc = simple_read_from_buffer(buf, count, ppos, page, len); 1581 rc = simple_read_from_buffer(buf, count, ppos, page, len);
1339 free_page((unsigned long)page); 1582 free_page((unsigned long)page);
1340out: 1583
1341 return rc; 1584 return rc;
1342} 1585}
1343 1586
@@ -1354,15 +1597,13 @@ static ssize_t sel_read_perm(struct file *file, char __user *buf,
1354 unsigned long ino = file->f_path.dentry->d_inode->i_ino; 1597 unsigned long ino = file->f_path.dentry->d_inode->i_ino;
1355 1598
1356 page = (char *)__get_free_page(GFP_KERNEL); 1599 page = (char *)__get_free_page(GFP_KERNEL);
1357 if (!page) { 1600 if (!page)
1358 rc = -ENOMEM; 1601 return -ENOMEM;
1359 goto out;
1360 }
1361 1602
1362 len = snprintf(page, PAGE_SIZE, "%d", sel_ino_to_perm(ino)); 1603 len = snprintf(page, PAGE_SIZE, "%d", sel_ino_to_perm(ino));
1363 rc = simple_read_from_buffer(buf, count, ppos, page, len); 1604 rc = simple_read_from_buffer(buf, count, ppos, page, len);
1364 free_page((unsigned long)page); 1605 free_page((unsigned long)page);
1365out: 1606
1366 return rc; 1607 return rc;
1367} 1608}
1368 1609
@@ -1393,39 +1634,37 @@ static const struct file_operations sel_policycap_ops = {
1393static int sel_make_perm_files(char *objclass, int classvalue, 1634static int sel_make_perm_files(char *objclass, int classvalue,
1394 struct dentry *dir) 1635 struct dentry *dir)
1395{ 1636{
1396 int i, rc = 0, nperms; 1637 int i, rc, nperms;
1397 char **perms; 1638 char **perms;
1398 1639
1399 rc = security_get_permissions(objclass, &perms, &nperms); 1640 rc = security_get_permissions(objclass, &perms, &nperms);
1400 if (rc) 1641 if (rc)
1401 goto out; 1642 return rc;
1402 1643
1403 for (i = 0; i < nperms; i++) { 1644 for (i = 0; i < nperms; i++) {
1404 struct inode *inode; 1645 struct inode *inode;
1405 struct dentry *dentry; 1646 struct dentry *dentry;
1406 1647
1648 rc = -ENOMEM;
1407 dentry = d_alloc_name(dir, perms[i]); 1649 dentry = d_alloc_name(dir, perms[i]);
1408 if (!dentry) { 1650 if (!dentry)
1409 rc = -ENOMEM; 1651 goto out;
1410 goto out1;
1411 }
1412 1652
1653 rc = -ENOMEM;
1413 inode = sel_make_inode(dir->d_sb, S_IFREG|S_IRUGO); 1654 inode = sel_make_inode(dir->d_sb, S_IFREG|S_IRUGO);
1414 if (!inode) { 1655 if (!inode)
1415 rc = -ENOMEM; 1656 goto out;
1416 goto out1; 1657
1417 }
1418 inode->i_fop = &sel_perm_ops; 1658 inode->i_fop = &sel_perm_ops;
1419 /* i+1 since perm values are 1-indexed */ 1659 /* i+1 since perm values are 1-indexed */
1420 inode->i_ino = sel_perm_to_ino(classvalue, i + 1); 1660 inode->i_ino = sel_perm_to_ino(classvalue, i + 1);
1421 d_add(dentry, inode); 1661 d_add(dentry, inode);
1422 } 1662 }
1423 1663 rc = 0;
1424out1: 1664out:
1425 for (i = 0; i < nperms; i++) 1665 for (i = 0; i < nperms; i++)
1426 kfree(perms[i]); 1666 kfree(perms[i]);
1427 kfree(perms); 1667 kfree(perms);
1428out:
1429 return rc; 1668 return rc;
1430} 1669}
1431 1670
@@ -1437,34 +1676,27 @@ static int sel_make_class_dir_entries(char *classname, int index,
1437 int rc; 1676 int rc;
1438 1677
1439 dentry = d_alloc_name(dir, "index"); 1678 dentry = d_alloc_name(dir, "index");
1440 if (!dentry) { 1679 if (!dentry)
1441 rc = -ENOMEM; 1680 return -ENOMEM;
1442 goto out;
1443 }
1444 1681
1445 inode = sel_make_inode(dir->d_sb, S_IFREG|S_IRUGO); 1682 inode = sel_make_inode(dir->d_sb, S_IFREG|S_IRUGO);
1446 if (!inode) { 1683 if (!inode)
1447 rc = -ENOMEM; 1684 return -ENOMEM;
1448 goto out;
1449 }
1450 1685
1451 inode->i_fop = &sel_class_ops; 1686 inode->i_fop = &sel_class_ops;
1452 inode->i_ino = sel_class_to_ino(index); 1687 inode->i_ino = sel_class_to_ino(index);
1453 d_add(dentry, inode); 1688 d_add(dentry, inode);
1454 1689
1455 dentry = d_alloc_name(dir, "perms"); 1690 dentry = d_alloc_name(dir, "perms");
1456 if (!dentry) { 1691 if (!dentry)
1457 rc = -ENOMEM; 1692 return -ENOMEM;
1458 goto out;
1459 }
1460 1693
1461 rc = sel_make_dir(dir->d_inode, dentry, &last_class_ino); 1694 rc = sel_make_dir(dir->d_inode, dentry, &last_class_ino);
1462 if (rc) 1695 if (rc)
1463 goto out; 1696 return rc;
1464 1697
1465 rc = sel_make_perm_files(classname, index, dentry); 1698 rc = sel_make_perm_files(classname, index, dentry);
1466 1699
1467out:
1468 return rc; 1700 return rc;
1469} 1701}
1470 1702
@@ -1494,15 +1726,15 @@ static void sel_remove_classes(void)
1494 1726
1495static int sel_make_classes(void) 1727static int sel_make_classes(void)
1496{ 1728{
1497 int rc = 0, nclasses, i; 1729 int rc, nclasses, i;
1498 char **classes; 1730 char **classes;
1499 1731
1500 /* delete any existing entries */ 1732 /* delete any existing entries */
1501 sel_remove_classes(); 1733 sel_remove_classes();
1502 1734
1503 rc = security_get_classes(&classes, &nclasses); 1735 rc = security_get_classes(&classes, &nclasses);
1504 if (rc < 0) 1736 if (rc)
1505 goto out; 1737 return rc;
1506 1738
1507 /* +2 since classes are 1-indexed */ 1739 /* +2 since classes are 1-indexed */
1508 last_class_ino = sel_class_to_ino(nclasses + 2); 1740 last_class_ino = sel_class_to_ino(nclasses + 2);
@@ -1510,29 +1742,27 @@ static int sel_make_classes(void)
1510 for (i = 0; i < nclasses; i++) { 1742 for (i = 0; i < nclasses; i++) {
1511 struct dentry *class_name_dir; 1743 struct dentry *class_name_dir;
1512 1744
1745 rc = -ENOMEM;
1513 class_name_dir = d_alloc_name(class_dir, classes[i]); 1746 class_name_dir = d_alloc_name(class_dir, classes[i]);
1514 if (!class_name_dir) { 1747 if (!class_name_dir)
1515 rc = -ENOMEM; 1748 goto out;
1516 goto out1;
1517 }
1518 1749
1519 rc = sel_make_dir(class_dir->d_inode, class_name_dir, 1750 rc = sel_make_dir(class_dir->d_inode, class_name_dir,
1520 &last_class_ino); 1751 &last_class_ino);
1521 if (rc) 1752 if (rc)
1522 goto out1; 1753 goto out;
1523 1754
1524 /* i+1 since class values are 1-indexed */ 1755 /* i+1 since class values are 1-indexed */
1525 rc = sel_make_class_dir_entries(classes[i], i + 1, 1756 rc = sel_make_class_dir_entries(classes[i], i + 1,
1526 class_name_dir); 1757 class_name_dir);
1527 if (rc) 1758 if (rc)
1528 goto out1; 1759 goto out;
1529 } 1760 }
1530 1761 rc = 0;
1531out1: 1762out:
1532 for (i = 0; i < nclasses; i++) 1763 for (i = 0; i < nclasses; i++)
1533 kfree(classes[i]); 1764 kfree(classes[i]);
1534 kfree(classes); 1765 kfree(classes);
1535out:
1536 return rc; 1766 return rc;
1537} 1767}
1538 1768
@@ -1569,14 +1799,12 @@ static int sel_make_policycap(void)
1569static int sel_make_dir(struct inode *dir, struct dentry *dentry, 1799static int sel_make_dir(struct inode *dir, struct dentry *dentry,
1570 unsigned long *ino) 1800 unsigned long *ino)
1571{ 1801{
1572 int ret = 0;
1573 struct inode *inode; 1802 struct inode *inode;
1574 1803
1575 inode = sel_make_inode(dir->i_sb, S_IFDIR | S_IRUGO | S_IXUGO); 1804 inode = sel_make_inode(dir->i_sb, S_IFDIR | S_IRUGO | S_IXUGO);
1576 if (!inode) { 1805 if (!inode)
1577 ret = -ENOMEM; 1806 return -ENOMEM;
1578 goto out; 1807
1579 }
1580 inode->i_op = &simple_dir_inode_operations; 1808 inode->i_op = &simple_dir_inode_operations;
1581 inode->i_fop = &simple_dir_operations; 1809 inode->i_fop = &simple_dir_operations;
1582 inode->i_ino = ++(*ino); 1810 inode->i_ino = ++(*ino);
@@ -1585,8 +1813,8 @@ static int sel_make_dir(struct inode *dir, struct dentry *dentry,
1585 d_add(dentry, inode); 1813 d_add(dentry, inode);
1586 /* bump link count on parent directory, too */ 1814 /* bump link count on parent directory, too */
1587 inc_nlink(dir); 1815 inc_nlink(dir);
1588out: 1816
1589 return ret; 1817 return 0;
1590} 1818}
1591 1819
1592static int sel_fill_super(struct super_block *sb, void *data, int silent) 1820static int sel_fill_super(struct super_block *sb, void *data, int silent)
@@ -1612,6 +1840,8 @@ static int sel_fill_super(struct super_block *sb, void *data, int silent)
1612 [SEL_CHECKREQPROT] = {"checkreqprot", &sel_checkreqprot_ops, S_IRUGO|S_IWUSR}, 1840 [SEL_CHECKREQPROT] = {"checkreqprot", &sel_checkreqprot_ops, S_IRUGO|S_IWUSR},
1613 [SEL_REJECT_UNKNOWN] = {"reject_unknown", &sel_handle_unknown_ops, S_IRUGO}, 1841 [SEL_REJECT_UNKNOWN] = {"reject_unknown", &sel_handle_unknown_ops, S_IRUGO},
1614 [SEL_DENY_UNKNOWN] = {"deny_unknown", &sel_handle_unknown_ops, S_IRUGO}, 1842 [SEL_DENY_UNKNOWN] = {"deny_unknown", &sel_handle_unknown_ops, S_IRUGO},
1843 [SEL_STATUS] = {"status", &sel_handle_status_ops, S_IRUGO},
1844 [SEL_POLICY] = {"policy", &sel_policy_ops, S_IRUSR},
1615 /* last one */ {""} 1845 /* last one */ {""}
1616 }; 1846 };
1617 ret = simple_fill_super(sb, SELINUX_MAGIC, selinux_files); 1847 ret = simple_fill_super(sb, SELINUX_MAGIC, selinux_files);
@@ -1620,11 +1850,10 @@ static int sel_fill_super(struct super_block *sb, void *data, int silent)
1620 1850
1621 root_inode = sb->s_root->d_inode; 1851 root_inode = sb->s_root->d_inode;
1622 1852
1853 ret = -ENOMEM;
1623 dentry = d_alloc_name(sb->s_root, BOOL_DIR_NAME); 1854 dentry = d_alloc_name(sb->s_root, BOOL_DIR_NAME);
1624 if (!dentry) { 1855 if (!dentry)
1625 ret = -ENOMEM;
1626 goto err; 1856 goto err;
1627 }
1628 1857
1629 ret = sel_make_dir(root_inode, dentry, &sel_last_ino); 1858 ret = sel_make_dir(root_inode, dentry, &sel_last_ino);
1630 if (ret) 1859 if (ret)
@@ -1632,17 +1861,16 @@ static int sel_fill_super(struct super_block *sb, void *data, int silent)
1632 1861
1633 bool_dir = dentry; 1862 bool_dir = dentry;
1634 1863
1864 ret = -ENOMEM;
1635 dentry = d_alloc_name(sb->s_root, NULL_FILE_NAME); 1865 dentry = d_alloc_name(sb->s_root, NULL_FILE_NAME);
1636 if (!dentry) { 1866 if (!dentry)
1637 ret = -ENOMEM;
1638 goto err; 1867 goto err;
1639 }
1640 1868
1869 ret = -ENOMEM;
1641 inode = sel_make_inode(sb, S_IFCHR | S_IRUGO | S_IWUGO); 1870 inode = sel_make_inode(sb, S_IFCHR | S_IRUGO | S_IWUGO);
1642 if (!inode) { 1871 if (!inode)
1643 ret = -ENOMEM;
1644 goto err; 1872 goto err;
1645 } 1873
1646 inode->i_ino = ++sel_last_ino; 1874 inode->i_ino = ++sel_last_ino;
1647 isec = (struct inode_security_struct *)inode->i_security; 1875 isec = (struct inode_security_struct *)inode->i_security;
1648 isec->sid = SECINITSID_DEVNULL; 1876 isec->sid = SECINITSID_DEVNULL;
@@ -1653,11 +1881,10 @@ static int sel_fill_super(struct super_block *sb, void *data, int silent)
1653 d_add(dentry, inode); 1881 d_add(dentry, inode);
1654 selinux_null = dentry; 1882 selinux_null = dentry;
1655 1883
1884 ret = -ENOMEM;
1656 dentry = d_alloc_name(sb->s_root, "avc"); 1885 dentry = d_alloc_name(sb->s_root, "avc");
1657 if (!dentry) { 1886 if (!dentry)
1658 ret = -ENOMEM;
1659 goto err; 1887 goto err;
1660 }
1661 1888
1662 ret = sel_make_dir(root_inode, dentry, &sel_last_ino); 1889 ret = sel_make_dir(root_inode, dentry, &sel_last_ino);
1663 if (ret) 1890 if (ret)
@@ -1667,11 +1894,10 @@ static int sel_fill_super(struct super_block *sb, void *data, int silent)
1667 if (ret) 1894 if (ret)
1668 goto err; 1895 goto err;
1669 1896
1897 ret = -ENOMEM;
1670 dentry = d_alloc_name(sb->s_root, "initial_contexts"); 1898 dentry = d_alloc_name(sb->s_root, "initial_contexts");
1671 if (!dentry) { 1899 if (!dentry)
1672 ret = -ENOMEM;
1673 goto err; 1900 goto err;
1674 }
1675 1901
1676 ret = sel_make_dir(root_inode, dentry, &sel_last_ino); 1902 ret = sel_make_dir(root_inode, dentry, &sel_last_ino);
1677 if (ret) 1903 if (ret)
@@ -1681,11 +1907,10 @@ static int sel_fill_super(struct super_block *sb, void *data, int silent)
1681 if (ret) 1907 if (ret)
1682 goto err; 1908 goto err;
1683 1909
1910 ret = -ENOMEM;
1684 dentry = d_alloc_name(sb->s_root, "class"); 1911 dentry = d_alloc_name(sb->s_root, "class");
1685 if (!dentry) { 1912 if (!dentry)
1686 ret = -ENOMEM;
1687 goto err; 1913 goto err;
1688 }
1689 1914
1690 ret = sel_make_dir(root_inode, dentry, &sel_last_ino); 1915 ret = sel_make_dir(root_inode, dentry, &sel_last_ino);
1691 if (ret) 1916 if (ret)
@@ -1693,11 +1918,10 @@ static int sel_fill_super(struct super_block *sb, void *data, int silent)
1693 1918
1694 class_dir = dentry; 1919 class_dir = dentry;
1695 1920
1921 ret = -ENOMEM;
1696 dentry = d_alloc_name(sb->s_root, "policy_capabilities"); 1922 dentry = d_alloc_name(sb->s_root, "policy_capabilities");
1697 if (!dentry) { 1923 if (!dentry)
1698 ret = -ENOMEM;
1699 goto err; 1924 goto err;
1700 }
1701 1925
1702 ret = sel_make_dir(root_inode, dentry, &sel_last_ino); 1926 ret = sel_make_dir(root_inode, dentry, &sel_last_ino);
1703 if (ret) 1927 if (ret)
@@ -1705,28 +1929,27 @@ static int sel_fill_super(struct super_block *sb, void *data, int silent)
1705 1929
1706 policycap_dir = dentry; 1930 policycap_dir = dentry;
1707 1931
1708out: 1932 return 0;
1709 return ret;
1710err: 1933err:
1711 printk(KERN_ERR "SELinux: %s: failed while creating inodes\n", 1934 printk(KERN_ERR "SELinux: %s: failed while creating inodes\n",
1712 __func__); 1935 __func__);
1713 goto out; 1936 return ret;
1714} 1937}
1715 1938
1716static int sel_get_sb(struct file_system_type *fs_type, 1939static struct dentry *sel_mount(struct file_system_type *fs_type,
1717 int flags, const char *dev_name, void *data, 1940 int flags, const char *dev_name, void *data)
1718 struct vfsmount *mnt)
1719{ 1941{
1720 return get_sb_single(fs_type, flags, data, sel_fill_super, mnt); 1942 return mount_single(fs_type, flags, data, sel_fill_super);
1721} 1943}
1722 1944
1723static struct file_system_type sel_fs_type = { 1945static struct file_system_type sel_fs_type = {
1724 .name = "selinuxfs", 1946 .name = "selinuxfs",
1725 .get_sb = sel_get_sb, 1947 .mount = sel_mount,
1726 .kill_sb = kill_litter_super, 1948 .kill_sb = kill_litter_super,
1727}; 1949};
1728 1950
1729struct vfsmount *selinuxfs_mount; 1951struct vfsmount *selinuxfs_mount;
1952static struct kobject *selinuxfs_kobj;
1730 1953
1731static int __init init_sel_fs(void) 1954static int __init init_sel_fs(void)
1732{ 1955{
@@ -1734,15 +1957,24 @@ static int __init init_sel_fs(void)
1734 1957
1735 if (!selinux_enabled) 1958 if (!selinux_enabled)
1736 return 0; 1959 return 0;
1960
1961 selinuxfs_kobj = kobject_create_and_add("selinux", fs_kobj);
1962 if (!selinuxfs_kobj)
1963 return -ENOMEM;
1964
1737 err = register_filesystem(&sel_fs_type); 1965 err = register_filesystem(&sel_fs_type);
1738 if (!err) { 1966 if (err) {
1739 selinuxfs_mount = kern_mount(&sel_fs_type); 1967 kobject_put(selinuxfs_kobj);
1740 if (IS_ERR(selinuxfs_mount)) { 1968 return err;
1741 printk(KERN_ERR "selinuxfs: could not mount!\n");
1742 err = PTR_ERR(selinuxfs_mount);
1743 selinuxfs_mount = NULL;
1744 }
1745 } 1969 }
1970
1971 selinuxfs_mount = kern_mount(&sel_fs_type);
1972 if (IS_ERR(selinuxfs_mount)) {
1973 printk(KERN_ERR "selinuxfs: could not mount!\n");
1974 err = PTR_ERR(selinuxfs_mount);
1975 selinuxfs_mount = NULL;
1976 }
1977
1746 return err; 1978 return err;
1747} 1979}
1748 1980
@@ -1751,6 +1983,7 @@ __initcall(init_sel_fs);
1751#ifdef CONFIG_SECURITY_SELINUX_DISABLE 1983#ifdef CONFIG_SECURITY_SELINUX_DISABLE
1752void exit_sel_fs(void) 1984void exit_sel_fs(void)
1753{ 1985{
1986 kobject_put(selinuxfs_kobj);
1754 unregister_filesystem(&sel_fs_type); 1987 unregister_filesystem(&sel_fs_type);
1755} 1988}
1756#endif 1989#endif
diff --git a/security/selinux/ss/Makefile b/security/selinux/ss/Makefile
deleted file mode 100644
index 15d4e62917de..000000000000
--- a/security/selinux/ss/Makefile
+++ /dev/null
@@ -1,9 +0,0 @@
1#
2# Makefile for building the SELinux security server as part of the kernel tree.
3#
4
5EXTRA_CFLAGS += -Isecurity/selinux -Isecurity/selinux/include
6obj-y := ss.o
7
8ss-y := ebitmap.o hashtab.o symtab.o sidtab.o avtab.o policydb.o services.o conditional.o mls.o
9
diff --git a/security/selinux/ss/avtab.c b/security/selinux/ss/avtab.c
index 929480c6c430..a3dd9faa19c0 100644
--- a/security/selinux/ss/avtab.c
+++ b/security/selinux/ss/avtab.c
@@ -266,8 +266,8 @@ int avtab_alloc(struct avtab *h, u32 nrules)
266 if (shift > 2) 266 if (shift > 2)
267 shift = shift - 2; 267 shift = shift - 2;
268 nslot = 1 << shift; 268 nslot = 1 << shift;
269 if (nslot > MAX_AVTAB_SIZE) 269 if (nslot > MAX_AVTAB_HASH_BUCKETS)
270 nslot = MAX_AVTAB_SIZE; 270 nslot = MAX_AVTAB_HASH_BUCKETS;
271 mask = nslot - 1; 271 mask = nslot - 1;
272 272
273 h->htable = kcalloc(nslot, sizeof(*(h->htable)), GFP_KERNEL); 273 h->htable = kcalloc(nslot, sizeof(*(h->htable)), GFP_KERNEL);
@@ -501,6 +501,48 @@ bad:
501 goto out; 501 goto out;
502} 502}
503 503
504int avtab_write_item(struct policydb *p, struct avtab_node *cur, void *fp)
505{
506 __le16 buf16[4];
507 __le32 buf32[1];
508 int rc;
509
510 buf16[0] = cpu_to_le16(cur->key.source_type);
511 buf16[1] = cpu_to_le16(cur->key.target_type);
512 buf16[2] = cpu_to_le16(cur->key.target_class);
513 buf16[3] = cpu_to_le16(cur->key.specified);
514 rc = put_entry(buf16, sizeof(u16), 4, fp);
515 if (rc)
516 return rc;
517 buf32[0] = cpu_to_le32(cur->datum.data);
518 rc = put_entry(buf32, sizeof(u32), 1, fp);
519 if (rc)
520 return rc;
521 return 0;
522}
523
524int avtab_write(struct policydb *p, struct avtab *a, void *fp)
525{
526 unsigned int i;
527 int rc = 0;
528 struct avtab_node *cur;
529 __le32 buf[1];
530
531 buf[0] = cpu_to_le32(a->nel);
532 rc = put_entry(buf, sizeof(u32), 1, fp);
533 if (rc)
534 return rc;
535
536 for (i = 0; i < a->nslot; i++) {
537 for (cur = a->htable[i]; cur; cur = cur->next) {
538 rc = avtab_write_item(p, cur, fp);
539 if (rc)
540 return rc;
541 }
542 }
543
544 return rc;
545}
504void avtab_cache_init(void) 546void avtab_cache_init(void)
505{ 547{
506 avtab_node_cachep = kmem_cache_create("avtab_node", 548 avtab_node_cachep = kmem_cache_create("avtab_node",
diff --git a/security/selinux/ss/avtab.h b/security/selinux/ss/avtab.h
index cd4f734e2749..63ce2f9e441d 100644
--- a/security/selinux/ss/avtab.h
+++ b/security/selinux/ss/avtab.h
@@ -14,7 +14,7 @@
14 * 14 *
15 * Copyright (C) 2003 Tresys Technology, LLC 15 * Copyright (C) 2003 Tresys Technology, LLC
16 * This program is free software; you can redistribute it and/or modify 16 * This program is free software; you can redistribute it and/or modify
17 * it under the terms of the GNU General Public License as published by 17 * it under the terms of the GNU General Public License as published by
18 * the Free Software Foundation, version 2. 18 * the Free Software Foundation, version 2.
19 * 19 *
20 * Updated: Yuichi Nakamura <ynakam@hitachisoft.jp> 20 * Updated: Yuichi Nakamura <ynakam@hitachisoft.jp>
@@ -27,16 +27,16 @@ struct avtab_key {
27 u16 source_type; /* source type */ 27 u16 source_type; /* source type */
28 u16 target_type; /* target type */ 28 u16 target_type; /* target type */
29 u16 target_class; /* target object class */ 29 u16 target_class; /* target object class */
30#define AVTAB_ALLOWED 1 30#define AVTAB_ALLOWED 0x0001
31#define AVTAB_AUDITALLOW 2 31#define AVTAB_AUDITALLOW 0x0002
32#define AVTAB_AUDITDENY 4 32#define AVTAB_AUDITDENY 0x0004
33#define AVTAB_AV (AVTAB_ALLOWED | AVTAB_AUDITALLOW | AVTAB_AUDITDENY) 33#define AVTAB_AV (AVTAB_ALLOWED | AVTAB_AUDITALLOW | AVTAB_AUDITDENY)
34#define AVTAB_TRANSITION 16 34#define AVTAB_TRANSITION 0x0010
35#define AVTAB_MEMBER 32 35#define AVTAB_MEMBER 0x0020
36#define AVTAB_CHANGE 64 36#define AVTAB_CHANGE 0x0040
37#define AVTAB_TYPE (AVTAB_TRANSITION | AVTAB_MEMBER | AVTAB_CHANGE) 37#define AVTAB_TYPE (AVTAB_TRANSITION | AVTAB_MEMBER | AVTAB_CHANGE)
38#define AVTAB_ENABLED_OLD 0x80000000 /* reserved for used in cond_avtab */ 38#define AVTAB_ENABLED_OLD 0x80000000 /* reserved for used in cond_avtab */
39#define AVTAB_ENABLED 0x8000 /* reserved for used in cond_avtab */ 39#define AVTAB_ENABLED 0x8000 /* reserved for used in cond_avtab */
40 u16 specified; /* what field is specified */ 40 u16 specified; /* what field is specified */
41}; 41};
42 42
@@ -71,6 +71,8 @@ int avtab_read_item(struct avtab *a, void *fp, struct policydb *pol,
71 void *p); 71 void *p);
72 72
73int avtab_read(struct avtab *a, void *fp, struct policydb *pol); 73int avtab_read(struct avtab *a, void *fp, struct policydb *pol);
74int avtab_write_item(struct policydb *p, struct avtab_node *cur, void *fp);
75int avtab_write(struct policydb *p, struct avtab *a, void *fp);
74 76
75struct avtab_node *avtab_insert_nonunique(struct avtab *h, struct avtab_key *key, 77struct avtab_node *avtab_insert_nonunique(struct avtab *h, struct avtab_key *key,
76 struct avtab_datum *datum); 78 struct avtab_datum *datum);
@@ -84,8 +86,6 @@ void avtab_cache_destroy(void);
84 86
85#define MAX_AVTAB_HASH_BITS 11 87#define MAX_AVTAB_HASH_BITS 11
86#define MAX_AVTAB_HASH_BUCKETS (1 << MAX_AVTAB_HASH_BITS) 88#define MAX_AVTAB_HASH_BUCKETS (1 << MAX_AVTAB_HASH_BITS)
87#define MAX_AVTAB_HASH_MASK (MAX_AVTAB_HASH_BUCKETS-1)
88#define MAX_AVTAB_SIZE MAX_AVTAB_HASH_BUCKETS
89 89
90#endif /* _SS_AVTAB_H_ */ 90#endif /* _SS_AVTAB_H_ */
91 91
diff --git a/security/selinux/ss/conditional.c b/security/selinux/ss/conditional.c
index c91e150c3087..a53373207fb4 100644
--- a/security/selinux/ss/conditional.c
+++ b/security/selinux/ss/conditional.c
@@ -178,7 +178,7 @@ int cond_init_bool_indexes(struct policydb *p)
178 p->bool_val_to_struct = (struct cond_bool_datum **) 178 p->bool_val_to_struct = (struct cond_bool_datum **)
179 kmalloc(p->p_bools.nprim * sizeof(struct cond_bool_datum *), GFP_KERNEL); 179 kmalloc(p->p_bools.nprim * sizeof(struct cond_bool_datum *), GFP_KERNEL);
180 if (!p->bool_val_to_struct) 180 if (!p->bool_val_to_struct)
181 return -1; 181 return -ENOMEM;
182 return 0; 182 return 0;
183} 183}
184 184
@@ -193,6 +193,7 @@ int cond_index_bool(void *key, void *datum, void *datap)
193{ 193{
194 struct policydb *p; 194 struct policydb *p;
195 struct cond_bool_datum *booldatum; 195 struct cond_bool_datum *booldatum;
196 struct flex_array *fa;
196 197
197 booldatum = datum; 198 booldatum = datum;
198 p = datap; 199 p = datap;
@@ -200,7 +201,10 @@ int cond_index_bool(void *key, void *datum, void *datap)
200 if (!booldatum->value || booldatum->value > p->p_bools.nprim) 201 if (!booldatum->value || booldatum->value > p->p_bools.nprim)
201 return -EINVAL; 202 return -EINVAL;
202 203
203 p->p_bool_val_to_name[booldatum->value - 1] = key; 204 fa = p->sym_val_to_name[SYM_BOOLS];
205 if (flex_array_put_ptr(fa, booldatum->value - 1, key,
206 GFP_KERNEL | __GFP_ZERO))
207 BUG();
204 p->bool_val_to_struct[booldatum->value - 1] = booldatum; 208 p->bool_val_to_struct[booldatum->value - 1] = booldatum;
205 209
206 return 0; 210 return 0;
@@ -490,6 +494,129 @@ err:
490 return rc; 494 return rc;
491} 495}
492 496
497int cond_write_bool(void *vkey, void *datum, void *ptr)
498{
499 char *key = vkey;
500 struct cond_bool_datum *booldatum = datum;
501 struct policy_data *pd = ptr;
502 void *fp = pd->fp;
503 __le32 buf[3];
504 u32 len;
505 int rc;
506
507 len = strlen(key);
508 buf[0] = cpu_to_le32(booldatum->value);
509 buf[1] = cpu_to_le32(booldatum->state);
510 buf[2] = cpu_to_le32(len);
511 rc = put_entry(buf, sizeof(u32), 3, fp);
512 if (rc)
513 return rc;
514 rc = put_entry(key, 1, len, fp);
515 if (rc)
516 return rc;
517 return 0;
518}
519
520/*
521 * cond_write_cond_av_list doesn't write out the av_list nodes.
522 * Instead it writes out the key/value pairs from the avtab. This
523 * is necessary because there is no way to uniquely identifying rules
524 * in the avtab so it is not possible to associate individual rules
525 * in the avtab with a conditional without saving them as part of
526 * the conditional. This means that the avtab with the conditional
527 * rules will not be saved but will be rebuilt on policy load.
528 */
529static int cond_write_av_list(struct policydb *p,
530 struct cond_av_list *list, struct policy_file *fp)
531{
532 __le32 buf[1];
533 struct cond_av_list *cur_list;
534 u32 len;
535 int rc;
536
537 len = 0;
538 for (cur_list = list; cur_list != NULL; cur_list = cur_list->next)
539 len++;
540
541 buf[0] = cpu_to_le32(len);
542 rc = put_entry(buf, sizeof(u32), 1, fp);
543 if (rc)
544 return rc;
545
546 if (len == 0)
547 return 0;
548
549 for (cur_list = list; cur_list != NULL; cur_list = cur_list->next) {
550 rc = avtab_write_item(p, cur_list->node, fp);
551 if (rc)
552 return rc;
553 }
554
555 return 0;
556}
557
558int cond_write_node(struct policydb *p, struct cond_node *node,
559 struct policy_file *fp)
560{
561 struct cond_expr *cur_expr;
562 __le32 buf[2];
563 int rc;
564 u32 len = 0;
565
566 buf[0] = cpu_to_le32(node->cur_state);
567 rc = put_entry(buf, sizeof(u32), 1, fp);
568 if (rc)
569 return rc;
570
571 for (cur_expr = node->expr; cur_expr != NULL; cur_expr = cur_expr->next)
572 len++;
573
574 buf[0] = cpu_to_le32(len);
575 rc = put_entry(buf, sizeof(u32), 1, fp);
576 if (rc)
577 return rc;
578
579 for (cur_expr = node->expr; cur_expr != NULL; cur_expr = cur_expr->next) {
580 buf[0] = cpu_to_le32(cur_expr->expr_type);
581 buf[1] = cpu_to_le32(cur_expr->bool);
582 rc = put_entry(buf, sizeof(u32), 2, fp);
583 if (rc)
584 return rc;
585 }
586
587 rc = cond_write_av_list(p, node->true_list, fp);
588 if (rc)
589 return rc;
590 rc = cond_write_av_list(p, node->false_list, fp);
591 if (rc)
592 return rc;
593
594 return 0;
595}
596
597int cond_write_list(struct policydb *p, struct cond_node *list, void *fp)
598{
599 struct cond_node *cur;
600 u32 len;
601 __le32 buf[1];
602 int rc;
603
604 len = 0;
605 for (cur = list; cur != NULL; cur = cur->next)
606 len++;
607 buf[0] = cpu_to_le32(len);
608 rc = put_entry(buf, sizeof(u32), 1, fp);
609 if (rc)
610 return rc;
611
612 for (cur = list; cur != NULL; cur = cur->next) {
613 rc = cond_write_node(p, cur, fp);
614 if (rc)
615 return rc;
616 }
617
618 return 0;
619}
493/* Determine whether additional permissions are granted by the conditional 620/* Determine whether additional permissions are granted by the conditional
494 * av table, and if so, add them to the result 621 * av table, and if so, add them to the result
495 */ 622 */
diff --git a/security/selinux/ss/conditional.h b/security/selinux/ss/conditional.h
index 53ddb013ae57..3f209c635295 100644
--- a/security/selinux/ss/conditional.h
+++ b/security/selinux/ss/conditional.h
@@ -69,6 +69,8 @@ int cond_index_bool(void *key, void *datum, void *datap);
69 69
70int cond_read_bool(struct policydb *p, struct hashtab *h, void *fp); 70int cond_read_bool(struct policydb *p, struct hashtab *h, void *fp);
71int cond_read_list(struct policydb *p, void *fp); 71int cond_read_list(struct policydb *p, void *fp);
72int cond_write_bool(void *key, void *datum, void *ptr);
73int cond_write_list(struct policydb *p, struct cond_node *list, void *fp);
72 74
73void cond_compute_av(struct avtab *ctab, struct avtab_key *key, struct av_decision *avd); 75void cond_compute_av(struct avtab *ctab, struct avtab_key *key, struct av_decision *avd);
74 76
diff --git a/security/selinux/ss/ebitmap.c b/security/selinux/ss/ebitmap.c
index 04b6145d767f..d42951fcbe87 100644
--- a/security/selinux/ss/ebitmap.c
+++ b/security/selinux/ss/ebitmap.c
@@ -22,6 +22,8 @@
22#include "ebitmap.h" 22#include "ebitmap.h"
23#include "policydb.h" 23#include "policydb.h"
24 24
25#define BITS_PER_U64 (sizeof(u64) * 8)
26
25int ebitmap_cmp(struct ebitmap *e1, struct ebitmap *e2) 27int ebitmap_cmp(struct ebitmap *e1, struct ebitmap *e2)
26{ 28{
27 struct ebitmap_node *n1, *n2; 29 struct ebitmap_node *n1, *n2;
@@ -363,10 +365,10 @@ int ebitmap_read(struct ebitmap *e, void *fp)
363 e->highbit = le32_to_cpu(buf[1]); 365 e->highbit = le32_to_cpu(buf[1]);
364 count = le32_to_cpu(buf[2]); 366 count = le32_to_cpu(buf[2]);
365 367
366 if (mapunit != sizeof(u64) * 8) { 368 if (mapunit != BITS_PER_U64) {
367 printk(KERN_ERR "SELinux: ebitmap: map size %u does not " 369 printk(KERN_ERR "SELinux: ebitmap: map size %u does not "
368 "match my size %Zd (high bit was %d)\n", 370 "match my size %Zd (high bit was %d)\n",
369 mapunit, sizeof(u64) * 8, e->highbit); 371 mapunit, BITS_PER_U64, e->highbit);
370 goto bad; 372 goto bad;
371 } 373 }
372 374
@@ -446,3 +448,78 @@ bad:
446 ebitmap_destroy(e); 448 ebitmap_destroy(e);
447 goto out; 449 goto out;
448} 450}
451
452int ebitmap_write(struct ebitmap *e, void *fp)
453{
454 struct ebitmap_node *n;
455 u32 count;
456 __le32 buf[3];
457 u64 map;
458 int bit, last_bit, last_startbit, rc;
459
460 buf[0] = cpu_to_le32(BITS_PER_U64);
461
462 count = 0;
463 last_bit = 0;
464 last_startbit = -1;
465 ebitmap_for_each_positive_bit(e, n, bit) {
466 if (rounddown(bit, (int)BITS_PER_U64) > last_startbit) {
467 count++;
468 last_startbit = rounddown(bit, BITS_PER_U64);
469 }
470 last_bit = roundup(bit + 1, BITS_PER_U64);
471 }
472 buf[1] = cpu_to_le32(last_bit);
473 buf[2] = cpu_to_le32(count);
474
475 rc = put_entry(buf, sizeof(u32), 3, fp);
476 if (rc)
477 return rc;
478
479 map = 0;
480 last_startbit = INT_MIN;
481 ebitmap_for_each_positive_bit(e, n, bit) {
482 if (rounddown(bit, (int)BITS_PER_U64) > last_startbit) {
483 __le64 buf64[1];
484
485 /* this is the very first bit */
486 if (!map) {
487 last_startbit = rounddown(bit, BITS_PER_U64);
488 map = (u64)1 << (bit - last_startbit);
489 continue;
490 }
491
492 /* write the last node */
493 buf[0] = cpu_to_le32(last_startbit);
494 rc = put_entry(buf, sizeof(u32), 1, fp);
495 if (rc)
496 return rc;
497
498 buf64[0] = cpu_to_le64(map);
499 rc = put_entry(buf64, sizeof(u64), 1, fp);
500 if (rc)
501 return rc;
502
503 /* set up for the next node */
504 map = 0;
505 last_startbit = rounddown(bit, BITS_PER_U64);
506 }
507 map |= (u64)1 << (bit - last_startbit);
508 }
509 /* write the last node */
510 if (map) {
511 __le64 buf64[1];
512
513 /* write the last node */
514 buf[0] = cpu_to_le32(last_startbit);
515 rc = put_entry(buf, sizeof(u32), 1, fp);
516 if (rc)
517 return rc;
518
519 buf64[0] = cpu_to_le64(map);
520 rc = put_entry(buf64, sizeof(u64), 1, fp);
521 if (rc)
522 return rc;
523 }
524 return 0;
525}
diff --git a/security/selinux/ss/ebitmap.h b/security/selinux/ss/ebitmap.h
index f283b4367f54..922f8afa89dd 100644
--- a/security/selinux/ss/ebitmap.h
+++ b/security/selinux/ss/ebitmap.h
@@ -36,7 +36,6 @@ struct ebitmap {
36}; 36};
37 37
38#define ebitmap_length(e) ((e)->highbit) 38#define ebitmap_length(e) ((e)->highbit)
39#define ebitmap_startbit(e) ((e)->node ? (e)->node->startbit : 0)
40 39
41static inline unsigned int ebitmap_start_positive(struct ebitmap *e, 40static inline unsigned int ebitmap_start_positive(struct ebitmap *e,
42 struct ebitmap_node **n) 41 struct ebitmap_node **n)
@@ -123,6 +122,7 @@ int ebitmap_get_bit(struct ebitmap *e, unsigned long bit);
123int ebitmap_set_bit(struct ebitmap *e, unsigned long bit, int value); 122int ebitmap_set_bit(struct ebitmap *e, unsigned long bit, int value);
124void ebitmap_destroy(struct ebitmap *e); 123void ebitmap_destroy(struct ebitmap *e);
125int ebitmap_read(struct ebitmap *e, void *fp); 124int ebitmap_read(struct ebitmap *e, void *fp);
125int ebitmap_write(struct ebitmap *e, void *fp);
126 126
127#ifdef CONFIG_NETLABEL 127#ifdef CONFIG_NETLABEL
128int ebitmap_netlbl_export(struct ebitmap *ebmap, 128int ebitmap_netlbl_export(struct ebitmap *ebmap,
diff --git a/security/selinux/ss/mls.c b/security/selinux/ss/mls.c
index b4eff7a60c50..e96174216bc9 100644
--- a/security/selinux/ss/mls.c
+++ b/security/selinux/ss/mls.c
@@ -45,7 +45,7 @@ int mls_compute_context_len(struct context *context)
45 len = 1; /* for the beginning ":" */ 45 len = 1; /* for the beginning ":" */
46 for (l = 0; l < 2; l++) { 46 for (l = 0; l < 2; l++) {
47 int index_sens = context->range.level[l].sens; 47 int index_sens = context->range.level[l].sens;
48 len += strlen(policydb.p_sens_val_to_name[index_sens - 1]); 48 len += strlen(sym_name(&policydb, SYM_LEVELS, index_sens - 1));
49 49
50 /* categories */ 50 /* categories */
51 head = -2; 51 head = -2;
@@ -55,17 +55,17 @@ int mls_compute_context_len(struct context *context)
55 if (i - prev > 1) { 55 if (i - prev > 1) {
56 /* one or more negative bits are skipped */ 56 /* one or more negative bits are skipped */
57 if (head != prev) { 57 if (head != prev) {
58 nm = policydb.p_cat_val_to_name[prev]; 58 nm = sym_name(&policydb, SYM_CATS, prev);
59 len += strlen(nm) + 1; 59 len += strlen(nm) + 1;
60 } 60 }
61 nm = policydb.p_cat_val_to_name[i]; 61 nm = sym_name(&policydb, SYM_CATS, i);
62 len += strlen(nm) + 1; 62 len += strlen(nm) + 1;
63 head = i; 63 head = i;
64 } 64 }
65 prev = i; 65 prev = i;
66 } 66 }
67 if (prev != head) { 67 if (prev != head) {
68 nm = policydb.p_cat_val_to_name[prev]; 68 nm = sym_name(&policydb, SYM_CATS, prev);
69 len += strlen(nm) + 1; 69 len += strlen(nm) + 1;
70 } 70 }
71 if (l == 0) { 71 if (l == 0) {
@@ -102,8 +102,8 @@ void mls_sid_to_context(struct context *context,
102 scontextp++; 102 scontextp++;
103 103
104 for (l = 0; l < 2; l++) { 104 for (l = 0; l < 2; l++) {
105 strcpy(scontextp, 105 strcpy(scontextp, sym_name(&policydb, SYM_LEVELS,
106 policydb.p_sens_val_to_name[context->range.level[l].sens - 1]); 106 context->range.level[l].sens - 1));
107 scontextp += strlen(scontextp); 107 scontextp += strlen(scontextp);
108 108
109 /* categories */ 109 /* categories */
@@ -118,7 +118,7 @@ void mls_sid_to_context(struct context *context,
118 *scontextp++ = '.'; 118 *scontextp++ = '.';
119 else 119 else
120 *scontextp++ = ','; 120 *scontextp++ = ',';
121 nm = policydb.p_cat_val_to_name[prev]; 121 nm = sym_name(&policydb, SYM_CATS, prev);
122 strcpy(scontextp, nm); 122 strcpy(scontextp, nm);
123 scontextp += strlen(nm); 123 scontextp += strlen(nm);
124 } 124 }
@@ -126,7 +126,7 @@ void mls_sid_to_context(struct context *context,
126 *scontextp++ = ':'; 126 *scontextp++ = ':';
127 else 127 else
128 *scontextp++ = ','; 128 *scontextp++ = ',';
129 nm = policydb.p_cat_val_to_name[i]; 129 nm = sym_name(&policydb, SYM_CATS, i);
130 strcpy(scontextp, nm); 130 strcpy(scontextp, nm);
131 scontextp += strlen(nm); 131 scontextp += strlen(nm);
132 head = i; 132 head = i;
@@ -139,7 +139,7 @@ void mls_sid_to_context(struct context *context,
139 *scontextp++ = '.'; 139 *scontextp++ = '.';
140 else 140 else
141 *scontextp++ = ','; 141 *scontextp++ = ',';
142 nm = policydb.p_cat_val_to_name[prev]; 142 nm = sym_name(&policydb, SYM_CATS, prev);
143 strcpy(scontextp, nm); 143 strcpy(scontextp, nm);
144 scontextp += strlen(nm); 144 scontextp += strlen(nm);
145 } 145 }
@@ -166,7 +166,7 @@ int mls_level_isvalid(struct policydb *p, struct mls_level *l)
166 if (!l->sens || l->sens > p->p_levels.nprim) 166 if (!l->sens || l->sens > p->p_levels.nprim)
167 return 0; 167 return 0;
168 levdatum = hashtab_search(p->p_levels.table, 168 levdatum = hashtab_search(p->p_levels.table,
169 p->p_sens_val_to_name[l->sens - 1]); 169 sym_name(p, SYM_LEVELS, l->sens - 1));
170 if (!levdatum) 170 if (!levdatum)
171 return 0; 171 return 0;
172 172
@@ -482,7 +482,8 @@ int mls_convert_context(struct policydb *oldp,
482 482
483 for (l = 0; l < 2; l++) { 483 for (l = 0; l < 2; l++) {
484 levdatum = hashtab_search(newp->p_levels.table, 484 levdatum = hashtab_search(newp->p_levels.table,
485 oldp->p_sens_val_to_name[c->range.level[l].sens - 1]); 485 sym_name(oldp, SYM_LEVELS,
486 c->range.level[l].sens - 1));
486 487
487 if (!levdatum) 488 if (!levdatum)
488 return -EINVAL; 489 return -EINVAL;
@@ -493,7 +494,7 @@ int mls_convert_context(struct policydb *oldp,
493 int rc; 494 int rc;
494 495
495 catdatum = hashtab_search(newp->p_cats.table, 496 catdatum = hashtab_search(newp->p_cats.table,
496 oldp->p_cat_val_to_name[i]); 497 sym_name(oldp, SYM_CATS, i));
497 if (!catdatum) 498 if (!catdatum)
498 return -EINVAL; 499 return -EINVAL;
499 rc = ebitmap_set_bit(&bitmap, catdatum->value - 1, 1); 500 rc = ebitmap_set_bit(&bitmap, catdatum->value - 1, 1);
@@ -511,7 +512,8 @@ int mls_compute_sid(struct context *scontext,
511 struct context *tcontext, 512 struct context *tcontext,
512 u16 tclass, 513 u16 tclass,
513 u32 specified, 514 u32 specified,
514 struct context *newcontext) 515 struct context *newcontext,
516 bool sock)
515{ 517{
516 struct range_trans rtr; 518 struct range_trans rtr;
517 struct mls_range *r; 519 struct mls_range *r;
@@ -530,7 +532,7 @@ int mls_compute_sid(struct context *scontext,
530 return mls_range_set(newcontext, r); 532 return mls_range_set(newcontext, r);
531 /* Fallthrough */ 533 /* Fallthrough */
532 case AVTAB_CHANGE: 534 case AVTAB_CHANGE:
533 if (tclass == policydb.process_class) 535 if ((tclass == policydb.process_class) || (sock == true))
534 /* Use the process MLS attributes. */ 536 /* Use the process MLS attributes. */
535 return mls_context_cpy(newcontext, scontext); 537 return mls_context_cpy(newcontext, scontext);
536 else 538 else
diff --git a/security/selinux/ss/mls.h b/security/selinux/ss/mls.h
index cd9152632e54..037bf9d82d41 100644
--- a/security/selinux/ss/mls.h
+++ b/security/selinux/ss/mls.h
@@ -49,7 +49,8 @@ int mls_compute_sid(struct context *scontext,
49 struct context *tcontext, 49 struct context *tcontext,
50 u16 tclass, 50 u16 tclass,
51 u32 specified, 51 u32 specified,
52 struct context *newcontext); 52 struct context *newcontext,
53 bool sock);
53 54
54int mls_setup_user_range(struct context *fromcon, struct user_datum *user, 55int mls_setup_user_range(struct context *fromcon, struct user_datum *user,
55 struct context *usercon); 56 struct context *usercon);
diff --git a/security/selinux/ss/policydb.c b/security/selinux/ss/policydb.c
index 3a29704be8ce..d246aca3f4fb 100644
--- a/security/selinux/ss/policydb.c
+++ b/security/selinux/ss/policydb.c
@@ -37,6 +37,7 @@
37#include "policydb.h" 37#include "policydb.h"
38#include "conditional.h" 38#include "conditional.h"
39#include "mls.h" 39#include "mls.h"
40#include "services.h"
40 41
41#define _DEBUG_HASHES 42#define _DEBUG_HASHES
42 43
@@ -122,6 +123,16 @@ static struct policydb_compat_info policydb_compat[] = {
122 .sym_num = SYM_NUM, 123 .sym_num = SYM_NUM,
123 .ocon_num = OCON_NUM, 124 .ocon_num = OCON_NUM,
124 }, 125 },
126 {
127 .version = POLICYDB_VERSION_FILENAME_TRANS,
128 .sym_num = SYM_NUM,
129 .ocon_num = OCON_NUM,
130 },
131 {
132 .version = POLICYDB_VERSION_ROLETRANS,
133 .sym_num = SYM_NUM,
134 .ocon_num = OCON_NUM,
135 },
125}; 136};
126 137
127static struct policydb_compat_info *policydb_lookup_compat(int version) 138static struct policydb_compat_info *policydb_lookup_compat(int version)
@@ -147,32 +158,67 @@ static int roles_init(struct policydb *p)
147 int rc; 158 int rc;
148 struct role_datum *role; 159 struct role_datum *role;
149 160
161 rc = -ENOMEM;
150 role = kzalloc(sizeof(*role), GFP_KERNEL); 162 role = kzalloc(sizeof(*role), GFP_KERNEL);
151 if (!role) { 163 if (!role)
152 rc = -ENOMEM;
153 goto out; 164 goto out;
154 } 165
166 rc = -EINVAL;
155 role->value = ++p->p_roles.nprim; 167 role->value = ++p->p_roles.nprim;
156 if (role->value != OBJECT_R_VAL) { 168 if (role->value != OBJECT_R_VAL)
157 rc = -EINVAL; 169 goto out;
158 goto out_free_role; 170
159 } 171 rc = -ENOMEM;
160 key = kstrdup(OBJECT_R, GFP_KERNEL); 172 key = kstrdup(OBJECT_R, GFP_KERNEL);
161 if (!key) { 173 if (!key)
162 rc = -ENOMEM; 174 goto out;
163 goto out_free_role; 175
164 }
165 rc = hashtab_insert(p->p_roles.table, key, role); 176 rc = hashtab_insert(p->p_roles.table, key, role);
166 if (rc) 177 if (rc)
167 goto out_free_key; 178 goto out;
168out:
169 return rc;
170 179
171out_free_key: 180 return 0;
181out:
172 kfree(key); 182 kfree(key);
173out_free_role:
174 kfree(role); 183 kfree(role);
175 goto out; 184 return rc;
185}
186
187static u32 filenametr_hash(struct hashtab *h, const void *k)
188{
189 const struct filename_trans *ft = k;
190 unsigned long hash;
191 unsigned int byte_num;
192 unsigned char focus;
193
194 hash = ft->stype ^ ft->ttype ^ ft->tclass;
195
196 byte_num = 0;
197 while ((focus = ft->name[byte_num++]))
198 hash = partial_name_hash(focus, hash);
199 return hash & (h->size - 1);
200}
201
202static int filenametr_cmp(struct hashtab *h, const void *k1, const void *k2)
203{
204 const struct filename_trans *ft1 = k1;
205 const struct filename_trans *ft2 = k2;
206 int v;
207
208 v = ft1->stype - ft2->stype;
209 if (v)
210 return v;
211
212 v = ft1->ttype - ft2->ttype;
213 if (v)
214 return v;
215
216 v = ft1->tclass - ft2->tclass;
217 if (v)
218 return v;
219
220 return strcmp(ft1->name, ft2->name);
221
176} 222}
177 223
178static u32 rangetr_hash(struct hashtab *h, const void *k) 224static u32 rangetr_hash(struct hashtab *h, const void *k)
@@ -185,9 +231,19 @@ static u32 rangetr_hash(struct hashtab *h, const void *k)
185static int rangetr_cmp(struct hashtab *h, const void *k1, const void *k2) 231static int rangetr_cmp(struct hashtab *h, const void *k1, const void *k2)
186{ 232{
187 const struct range_trans *key1 = k1, *key2 = k2; 233 const struct range_trans *key1 = k1, *key2 = k2;
188 return (key1->source_type != key2->source_type || 234 int v;
189 key1->target_type != key2->target_type || 235
190 key1->target_class != key2->target_class); 236 v = key1->source_type - key2->source_type;
237 if (v)
238 return v;
239
240 v = key1->target_type - key2->target_type;
241 if (v)
242 return v;
243
244 v = key1->target_class - key2->target_class;
245
246 return v;
191} 247}
192 248
193/* 249/*
@@ -202,35 +258,40 @@ static int policydb_init(struct policydb *p)
202 for (i = 0; i < SYM_NUM; i++) { 258 for (i = 0; i < SYM_NUM; i++) {
203 rc = symtab_init(&p->symtab[i], symtab_sizes[i]); 259 rc = symtab_init(&p->symtab[i], symtab_sizes[i]);
204 if (rc) 260 if (rc)
205 goto out_free_symtab; 261 goto out;
206 } 262 }
207 263
208 rc = avtab_init(&p->te_avtab); 264 rc = avtab_init(&p->te_avtab);
209 if (rc) 265 if (rc)
210 goto out_free_symtab; 266 goto out;
211 267
212 rc = roles_init(p); 268 rc = roles_init(p);
213 if (rc) 269 if (rc)
214 goto out_free_symtab; 270 goto out;
215 271
216 rc = cond_policydb_init(p); 272 rc = cond_policydb_init(p);
217 if (rc) 273 if (rc)
218 goto out_free_symtab; 274 goto out;
275
276 p->filename_trans = hashtab_create(filenametr_hash, filenametr_cmp, (1 << 10));
277 if (!p->filename_trans)
278 goto out;
219 279
220 p->range_tr = hashtab_create(rangetr_hash, rangetr_cmp, 256); 280 p->range_tr = hashtab_create(rangetr_hash, rangetr_cmp, 256);
221 if (!p->range_tr) 281 if (!p->range_tr)
222 goto out_free_symtab; 282 goto out;
223 283
284 ebitmap_init(&p->filename_trans_ttypes);
224 ebitmap_init(&p->policycaps); 285 ebitmap_init(&p->policycaps);
225 ebitmap_init(&p->permissive_map); 286 ebitmap_init(&p->permissive_map);
226 287
288 return 0;
227out: 289out:
228 return rc; 290 hashtab_destroy(p->filename_trans);
229 291 hashtab_destroy(p->range_tr);
230out_free_symtab:
231 for (i = 0; i < SYM_NUM; i++) 292 for (i = 0; i < SYM_NUM; i++)
232 hashtab_destroy(p->symtab[i].table); 293 hashtab_destroy(p->symtab[i].table);
233 goto out; 294 return rc;
234} 295}
235 296
236/* 297/*
@@ -247,12 +308,17 @@ static int common_index(void *key, void *datum, void *datap)
247{ 308{
248 struct policydb *p; 309 struct policydb *p;
249 struct common_datum *comdatum; 310 struct common_datum *comdatum;
311 struct flex_array *fa;
250 312
251 comdatum = datum; 313 comdatum = datum;
252 p = datap; 314 p = datap;
253 if (!comdatum->value || comdatum->value > p->p_commons.nprim) 315 if (!comdatum->value || comdatum->value > p->p_commons.nprim)
254 return -EINVAL; 316 return -EINVAL;
255 p->p_common_val_to_name[comdatum->value - 1] = key; 317
318 fa = p->sym_val_to_name[SYM_COMMONS];
319 if (flex_array_put_ptr(fa, comdatum->value - 1, key,
320 GFP_KERNEL | __GFP_ZERO))
321 BUG();
256 return 0; 322 return 0;
257} 323}
258 324
@@ -260,12 +326,16 @@ static int class_index(void *key, void *datum, void *datap)
260{ 326{
261 struct policydb *p; 327 struct policydb *p;
262 struct class_datum *cladatum; 328 struct class_datum *cladatum;
329 struct flex_array *fa;
263 330
264 cladatum = datum; 331 cladatum = datum;
265 p = datap; 332 p = datap;
266 if (!cladatum->value || cladatum->value > p->p_classes.nprim) 333 if (!cladatum->value || cladatum->value > p->p_classes.nprim)
267 return -EINVAL; 334 return -EINVAL;
268 p->p_class_val_to_name[cladatum->value - 1] = key; 335 fa = p->sym_val_to_name[SYM_CLASSES];
336 if (flex_array_put_ptr(fa, cladatum->value - 1, key,
337 GFP_KERNEL | __GFP_ZERO))
338 BUG();
269 p->class_val_to_struct[cladatum->value - 1] = cladatum; 339 p->class_val_to_struct[cladatum->value - 1] = cladatum;
270 return 0; 340 return 0;
271} 341}
@@ -274,6 +344,7 @@ static int role_index(void *key, void *datum, void *datap)
274{ 344{
275 struct policydb *p; 345 struct policydb *p;
276 struct role_datum *role; 346 struct role_datum *role;
347 struct flex_array *fa;
277 348
278 role = datum; 349 role = datum;
279 p = datap; 350 p = datap;
@@ -281,7 +352,11 @@ static int role_index(void *key, void *datum, void *datap)
281 || role->value > p->p_roles.nprim 352 || role->value > p->p_roles.nprim
282 || role->bounds > p->p_roles.nprim) 353 || role->bounds > p->p_roles.nprim)
283 return -EINVAL; 354 return -EINVAL;
284 p->p_role_val_to_name[role->value - 1] = key; 355
356 fa = p->sym_val_to_name[SYM_ROLES];
357 if (flex_array_put_ptr(fa, role->value - 1, key,
358 GFP_KERNEL | __GFP_ZERO))
359 BUG();
285 p->role_val_to_struct[role->value - 1] = role; 360 p->role_val_to_struct[role->value - 1] = role;
286 return 0; 361 return 0;
287} 362}
@@ -290,6 +365,7 @@ static int type_index(void *key, void *datum, void *datap)
290{ 365{
291 struct policydb *p; 366 struct policydb *p;
292 struct type_datum *typdatum; 367 struct type_datum *typdatum;
368 struct flex_array *fa;
293 369
294 typdatum = datum; 370 typdatum = datum;
295 p = datap; 371 p = datap;
@@ -299,8 +375,15 @@ static int type_index(void *key, void *datum, void *datap)
299 || typdatum->value > p->p_types.nprim 375 || typdatum->value > p->p_types.nprim
300 || typdatum->bounds > p->p_types.nprim) 376 || typdatum->bounds > p->p_types.nprim)
301 return -EINVAL; 377 return -EINVAL;
302 p->p_type_val_to_name[typdatum->value - 1] = key; 378 fa = p->sym_val_to_name[SYM_TYPES];
303 p->type_val_to_struct[typdatum->value - 1] = typdatum; 379 if (flex_array_put_ptr(fa, typdatum->value - 1, key,
380 GFP_KERNEL | __GFP_ZERO))
381 BUG();
382
383 fa = p->type_val_to_struct_array;
384 if (flex_array_put_ptr(fa, typdatum->value - 1, typdatum,
385 GFP_KERNEL | __GFP_ZERO))
386 BUG();
304 } 387 }
305 388
306 return 0; 389 return 0;
@@ -310,6 +393,7 @@ static int user_index(void *key, void *datum, void *datap)
310{ 393{
311 struct policydb *p; 394 struct policydb *p;
312 struct user_datum *usrdatum; 395 struct user_datum *usrdatum;
396 struct flex_array *fa;
313 397
314 usrdatum = datum; 398 usrdatum = datum;
315 p = datap; 399 p = datap;
@@ -317,7 +401,11 @@ static int user_index(void *key, void *datum, void *datap)
317 || usrdatum->value > p->p_users.nprim 401 || usrdatum->value > p->p_users.nprim
318 || usrdatum->bounds > p->p_users.nprim) 402 || usrdatum->bounds > p->p_users.nprim)
319 return -EINVAL; 403 return -EINVAL;
320 p->p_user_val_to_name[usrdatum->value - 1] = key; 404
405 fa = p->sym_val_to_name[SYM_USERS];
406 if (flex_array_put_ptr(fa, usrdatum->value - 1, key,
407 GFP_KERNEL | __GFP_ZERO))
408 BUG();
321 p->user_val_to_struct[usrdatum->value - 1] = usrdatum; 409 p->user_val_to_struct[usrdatum->value - 1] = usrdatum;
322 return 0; 410 return 0;
323} 411}
@@ -326,6 +414,7 @@ static int sens_index(void *key, void *datum, void *datap)
326{ 414{
327 struct policydb *p; 415 struct policydb *p;
328 struct level_datum *levdatum; 416 struct level_datum *levdatum;
417 struct flex_array *fa;
329 418
330 levdatum = datum; 419 levdatum = datum;
331 p = datap; 420 p = datap;
@@ -334,7 +423,10 @@ static int sens_index(void *key, void *datum, void *datap)
334 if (!levdatum->level->sens || 423 if (!levdatum->level->sens ||
335 levdatum->level->sens > p->p_levels.nprim) 424 levdatum->level->sens > p->p_levels.nprim)
336 return -EINVAL; 425 return -EINVAL;
337 p->p_sens_val_to_name[levdatum->level->sens - 1] = key; 426 fa = p->sym_val_to_name[SYM_LEVELS];
427 if (flex_array_put_ptr(fa, levdatum->level->sens - 1, key,
428 GFP_KERNEL | __GFP_ZERO))
429 BUG();
338 } 430 }
339 431
340 return 0; 432 return 0;
@@ -344,6 +436,7 @@ static int cat_index(void *key, void *datum, void *datap)
344{ 436{
345 struct policydb *p; 437 struct policydb *p;
346 struct cat_datum *catdatum; 438 struct cat_datum *catdatum;
439 struct flex_array *fa;
347 440
348 catdatum = datum; 441 catdatum = datum;
349 p = datap; 442 p = datap;
@@ -351,7 +444,10 @@ static int cat_index(void *key, void *datum, void *datap)
351 if (!catdatum->isalias) { 444 if (!catdatum->isalias) {
352 if (!catdatum->value || catdatum->value > p->p_cats.nprim) 445 if (!catdatum->value || catdatum->value > p->p_cats.nprim)
353 return -EINVAL; 446 return -EINVAL;
354 p->p_cat_val_to_name[catdatum->value - 1] = key; 447 fa = p->sym_val_to_name[SYM_CATS];
448 if (flex_array_put_ptr(fa, catdatum->value - 1, key,
449 GFP_KERNEL | __GFP_ZERO))
450 BUG();
355 } 451 }
356 452
357 return 0; 453 return 0;
@@ -369,74 +465,27 @@ static int (*index_f[SYM_NUM]) (void *key, void *datum, void *datap) =
369 cat_index, 465 cat_index,
370}; 466};
371 467
372/* 468#ifdef DEBUG_HASHES
373 * Define the common val_to_name array and the class 469static void hash_eval(struct hashtab *h, const char *hash_name)
374 * val_to_name and val_to_struct arrays in a policy
375 * database structure.
376 *
377 * Caller must clean up upon failure.
378 */
379static int policydb_index_classes(struct policydb *p)
380{ 470{
381 int rc; 471 struct hashtab_info info;
382
383 p->p_common_val_to_name =
384 kmalloc(p->p_commons.nprim * sizeof(char *), GFP_KERNEL);
385 if (!p->p_common_val_to_name) {
386 rc = -ENOMEM;
387 goto out;
388 }
389
390 rc = hashtab_map(p->p_commons.table, common_index, p);
391 if (rc)
392 goto out;
393
394 p->class_val_to_struct =
395 kmalloc(p->p_classes.nprim * sizeof(*(p->class_val_to_struct)), GFP_KERNEL);
396 if (!p->class_val_to_struct) {
397 rc = -ENOMEM;
398 goto out;
399 }
400
401 p->p_class_val_to_name =
402 kmalloc(p->p_classes.nprim * sizeof(char *), GFP_KERNEL);
403 if (!p->p_class_val_to_name) {
404 rc = -ENOMEM;
405 goto out;
406 }
407 472
408 rc = hashtab_map(p->p_classes.table, class_index, p); 473 hashtab_stat(h, &info);
409out: 474 printk(KERN_DEBUG "SELinux: %s: %d entries and %d/%d buckets used, "
410 return rc; 475 "longest chain length %d\n", hash_name, h->nel,
476 info.slots_used, h->size, info.max_chain_len);
411} 477}
412 478
413#ifdef DEBUG_HASHES
414static void symtab_hash_eval(struct symtab *s) 479static void symtab_hash_eval(struct symtab *s)
415{ 480{
416 int i; 481 int i;
417 482
418 for (i = 0; i < SYM_NUM; i++) { 483 for (i = 0; i < SYM_NUM; i++)
419 struct hashtab *h = s[i].table; 484 hash_eval(s[i].table, symtab_name[i]);
420 struct hashtab_info info;
421
422 hashtab_stat(h, &info);
423 printk(KERN_DEBUG "SELinux: %s: %d entries and %d/%d buckets used, "
424 "longest chain length %d\n", symtab_name[i], h->nel,
425 info.slots_used, h->size, info.max_chain_len);
426 }
427} 485}
428 486
429static void rangetr_hash_eval(struct hashtab *h)
430{
431 struct hashtab_info info;
432
433 hashtab_stat(h, &info);
434 printk(KERN_DEBUG "SELinux: rangetr: %d entries and %d/%d buckets used, "
435 "longest chain length %d\n", h->nel,
436 info.slots_used, h->size, info.max_chain_len);
437}
438#else 487#else
439static inline void rangetr_hash_eval(struct hashtab *h) 488static inline void hash_eval(struct hashtab *h, char *hash_name)
440{ 489{
441} 490}
442#endif 491#endif
@@ -447,9 +496,9 @@ static inline void rangetr_hash_eval(struct hashtab *h)
447 * 496 *
448 * Caller must clean up on failure. 497 * Caller must clean up on failure.
449 */ 498 */
450static int policydb_index_others(struct policydb *p) 499static int policydb_index(struct policydb *p)
451{ 500{
452 int i, rc = 0; 501 int i, rc;
453 502
454 printk(KERN_DEBUG "SELinux: %d users, %d roles, %d types, %d bools", 503 printk(KERN_DEBUG "SELinux: %d users, %d roles, %d types, %d bools",
455 p->p_users.nprim, p->p_roles.nprim, p->p_types.nprim, p->p_bools.nprim); 504 p->p_users.nprim, p->p_roles.nprim, p->p_types.nprim, p->p_bools.nprim);
@@ -466,47 +515,63 @@ static int policydb_index_others(struct policydb *p)
466 symtab_hash_eval(p->symtab); 515 symtab_hash_eval(p->symtab);
467#endif 516#endif
468 517
518 rc = -ENOMEM;
519 p->class_val_to_struct =
520 kmalloc(p->p_classes.nprim * sizeof(*(p->class_val_to_struct)),
521 GFP_KERNEL);
522 if (!p->class_val_to_struct)
523 goto out;
524
525 rc = -ENOMEM;
469 p->role_val_to_struct = 526 p->role_val_to_struct =
470 kmalloc(p->p_roles.nprim * sizeof(*(p->role_val_to_struct)), 527 kmalloc(p->p_roles.nprim * sizeof(*(p->role_val_to_struct)),
471 GFP_KERNEL); 528 GFP_KERNEL);
472 if (!p->role_val_to_struct) { 529 if (!p->role_val_to_struct)
473 rc = -ENOMEM;
474 goto out; 530 goto out;
475 }
476 531
532 rc = -ENOMEM;
477 p->user_val_to_struct = 533 p->user_val_to_struct =
478 kmalloc(p->p_users.nprim * sizeof(*(p->user_val_to_struct)), 534 kmalloc(p->p_users.nprim * sizeof(*(p->user_val_to_struct)),
479 GFP_KERNEL); 535 GFP_KERNEL);
480 if (!p->user_val_to_struct) { 536 if (!p->user_val_to_struct)
481 rc = -ENOMEM;
482 goto out; 537 goto out;
483 }
484 538
485 p->type_val_to_struct = 539 /* Yes, I want the sizeof the pointer, not the structure */
486 kmalloc(p->p_types.nprim * sizeof(*(p->type_val_to_struct)), 540 rc = -ENOMEM;
487 GFP_KERNEL); 541 p->type_val_to_struct_array = flex_array_alloc(sizeof(struct type_datum *),
488 if (!p->type_val_to_struct) { 542 p->p_types.nprim,
489 rc = -ENOMEM; 543 GFP_KERNEL | __GFP_ZERO);
544 if (!p->type_val_to_struct_array)
490 goto out; 545 goto out;
491 }
492 546
493 if (cond_init_bool_indexes(p)) { 547 rc = flex_array_prealloc(p->type_val_to_struct_array, 0,
494 rc = -ENOMEM; 548 p->p_types.nprim, GFP_KERNEL | __GFP_ZERO);
549 if (rc)
495 goto out; 550 goto out;
496 }
497 551
498 for (i = SYM_ROLES; i < SYM_NUM; i++) { 552 rc = cond_init_bool_indexes(p);
499 p->sym_val_to_name[i] = 553 if (rc)
500 kmalloc(p->symtab[i].nprim * sizeof(char *), GFP_KERNEL); 554 goto out;
501 if (!p->sym_val_to_name[i]) { 555
502 rc = -ENOMEM; 556 for (i = 0; i < SYM_NUM; i++) {
557 rc = -ENOMEM;
558 p->sym_val_to_name[i] = flex_array_alloc(sizeof(char *),
559 p->symtab[i].nprim,
560 GFP_KERNEL | __GFP_ZERO);
561 if (!p->sym_val_to_name[i])
503 goto out; 562 goto out;
504 } 563
564 rc = flex_array_prealloc(p->sym_val_to_name[i],
565 0, p->symtab[i].nprim,
566 GFP_KERNEL | __GFP_ZERO);
567 if (rc)
568 goto out;
569
505 rc = hashtab_map(p->symtab[i].table, index_f[i], p); 570 rc = hashtab_map(p->symtab[i].table, index_f[i], p);
506 if (rc) 571 if (rc)
507 goto out; 572 goto out;
508 } 573 }
509 574 rc = 0;
510out: 575out:
511 return rc; 576 return rc;
512} 577}
@@ -529,9 +594,11 @@ static int common_destroy(void *key, void *datum, void *p)
529 struct common_datum *comdatum; 594 struct common_datum *comdatum;
530 595
531 kfree(key); 596 kfree(key);
532 comdatum = datum; 597 if (datum) {
533 hashtab_map(comdatum->permissions.table, perm_destroy, NULL); 598 comdatum = datum;
534 hashtab_destroy(comdatum->permissions.table); 599 hashtab_map(comdatum->permissions.table, perm_destroy, NULL);
600 hashtab_destroy(comdatum->permissions.table);
601 }
535 kfree(datum); 602 kfree(datum);
536 return 0; 603 return 0;
537} 604}
@@ -543,38 +610,40 @@ static int cls_destroy(void *key, void *datum, void *p)
543 struct constraint_expr *e, *etmp; 610 struct constraint_expr *e, *etmp;
544 611
545 kfree(key); 612 kfree(key);
546 cladatum = datum; 613 if (datum) {
547 hashtab_map(cladatum->permissions.table, perm_destroy, NULL); 614 cladatum = datum;
548 hashtab_destroy(cladatum->permissions.table); 615 hashtab_map(cladatum->permissions.table, perm_destroy, NULL);
549 constraint = cladatum->constraints; 616 hashtab_destroy(cladatum->permissions.table);
550 while (constraint) { 617 constraint = cladatum->constraints;
551 e = constraint->expr; 618 while (constraint) {
552 while (e) { 619 e = constraint->expr;
553 ebitmap_destroy(&e->names); 620 while (e) {
554 etmp = e; 621 ebitmap_destroy(&e->names);
555 e = e->next; 622 etmp = e;
556 kfree(etmp); 623 e = e->next;
624 kfree(etmp);
625 }
626 ctemp = constraint;
627 constraint = constraint->next;
628 kfree(ctemp);
557 } 629 }
558 ctemp = constraint; 630
559 constraint = constraint->next; 631 constraint = cladatum->validatetrans;
560 kfree(ctemp); 632 while (constraint) {
561 } 633 e = constraint->expr;
562 634 while (e) {
563 constraint = cladatum->validatetrans; 635 ebitmap_destroy(&e->names);
564 while (constraint) { 636 etmp = e;
565 e = constraint->expr; 637 e = e->next;
566 while (e) { 638 kfree(etmp);
567 ebitmap_destroy(&e->names); 639 }
568 etmp = e; 640 ctemp = constraint;
569 e = e->next; 641 constraint = constraint->next;
570 kfree(etmp); 642 kfree(ctemp);
571 } 643 }
572 ctemp = constraint;
573 constraint = constraint->next;
574 kfree(ctemp);
575 }
576 644
577 kfree(cladatum->comkey); 645 kfree(cladatum->comkey);
646 }
578 kfree(datum); 647 kfree(datum);
579 return 0; 648 return 0;
580} 649}
@@ -584,9 +653,11 @@ static int role_destroy(void *key, void *datum, void *p)
584 struct role_datum *role; 653 struct role_datum *role;
585 654
586 kfree(key); 655 kfree(key);
587 role = datum; 656 if (datum) {
588 ebitmap_destroy(&role->dominates); 657 role = datum;
589 ebitmap_destroy(&role->types); 658 ebitmap_destroy(&role->dominates);
659 ebitmap_destroy(&role->types);
660 }
590 kfree(datum); 661 kfree(datum);
591 return 0; 662 return 0;
592} 663}
@@ -603,11 +674,13 @@ static int user_destroy(void *key, void *datum, void *p)
603 struct user_datum *usrdatum; 674 struct user_datum *usrdatum;
604 675
605 kfree(key); 676 kfree(key);
606 usrdatum = datum; 677 if (datum) {
607 ebitmap_destroy(&usrdatum->roles); 678 usrdatum = datum;
608 ebitmap_destroy(&usrdatum->range.level[0].cat); 679 ebitmap_destroy(&usrdatum->roles);
609 ebitmap_destroy(&usrdatum->range.level[1].cat); 680 ebitmap_destroy(&usrdatum->range.level[0].cat);
610 ebitmap_destroy(&usrdatum->dfltlevel.cat); 681 ebitmap_destroy(&usrdatum->range.level[1].cat);
682 ebitmap_destroy(&usrdatum->dfltlevel.cat);
683 }
611 kfree(datum); 684 kfree(datum);
612 return 0; 685 return 0;
613} 686}
@@ -617,9 +690,11 @@ static int sens_destroy(void *key, void *datum, void *p)
617 struct level_datum *levdatum; 690 struct level_datum *levdatum;
618 691
619 kfree(key); 692 kfree(key);
620 levdatum = datum; 693 if (datum) {
621 ebitmap_destroy(&levdatum->level->cat); 694 levdatum = datum;
622 kfree(levdatum->level); 695 ebitmap_destroy(&levdatum->level->cat);
696 kfree(levdatum->level);
697 }
623 kfree(datum); 698 kfree(datum);
624 return 0; 699 return 0;
625} 700}
@@ -643,6 +718,16 @@ static int (*destroy_f[SYM_NUM]) (void *key, void *datum, void *datap) =
643 cat_destroy, 718 cat_destroy,
644}; 719};
645 720
721static int filenametr_destroy(void *key, void *datum, void *p)
722{
723 struct filename_trans *ft = key;
724 kfree(ft->name);
725 kfree(key);
726 kfree(datum);
727 cond_resched();
728 return 0;
729}
730
646static int range_tr_destroy(void *key, void *datum, void *p) 731static int range_tr_destroy(void *key, void *datum, void *p)
647{ 732{
648 struct mls_range *rt = datum; 733 struct mls_range *rt = datum;
@@ -684,13 +769,16 @@ void policydb_destroy(struct policydb *p)
684 hashtab_destroy(p->symtab[i].table); 769 hashtab_destroy(p->symtab[i].table);
685 } 770 }
686 771
687 for (i = 0; i < SYM_NUM; i++) 772 for (i = 0; i < SYM_NUM; i++) {
688 kfree(p->sym_val_to_name[i]); 773 if (p->sym_val_to_name[i])
774 flex_array_free(p->sym_val_to_name[i]);
775 }
689 776
690 kfree(p->class_val_to_struct); 777 kfree(p->class_val_to_struct);
691 kfree(p->role_val_to_struct); 778 kfree(p->role_val_to_struct);
692 kfree(p->user_val_to_struct); 779 kfree(p->user_val_to_struct);
693 kfree(p->type_val_to_struct); 780 if (p->type_val_to_struct_array)
781 flex_array_free(p->type_val_to_struct_array);
694 782
695 avtab_destroy(&p->te_avtab); 783 avtab_destroy(&p->te_avtab);
696 784
@@ -737,6 +825,9 @@ void policydb_destroy(struct policydb *p)
737 } 825 }
738 kfree(lra); 826 kfree(lra);
739 827
828 hashtab_map(p->filename_trans, filenametr_destroy, NULL);
829 hashtab_destroy(p->filename_trans);
830
740 hashtab_map(p->range_tr, range_tr_destroy, NULL); 831 hashtab_map(p->range_tr, range_tr_destroy, NULL);
741 hashtab_destroy(p->range_tr); 832 hashtab_destroy(p->range_tr);
742 833
@@ -751,6 +842,8 @@ void policydb_destroy(struct policydb *p)
751 } 842 }
752 flex_array_free(p->type_attr_map_array); 843 flex_array_free(p->type_attr_map_array);
753 } 844 }
845
846 ebitmap_destroy(&p->filename_trans_ttypes);
754 ebitmap_destroy(&p->policycaps); 847 ebitmap_destroy(&p->policycaps);
755 ebitmap_destroy(&p->permissive_map); 848 ebitmap_destroy(&p->permissive_map);
756 849
@@ -774,19 +867,21 @@ int policydb_load_isids(struct policydb *p, struct sidtab *s)
774 867
775 head = p->ocontexts[OCON_ISID]; 868 head = p->ocontexts[OCON_ISID];
776 for (c = head; c; c = c->next) { 869 for (c = head; c; c = c->next) {
870 rc = -EINVAL;
777 if (!c->context[0].user) { 871 if (!c->context[0].user) {
778 printk(KERN_ERR "SELinux: SID %s was never " 872 printk(KERN_ERR "SELinux: SID %s was never defined.\n",
779 "defined.\n", c->u.name); 873 c->u.name);
780 rc = -EINVAL;
781 goto out; 874 goto out;
782 } 875 }
783 if (sidtab_insert(s, c->sid[0], &c->context[0])) { 876
784 printk(KERN_ERR "SELinux: unable to load initial " 877 rc = sidtab_insert(s, c->sid[0], &c->context[0]);
785 "SID %s.\n", c->u.name); 878 if (rc) {
786 rc = -EINVAL; 879 printk(KERN_ERR "SELinux: unable to load initial SID %s.\n",
880 c->u.name);
787 goto out; 881 goto out;
788 } 882 }
789 } 883 }
884 rc = 0;
790out: 885out:
791 return rc; 886 return rc;
792} 887}
@@ -835,8 +930,7 @@ int policydb_context_isvalid(struct policydb *p, struct context *c)
835 * Role must be authorized for the type. 930 * Role must be authorized for the type.
836 */ 931 */
837 role = p->role_val_to_struct[c->role - 1]; 932 role = p->role_val_to_struct[c->role - 1];
838 if (!ebitmap_get_bit(&role->types, 933 if (!ebitmap_get_bit(&role->types, c->type - 1))
839 c->type - 1))
840 /* role may not be associated with type */ 934 /* role may not be associated with type */
841 return 0; 935 return 0;
842 936
@@ -847,8 +941,7 @@ int policydb_context_isvalid(struct policydb *p, struct context *c)
847 if (!usrdatum) 941 if (!usrdatum)
848 return 0; 942 return 0;
849 943
850 if (!ebitmap_get_bit(&usrdatum->roles, 944 if (!ebitmap_get_bit(&usrdatum->roles, c->role - 1))
851 c->role - 1))
852 /* user may not be associated with role */ 945 /* user may not be associated with role */
853 return 0; 946 return 0;
854 } 947 }
@@ -870,20 +963,22 @@ static int mls_read_range_helper(struct mls_range *r, void *fp)
870 int rc; 963 int rc;
871 964
872 rc = next_entry(buf, fp, sizeof(u32)); 965 rc = next_entry(buf, fp, sizeof(u32));
873 if (rc < 0) 966 if (rc)
874 goto out; 967 goto out;
875 968
969 rc = -EINVAL;
876 items = le32_to_cpu(buf[0]); 970 items = le32_to_cpu(buf[0]);
877 if (items > ARRAY_SIZE(buf)) { 971 if (items > ARRAY_SIZE(buf)) {
878 printk(KERN_ERR "SELinux: mls: range overflow\n"); 972 printk(KERN_ERR "SELinux: mls: range overflow\n");
879 rc = -EINVAL;
880 goto out; 973 goto out;
881 } 974 }
975
882 rc = next_entry(buf, fp, sizeof(u32) * items); 976 rc = next_entry(buf, fp, sizeof(u32) * items);
883 if (rc < 0) { 977 if (rc) {
884 printk(KERN_ERR "SELinux: mls: truncated range\n"); 978 printk(KERN_ERR "SELinux: mls: truncated range\n");
885 goto out; 979 goto out;
886 } 980 }
981
887 r->level[0].sens = le32_to_cpu(buf[0]); 982 r->level[0].sens = le32_to_cpu(buf[0]);
888 if (items > 1) 983 if (items > 1)
889 r->level[1].sens = le32_to_cpu(buf[1]); 984 r->level[1].sens = le32_to_cpu(buf[1]);
@@ -892,15 +987,13 @@ static int mls_read_range_helper(struct mls_range *r, void *fp)
892 987
893 rc = ebitmap_read(&r->level[0].cat, fp); 988 rc = ebitmap_read(&r->level[0].cat, fp);
894 if (rc) { 989 if (rc) {
895 printk(KERN_ERR "SELinux: mls: error reading low " 990 printk(KERN_ERR "SELinux: mls: error reading low categories\n");
896 "categories\n");
897 goto out; 991 goto out;
898 } 992 }
899 if (items > 1) { 993 if (items > 1) {
900 rc = ebitmap_read(&r->level[1].cat, fp); 994 rc = ebitmap_read(&r->level[1].cat, fp);
901 if (rc) { 995 if (rc) {
902 printk(KERN_ERR "SELinux: mls: error reading high " 996 printk(KERN_ERR "SELinux: mls: error reading high categories\n");
903 "categories\n");
904 goto bad_high; 997 goto bad_high;
905 } 998 }
906 } else { 999 } else {
@@ -911,12 +1004,11 @@ static int mls_read_range_helper(struct mls_range *r, void *fp)
911 } 1004 }
912 } 1005 }
913 1006
914 rc = 0; 1007 return 0;
915out:
916 return rc;
917bad_high: 1008bad_high:
918 ebitmap_destroy(&r->level[0].cat); 1009 ebitmap_destroy(&r->level[0].cat);
919 goto out; 1010out:
1011 return rc;
920} 1012}
921 1013
922/* 1014/*
@@ -931,7 +1023,7 @@ static int context_read_and_validate(struct context *c,
931 int rc; 1023 int rc;
932 1024
933 rc = next_entry(buf, fp, sizeof buf); 1025 rc = next_entry(buf, fp, sizeof buf);
934 if (rc < 0) { 1026 if (rc) {
935 printk(KERN_ERR "SELinux: context truncated\n"); 1027 printk(KERN_ERR "SELinux: context truncated\n");
936 goto out; 1028 goto out;
937 } 1029 }
@@ -939,19 +1031,20 @@ static int context_read_and_validate(struct context *c,
939 c->role = le32_to_cpu(buf[1]); 1031 c->role = le32_to_cpu(buf[1]);
940 c->type = le32_to_cpu(buf[2]); 1032 c->type = le32_to_cpu(buf[2]);
941 if (p->policyvers >= POLICYDB_VERSION_MLS) { 1033 if (p->policyvers >= POLICYDB_VERSION_MLS) {
942 if (mls_read_range_helper(&c->range, fp)) { 1034 rc = mls_read_range_helper(&c->range, fp);
943 printk(KERN_ERR "SELinux: error reading MLS range of " 1035 if (rc) {
944 "context\n"); 1036 printk(KERN_ERR "SELinux: error reading MLS range of context\n");
945 rc = -EINVAL;
946 goto out; 1037 goto out;
947 } 1038 }
948 } 1039 }
949 1040
1041 rc = -EINVAL;
950 if (!policydb_context_isvalid(p, c)) { 1042 if (!policydb_context_isvalid(p, c)) {
951 printk(KERN_ERR "SELinux: invalid security context\n"); 1043 printk(KERN_ERR "SELinux: invalid security context\n");
952 context_destroy(c); 1044 context_destroy(c);
953 rc = -EINVAL; 1045 goto out;
954 } 1046 }
1047 rc = 0;
955out: 1048out:
956 return rc; 1049 return rc;
957} 1050}
@@ -970,37 +1063,36 @@ static int perm_read(struct policydb *p, struct hashtab *h, void *fp)
970 __le32 buf[2]; 1063 __le32 buf[2];
971 u32 len; 1064 u32 len;
972 1065
1066 rc = -ENOMEM;
973 perdatum = kzalloc(sizeof(*perdatum), GFP_KERNEL); 1067 perdatum = kzalloc(sizeof(*perdatum), GFP_KERNEL);
974 if (!perdatum) { 1068 if (!perdatum)
975 rc = -ENOMEM; 1069 goto bad;
976 goto out;
977 }
978 1070
979 rc = next_entry(buf, fp, sizeof buf); 1071 rc = next_entry(buf, fp, sizeof buf);
980 if (rc < 0) 1072 if (rc)
981 goto bad; 1073 goto bad;
982 1074
983 len = le32_to_cpu(buf[0]); 1075 len = le32_to_cpu(buf[0]);
984 perdatum->value = le32_to_cpu(buf[1]); 1076 perdatum->value = le32_to_cpu(buf[1]);
985 1077
1078 rc = -ENOMEM;
986 key = kmalloc(len + 1, GFP_KERNEL); 1079 key = kmalloc(len + 1, GFP_KERNEL);
987 if (!key) { 1080 if (!key)
988 rc = -ENOMEM;
989 goto bad; 1081 goto bad;
990 } 1082
991 rc = next_entry(key, fp, len); 1083 rc = next_entry(key, fp, len);
992 if (rc < 0) 1084 if (rc)
993 goto bad; 1085 goto bad;
994 key[len] = '\0'; 1086 key[len] = '\0';
995 1087
996 rc = hashtab_insert(h, key, perdatum); 1088 rc = hashtab_insert(h, key, perdatum);
997 if (rc) 1089 if (rc)
998 goto bad; 1090 goto bad;
999out: 1091
1000 return rc; 1092 return 0;
1001bad: 1093bad:
1002 perm_destroy(key, perdatum, NULL); 1094 perm_destroy(key, perdatum, NULL);
1003 goto out; 1095 return rc;
1004} 1096}
1005 1097
1006static int common_read(struct policydb *p, struct hashtab *h, void *fp) 1098static int common_read(struct policydb *p, struct hashtab *h, void *fp)
@@ -1011,14 +1103,13 @@ static int common_read(struct policydb *p, struct hashtab *h, void *fp)
1011 u32 len, nel; 1103 u32 len, nel;
1012 int i, rc; 1104 int i, rc;
1013 1105
1106 rc = -ENOMEM;
1014 comdatum = kzalloc(sizeof(*comdatum), GFP_KERNEL); 1107 comdatum = kzalloc(sizeof(*comdatum), GFP_KERNEL);
1015 if (!comdatum) { 1108 if (!comdatum)
1016 rc = -ENOMEM; 1109 goto bad;
1017 goto out;
1018 }
1019 1110
1020 rc = next_entry(buf, fp, sizeof buf); 1111 rc = next_entry(buf, fp, sizeof buf);
1021 if (rc < 0) 1112 if (rc)
1022 goto bad; 1113 goto bad;
1023 1114
1024 len = le32_to_cpu(buf[0]); 1115 len = le32_to_cpu(buf[0]);
@@ -1030,13 +1121,13 @@ static int common_read(struct policydb *p, struct hashtab *h, void *fp)
1030 comdatum->permissions.nprim = le32_to_cpu(buf[2]); 1121 comdatum->permissions.nprim = le32_to_cpu(buf[2]);
1031 nel = le32_to_cpu(buf[3]); 1122 nel = le32_to_cpu(buf[3]);
1032 1123
1124 rc = -ENOMEM;
1033 key = kmalloc(len + 1, GFP_KERNEL); 1125 key = kmalloc(len + 1, GFP_KERNEL);
1034 if (!key) { 1126 if (!key)
1035 rc = -ENOMEM;
1036 goto bad; 1127 goto bad;
1037 } 1128
1038 rc = next_entry(key, fp, len); 1129 rc = next_entry(key, fp, len);
1039 if (rc < 0) 1130 if (rc)
1040 goto bad; 1131 goto bad;
1041 key[len] = '\0'; 1132 key[len] = '\0';
1042 1133
@@ -1049,11 +1140,10 @@ static int common_read(struct policydb *p, struct hashtab *h, void *fp)
1049 rc = hashtab_insert(h, key, comdatum); 1140 rc = hashtab_insert(h, key, comdatum);
1050 if (rc) 1141 if (rc)
1051 goto bad; 1142 goto bad;
1052out: 1143 return 0;
1053 return rc;
1054bad: 1144bad:
1055 common_destroy(key, comdatum, NULL); 1145 common_destroy(key, comdatum, NULL);
1056 goto out; 1146 return rc;
1057} 1147}
1058 1148
1059static int read_cons_helper(struct constraint_node **nodep, int ncons, 1149static int read_cons_helper(struct constraint_node **nodep, int ncons,
@@ -1077,7 +1167,7 @@ static int read_cons_helper(struct constraint_node **nodep, int ncons,
1077 *nodep = c; 1167 *nodep = c;
1078 1168
1079 rc = next_entry(buf, fp, (sizeof(u32) * 2)); 1169 rc = next_entry(buf, fp, (sizeof(u32) * 2));
1080 if (rc < 0) 1170 if (rc)
1081 return rc; 1171 return rc;
1082 c->permissions = le32_to_cpu(buf[0]); 1172 c->permissions = le32_to_cpu(buf[0]);
1083 nexpr = le32_to_cpu(buf[1]); 1173 nexpr = le32_to_cpu(buf[1]);
@@ -1094,7 +1184,7 @@ static int read_cons_helper(struct constraint_node **nodep, int ncons,
1094 c->expr = e; 1184 c->expr = e;
1095 1185
1096 rc = next_entry(buf, fp, (sizeof(u32) * 3)); 1186 rc = next_entry(buf, fp, (sizeof(u32) * 3));
1097 if (rc < 0) 1187 if (rc)
1098 return rc; 1188 return rc;
1099 e->expr_type = le32_to_cpu(buf[0]); 1189 e->expr_type = le32_to_cpu(buf[0]);
1100 e->attr = le32_to_cpu(buf[1]); 1190 e->attr = le32_to_cpu(buf[1]);
@@ -1122,8 +1212,9 @@ static int read_cons_helper(struct constraint_node **nodep, int ncons,
1122 if (depth == (CEXPR_MAXDEPTH - 1)) 1212 if (depth == (CEXPR_MAXDEPTH - 1))
1123 return -EINVAL; 1213 return -EINVAL;
1124 depth++; 1214 depth++;
1125 if (ebitmap_read(&e->names, fp)) 1215 rc = ebitmap_read(&e->names, fp);
1126 return -EINVAL; 1216 if (rc)
1217 return rc;
1127 break; 1218 break;
1128 default: 1219 default:
1129 return -EINVAL; 1220 return -EINVAL;
@@ -1146,14 +1237,13 @@ static int class_read(struct policydb *p, struct hashtab *h, void *fp)
1146 u32 len, len2, ncons, nel; 1237 u32 len, len2, ncons, nel;
1147 int i, rc; 1238 int i, rc;
1148 1239
1240 rc = -ENOMEM;
1149 cladatum = kzalloc(sizeof(*cladatum), GFP_KERNEL); 1241 cladatum = kzalloc(sizeof(*cladatum), GFP_KERNEL);
1150 if (!cladatum) { 1242 if (!cladatum)
1151 rc = -ENOMEM; 1243 goto bad;
1152 goto out;
1153 }
1154 1244
1155 rc = next_entry(buf, fp, sizeof(u32)*6); 1245 rc = next_entry(buf, fp, sizeof(u32)*6);
1156 if (rc < 0) 1246 if (rc)
1157 goto bad; 1247 goto bad;
1158 1248
1159 len = le32_to_cpu(buf[0]); 1249 len = le32_to_cpu(buf[0]);
@@ -1168,33 +1258,30 @@ static int class_read(struct policydb *p, struct hashtab *h, void *fp)
1168 1258
1169 ncons = le32_to_cpu(buf[5]); 1259 ncons = le32_to_cpu(buf[5]);
1170 1260
1261 rc = -ENOMEM;
1171 key = kmalloc(len + 1, GFP_KERNEL); 1262 key = kmalloc(len + 1, GFP_KERNEL);
1172 if (!key) { 1263 if (!key)
1173 rc = -ENOMEM;
1174 goto bad; 1264 goto bad;
1175 } 1265
1176 rc = next_entry(key, fp, len); 1266 rc = next_entry(key, fp, len);
1177 if (rc < 0) 1267 if (rc)
1178 goto bad; 1268 goto bad;
1179 key[len] = '\0'; 1269 key[len] = '\0';
1180 1270
1181 if (len2) { 1271 if (len2) {
1272 rc = -ENOMEM;
1182 cladatum->comkey = kmalloc(len2 + 1, GFP_KERNEL); 1273 cladatum->comkey = kmalloc(len2 + 1, GFP_KERNEL);
1183 if (!cladatum->comkey) { 1274 if (!cladatum->comkey)
1184 rc = -ENOMEM;
1185 goto bad; 1275 goto bad;
1186 }
1187 rc = next_entry(cladatum->comkey, fp, len2); 1276 rc = next_entry(cladatum->comkey, fp, len2);
1188 if (rc < 0) 1277 if (rc)
1189 goto bad; 1278 goto bad;
1190 cladatum->comkey[len2] = '\0'; 1279 cladatum->comkey[len2] = '\0';
1191 1280
1192 cladatum->comdatum = hashtab_search(p->p_commons.table, 1281 rc = -EINVAL;
1193 cladatum->comkey); 1282 cladatum->comdatum = hashtab_search(p->p_commons.table, cladatum->comkey);
1194 if (!cladatum->comdatum) { 1283 if (!cladatum->comdatum) {
1195 printk(KERN_ERR "SELinux: unknown common %s\n", 1284 printk(KERN_ERR "SELinux: unknown common %s\n", cladatum->comkey);
1196 cladatum->comkey);
1197 rc = -EINVAL;
1198 goto bad; 1285 goto bad;
1199 } 1286 }
1200 } 1287 }
@@ -1211,7 +1298,7 @@ static int class_read(struct policydb *p, struct hashtab *h, void *fp)
1211 if (p->policyvers >= POLICYDB_VERSION_VALIDATETRANS) { 1298 if (p->policyvers >= POLICYDB_VERSION_VALIDATETRANS) {
1212 /* grab the validatetrans rules */ 1299 /* grab the validatetrans rules */
1213 rc = next_entry(buf, fp, sizeof(u32)); 1300 rc = next_entry(buf, fp, sizeof(u32));
1214 if (rc < 0) 1301 if (rc)
1215 goto bad; 1302 goto bad;
1216 ncons = le32_to_cpu(buf[0]); 1303 ncons = le32_to_cpu(buf[0]);
1217 rc = read_cons_helper(&cladatum->validatetrans, ncons, 1, fp); 1304 rc = read_cons_helper(&cladatum->validatetrans, ncons, 1, fp);
@@ -1223,12 +1310,10 @@ static int class_read(struct policydb *p, struct hashtab *h, void *fp)
1223 if (rc) 1310 if (rc)
1224 goto bad; 1311 goto bad;
1225 1312
1226 rc = 0; 1313 return 0;
1227out:
1228 return rc;
1229bad: 1314bad:
1230 cls_destroy(key, cladatum, NULL); 1315 cls_destroy(key, cladatum, NULL);
1231 goto out; 1316 return rc;
1232} 1317}
1233 1318
1234static int role_read(struct policydb *p, struct hashtab *h, void *fp) 1319static int role_read(struct policydb *p, struct hashtab *h, void *fp)
@@ -1239,17 +1324,16 @@ static int role_read(struct policydb *p, struct hashtab *h, void *fp)
1239 __le32 buf[3]; 1324 __le32 buf[3];
1240 u32 len; 1325 u32 len;
1241 1326
1327 rc = -ENOMEM;
1242 role = kzalloc(sizeof(*role), GFP_KERNEL); 1328 role = kzalloc(sizeof(*role), GFP_KERNEL);
1243 if (!role) { 1329 if (!role)
1244 rc = -ENOMEM; 1330 goto bad;
1245 goto out;
1246 }
1247 1331
1248 if (p->policyvers >= POLICYDB_VERSION_BOUNDARY) 1332 if (p->policyvers >= POLICYDB_VERSION_BOUNDARY)
1249 to_read = 3; 1333 to_read = 3;
1250 1334
1251 rc = next_entry(buf, fp, sizeof(buf[0]) * to_read); 1335 rc = next_entry(buf, fp, sizeof(buf[0]) * to_read);
1252 if (rc < 0) 1336 if (rc)
1253 goto bad; 1337 goto bad;
1254 1338
1255 len = le32_to_cpu(buf[0]); 1339 len = le32_to_cpu(buf[0]);
@@ -1257,13 +1341,13 @@ static int role_read(struct policydb *p, struct hashtab *h, void *fp)
1257 if (p->policyvers >= POLICYDB_VERSION_BOUNDARY) 1341 if (p->policyvers >= POLICYDB_VERSION_BOUNDARY)
1258 role->bounds = le32_to_cpu(buf[2]); 1342 role->bounds = le32_to_cpu(buf[2]);
1259 1343
1344 rc = -ENOMEM;
1260 key = kmalloc(len + 1, GFP_KERNEL); 1345 key = kmalloc(len + 1, GFP_KERNEL);
1261 if (!key) { 1346 if (!key)
1262 rc = -ENOMEM;
1263 goto bad; 1347 goto bad;
1264 } 1348
1265 rc = next_entry(key, fp, len); 1349 rc = next_entry(key, fp, len);
1266 if (rc < 0) 1350 if (rc)
1267 goto bad; 1351 goto bad;
1268 key[len] = '\0'; 1352 key[len] = '\0';
1269 1353
@@ -1276,10 +1360,10 @@ static int role_read(struct policydb *p, struct hashtab *h, void *fp)
1276 goto bad; 1360 goto bad;
1277 1361
1278 if (strcmp(key, OBJECT_R) == 0) { 1362 if (strcmp(key, OBJECT_R) == 0) {
1363 rc = -EINVAL;
1279 if (role->value != OBJECT_R_VAL) { 1364 if (role->value != OBJECT_R_VAL) {
1280 printk(KERN_ERR "SELinux: Role %s has wrong value %d\n", 1365 printk(KERN_ERR "SELinux: Role %s has wrong value %d\n",
1281 OBJECT_R, role->value); 1366 OBJECT_R, role->value);
1282 rc = -EINVAL;
1283 goto bad; 1367 goto bad;
1284 } 1368 }
1285 rc = 0; 1369 rc = 0;
@@ -1289,11 +1373,10 @@ static int role_read(struct policydb *p, struct hashtab *h, void *fp)
1289 rc = hashtab_insert(h, key, role); 1373 rc = hashtab_insert(h, key, role);
1290 if (rc) 1374 if (rc)
1291 goto bad; 1375 goto bad;
1292out: 1376 return 0;
1293 return rc;
1294bad: 1377bad:
1295 role_destroy(key, role, NULL); 1378 role_destroy(key, role, NULL);
1296 goto out; 1379 return rc;
1297} 1380}
1298 1381
1299static int type_read(struct policydb *p, struct hashtab *h, void *fp) 1382static int type_read(struct policydb *p, struct hashtab *h, void *fp)
@@ -1304,17 +1387,16 @@ static int type_read(struct policydb *p, struct hashtab *h, void *fp)
1304 __le32 buf[4]; 1387 __le32 buf[4];
1305 u32 len; 1388 u32 len;
1306 1389
1390 rc = -ENOMEM;
1307 typdatum = kzalloc(sizeof(*typdatum), GFP_KERNEL); 1391 typdatum = kzalloc(sizeof(*typdatum), GFP_KERNEL);
1308 if (!typdatum) { 1392 if (!typdatum)
1309 rc = -ENOMEM; 1393 goto bad;
1310 return rc;
1311 }
1312 1394
1313 if (p->policyvers >= POLICYDB_VERSION_BOUNDARY) 1395 if (p->policyvers >= POLICYDB_VERSION_BOUNDARY)
1314 to_read = 4; 1396 to_read = 4;
1315 1397
1316 rc = next_entry(buf, fp, sizeof(buf[0]) * to_read); 1398 rc = next_entry(buf, fp, sizeof(buf[0]) * to_read);
1317 if (rc < 0) 1399 if (rc)
1318 goto bad; 1400 goto bad;
1319 1401
1320 len = le32_to_cpu(buf[0]); 1402 len = le32_to_cpu(buf[0]);
@@ -1332,24 +1414,22 @@ static int type_read(struct policydb *p, struct hashtab *h, void *fp)
1332 typdatum->primary = le32_to_cpu(buf[2]); 1414 typdatum->primary = le32_to_cpu(buf[2]);
1333 } 1415 }
1334 1416
1417 rc = -ENOMEM;
1335 key = kmalloc(len + 1, GFP_KERNEL); 1418 key = kmalloc(len + 1, GFP_KERNEL);
1336 if (!key) { 1419 if (!key)
1337 rc = -ENOMEM;
1338 goto bad; 1420 goto bad;
1339 }
1340 rc = next_entry(key, fp, len); 1421 rc = next_entry(key, fp, len);
1341 if (rc < 0) 1422 if (rc)
1342 goto bad; 1423 goto bad;
1343 key[len] = '\0'; 1424 key[len] = '\0';
1344 1425
1345 rc = hashtab_insert(h, key, typdatum); 1426 rc = hashtab_insert(h, key, typdatum);
1346 if (rc) 1427 if (rc)
1347 goto bad; 1428 goto bad;
1348out: 1429 return 0;
1349 return rc;
1350bad: 1430bad:
1351 type_destroy(key, typdatum, NULL); 1431 type_destroy(key, typdatum, NULL);
1352 goto out; 1432 return rc;
1353} 1433}
1354 1434
1355 1435
@@ -1365,22 +1445,18 @@ static int mls_read_level(struct mls_level *lp, void *fp)
1365 memset(lp, 0, sizeof(*lp)); 1445 memset(lp, 0, sizeof(*lp));
1366 1446
1367 rc = next_entry(buf, fp, sizeof buf); 1447 rc = next_entry(buf, fp, sizeof buf);
1368 if (rc < 0) { 1448 if (rc) {
1369 printk(KERN_ERR "SELinux: mls: truncated level\n"); 1449 printk(KERN_ERR "SELinux: mls: truncated level\n");
1370 goto bad; 1450 return rc;
1371 } 1451 }
1372 lp->sens = le32_to_cpu(buf[0]); 1452 lp->sens = le32_to_cpu(buf[0]);
1373 1453
1374 if (ebitmap_read(&lp->cat, fp)) { 1454 rc = ebitmap_read(&lp->cat, fp);
1375 printk(KERN_ERR "SELinux: mls: error reading level " 1455 if (rc) {
1376 "categories\n"); 1456 printk(KERN_ERR "SELinux: mls: error reading level categories\n");
1377 goto bad; 1457 return rc;
1378 } 1458 }
1379
1380 return 0; 1459 return 0;
1381
1382bad:
1383 return -EINVAL;
1384} 1460}
1385 1461
1386static int user_read(struct policydb *p, struct hashtab *h, void *fp) 1462static int user_read(struct policydb *p, struct hashtab *h, void *fp)
@@ -1391,17 +1467,16 @@ static int user_read(struct policydb *p, struct hashtab *h, void *fp)
1391 __le32 buf[3]; 1467 __le32 buf[3];
1392 u32 len; 1468 u32 len;
1393 1469
1470 rc = -ENOMEM;
1394 usrdatum = kzalloc(sizeof(*usrdatum), GFP_KERNEL); 1471 usrdatum = kzalloc(sizeof(*usrdatum), GFP_KERNEL);
1395 if (!usrdatum) { 1472 if (!usrdatum)
1396 rc = -ENOMEM; 1473 goto bad;
1397 goto out;
1398 }
1399 1474
1400 if (p->policyvers >= POLICYDB_VERSION_BOUNDARY) 1475 if (p->policyvers >= POLICYDB_VERSION_BOUNDARY)
1401 to_read = 3; 1476 to_read = 3;
1402 1477
1403 rc = next_entry(buf, fp, sizeof(buf[0]) * to_read); 1478 rc = next_entry(buf, fp, sizeof(buf[0]) * to_read);
1404 if (rc < 0) 1479 if (rc)
1405 goto bad; 1480 goto bad;
1406 1481
1407 len = le32_to_cpu(buf[0]); 1482 len = le32_to_cpu(buf[0]);
@@ -1409,13 +1484,12 @@ static int user_read(struct policydb *p, struct hashtab *h, void *fp)
1409 if (p->policyvers >= POLICYDB_VERSION_BOUNDARY) 1484 if (p->policyvers >= POLICYDB_VERSION_BOUNDARY)
1410 usrdatum->bounds = le32_to_cpu(buf[2]); 1485 usrdatum->bounds = le32_to_cpu(buf[2]);
1411 1486
1487 rc = -ENOMEM;
1412 key = kmalloc(len + 1, GFP_KERNEL); 1488 key = kmalloc(len + 1, GFP_KERNEL);
1413 if (!key) { 1489 if (!key)
1414 rc = -ENOMEM;
1415 goto bad; 1490 goto bad;
1416 }
1417 rc = next_entry(key, fp, len); 1491 rc = next_entry(key, fp, len);
1418 if (rc < 0) 1492 if (rc)
1419 goto bad; 1493 goto bad;
1420 key[len] = '\0'; 1494 key[len] = '\0';
1421 1495
@@ -1435,11 +1509,10 @@ static int user_read(struct policydb *p, struct hashtab *h, void *fp)
1435 rc = hashtab_insert(h, key, usrdatum); 1509 rc = hashtab_insert(h, key, usrdatum);
1436 if (rc) 1510 if (rc)
1437 goto bad; 1511 goto bad;
1438out: 1512 return 0;
1439 return rc;
1440bad: 1513bad:
1441 user_destroy(key, usrdatum, NULL); 1514 user_destroy(key, usrdatum, NULL);
1442 goto out; 1515 return rc;
1443} 1516}
1444 1517
1445static int sens_read(struct policydb *p, struct hashtab *h, void *fp) 1518static int sens_read(struct policydb *p, struct hashtab *h, void *fp)
@@ -1450,47 +1523,43 @@ static int sens_read(struct policydb *p, struct hashtab *h, void *fp)
1450 __le32 buf[2]; 1523 __le32 buf[2];
1451 u32 len; 1524 u32 len;
1452 1525
1526 rc = -ENOMEM;
1453 levdatum = kzalloc(sizeof(*levdatum), GFP_ATOMIC); 1527 levdatum = kzalloc(sizeof(*levdatum), GFP_ATOMIC);
1454 if (!levdatum) { 1528 if (!levdatum)
1455 rc = -ENOMEM; 1529 goto bad;
1456 goto out;
1457 }
1458 1530
1459 rc = next_entry(buf, fp, sizeof buf); 1531 rc = next_entry(buf, fp, sizeof buf);
1460 if (rc < 0) 1532 if (rc)
1461 goto bad; 1533 goto bad;
1462 1534
1463 len = le32_to_cpu(buf[0]); 1535 len = le32_to_cpu(buf[0]);
1464 levdatum->isalias = le32_to_cpu(buf[1]); 1536 levdatum->isalias = le32_to_cpu(buf[1]);
1465 1537
1538 rc = -ENOMEM;
1466 key = kmalloc(len + 1, GFP_ATOMIC); 1539 key = kmalloc(len + 1, GFP_ATOMIC);
1467 if (!key) { 1540 if (!key)
1468 rc = -ENOMEM;
1469 goto bad; 1541 goto bad;
1470 }
1471 rc = next_entry(key, fp, len); 1542 rc = next_entry(key, fp, len);
1472 if (rc < 0) 1543 if (rc)
1473 goto bad; 1544 goto bad;
1474 key[len] = '\0'; 1545 key[len] = '\0';
1475 1546
1547 rc = -ENOMEM;
1476 levdatum->level = kmalloc(sizeof(struct mls_level), GFP_ATOMIC); 1548 levdatum->level = kmalloc(sizeof(struct mls_level), GFP_ATOMIC);
1477 if (!levdatum->level) { 1549 if (!levdatum->level)
1478 rc = -ENOMEM;
1479 goto bad; 1550 goto bad;
1480 } 1551
1481 if (mls_read_level(levdatum->level, fp)) { 1552 rc = mls_read_level(levdatum->level, fp);
1482 rc = -EINVAL; 1553 if (rc)
1483 goto bad; 1554 goto bad;
1484 }
1485 1555
1486 rc = hashtab_insert(h, key, levdatum); 1556 rc = hashtab_insert(h, key, levdatum);
1487 if (rc) 1557 if (rc)
1488 goto bad; 1558 goto bad;
1489out: 1559 return 0;
1490 return rc;
1491bad: 1560bad:
1492 sens_destroy(key, levdatum, NULL); 1561 sens_destroy(key, levdatum, NULL);
1493 goto out; 1562 return rc;
1494} 1563}
1495 1564
1496static int cat_read(struct policydb *p, struct hashtab *h, void *fp) 1565static int cat_read(struct policydb *p, struct hashtab *h, void *fp)
@@ -1501,39 +1570,35 @@ static int cat_read(struct policydb *p, struct hashtab *h, void *fp)
1501 __le32 buf[3]; 1570 __le32 buf[3];
1502 u32 len; 1571 u32 len;
1503 1572
1573 rc = -ENOMEM;
1504 catdatum = kzalloc(sizeof(*catdatum), GFP_ATOMIC); 1574 catdatum = kzalloc(sizeof(*catdatum), GFP_ATOMIC);
1505 if (!catdatum) { 1575 if (!catdatum)
1506 rc = -ENOMEM; 1576 goto bad;
1507 goto out;
1508 }
1509 1577
1510 rc = next_entry(buf, fp, sizeof buf); 1578 rc = next_entry(buf, fp, sizeof buf);
1511 if (rc < 0) 1579 if (rc)
1512 goto bad; 1580 goto bad;
1513 1581
1514 len = le32_to_cpu(buf[0]); 1582 len = le32_to_cpu(buf[0]);
1515 catdatum->value = le32_to_cpu(buf[1]); 1583 catdatum->value = le32_to_cpu(buf[1]);
1516 catdatum->isalias = le32_to_cpu(buf[2]); 1584 catdatum->isalias = le32_to_cpu(buf[2]);
1517 1585
1586 rc = -ENOMEM;
1518 key = kmalloc(len + 1, GFP_ATOMIC); 1587 key = kmalloc(len + 1, GFP_ATOMIC);
1519 if (!key) { 1588 if (!key)
1520 rc = -ENOMEM;
1521 goto bad; 1589 goto bad;
1522 }
1523 rc = next_entry(key, fp, len); 1590 rc = next_entry(key, fp, len);
1524 if (rc < 0) 1591 if (rc)
1525 goto bad; 1592 goto bad;
1526 key[len] = '\0'; 1593 key[len] = '\0';
1527 1594
1528 rc = hashtab_insert(h, key, catdatum); 1595 rc = hashtab_insert(h, key, catdatum);
1529 if (rc) 1596 if (rc)
1530 goto bad; 1597 goto bad;
1531out: 1598 return 0;
1532 return rc;
1533
1534bad: 1599bad:
1535 cat_destroy(key, catdatum, NULL); 1600 cat_destroy(key, catdatum, NULL);
1536 goto out; 1601 return rc;
1537} 1602}
1538 1603
1539static int (*read_f[SYM_NUM]) (struct policydb *p, struct hashtab *h, void *fp) = 1604static int (*read_f[SYM_NUM]) (struct policydb *p, struct hashtab *h, void *fp) =
@@ -1574,9 +1639,9 @@ static int user_bounds_sanity_check(void *key, void *datum, void *datap)
1574 printk(KERN_ERR 1639 printk(KERN_ERR
1575 "SELinux: boundary violated policy: " 1640 "SELinux: boundary violated policy: "
1576 "user=%s role=%s bounds=%s\n", 1641 "user=%s role=%s bounds=%s\n",
1577 p->p_user_val_to_name[user->value - 1], 1642 sym_name(p, SYM_USERS, user->value - 1),
1578 p->p_role_val_to_name[bit], 1643 sym_name(p, SYM_ROLES, bit),
1579 p->p_user_val_to_name[upper->value - 1]); 1644 sym_name(p, SYM_USERS, upper->value - 1));
1580 1645
1581 return -EINVAL; 1646 return -EINVAL;
1582 } 1647 }
@@ -1611,9 +1676,9 @@ static int role_bounds_sanity_check(void *key, void *datum, void *datap)
1611 printk(KERN_ERR 1676 printk(KERN_ERR
1612 "SELinux: boundary violated policy: " 1677 "SELinux: boundary violated policy: "
1613 "role=%s type=%s bounds=%s\n", 1678 "role=%s type=%s bounds=%s\n",
1614 p->p_role_val_to_name[role->value - 1], 1679 sym_name(p, SYM_ROLES, role->value - 1),
1615 p->p_type_val_to_name[bit], 1680 sym_name(p, SYM_TYPES, bit),
1616 p->p_role_val_to_name[upper->value - 1]); 1681 sym_name(p, SYM_ROLES, upper->value - 1));
1617 1682
1618 return -EINVAL; 1683 return -EINVAL;
1619 } 1684 }
@@ -1624,11 +1689,11 @@ static int role_bounds_sanity_check(void *key, void *datum, void *datap)
1624 1689
1625static int type_bounds_sanity_check(void *key, void *datum, void *datap) 1690static int type_bounds_sanity_check(void *key, void *datum, void *datap)
1626{ 1691{
1627 struct type_datum *upper, *type; 1692 struct type_datum *upper;
1628 struct policydb *p = datap; 1693 struct policydb *p = datap;
1629 int depth = 0; 1694 int depth = 0;
1630 1695
1631 upper = type = datum; 1696 upper = datum;
1632 while (upper->bounds) { 1697 while (upper->bounds) {
1633 if (++depth == POLICYDB_BOUNDS_MAXDEPTH) { 1698 if (++depth == POLICYDB_BOUNDS_MAXDEPTH) {
1634 printk(KERN_ERR "SELinux: type %s: " 1699 printk(KERN_ERR "SELinux: type %s: "
@@ -1637,12 +1702,15 @@ static int type_bounds_sanity_check(void *key, void *datum, void *datap)
1637 return -EINVAL; 1702 return -EINVAL;
1638 } 1703 }
1639 1704
1640 upper = p->type_val_to_struct[upper->bounds - 1]; 1705 upper = flex_array_get_ptr(p->type_val_to_struct_array,
1706 upper->bounds - 1);
1707 BUG_ON(!upper);
1708
1641 if (upper->attribute) { 1709 if (upper->attribute) {
1642 printk(KERN_ERR "SELinux: type %s: " 1710 printk(KERN_ERR "SELinux: type %s: "
1643 "bounded by attribute %s", 1711 "bounded by attribute %s",
1644 (char *) key, 1712 (char *) key,
1645 p->p_type_val_to_name[upper->value - 1]); 1713 sym_name(p, SYM_TYPES, upper->value - 1));
1646 return -EINVAL; 1714 return -EINVAL;
1647 } 1715 }
1648 } 1716 }
@@ -1775,7 +1843,7 @@ static int range_read(struct policydb *p, void *fp)
1775 rt = NULL; 1843 rt = NULL;
1776 r = NULL; 1844 r = NULL;
1777 } 1845 }
1778 rangetr_hash_eval(p->range_tr); 1846 hash_eval(p->range_tr, "rangetr");
1779 rc = 0; 1847 rc = 0;
1780out: 1848out:
1781 kfree(rt); 1849 kfree(rt);
@@ -1783,6 +1851,83 @@ out:
1783 return rc; 1851 return rc;
1784} 1852}
1785 1853
1854static int filename_trans_read(struct policydb *p, void *fp)
1855{
1856 struct filename_trans *ft;
1857 struct filename_trans_datum *otype;
1858 char *name;
1859 u32 nel, len;
1860 __le32 buf[4];
1861 int rc, i;
1862
1863 if (p->policyvers < POLICYDB_VERSION_FILENAME_TRANS)
1864 return 0;
1865
1866 rc = next_entry(buf, fp, sizeof(u32));
1867 if (rc)
1868 return rc;
1869 nel = le32_to_cpu(buf[0]);
1870
1871 for (i = 0; i < nel; i++) {
1872 ft = NULL;
1873 otype = NULL;
1874 name = NULL;
1875
1876 rc = -ENOMEM;
1877 ft = kzalloc(sizeof(*ft), GFP_KERNEL);
1878 if (!ft)
1879 goto out;
1880
1881 rc = -ENOMEM;
1882 otype = kmalloc(sizeof(*otype), GFP_KERNEL);
1883 if (!otype)
1884 goto out;
1885
1886 /* length of the path component string */
1887 rc = next_entry(buf, fp, sizeof(u32));
1888 if (rc)
1889 goto out;
1890 len = le32_to_cpu(buf[0]);
1891
1892 rc = -ENOMEM;
1893 name = kmalloc(len + 1, GFP_KERNEL);
1894 if (!name)
1895 goto out;
1896
1897 ft->name = name;
1898
1899 /* path component string */
1900 rc = next_entry(name, fp, len);
1901 if (rc)
1902 goto out;
1903 name[len] = 0;
1904
1905 rc = next_entry(buf, fp, sizeof(u32) * 4);
1906 if (rc)
1907 goto out;
1908
1909 ft->stype = le32_to_cpu(buf[0]);
1910 ft->ttype = le32_to_cpu(buf[1]);
1911 ft->tclass = le32_to_cpu(buf[2]);
1912
1913 otype->otype = le32_to_cpu(buf[3]);
1914
1915 rc = ebitmap_set_bit(&p->filename_trans_ttypes, ft->ttype, 1);
1916 if (rc)
1917 goto out;
1918
1919 hashtab_insert(p->filename_trans, ft, otype);
1920 }
1921 hash_eval(p->filename_trans, "filenametr");
1922 return 0;
1923out:
1924 kfree(ft);
1925 kfree(name);
1926 kfree(otype);
1927
1928 return rc;
1929}
1930
1786static int genfs_read(struct policydb *p, void *fp) 1931static int genfs_read(struct policydb *p, void *fp)
1787{ 1932{
1788 int i, j, rc; 1933 int i, j, rc;
@@ -2055,13 +2200,14 @@ int policydb_read(struct policydb *p, void *fp)
2055 2200
2056 rc = policydb_init(p); 2201 rc = policydb_init(p);
2057 if (rc) 2202 if (rc)
2058 goto out; 2203 return rc;
2059 2204
2060 /* Read the magic number and string length. */ 2205 /* Read the magic number and string length. */
2061 rc = next_entry(buf, fp, sizeof(u32) * 2); 2206 rc = next_entry(buf, fp, sizeof(u32) * 2);
2062 if (rc < 0) 2207 if (rc)
2063 goto bad; 2208 goto bad;
2064 2209
2210 rc = -EINVAL;
2065 if (le32_to_cpu(buf[0]) != POLICYDB_MAGIC) { 2211 if (le32_to_cpu(buf[0]) != POLICYDB_MAGIC) {
2066 printk(KERN_ERR "SELinux: policydb magic number 0x%x does " 2212 printk(KERN_ERR "SELinux: policydb magic number 0x%x does "
2067 "not match expected magic number 0x%x\n", 2213 "not match expected magic number 0x%x\n",
@@ -2069,6 +2215,7 @@ int policydb_read(struct policydb *p, void *fp)
2069 goto bad; 2215 goto bad;
2070 } 2216 }
2071 2217
2218 rc = -EINVAL;
2072 len = le32_to_cpu(buf[1]); 2219 len = le32_to_cpu(buf[1]);
2073 if (len != strlen(POLICYDB_STRING)) { 2220 if (len != strlen(POLICYDB_STRING)) {
2074 printk(KERN_ERR "SELinux: policydb string length %d does not " 2221 printk(KERN_ERR "SELinux: policydb string length %d does not "
@@ -2076,19 +2223,23 @@ int policydb_read(struct policydb *p, void *fp)
2076 len, strlen(POLICYDB_STRING)); 2223 len, strlen(POLICYDB_STRING));
2077 goto bad; 2224 goto bad;
2078 } 2225 }
2226
2227 rc = -ENOMEM;
2079 policydb_str = kmalloc(len + 1, GFP_KERNEL); 2228 policydb_str = kmalloc(len + 1, GFP_KERNEL);
2080 if (!policydb_str) { 2229 if (!policydb_str) {
2081 printk(KERN_ERR "SELinux: unable to allocate memory for policydb " 2230 printk(KERN_ERR "SELinux: unable to allocate memory for policydb "
2082 "string of length %d\n", len); 2231 "string of length %d\n", len);
2083 rc = -ENOMEM;
2084 goto bad; 2232 goto bad;
2085 } 2233 }
2234
2086 rc = next_entry(policydb_str, fp, len); 2235 rc = next_entry(policydb_str, fp, len);
2087 if (rc < 0) { 2236 if (rc) {
2088 printk(KERN_ERR "SELinux: truncated policydb string identifier\n"); 2237 printk(KERN_ERR "SELinux: truncated policydb string identifier\n");
2089 kfree(policydb_str); 2238 kfree(policydb_str);
2090 goto bad; 2239 goto bad;
2091 } 2240 }
2241
2242 rc = -EINVAL;
2092 policydb_str[len] = '\0'; 2243 policydb_str[len] = '\0';
2093 if (strcmp(policydb_str, POLICYDB_STRING)) { 2244 if (strcmp(policydb_str, POLICYDB_STRING)) {
2094 printk(KERN_ERR "SELinux: policydb string %s does not match " 2245 printk(KERN_ERR "SELinux: policydb string %s does not match "
@@ -2102,9 +2253,10 @@ int policydb_read(struct policydb *p, void *fp)
2102 2253
2103 /* Read the version and table sizes. */ 2254 /* Read the version and table sizes. */
2104 rc = next_entry(buf, fp, sizeof(u32)*4); 2255 rc = next_entry(buf, fp, sizeof(u32)*4);
2105 if (rc < 0) 2256 if (rc)
2106 goto bad; 2257 goto bad;
2107 2258
2259 rc = -EINVAL;
2108 p->policyvers = le32_to_cpu(buf[0]); 2260 p->policyvers = le32_to_cpu(buf[0]);
2109 if (p->policyvers < POLICYDB_VERSION_MIN || 2261 if (p->policyvers < POLICYDB_VERSION_MIN ||
2110 p->policyvers > POLICYDB_VERSION_MAX) { 2262 p->policyvers > POLICYDB_VERSION_MAX) {
@@ -2117,6 +2269,7 @@ int policydb_read(struct policydb *p, void *fp)
2117 if ((le32_to_cpu(buf[1]) & POLICYDB_CONFIG_MLS)) { 2269 if ((le32_to_cpu(buf[1]) & POLICYDB_CONFIG_MLS)) {
2118 p->mls_enabled = 1; 2270 p->mls_enabled = 1;
2119 2271
2272 rc = -EINVAL;
2120 if (p->policyvers < POLICYDB_VERSION_MLS) { 2273 if (p->policyvers < POLICYDB_VERSION_MLS) {
2121 printk(KERN_ERR "SELinux: security policydb version %d " 2274 printk(KERN_ERR "SELinux: security policydb version %d "
2122 "(MLS) not backwards compatible\n", 2275 "(MLS) not backwards compatible\n",
@@ -2127,14 +2280,19 @@ int policydb_read(struct policydb *p, void *fp)
2127 p->reject_unknown = !!(le32_to_cpu(buf[1]) & REJECT_UNKNOWN); 2280 p->reject_unknown = !!(le32_to_cpu(buf[1]) & REJECT_UNKNOWN);
2128 p->allow_unknown = !!(le32_to_cpu(buf[1]) & ALLOW_UNKNOWN); 2281 p->allow_unknown = !!(le32_to_cpu(buf[1]) & ALLOW_UNKNOWN);
2129 2282
2130 if (p->policyvers >= POLICYDB_VERSION_POLCAP && 2283 if (p->policyvers >= POLICYDB_VERSION_POLCAP) {
2131 ebitmap_read(&p->policycaps, fp) != 0) 2284 rc = ebitmap_read(&p->policycaps, fp);
2132 goto bad; 2285 if (rc)
2286 goto bad;
2287 }
2133 2288
2134 if (p->policyvers >= POLICYDB_VERSION_PERMISSIVE && 2289 if (p->policyvers >= POLICYDB_VERSION_PERMISSIVE) {
2135 ebitmap_read(&p->permissive_map, fp) != 0) 2290 rc = ebitmap_read(&p->permissive_map, fp);
2136 goto bad; 2291 if (rc)
2292 goto bad;
2293 }
2137 2294
2295 rc = -EINVAL;
2138 info = policydb_lookup_compat(p->policyvers); 2296 info = policydb_lookup_compat(p->policyvers);
2139 if (!info) { 2297 if (!info) {
2140 printk(KERN_ERR "SELinux: unable to find policy compat info " 2298 printk(KERN_ERR "SELinux: unable to find policy compat info "
@@ -2142,6 +2300,7 @@ int policydb_read(struct policydb *p, void *fp)
2142 goto bad; 2300 goto bad;
2143 } 2301 }
2144 2302
2303 rc = -EINVAL;
2145 if (le32_to_cpu(buf[2]) != info->sym_num || 2304 if (le32_to_cpu(buf[2]) != info->sym_num ||
2146 le32_to_cpu(buf[3]) != info->ocon_num) { 2305 le32_to_cpu(buf[3]) != info->ocon_num) {
2147 printk(KERN_ERR "SELinux: policydb table sizes (%d,%d) do " 2306 printk(KERN_ERR "SELinux: policydb table sizes (%d,%d) do "
@@ -2153,7 +2312,7 @@ int policydb_read(struct policydb *p, void *fp)
2153 2312
2154 for (i = 0; i < info->sym_num; i++) { 2313 for (i = 0; i < info->sym_num; i++) {
2155 rc = next_entry(buf, fp, sizeof(u32)*2); 2314 rc = next_entry(buf, fp, sizeof(u32)*2);
2156 if (rc < 0) 2315 if (rc)
2157 goto bad; 2316 goto bad;
2158 nprim = le32_to_cpu(buf[0]); 2317 nprim = le32_to_cpu(buf[0]);
2159 nel = le32_to_cpu(buf[1]); 2318 nel = le32_to_cpu(buf[1]);
@@ -2166,6 +2325,11 @@ int policydb_read(struct policydb *p, void *fp)
2166 p->symtab[i].nprim = nprim; 2325 p->symtab[i].nprim = nprim;
2167 } 2326 }
2168 2327
2328 rc = -EINVAL;
2329 p->process_class = string_to_security_class(p, "process");
2330 if (!p->process_class)
2331 goto bad;
2332
2169 rc = avtab_read(&p->te_avtab, fp, p); 2333 rc = avtab_read(&p->te_avtab, fp, p);
2170 if (rc) 2334 if (rc)
2171 goto bad; 2335 goto bad;
@@ -2177,78 +2341,81 @@ int policydb_read(struct policydb *p, void *fp)
2177 } 2341 }
2178 2342
2179 rc = next_entry(buf, fp, sizeof(u32)); 2343 rc = next_entry(buf, fp, sizeof(u32));
2180 if (rc < 0) 2344 if (rc)
2181 goto bad; 2345 goto bad;
2182 nel = le32_to_cpu(buf[0]); 2346 nel = le32_to_cpu(buf[0]);
2183 ltr = NULL; 2347 ltr = NULL;
2184 for (i = 0; i < nel; i++) { 2348 for (i = 0; i < nel; i++) {
2349 rc = -ENOMEM;
2185 tr = kzalloc(sizeof(*tr), GFP_KERNEL); 2350 tr = kzalloc(sizeof(*tr), GFP_KERNEL);
2186 if (!tr) { 2351 if (!tr)
2187 rc = -ENOMEM;
2188 goto bad; 2352 goto bad;
2189 }
2190 if (ltr) 2353 if (ltr)
2191 ltr->next = tr; 2354 ltr->next = tr;
2192 else 2355 else
2193 p->role_tr = tr; 2356 p->role_tr = tr;
2194 rc = next_entry(buf, fp, sizeof(u32)*3); 2357 rc = next_entry(buf, fp, sizeof(u32)*3);
2195 if (rc < 0) 2358 if (rc)
2196 goto bad; 2359 goto bad;
2360
2361 rc = -EINVAL;
2197 tr->role = le32_to_cpu(buf[0]); 2362 tr->role = le32_to_cpu(buf[0]);
2198 tr->type = le32_to_cpu(buf[1]); 2363 tr->type = le32_to_cpu(buf[1]);
2199 tr->new_role = le32_to_cpu(buf[2]); 2364 tr->new_role = le32_to_cpu(buf[2]);
2365 if (p->policyvers >= POLICYDB_VERSION_ROLETRANS) {
2366 rc = next_entry(buf, fp, sizeof(u32));
2367 if (rc)
2368 goto bad;
2369 tr->tclass = le32_to_cpu(buf[0]);
2370 } else
2371 tr->tclass = p->process_class;
2372
2200 if (!policydb_role_isvalid(p, tr->role) || 2373 if (!policydb_role_isvalid(p, tr->role) ||
2201 !policydb_type_isvalid(p, tr->type) || 2374 !policydb_type_isvalid(p, tr->type) ||
2202 !policydb_role_isvalid(p, tr->new_role)) { 2375 !policydb_class_isvalid(p, tr->tclass) ||
2203 rc = -EINVAL; 2376 !policydb_role_isvalid(p, tr->new_role))
2204 goto bad; 2377 goto bad;
2205 }
2206 ltr = tr; 2378 ltr = tr;
2207 } 2379 }
2208 2380
2209 rc = next_entry(buf, fp, sizeof(u32)); 2381 rc = next_entry(buf, fp, sizeof(u32));
2210 if (rc < 0) 2382 if (rc)
2211 goto bad; 2383 goto bad;
2212 nel = le32_to_cpu(buf[0]); 2384 nel = le32_to_cpu(buf[0]);
2213 lra = NULL; 2385 lra = NULL;
2214 for (i = 0; i < nel; i++) { 2386 for (i = 0; i < nel; i++) {
2387 rc = -ENOMEM;
2215 ra = kzalloc(sizeof(*ra), GFP_KERNEL); 2388 ra = kzalloc(sizeof(*ra), GFP_KERNEL);
2216 if (!ra) { 2389 if (!ra)
2217 rc = -ENOMEM;
2218 goto bad; 2390 goto bad;
2219 }
2220 if (lra) 2391 if (lra)
2221 lra->next = ra; 2392 lra->next = ra;
2222 else 2393 else
2223 p->role_allow = ra; 2394 p->role_allow = ra;
2224 rc = next_entry(buf, fp, sizeof(u32)*2); 2395 rc = next_entry(buf, fp, sizeof(u32)*2);
2225 if (rc < 0) 2396 if (rc)
2226 goto bad; 2397 goto bad;
2398
2399 rc = -EINVAL;
2227 ra->role = le32_to_cpu(buf[0]); 2400 ra->role = le32_to_cpu(buf[0]);
2228 ra->new_role = le32_to_cpu(buf[1]); 2401 ra->new_role = le32_to_cpu(buf[1]);
2229 if (!policydb_role_isvalid(p, ra->role) || 2402 if (!policydb_role_isvalid(p, ra->role) ||
2230 !policydb_role_isvalid(p, ra->new_role)) { 2403 !policydb_role_isvalid(p, ra->new_role))
2231 rc = -EINVAL;
2232 goto bad; 2404 goto bad;
2233 }
2234 lra = ra; 2405 lra = ra;
2235 } 2406 }
2236 2407
2237 rc = policydb_index_classes(p); 2408 rc = filename_trans_read(p, fp);
2238 if (rc) 2409 if (rc)
2239 goto bad; 2410 goto bad;
2240 2411
2241 rc = policydb_index_others(p); 2412 rc = policydb_index(p);
2242 if (rc) 2413 if (rc)
2243 goto bad; 2414 goto bad;
2244 2415
2245 p->process_class = string_to_security_class(p, "process"); 2416 rc = -EINVAL;
2246 if (!p->process_class) 2417 p->process_trans_perms = string_to_av_perm(p, p->process_class, "transition");
2247 goto bad; 2418 p->process_trans_perms |= string_to_av_perm(p, p->process_class, "dyntransition");
2248 p->process_trans_perms = string_to_av_perm(p, p->process_class,
2249 "transition");
2250 p->process_trans_perms |= string_to_av_perm(p, p->process_class,
2251 "dyntransition");
2252 if (!p->process_trans_perms) 2419 if (!p->process_trans_perms)
2253 goto bad; 2420 goto bad;
2254 2421
@@ -2272,7 +2439,7 @@ int policydb_read(struct policydb *p, void *fp)
2272 goto bad; 2439 goto bad;
2273 2440
2274 /* preallocate so we don't have to worry about the put ever failing */ 2441 /* preallocate so we don't have to worry about the put ever failing */
2275 rc = flex_array_prealloc(p->type_attr_map_array, 0, p->p_types.nprim - 1, 2442 rc = flex_array_prealloc(p->type_attr_map_array, 0, p->p_types.nprim,
2276 GFP_KERNEL | __GFP_ZERO); 2443 GFP_KERNEL | __GFP_ZERO);
2277 if (rc) 2444 if (rc)
2278 goto bad; 2445 goto bad;
@@ -2301,8 +2468,914 @@ int policydb_read(struct policydb *p, void *fp)
2301out: 2468out:
2302 return rc; 2469 return rc;
2303bad: 2470bad:
2304 if (!rc)
2305 rc = -EINVAL;
2306 policydb_destroy(p); 2471 policydb_destroy(p);
2307 goto out; 2472 goto out;
2308} 2473}
2474
2475/*
2476 * Write a MLS level structure to a policydb binary
2477 * representation file.
2478 */
2479static int mls_write_level(struct mls_level *l, void *fp)
2480{
2481 __le32 buf[1];
2482 int rc;
2483
2484 buf[0] = cpu_to_le32(l->sens);
2485 rc = put_entry(buf, sizeof(u32), 1, fp);
2486 if (rc)
2487 return rc;
2488
2489 rc = ebitmap_write(&l->cat, fp);
2490 if (rc)
2491 return rc;
2492
2493 return 0;
2494}
2495
2496/*
2497 * Write a MLS range structure to a policydb binary
2498 * representation file.
2499 */
2500static int mls_write_range_helper(struct mls_range *r, void *fp)
2501{
2502 __le32 buf[3];
2503 size_t items;
2504 int rc, eq;
2505
2506 eq = mls_level_eq(&r->level[1], &r->level[0]);
2507
2508 if (eq)
2509 items = 2;
2510 else
2511 items = 3;
2512 buf[0] = cpu_to_le32(items-1);
2513 buf[1] = cpu_to_le32(r->level[0].sens);
2514 if (!eq)
2515 buf[2] = cpu_to_le32(r->level[1].sens);
2516
2517 BUG_ON(items > (sizeof(buf)/sizeof(buf[0])));
2518
2519 rc = put_entry(buf, sizeof(u32), items, fp);
2520 if (rc)
2521 return rc;
2522
2523 rc = ebitmap_write(&r->level[0].cat, fp);
2524 if (rc)
2525 return rc;
2526 if (!eq) {
2527 rc = ebitmap_write(&r->level[1].cat, fp);
2528 if (rc)
2529 return rc;
2530 }
2531
2532 return 0;
2533}
2534
2535static int sens_write(void *vkey, void *datum, void *ptr)
2536{
2537 char *key = vkey;
2538 struct level_datum *levdatum = datum;
2539 struct policy_data *pd = ptr;
2540 void *fp = pd->fp;
2541 __le32 buf[2];
2542 size_t len;
2543 int rc;
2544
2545 len = strlen(key);
2546 buf[0] = cpu_to_le32(len);
2547 buf[1] = cpu_to_le32(levdatum->isalias);
2548 rc = put_entry(buf, sizeof(u32), 2, fp);
2549 if (rc)
2550 return rc;
2551
2552 rc = put_entry(key, 1, len, fp);
2553 if (rc)
2554 return rc;
2555
2556 rc = mls_write_level(levdatum->level, fp);
2557 if (rc)
2558 return rc;
2559
2560 return 0;
2561}
2562
2563static int cat_write(void *vkey, void *datum, void *ptr)
2564{
2565 char *key = vkey;
2566 struct cat_datum *catdatum = datum;
2567 struct policy_data *pd = ptr;
2568 void *fp = pd->fp;
2569 __le32 buf[3];
2570 size_t len;
2571 int rc;
2572
2573 len = strlen(key);
2574 buf[0] = cpu_to_le32(len);
2575 buf[1] = cpu_to_le32(catdatum->value);
2576 buf[2] = cpu_to_le32(catdatum->isalias);
2577 rc = put_entry(buf, sizeof(u32), 3, fp);
2578 if (rc)
2579 return rc;
2580
2581 rc = put_entry(key, 1, len, fp);
2582 if (rc)
2583 return rc;
2584
2585 return 0;
2586}
2587
2588static int role_trans_write(struct policydb *p, void *fp)
2589{
2590 struct role_trans *r = p->role_tr;
2591 struct role_trans *tr;
2592 u32 buf[3];
2593 size_t nel;
2594 int rc;
2595
2596 nel = 0;
2597 for (tr = r; tr; tr = tr->next)
2598 nel++;
2599 buf[0] = cpu_to_le32(nel);
2600 rc = put_entry(buf, sizeof(u32), 1, fp);
2601 if (rc)
2602 return rc;
2603 for (tr = r; tr; tr = tr->next) {
2604 buf[0] = cpu_to_le32(tr->role);
2605 buf[1] = cpu_to_le32(tr->type);
2606 buf[2] = cpu_to_le32(tr->new_role);
2607 rc = put_entry(buf, sizeof(u32), 3, fp);
2608 if (rc)
2609 return rc;
2610 if (p->policyvers >= POLICYDB_VERSION_ROLETRANS) {
2611 buf[0] = cpu_to_le32(tr->tclass);
2612 rc = put_entry(buf, sizeof(u32), 1, fp);
2613 if (rc)
2614 return rc;
2615 }
2616 }
2617
2618 return 0;
2619}
2620
2621static int role_allow_write(struct role_allow *r, void *fp)
2622{
2623 struct role_allow *ra;
2624 u32 buf[2];
2625 size_t nel;
2626 int rc;
2627
2628 nel = 0;
2629 for (ra = r; ra; ra = ra->next)
2630 nel++;
2631 buf[0] = cpu_to_le32(nel);
2632 rc = put_entry(buf, sizeof(u32), 1, fp);
2633 if (rc)
2634 return rc;
2635 for (ra = r; ra; ra = ra->next) {
2636 buf[0] = cpu_to_le32(ra->role);
2637 buf[1] = cpu_to_le32(ra->new_role);
2638 rc = put_entry(buf, sizeof(u32), 2, fp);
2639 if (rc)
2640 return rc;
2641 }
2642 return 0;
2643}
2644
2645/*
2646 * Write a security context structure
2647 * to a policydb binary representation file.
2648 */
2649static int context_write(struct policydb *p, struct context *c,
2650 void *fp)
2651{
2652 int rc;
2653 __le32 buf[3];
2654
2655 buf[0] = cpu_to_le32(c->user);
2656 buf[1] = cpu_to_le32(c->role);
2657 buf[2] = cpu_to_le32(c->type);
2658
2659 rc = put_entry(buf, sizeof(u32), 3, fp);
2660 if (rc)
2661 return rc;
2662
2663 rc = mls_write_range_helper(&c->range, fp);
2664 if (rc)
2665 return rc;
2666
2667 return 0;
2668}
2669
2670/*
2671 * The following *_write functions are used to
2672 * write the symbol data to a policy database
2673 * binary representation file.
2674 */
2675
2676static int perm_write(void *vkey, void *datum, void *fp)
2677{
2678 char *key = vkey;
2679 struct perm_datum *perdatum = datum;
2680 __le32 buf[2];
2681 size_t len;
2682 int rc;
2683
2684 len = strlen(key);
2685 buf[0] = cpu_to_le32(len);
2686 buf[1] = cpu_to_le32(perdatum->value);
2687 rc = put_entry(buf, sizeof(u32), 2, fp);
2688 if (rc)
2689 return rc;
2690
2691 rc = put_entry(key, 1, len, fp);
2692 if (rc)
2693 return rc;
2694
2695 return 0;
2696}
2697
2698static int common_write(void *vkey, void *datum, void *ptr)
2699{
2700 char *key = vkey;
2701 struct common_datum *comdatum = datum;
2702 struct policy_data *pd = ptr;
2703 void *fp = pd->fp;
2704 __le32 buf[4];
2705 size_t len;
2706 int rc;
2707
2708 len = strlen(key);
2709 buf[0] = cpu_to_le32(len);
2710 buf[1] = cpu_to_le32(comdatum->value);
2711 buf[2] = cpu_to_le32(comdatum->permissions.nprim);
2712 buf[3] = cpu_to_le32(comdatum->permissions.table->nel);
2713 rc = put_entry(buf, sizeof(u32), 4, fp);
2714 if (rc)
2715 return rc;
2716
2717 rc = put_entry(key, 1, len, fp);
2718 if (rc)
2719 return rc;
2720
2721 rc = hashtab_map(comdatum->permissions.table, perm_write, fp);
2722 if (rc)
2723 return rc;
2724
2725 return 0;
2726}
2727
2728static int write_cons_helper(struct policydb *p, struct constraint_node *node,
2729 void *fp)
2730{
2731 struct constraint_node *c;
2732 struct constraint_expr *e;
2733 __le32 buf[3];
2734 u32 nel;
2735 int rc;
2736
2737 for (c = node; c; c = c->next) {
2738 nel = 0;
2739 for (e = c->expr; e; e = e->next)
2740 nel++;
2741 buf[0] = cpu_to_le32(c->permissions);
2742 buf[1] = cpu_to_le32(nel);
2743 rc = put_entry(buf, sizeof(u32), 2, fp);
2744 if (rc)
2745 return rc;
2746 for (e = c->expr; e; e = e->next) {
2747 buf[0] = cpu_to_le32(e->expr_type);
2748 buf[1] = cpu_to_le32(e->attr);
2749 buf[2] = cpu_to_le32(e->op);
2750 rc = put_entry(buf, sizeof(u32), 3, fp);
2751 if (rc)
2752 return rc;
2753
2754 switch (e->expr_type) {
2755 case CEXPR_NAMES:
2756 rc = ebitmap_write(&e->names, fp);
2757 if (rc)
2758 return rc;
2759 break;
2760 default:
2761 break;
2762 }
2763 }
2764 }
2765
2766 return 0;
2767}
2768
2769static int class_write(void *vkey, void *datum, void *ptr)
2770{
2771 char *key = vkey;
2772 struct class_datum *cladatum = datum;
2773 struct policy_data *pd = ptr;
2774 void *fp = pd->fp;
2775 struct policydb *p = pd->p;
2776 struct constraint_node *c;
2777 __le32 buf[6];
2778 u32 ncons;
2779 size_t len, len2;
2780 int rc;
2781
2782 len = strlen(key);
2783 if (cladatum->comkey)
2784 len2 = strlen(cladatum->comkey);
2785 else
2786 len2 = 0;
2787
2788 ncons = 0;
2789 for (c = cladatum->constraints; c; c = c->next)
2790 ncons++;
2791
2792 buf[0] = cpu_to_le32(len);
2793 buf[1] = cpu_to_le32(len2);
2794 buf[2] = cpu_to_le32(cladatum->value);
2795 buf[3] = cpu_to_le32(cladatum->permissions.nprim);
2796 if (cladatum->permissions.table)
2797 buf[4] = cpu_to_le32(cladatum->permissions.table->nel);
2798 else
2799 buf[4] = 0;
2800 buf[5] = cpu_to_le32(ncons);
2801 rc = put_entry(buf, sizeof(u32), 6, fp);
2802 if (rc)
2803 return rc;
2804
2805 rc = put_entry(key, 1, len, fp);
2806 if (rc)
2807 return rc;
2808
2809 if (cladatum->comkey) {
2810 rc = put_entry(cladatum->comkey, 1, len2, fp);
2811 if (rc)
2812 return rc;
2813 }
2814
2815 rc = hashtab_map(cladatum->permissions.table, perm_write, fp);
2816 if (rc)
2817 return rc;
2818
2819 rc = write_cons_helper(p, cladatum->constraints, fp);
2820 if (rc)
2821 return rc;
2822
2823 /* write out the validatetrans rule */
2824 ncons = 0;
2825 for (c = cladatum->validatetrans; c; c = c->next)
2826 ncons++;
2827
2828 buf[0] = cpu_to_le32(ncons);
2829 rc = put_entry(buf, sizeof(u32), 1, fp);
2830 if (rc)
2831 return rc;
2832
2833 rc = write_cons_helper(p, cladatum->validatetrans, fp);
2834 if (rc)
2835 return rc;
2836
2837 return 0;
2838}
2839
2840static int role_write(void *vkey, void *datum, void *ptr)
2841{
2842 char *key = vkey;
2843 struct role_datum *role = datum;
2844 struct policy_data *pd = ptr;
2845 void *fp = pd->fp;
2846 struct policydb *p = pd->p;
2847 __le32 buf[3];
2848 size_t items, len;
2849 int rc;
2850
2851 len = strlen(key);
2852 items = 0;
2853 buf[items++] = cpu_to_le32(len);
2854 buf[items++] = cpu_to_le32(role->value);
2855 if (p->policyvers >= POLICYDB_VERSION_BOUNDARY)
2856 buf[items++] = cpu_to_le32(role->bounds);
2857
2858 BUG_ON(items > (sizeof(buf)/sizeof(buf[0])));
2859
2860 rc = put_entry(buf, sizeof(u32), items, fp);
2861 if (rc)
2862 return rc;
2863
2864 rc = put_entry(key, 1, len, fp);
2865 if (rc)
2866 return rc;
2867
2868 rc = ebitmap_write(&role->dominates, fp);
2869 if (rc)
2870 return rc;
2871
2872 rc = ebitmap_write(&role->types, fp);
2873 if (rc)
2874 return rc;
2875
2876 return 0;
2877}
2878
2879static int type_write(void *vkey, void *datum, void *ptr)
2880{
2881 char *key = vkey;
2882 struct type_datum *typdatum = datum;
2883 struct policy_data *pd = ptr;
2884 struct policydb *p = pd->p;
2885 void *fp = pd->fp;
2886 __le32 buf[4];
2887 int rc;
2888 size_t items, len;
2889
2890 len = strlen(key);
2891 items = 0;
2892 buf[items++] = cpu_to_le32(len);
2893 buf[items++] = cpu_to_le32(typdatum->value);
2894 if (p->policyvers >= POLICYDB_VERSION_BOUNDARY) {
2895 u32 properties = 0;
2896
2897 if (typdatum->primary)
2898 properties |= TYPEDATUM_PROPERTY_PRIMARY;
2899
2900 if (typdatum->attribute)
2901 properties |= TYPEDATUM_PROPERTY_ATTRIBUTE;
2902
2903 buf[items++] = cpu_to_le32(properties);
2904 buf[items++] = cpu_to_le32(typdatum->bounds);
2905 } else {
2906 buf[items++] = cpu_to_le32(typdatum->primary);
2907 }
2908 BUG_ON(items > (sizeof(buf) / sizeof(buf[0])));
2909 rc = put_entry(buf, sizeof(u32), items, fp);
2910 if (rc)
2911 return rc;
2912
2913 rc = put_entry(key, 1, len, fp);
2914 if (rc)
2915 return rc;
2916
2917 return 0;
2918}
2919
2920static int user_write(void *vkey, void *datum, void *ptr)
2921{
2922 char *key = vkey;
2923 struct user_datum *usrdatum = datum;
2924 struct policy_data *pd = ptr;
2925 struct policydb *p = pd->p;
2926 void *fp = pd->fp;
2927 __le32 buf[3];
2928 size_t items, len;
2929 int rc;
2930
2931 len = strlen(key);
2932 items = 0;
2933 buf[items++] = cpu_to_le32(len);
2934 buf[items++] = cpu_to_le32(usrdatum->value);
2935 if (p->policyvers >= POLICYDB_VERSION_BOUNDARY)
2936 buf[items++] = cpu_to_le32(usrdatum->bounds);
2937 BUG_ON(items > (sizeof(buf) / sizeof(buf[0])));
2938 rc = put_entry(buf, sizeof(u32), items, fp);
2939 if (rc)
2940 return rc;
2941
2942 rc = put_entry(key, 1, len, fp);
2943 if (rc)
2944 return rc;
2945
2946 rc = ebitmap_write(&usrdatum->roles, fp);
2947 if (rc)
2948 return rc;
2949
2950 rc = mls_write_range_helper(&usrdatum->range, fp);
2951 if (rc)
2952 return rc;
2953
2954 rc = mls_write_level(&usrdatum->dfltlevel, fp);
2955 if (rc)
2956 return rc;
2957
2958 return 0;
2959}
2960
2961static int (*write_f[SYM_NUM]) (void *key, void *datum,
2962 void *datap) =
2963{
2964 common_write,
2965 class_write,
2966 role_write,
2967 type_write,
2968 user_write,
2969 cond_write_bool,
2970 sens_write,
2971 cat_write,
2972};
2973
2974static int ocontext_write(struct policydb *p, struct policydb_compat_info *info,
2975 void *fp)
2976{
2977 unsigned int i, j, rc;
2978 size_t nel, len;
2979 __le32 buf[3];
2980 u32 nodebuf[8];
2981 struct ocontext *c;
2982 for (i = 0; i < info->ocon_num; i++) {
2983 nel = 0;
2984 for (c = p->ocontexts[i]; c; c = c->next)
2985 nel++;
2986 buf[0] = cpu_to_le32(nel);
2987 rc = put_entry(buf, sizeof(u32), 1, fp);
2988 if (rc)
2989 return rc;
2990 for (c = p->ocontexts[i]; c; c = c->next) {
2991 switch (i) {
2992 case OCON_ISID:
2993 buf[0] = cpu_to_le32(c->sid[0]);
2994 rc = put_entry(buf, sizeof(u32), 1, fp);
2995 if (rc)
2996 return rc;
2997 rc = context_write(p, &c->context[0], fp);
2998 if (rc)
2999 return rc;
3000 break;
3001 case OCON_FS:
3002 case OCON_NETIF:
3003 len = strlen(c->u.name);
3004 buf[0] = cpu_to_le32(len);
3005 rc = put_entry(buf, sizeof(u32), 1, fp);
3006 if (rc)
3007 return rc;
3008 rc = put_entry(c->u.name, 1, len, fp);
3009 if (rc)
3010 return rc;
3011 rc = context_write(p, &c->context[0], fp);
3012 if (rc)
3013 return rc;
3014 rc = context_write(p, &c->context[1], fp);
3015 if (rc)
3016 return rc;
3017 break;
3018 case OCON_PORT:
3019 buf[0] = cpu_to_le32(c->u.port.protocol);
3020 buf[1] = cpu_to_le32(c->u.port.low_port);
3021 buf[2] = cpu_to_le32(c->u.port.high_port);
3022 rc = put_entry(buf, sizeof(u32), 3, fp);
3023 if (rc)
3024 return rc;
3025 rc = context_write(p, &c->context[0], fp);
3026 if (rc)
3027 return rc;
3028 break;
3029 case OCON_NODE:
3030 nodebuf[0] = c->u.node.addr; /* network order */
3031 nodebuf[1] = c->u.node.mask; /* network order */
3032 rc = put_entry(nodebuf, sizeof(u32), 2, fp);
3033 if (rc)
3034 return rc;
3035 rc = context_write(p, &c->context[0], fp);
3036 if (rc)
3037 return rc;
3038 break;
3039 case OCON_FSUSE:
3040 buf[0] = cpu_to_le32(c->v.behavior);
3041 len = strlen(c->u.name);
3042 buf[1] = cpu_to_le32(len);
3043 rc = put_entry(buf, sizeof(u32), 2, fp);
3044 if (rc)
3045 return rc;
3046 rc = put_entry(c->u.name, 1, len, fp);
3047 if (rc)
3048 return rc;
3049 rc = context_write(p, &c->context[0], fp);
3050 if (rc)
3051 return rc;
3052 break;
3053 case OCON_NODE6:
3054 for (j = 0; j < 4; j++)
3055 nodebuf[j] = c->u.node6.addr[j]; /* network order */
3056 for (j = 0; j < 4; j++)
3057 nodebuf[j + 4] = c->u.node6.mask[j]; /* network order */
3058 rc = put_entry(nodebuf, sizeof(u32), 8, fp);
3059 if (rc)
3060 return rc;
3061 rc = context_write(p, &c->context[0], fp);
3062 if (rc)
3063 return rc;
3064 break;
3065 }
3066 }
3067 }
3068 return 0;
3069}
3070
3071static int genfs_write(struct policydb *p, void *fp)
3072{
3073 struct genfs *genfs;
3074 struct ocontext *c;
3075 size_t len;
3076 __le32 buf[1];
3077 int rc;
3078
3079 len = 0;
3080 for (genfs = p->genfs; genfs; genfs = genfs->next)
3081 len++;
3082 buf[0] = cpu_to_le32(len);
3083 rc = put_entry(buf, sizeof(u32), 1, fp);
3084 if (rc)
3085 return rc;
3086 for (genfs = p->genfs; genfs; genfs = genfs->next) {
3087 len = strlen(genfs->fstype);
3088 buf[0] = cpu_to_le32(len);
3089 rc = put_entry(buf, sizeof(u32), 1, fp);
3090 if (rc)
3091 return rc;
3092 rc = put_entry(genfs->fstype, 1, len, fp);
3093 if (rc)
3094 return rc;
3095 len = 0;
3096 for (c = genfs->head; c; c = c->next)
3097 len++;
3098 buf[0] = cpu_to_le32(len);
3099 rc = put_entry(buf, sizeof(u32), 1, fp);
3100 if (rc)
3101 return rc;
3102 for (c = genfs->head; c; c = c->next) {
3103 len = strlen(c->u.name);
3104 buf[0] = cpu_to_le32(len);
3105 rc = put_entry(buf, sizeof(u32), 1, fp);
3106 if (rc)
3107 return rc;
3108 rc = put_entry(c->u.name, 1, len, fp);
3109 if (rc)
3110 return rc;
3111 buf[0] = cpu_to_le32(c->v.sclass);
3112 rc = put_entry(buf, sizeof(u32), 1, fp);
3113 if (rc)
3114 return rc;
3115 rc = context_write(p, &c->context[0], fp);
3116 if (rc)
3117 return rc;
3118 }
3119 }
3120 return 0;
3121}
3122
3123static int hashtab_cnt(void *key, void *data, void *ptr)
3124{
3125 int *cnt = ptr;
3126 *cnt = *cnt + 1;
3127
3128 return 0;
3129}
3130
3131static int range_write_helper(void *key, void *data, void *ptr)
3132{
3133 __le32 buf[2];
3134 struct range_trans *rt = key;
3135 struct mls_range *r = data;
3136 struct policy_data *pd = ptr;
3137 void *fp = pd->fp;
3138 struct policydb *p = pd->p;
3139 int rc;
3140
3141 buf[0] = cpu_to_le32(rt->source_type);
3142 buf[1] = cpu_to_le32(rt->target_type);
3143 rc = put_entry(buf, sizeof(u32), 2, fp);
3144 if (rc)
3145 return rc;
3146 if (p->policyvers >= POLICYDB_VERSION_RANGETRANS) {
3147 buf[0] = cpu_to_le32(rt->target_class);
3148 rc = put_entry(buf, sizeof(u32), 1, fp);
3149 if (rc)
3150 return rc;
3151 }
3152 rc = mls_write_range_helper(r, fp);
3153 if (rc)
3154 return rc;
3155
3156 return 0;
3157}
3158
3159static int range_write(struct policydb *p, void *fp)
3160{
3161 size_t nel;
3162 __le32 buf[1];
3163 int rc;
3164 struct policy_data pd;
3165
3166 pd.p = p;
3167 pd.fp = fp;
3168
3169 /* count the number of entries in the hashtab */
3170 nel = 0;
3171 rc = hashtab_map(p->range_tr, hashtab_cnt, &nel);
3172 if (rc)
3173 return rc;
3174
3175 buf[0] = cpu_to_le32(nel);
3176 rc = put_entry(buf, sizeof(u32), 1, fp);
3177 if (rc)
3178 return rc;
3179
3180 /* actually write all of the entries */
3181 rc = hashtab_map(p->range_tr, range_write_helper, &pd);
3182 if (rc)
3183 return rc;
3184
3185 return 0;
3186}
3187
3188static int filename_write_helper(void *key, void *data, void *ptr)
3189{
3190 __le32 buf[4];
3191 struct filename_trans *ft = key;
3192 struct filename_trans_datum *otype = data;
3193 void *fp = ptr;
3194 int rc;
3195 u32 len;
3196
3197 len = strlen(ft->name);
3198 buf[0] = cpu_to_le32(len);
3199 rc = put_entry(buf, sizeof(u32), 1, fp);
3200 if (rc)
3201 return rc;
3202
3203 rc = put_entry(ft->name, sizeof(char), len, fp);
3204 if (rc)
3205 return rc;
3206
3207 buf[0] = ft->stype;
3208 buf[1] = ft->ttype;
3209 buf[2] = ft->tclass;
3210 buf[3] = otype->otype;
3211
3212 rc = put_entry(buf, sizeof(u32), 4, fp);
3213 if (rc)
3214 return rc;
3215
3216 return 0;
3217}
3218
3219static int filename_trans_write(struct policydb *p, void *fp)
3220{
3221 u32 nel;
3222 __le32 buf[1];
3223 int rc;
3224
3225 if (p->policyvers < POLICYDB_VERSION_FILENAME_TRANS)
3226 return 0;
3227
3228 nel = 0;
3229 rc = hashtab_map(p->filename_trans, hashtab_cnt, &nel);
3230 if (rc)
3231 return rc;
3232
3233 buf[0] = cpu_to_le32(nel);
3234 rc = put_entry(buf, sizeof(u32), 1, fp);
3235 if (rc)
3236 return rc;
3237
3238 rc = hashtab_map(p->filename_trans, filename_write_helper, fp);
3239 if (rc)
3240 return rc;
3241
3242 return 0;
3243}
3244
3245/*
3246 * Write the configuration data in a policy database
3247 * structure to a policy database binary representation
3248 * file.
3249 */
3250int policydb_write(struct policydb *p, void *fp)
3251{
3252 unsigned int i, num_syms;
3253 int rc;
3254 __le32 buf[4];
3255 u32 config;
3256 size_t len;
3257 struct policydb_compat_info *info;
3258
3259 /*
3260 * refuse to write policy older than compressed avtab
3261 * to simplify the writer. There are other tests dropped
3262 * since we assume this throughout the writer code. Be
3263 * careful if you ever try to remove this restriction
3264 */
3265 if (p->policyvers < POLICYDB_VERSION_AVTAB) {
3266 printk(KERN_ERR "SELinux: refusing to write policy version %d."
3267 " Because it is less than version %d\n", p->policyvers,
3268 POLICYDB_VERSION_AVTAB);
3269 return -EINVAL;
3270 }
3271
3272 config = 0;
3273 if (p->mls_enabled)
3274 config |= POLICYDB_CONFIG_MLS;
3275
3276 if (p->reject_unknown)
3277 config |= REJECT_UNKNOWN;
3278 if (p->allow_unknown)
3279 config |= ALLOW_UNKNOWN;
3280
3281 /* Write the magic number and string identifiers. */
3282 buf[0] = cpu_to_le32(POLICYDB_MAGIC);
3283 len = strlen(POLICYDB_STRING);
3284 buf[1] = cpu_to_le32(len);
3285 rc = put_entry(buf, sizeof(u32), 2, fp);
3286 if (rc)
3287 return rc;
3288 rc = put_entry(POLICYDB_STRING, 1, len, fp);
3289 if (rc)
3290 return rc;
3291
3292 /* Write the version, config, and table sizes. */
3293 info = policydb_lookup_compat(p->policyvers);
3294 if (!info) {
3295 printk(KERN_ERR "SELinux: compatibility lookup failed for policy "
3296 "version %d", p->policyvers);
3297 return -EINVAL;
3298 }
3299
3300 buf[0] = cpu_to_le32(p->policyvers);
3301 buf[1] = cpu_to_le32(config);
3302 buf[2] = cpu_to_le32(info->sym_num);
3303 buf[3] = cpu_to_le32(info->ocon_num);
3304
3305 rc = put_entry(buf, sizeof(u32), 4, fp);
3306 if (rc)
3307 return rc;
3308
3309 if (p->policyvers >= POLICYDB_VERSION_POLCAP) {
3310 rc = ebitmap_write(&p->policycaps, fp);
3311 if (rc)
3312 return rc;
3313 }
3314
3315 if (p->policyvers >= POLICYDB_VERSION_PERMISSIVE) {
3316 rc = ebitmap_write(&p->permissive_map, fp);
3317 if (rc)
3318 return rc;
3319 }
3320
3321 num_syms = info->sym_num;
3322 for (i = 0; i < num_syms; i++) {
3323 struct policy_data pd;
3324
3325 pd.fp = fp;
3326 pd.p = p;
3327
3328 buf[0] = cpu_to_le32(p->symtab[i].nprim);
3329 buf[1] = cpu_to_le32(p->symtab[i].table->nel);
3330
3331 rc = put_entry(buf, sizeof(u32), 2, fp);
3332 if (rc)
3333 return rc;
3334 rc = hashtab_map(p->symtab[i].table, write_f[i], &pd);
3335 if (rc)
3336 return rc;
3337 }
3338
3339 rc = avtab_write(p, &p->te_avtab, fp);
3340 if (rc)
3341 return rc;
3342
3343 rc = cond_write_list(p, p->cond_list, fp);
3344 if (rc)
3345 return rc;
3346
3347 rc = role_trans_write(p, fp);
3348 if (rc)
3349 return rc;
3350
3351 rc = role_allow_write(p->role_allow, fp);
3352 if (rc)
3353 return rc;
3354
3355 rc = filename_trans_write(p, fp);
3356 if (rc)
3357 return rc;
3358
3359 rc = ocontext_write(p, info, fp);
3360 if (rc)
3361 return rc;
3362
3363 rc = genfs_write(p, fp);
3364 if (rc)
3365 return rc;
3366
3367 rc = range_write(p, fp);
3368 if (rc)
3369 return rc;
3370
3371 for (i = 0; i < p->p_types.nprim; i++) {
3372 struct ebitmap *e = flex_array_get(p->type_attr_map_array, i);
3373
3374 BUG_ON(!e);
3375 rc = ebitmap_write(e, fp);
3376 if (rc)
3377 return rc;
3378 }
3379
3380 return 0;
3381}
diff --git a/security/selinux/ss/policydb.h b/security/selinux/ss/policydb.h
index 310e94442cb8..b846c0387180 100644
--- a/security/selinux/ss/policydb.h
+++ b/security/selinux/ss/policydb.h
@@ -72,11 +72,23 @@ struct role_datum {
72 72
73struct role_trans { 73struct role_trans {
74 u32 role; /* current role */ 74 u32 role; /* current role */
75 u32 type; /* program executable type */ 75 u32 type; /* program executable type, or new object type */
76 u32 tclass; /* process class, or new object class */
76 u32 new_role; /* new role */ 77 u32 new_role; /* new role */
77 struct role_trans *next; 78 struct role_trans *next;
78}; 79};
79 80
81struct filename_trans {
82 u32 stype; /* current process */
83 u32 ttype; /* parent dir context */
84 u16 tclass; /* class of new object */
85 const char *name; /* last path component */
86};
87
88struct filename_trans_datum {
89 u32 otype; /* expected of new object */
90};
91
80struct role_allow { 92struct role_allow {
81 u32 role; /* current role */ 93 u32 role; /* current role */
82 u32 new_role; /* new role */ 94 u32 new_role; /* new role */
@@ -203,21 +215,13 @@ struct policydb {
203#define p_cats symtab[SYM_CATS] 215#define p_cats symtab[SYM_CATS]
204 216
205 /* symbol names indexed by (value - 1) */ 217 /* symbol names indexed by (value - 1) */
206 char **sym_val_to_name[SYM_NUM]; 218 struct flex_array *sym_val_to_name[SYM_NUM];
207#define p_common_val_to_name sym_val_to_name[SYM_COMMONS]
208#define p_class_val_to_name sym_val_to_name[SYM_CLASSES]
209#define p_role_val_to_name sym_val_to_name[SYM_ROLES]
210#define p_type_val_to_name sym_val_to_name[SYM_TYPES]
211#define p_user_val_to_name sym_val_to_name[SYM_USERS]
212#define p_bool_val_to_name sym_val_to_name[SYM_BOOLS]
213#define p_sens_val_to_name sym_val_to_name[SYM_LEVELS]
214#define p_cat_val_to_name sym_val_to_name[SYM_CATS]
215 219
216 /* class, role, and user attributes indexed by (value - 1) */ 220 /* class, role, and user attributes indexed by (value - 1) */
217 struct class_datum **class_val_to_struct; 221 struct class_datum **class_val_to_struct;
218 struct role_datum **role_val_to_struct; 222 struct role_datum **role_val_to_struct;
219 struct user_datum **user_val_to_struct; 223 struct user_datum **user_val_to_struct;
220 struct type_datum **type_val_to_struct; 224 struct flex_array *type_val_to_struct_array;
221 225
222 /* type enforcement access vectors and transitions */ 226 /* type enforcement access vectors and transitions */
223 struct avtab te_avtab; 227 struct avtab te_avtab;
@@ -225,6 +229,12 @@ struct policydb {
225 /* role transitions */ 229 /* role transitions */
226 struct role_trans *role_tr; 230 struct role_trans *role_tr;
227 231
232 /* file transitions with the last path component */
233 /* quickly exclude lookups when parent ttype has no rules */
234 struct ebitmap filename_trans_ttypes;
235 /* actual set of filename_trans rules */
236 struct hashtab *filename_trans;
237
228 /* bools indexed by (value - 1) */ 238 /* bools indexed by (value - 1) */
229 struct cond_bool_datum **bool_val_to_struct; 239 struct cond_bool_datum **bool_val_to_struct;
230 /* type enforcement conditional access vectors and transitions */ 240 /* type enforcement conditional access vectors and transitions */
@@ -254,6 +264,9 @@ struct policydb {
254 264
255 struct ebitmap permissive_map; 265 struct ebitmap permissive_map;
256 266
267 /* length of this policy when it was loaded */
268 size_t len;
269
257 unsigned int policyvers; 270 unsigned int policyvers;
258 271
259 unsigned int reject_unknown : 1; 272 unsigned int reject_unknown : 1;
@@ -270,6 +283,7 @@ extern int policydb_class_isvalid(struct policydb *p, unsigned int class);
270extern int policydb_type_isvalid(struct policydb *p, unsigned int type); 283extern int policydb_type_isvalid(struct policydb *p, unsigned int type);
271extern int policydb_role_isvalid(struct policydb *p, unsigned int role); 284extern int policydb_role_isvalid(struct policydb *p, unsigned int role);
272extern int policydb_read(struct policydb *p, void *fp); 285extern int policydb_read(struct policydb *p, void *fp);
286extern int policydb_write(struct policydb *p, void *fp);
273 287
274#define PERM_SYMTAB_SIZE 32 288#define PERM_SYMTAB_SIZE 32
275 289
@@ -290,6 +304,11 @@ struct policy_file {
290 size_t len; 304 size_t len;
291}; 305};
292 306
307struct policy_data {
308 struct policydb *p;
309 void *fp;
310};
311
293static inline int next_entry(void *buf, struct policy_file *fp, size_t bytes) 312static inline int next_entry(void *buf, struct policy_file *fp, size_t bytes)
294{ 313{
295 if (bytes > fp->len) 314 if (bytes > fp->len)
@@ -301,6 +320,24 @@ static inline int next_entry(void *buf, struct policy_file *fp, size_t bytes)
301 return 0; 320 return 0;
302} 321}
303 322
323static inline int put_entry(const void *buf, size_t bytes, int num, struct policy_file *fp)
324{
325 size_t len = bytes * num;
326
327 memcpy(fp->data, buf, len);
328 fp->data += len;
329 fp->len -= len;
330
331 return 0;
332}
333
334static inline char *sym_name(struct policydb *p, unsigned int sym_num, unsigned int element_nr)
335{
336 struct flex_array *fa = p->sym_val_to_name[sym_num];
337
338 return flex_array_get_ptr(fa, element_nr);
339}
340
304extern u16 string_to_security_class(struct policydb *p, const char *name); 341extern u16 string_to_security_class(struct policydb *p, const char *name);
305extern u32 string_to_av_perm(struct policydb *p, u16 tclass, const char *name); 342extern u32 string_to_av_perm(struct policydb *p, u16 tclass, const char *name);
306 343
diff --git a/security/selinux/ss/services.c b/security/selinux/ss/services.c
index 9ea2feca3cd4..973e00e34fa9 100644
--- a/security/selinux/ss/services.c
+++ b/security/selinux/ss/services.c
@@ -51,6 +51,7 @@
51#include <linux/mutex.h> 51#include <linux/mutex.h>
52#include <linux/selinux.h> 52#include <linux/selinux.h>
53#include <linux/flex_array.h> 53#include <linux/flex_array.h>
54#include <linux/vmalloc.h>
54#include <net/netlabel.h> 55#include <net/netlabel.h>
55 56
56#include "flask.h" 57#include "flask.h"
@@ -200,6 +201,21 @@ static u16 unmap_class(u16 tclass)
200 return tclass; 201 return tclass;
201} 202}
202 203
204/*
205 * Get kernel value for class from its policy value
206 */
207static u16 map_class(u16 pol_value)
208{
209 u16 i;
210
211 for (i = 1; i < current_mapping_size; i++) {
212 if (current_mapping[i].value == pol_value)
213 return i;
214 }
215
216 return SECCLASS_NULL;
217}
218
203static void map_decision(u16 tclass, struct av_decision *avd, 219static void map_decision(u16 tclass, struct av_decision *avd,
204 int allow_unknown) 220 int allow_unknown)
205{ 221{
@@ -463,7 +479,7 @@ static void security_dump_masked_av(struct context *scontext,
463 if (!permissions) 479 if (!permissions)
464 return; 480 return;
465 481
466 tclass_name = policydb.p_class_val_to_name[tclass - 1]; 482 tclass_name = sym_name(&policydb, SYM_CLASSES, tclass - 1);
467 tclass_dat = policydb.class_val_to_struct[tclass - 1]; 483 tclass_dat = policydb.class_val_to_struct[tclass - 1];
468 common_dat = tclass_dat->comdatum; 484 common_dat = tclass_dat->comdatum;
469 485
@@ -529,12 +545,18 @@ static void type_attribute_bounds_av(struct context *scontext,
529 struct context lo_scontext; 545 struct context lo_scontext;
530 struct context lo_tcontext; 546 struct context lo_tcontext;
531 struct av_decision lo_avd; 547 struct av_decision lo_avd;
532 struct type_datum *source 548 struct type_datum *source;
533 = policydb.type_val_to_struct[scontext->type - 1]; 549 struct type_datum *target;
534 struct type_datum *target
535 = policydb.type_val_to_struct[tcontext->type - 1];
536 u32 masked = 0; 550 u32 masked = 0;
537 551
552 source = flex_array_get_ptr(policydb.type_val_to_struct_array,
553 scontext->type - 1);
554 BUG_ON(!source);
555
556 target = flex_array_get_ptr(policydb.type_val_to_struct_array,
557 tcontext->type - 1);
558 BUG_ON(!target);
559
538 if (source->bounds) { 560 if (source->bounds) {
539 memset(&lo_avd, 0, sizeof(lo_avd)); 561 memset(&lo_avd, 0, sizeof(lo_avd));
540 562
@@ -700,16 +722,16 @@ static int security_validtrans_handle_fail(struct context *ocontext,
700 char *o = NULL, *n = NULL, *t = NULL; 722 char *o = NULL, *n = NULL, *t = NULL;
701 u32 olen, nlen, tlen; 723 u32 olen, nlen, tlen;
702 724
703 if (context_struct_to_string(ocontext, &o, &olen) < 0) 725 if (context_struct_to_string(ocontext, &o, &olen))
704 goto out; 726 goto out;
705 if (context_struct_to_string(ncontext, &n, &nlen) < 0) 727 if (context_struct_to_string(ncontext, &n, &nlen))
706 goto out; 728 goto out;
707 if (context_struct_to_string(tcontext, &t, &tlen) < 0) 729 if (context_struct_to_string(tcontext, &t, &tlen))
708 goto out; 730 goto out;
709 audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR, 731 audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
710 "security_validate_transition: denied for" 732 "security_validate_transition: denied for"
711 " oldcontext=%s newcontext=%s taskcontext=%s tclass=%s", 733 " oldcontext=%s newcontext=%s taskcontext=%s tclass=%s",
712 o, n, t, policydb.p_class_val_to_name[tclass-1]); 734 o, n, t, sym_name(&policydb, SYM_CLASSES, tclass-1));
713out: 735out:
714 kfree(o); 736 kfree(o);
715 kfree(n); 737 kfree(n);
@@ -800,10 +822,11 @@ int security_bounded_transition(u32 old_sid, u32 new_sid)
800 struct context *old_context, *new_context; 822 struct context *old_context, *new_context;
801 struct type_datum *type; 823 struct type_datum *type;
802 int index; 824 int index;
803 int rc = -EINVAL; 825 int rc;
804 826
805 read_lock(&policy_rwlock); 827 read_lock(&policy_rwlock);
806 828
829 rc = -EINVAL;
807 old_context = sidtab_search(&sidtab, old_sid); 830 old_context = sidtab_search(&sidtab, old_sid);
808 if (!old_context) { 831 if (!old_context) {
809 printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n", 832 printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n",
@@ -811,6 +834,7 @@ int security_bounded_transition(u32 old_sid, u32 new_sid)
811 goto out; 834 goto out;
812 } 835 }
813 836
837 rc = -EINVAL;
814 new_context = sidtab_search(&sidtab, new_sid); 838 new_context = sidtab_search(&sidtab, new_sid);
815 if (!new_context) { 839 if (!new_context) {
816 printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n", 840 printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n",
@@ -818,28 +842,27 @@ int security_bounded_transition(u32 old_sid, u32 new_sid)
818 goto out; 842 goto out;
819 } 843 }
820 844
845 rc = 0;
821 /* type/domain unchanged */ 846 /* type/domain unchanged */
822 if (old_context->type == new_context->type) { 847 if (old_context->type == new_context->type)
823 rc = 0;
824 goto out; 848 goto out;
825 }
826 849
827 index = new_context->type; 850 index = new_context->type;
828 while (true) { 851 while (true) {
829 type = policydb.type_val_to_struct[index - 1]; 852 type = flex_array_get_ptr(policydb.type_val_to_struct_array,
853 index - 1);
830 BUG_ON(!type); 854 BUG_ON(!type);
831 855
832 /* not bounded anymore */ 856 /* not bounded anymore */
833 if (!type->bounds) { 857 rc = -EPERM;
834 rc = -EPERM; 858 if (!type->bounds)
835 break; 859 break;
836 }
837 860
838 /* @newsid is bounded by @oldsid */ 861 /* @newsid is bounded by @oldsid */
839 if (type->bounds == old_context->type) { 862 rc = 0;
840 rc = 0; 863 if (type->bounds == old_context->type)
841 break; 864 break;
842 } 865
843 index = type->bounds; 866 index = type->bounds;
844 } 867 }
845 868
@@ -991,7 +1014,8 @@ static int context_struct_to_string(struct context *context, char **scontext, u3
991{ 1014{
992 char *scontextp; 1015 char *scontextp;
993 1016
994 *scontext = NULL; 1017 if (scontext)
1018 *scontext = NULL;
995 *scontext_len = 0; 1019 *scontext_len = 0;
996 1020
997 if (context->len) { 1021 if (context->len) {
@@ -1003,11 +1027,14 @@ static int context_struct_to_string(struct context *context, char **scontext, u3
1003 } 1027 }
1004 1028
1005 /* Compute the size of the context. */ 1029 /* Compute the size of the context. */
1006 *scontext_len += strlen(policydb.p_user_val_to_name[context->user - 1]) + 1; 1030 *scontext_len += strlen(sym_name(&policydb, SYM_USERS, context->user - 1)) + 1;
1007 *scontext_len += strlen(policydb.p_role_val_to_name[context->role - 1]) + 1; 1031 *scontext_len += strlen(sym_name(&policydb, SYM_ROLES, context->role - 1)) + 1;
1008 *scontext_len += strlen(policydb.p_type_val_to_name[context->type - 1]) + 1; 1032 *scontext_len += strlen(sym_name(&policydb, SYM_TYPES, context->type - 1)) + 1;
1009 *scontext_len += mls_compute_context_len(context); 1033 *scontext_len += mls_compute_context_len(context);
1010 1034
1035 if (!scontext)
1036 return 0;
1037
1011 /* Allocate space for the context; caller must free this space. */ 1038 /* Allocate space for the context; caller must free this space. */
1012 scontextp = kmalloc(*scontext_len, GFP_ATOMIC); 1039 scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
1013 if (!scontextp) 1040 if (!scontextp)
@@ -1018,12 +1045,12 @@ static int context_struct_to_string(struct context *context, char **scontext, u3
1018 * Copy the user name, role name and type name into the context. 1045 * Copy the user name, role name and type name into the context.
1019 */ 1046 */
1020 sprintf(scontextp, "%s:%s:%s", 1047 sprintf(scontextp, "%s:%s:%s",
1021 policydb.p_user_val_to_name[context->user - 1], 1048 sym_name(&policydb, SYM_USERS, context->user - 1),
1022 policydb.p_role_val_to_name[context->role - 1], 1049 sym_name(&policydb, SYM_ROLES, context->role - 1),
1023 policydb.p_type_val_to_name[context->type - 1]); 1050 sym_name(&policydb, SYM_TYPES, context->type - 1));
1024 scontextp += strlen(policydb.p_user_val_to_name[context->user - 1]) + 1051 scontextp += strlen(sym_name(&policydb, SYM_USERS, context->user - 1)) +
1025 1 + strlen(policydb.p_role_val_to_name[context->role - 1]) + 1052 1 + strlen(sym_name(&policydb, SYM_ROLES, context->role - 1)) +
1026 1 + strlen(policydb.p_type_val_to_name[context->type - 1]); 1053 1 + strlen(sym_name(&policydb, SYM_TYPES, context->type - 1));
1027 1054
1028 mls_sid_to_context(context, &scontextp); 1055 mls_sid_to_context(context, &scontextp);
1029 1056
@@ -1047,7 +1074,8 @@ static int security_sid_to_context_core(u32 sid, char **scontext,
1047 struct context *context; 1074 struct context *context;
1048 int rc = 0; 1075 int rc = 0;
1049 1076
1050 *scontext = NULL; 1077 if (scontext)
1078 *scontext = NULL;
1051 *scontext_len = 0; 1079 *scontext_len = 0;
1052 1080
1053 if (!ss_initialized) { 1081 if (!ss_initialized) {
@@ -1055,6 +1083,8 @@ static int security_sid_to_context_core(u32 sid, char **scontext,
1055 char *scontextp; 1083 char *scontextp;
1056 1084
1057 *scontext_len = strlen(initial_sid_to_string[sid]) + 1; 1085 *scontext_len = strlen(initial_sid_to_string[sid]) + 1;
1086 if (!scontext)
1087 goto out;
1058 scontextp = kmalloc(*scontext_len, GFP_ATOMIC); 1088 scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
1059 if (!scontextp) { 1089 if (!scontextp) {
1060 rc = -ENOMEM; 1090 rc = -ENOMEM;
@@ -1179,16 +1209,13 @@ static int string_to_context_struct(struct policydb *pol,
1179 if (rc) 1209 if (rc)
1180 goto out; 1210 goto out;
1181 1211
1182 if ((p - scontext) < scontext_len) { 1212 rc = -EINVAL;
1183 rc = -EINVAL; 1213 if ((p - scontext) < scontext_len)
1184 goto out; 1214 goto out;
1185 }
1186 1215
1187 /* Check the validity of the new context. */ 1216 /* Check the validity of the new context. */
1188 if (!policydb_context_isvalid(pol, ctx)) { 1217 if (!policydb_context_isvalid(pol, ctx))
1189 rc = -EINVAL;
1190 goto out; 1218 goto out;
1191 }
1192 rc = 0; 1219 rc = 0;
1193out: 1220out:
1194 if (rc) 1221 if (rc)
@@ -1227,27 +1254,26 @@ static int security_context_to_sid_core(const char *scontext, u32 scontext_len,
1227 1254
1228 if (force) { 1255 if (force) {
1229 /* Save another copy for storing in uninterpreted form */ 1256 /* Save another copy for storing in uninterpreted form */
1257 rc = -ENOMEM;
1230 str = kstrdup(scontext2, gfp_flags); 1258 str = kstrdup(scontext2, gfp_flags);
1231 if (!str) { 1259 if (!str)
1232 kfree(scontext2); 1260 goto out;
1233 return -ENOMEM;
1234 }
1235 } 1261 }
1236 1262
1237 read_lock(&policy_rwlock); 1263 read_lock(&policy_rwlock);
1238 rc = string_to_context_struct(&policydb, &sidtab, 1264 rc = string_to_context_struct(&policydb, &sidtab, scontext2,
1239 scontext2, scontext_len, 1265 scontext_len, &context, def_sid);
1240 &context, def_sid);
1241 if (rc == -EINVAL && force) { 1266 if (rc == -EINVAL && force) {
1242 context.str = str; 1267 context.str = str;
1243 context.len = scontext_len; 1268 context.len = scontext_len;
1244 str = NULL; 1269 str = NULL;
1245 } else if (rc) 1270 } else if (rc)
1246 goto out; 1271 goto out_unlock;
1247 rc = sidtab_context_to_sid(&sidtab, &context, sid); 1272 rc = sidtab_context_to_sid(&sidtab, &context, sid);
1248 context_destroy(&context); 1273 context_destroy(&context);
1249out: 1274out_unlock:
1250 read_unlock(&policy_rwlock); 1275 read_unlock(&policy_rwlock);
1276out:
1251 kfree(scontext2); 1277 kfree(scontext2);
1252 kfree(str); 1278 kfree(str);
1253 return rc; 1279 return rc;
@@ -1311,18 +1337,18 @@ static int compute_sid_handle_invalid_context(
1311 char *s = NULL, *t = NULL, *n = NULL; 1337 char *s = NULL, *t = NULL, *n = NULL;
1312 u32 slen, tlen, nlen; 1338 u32 slen, tlen, nlen;
1313 1339
1314 if (context_struct_to_string(scontext, &s, &slen) < 0) 1340 if (context_struct_to_string(scontext, &s, &slen))
1315 goto out; 1341 goto out;
1316 if (context_struct_to_string(tcontext, &t, &tlen) < 0) 1342 if (context_struct_to_string(tcontext, &t, &tlen))
1317 goto out; 1343 goto out;
1318 if (context_struct_to_string(newcontext, &n, &nlen) < 0) 1344 if (context_struct_to_string(newcontext, &n, &nlen))
1319 goto out; 1345 goto out;
1320 audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR, 1346 audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
1321 "security_compute_sid: invalid context %s" 1347 "security_compute_sid: invalid context %s"
1322 " for scontext=%s" 1348 " for scontext=%s"
1323 " tcontext=%s" 1349 " tcontext=%s"
1324 " tclass=%s", 1350 " tclass=%s",
1325 n, s, t, policydb.p_class_val_to_name[tclass-1]); 1351 n, s, t, sym_name(&policydb, SYM_CLASSES, tclass-1));
1326out: 1352out:
1327 kfree(s); 1353 kfree(s);
1328 kfree(t); 1354 kfree(t);
@@ -1332,10 +1358,36 @@ out:
1332 return -EACCES; 1358 return -EACCES;
1333} 1359}
1334 1360
1361static void filename_compute_type(struct policydb *p, struct context *newcontext,
1362 u32 stype, u32 ttype, u16 tclass,
1363 const char *objname)
1364{
1365 struct filename_trans ft;
1366 struct filename_trans_datum *otype;
1367
1368 /*
1369 * Most filename trans rules are going to live in specific directories
1370 * like /dev or /var/run. This bitmap will quickly skip rule searches
1371 * if the ttype does not contain any rules.
1372 */
1373 if (!ebitmap_get_bit(&p->filename_trans_ttypes, ttype))
1374 return;
1375
1376 ft.stype = stype;
1377 ft.ttype = ttype;
1378 ft.tclass = tclass;
1379 ft.name = objname;
1380
1381 otype = hashtab_search(p->filename_trans, &ft);
1382 if (otype)
1383 newcontext->type = otype->otype;
1384}
1385
1335static int security_compute_sid(u32 ssid, 1386static int security_compute_sid(u32 ssid,
1336 u32 tsid, 1387 u32 tsid,
1337 u16 orig_tclass, 1388 u16 orig_tclass,
1338 u32 specified, 1389 u32 specified,
1390 const char *objname,
1339 u32 *out_sid, 1391 u32 *out_sid,
1340 bool kern) 1392 bool kern)
1341{ 1393{
@@ -1346,6 +1398,7 @@ static int security_compute_sid(u32 ssid,
1346 struct avtab_node *node; 1398 struct avtab_node *node;
1347 u16 tclass; 1399 u16 tclass;
1348 int rc = 0; 1400 int rc = 0;
1401 bool sock;
1349 1402
1350 if (!ss_initialized) { 1403 if (!ss_initialized) {
1351 switch (orig_tclass) { 1404 switch (orig_tclass) {
@@ -1363,10 +1416,13 @@ static int security_compute_sid(u32 ssid,
1363 1416
1364 read_lock(&policy_rwlock); 1417 read_lock(&policy_rwlock);
1365 1418
1366 if (kern) 1419 if (kern) {
1367 tclass = unmap_class(orig_tclass); 1420 tclass = unmap_class(orig_tclass);
1368 else 1421 sock = security_is_socket_class(orig_tclass);
1422 } else {
1369 tclass = orig_tclass; 1423 tclass = orig_tclass;
1424 sock = security_is_socket_class(map_class(tclass));
1425 }
1370 1426
1371 scontext = sidtab_search(&sidtab, ssid); 1427 scontext = sidtab_search(&sidtab, ssid);
1372 if (!scontext) { 1428 if (!scontext) {
@@ -1397,7 +1453,7 @@ static int security_compute_sid(u32 ssid,
1397 } 1453 }
1398 1454
1399 /* Set the role and type to default values. */ 1455 /* Set the role and type to default values. */
1400 if (tclass == policydb.process_class) { 1456 if ((tclass == policydb.process_class) || (sock == true)) {
1401 /* Use the current role and type of process. */ 1457 /* Use the current role and type of process. */
1402 newcontext.role = scontext->role; 1458 newcontext.role = scontext->role;
1403 newcontext.type = scontext->type; 1459 newcontext.type = scontext->type;
@@ -1431,25 +1487,29 @@ static int security_compute_sid(u32 ssid,
1431 newcontext.type = avdatum->data; 1487 newcontext.type = avdatum->data;
1432 } 1488 }
1433 1489
1490 /* if we have a objname this is a file trans check so check those rules */
1491 if (objname)
1492 filename_compute_type(&policydb, &newcontext, scontext->type,
1493 tcontext->type, tclass, objname);
1494
1434 /* Check for class-specific changes. */ 1495 /* Check for class-specific changes. */
1435 if (tclass == policydb.process_class) { 1496 if (specified & AVTAB_TRANSITION) {
1436 if (specified & AVTAB_TRANSITION) { 1497 /* Look for a role transition rule. */
1437 /* Look for a role transition rule. */ 1498 for (roletr = policydb.role_tr; roletr; roletr = roletr->next) {
1438 for (roletr = policydb.role_tr; roletr; 1499 if ((roletr->role == scontext->role) &&
1439 roletr = roletr->next) { 1500 (roletr->type == tcontext->type) &&
1440 if (roletr->role == scontext->role && 1501 (roletr->tclass == tclass)) {
1441 roletr->type == tcontext->type) { 1502 /* Use the role transition rule. */
1442 /* Use the role transition rule. */ 1503 newcontext.role = roletr->new_role;
1443 newcontext.role = roletr->new_role; 1504 break;
1444 break;
1445 }
1446 } 1505 }
1447 } 1506 }
1448 } 1507 }
1449 1508
1450 /* Set the MLS attributes. 1509 /* Set the MLS attributes.
1451 This is done last because it may allocate memory. */ 1510 This is done last because it may allocate memory. */
1452 rc = mls_compute_sid(scontext, tcontext, tclass, specified, &newcontext); 1511 rc = mls_compute_sid(scontext, tcontext, tclass, specified,
1512 &newcontext, sock);
1453 if (rc) 1513 if (rc)
1454 goto out_unlock; 1514 goto out_unlock;
1455 1515
@@ -1484,22 +1544,18 @@ out:
1484 * if insufficient memory is available, or %0 if the new SID was 1544 * if insufficient memory is available, or %0 if the new SID was
1485 * computed successfully. 1545 * computed successfully.
1486 */ 1546 */
1487int security_transition_sid(u32 ssid, 1547int security_transition_sid(u32 ssid, u32 tsid, u16 tclass,
1488 u32 tsid, 1548 const struct qstr *qstr, u32 *out_sid)
1489 u16 tclass,
1490 u32 *out_sid)
1491{ 1549{
1492 return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION, 1550 return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION,
1493 out_sid, true); 1551 qstr ? qstr->name : NULL, out_sid, true);
1494} 1552}
1495 1553
1496int security_transition_sid_user(u32 ssid, 1554int security_transition_sid_user(u32 ssid, u32 tsid, u16 tclass,
1497 u32 tsid, 1555 const char *objname, u32 *out_sid)
1498 u16 tclass,
1499 u32 *out_sid)
1500{ 1556{
1501 return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION, 1557 return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION,
1502 out_sid, false); 1558 objname, out_sid, false);
1503} 1559}
1504 1560
1505/** 1561/**
@@ -1520,8 +1576,8 @@ int security_member_sid(u32 ssid,
1520 u16 tclass, 1576 u16 tclass,
1521 u32 *out_sid) 1577 u32 *out_sid)
1522{ 1578{
1523 return security_compute_sid(ssid, tsid, tclass, AVTAB_MEMBER, out_sid, 1579 return security_compute_sid(ssid, tsid, tclass, AVTAB_MEMBER, NULL,
1524 false); 1580 out_sid, false);
1525} 1581}
1526 1582
1527/** 1583/**
@@ -1542,8 +1598,8 @@ int security_change_sid(u32 ssid,
1542 u16 tclass, 1598 u16 tclass,
1543 u32 *out_sid) 1599 u32 *out_sid)
1544{ 1600{
1545 return security_compute_sid(ssid, tsid, tclass, AVTAB_CHANGE, out_sid, 1601 return security_compute_sid(ssid, tsid, tclass, AVTAB_CHANGE, NULL,
1546 false); 1602 out_sid, false);
1547} 1603}
1548 1604
1549/* Clone the SID into the new SID table. */ 1605/* Clone the SID into the new SID table. */
@@ -1561,22 +1617,17 @@ static int clone_sid(u32 sid,
1561 1617
1562static inline int convert_context_handle_invalid_context(struct context *context) 1618static inline int convert_context_handle_invalid_context(struct context *context)
1563{ 1619{
1564 int rc = 0; 1620 char *s;
1621 u32 len;
1565 1622
1566 if (selinux_enforcing) { 1623 if (selinux_enforcing)
1567 rc = -EINVAL; 1624 return -EINVAL;
1568 } else { 1625
1569 char *s; 1626 if (!context_struct_to_string(context, &s, &len)) {
1570 u32 len; 1627 printk(KERN_WARNING "SELinux: Context %s would be invalid if enforcing\n", s);
1571 1628 kfree(s);
1572 if (!context_struct_to_string(context, &s, &len)) {
1573 printk(KERN_WARNING
1574 "SELinux: Context %s would be invalid if enforcing\n",
1575 s);
1576 kfree(s);
1577 }
1578 } 1629 }
1579 return rc; 1630 return 0;
1580} 1631}
1581 1632
1582struct convert_context_args { 1633struct convert_context_args {
@@ -1613,17 +1664,17 @@ static int convert_context(u32 key,
1613 1664
1614 if (c->str) { 1665 if (c->str) {
1615 struct context ctx; 1666 struct context ctx;
1667
1668 rc = -ENOMEM;
1616 s = kstrdup(c->str, GFP_KERNEL); 1669 s = kstrdup(c->str, GFP_KERNEL);
1617 if (!s) { 1670 if (!s)
1618 rc = -ENOMEM;
1619 goto out; 1671 goto out;
1620 } 1672
1621 rc = string_to_context_struct(args->newp, NULL, s, 1673 rc = string_to_context_struct(args->newp, NULL, s,
1622 c->len, &ctx, SECSID_NULL); 1674 c->len, &ctx, SECSID_NULL);
1623 kfree(s); 1675 kfree(s);
1624 if (!rc) { 1676 if (!rc) {
1625 printk(KERN_INFO 1677 printk(KERN_INFO "SELinux: Context %s became valid (mapped).\n",
1626 "SELinux: Context %s became valid (mapped).\n",
1627 c->str); 1678 c->str);
1628 /* Replace string with mapped representation. */ 1679 /* Replace string with mapped representation. */
1629 kfree(c->str); 1680 kfree(c->str);
@@ -1635,8 +1686,7 @@ static int convert_context(u32 key,
1635 goto out; 1686 goto out;
1636 } else { 1687 } else {
1637 /* Other error condition, e.g. ENOMEM. */ 1688 /* Other error condition, e.g. ENOMEM. */
1638 printk(KERN_ERR 1689 printk(KERN_ERR "SELinux: Unable to map context %s, rc = %d.\n",
1639 "SELinux: Unable to map context %s, rc = %d.\n",
1640 c->str, -rc); 1690 c->str, -rc);
1641 goto out; 1691 goto out;
1642 } 1692 }
@@ -1646,25 +1696,26 @@ static int convert_context(u32 key,
1646 if (rc) 1696 if (rc)
1647 goto out; 1697 goto out;
1648 1698
1649 rc = -EINVAL;
1650
1651 /* Convert the user. */ 1699 /* Convert the user. */
1700 rc = -EINVAL;
1652 usrdatum = hashtab_search(args->newp->p_users.table, 1701 usrdatum = hashtab_search(args->newp->p_users.table,
1653 args->oldp->p_user_val_to_name[c->user - 1]); 1702 sym_name(args->oldp, SYM_USERS, c->user - 1));
1654 if (!usrdatum) 1703 if (!usrdatum)
1655 goto bad; 1704 goto bad;
1656 c->user = usrdatum->value; 1705 c->user = usrdatum->value;
1657 1706
1658 /* Convert the role. */ 1707 /* Convert the role. */
1708 rc = -EINVAL;
1659 role = hashtab_search(args->newp->p_roles.table, 1709 role = hashtab_search(args->newp->p_roles.table,
1660 args->oldp->p_role_val_to_name[c->role - 1]); 1710 sym_name(args->oldp, SYM_ROLES, c->role - 1));
1661 if (!role) 1711 if (!role)
1662 goto bad; 1712 goto bad;
1663 c->role = role->value; 1713 c->role = role->value;
1664 1714
1665 /* Convert the type. */ 1715 /* Convert the type. */
1716 rc = -EINVAL;
1666 typdatum = hashtab_search(args->newp->p_types.table, 1717 typdatum = hashtab_search(args->newp->p_types.table,
1667 args->oldp->p_type_val_to_name[c->type - 1]); 1718 sym_name(args->oldp, SYM_TYPES, c->type - 1));
1668 if (!typdatum) 1719 if (!typdatum)
1669 goto bad; 1720 goto bad;
1670 c->type = typdatum->value; 1721 c->type = typdatum->value;
@@ -1692,6 +1743,7 @@ static int convert_context(u32 key,
1692 oc = args->newp->ocontexts[OCON_ISID]; 1743 oc = args->newp->ocontexts[OCON_ISID];
1693 while (oc && oc->sid[0] != SECINITSID_UNLABELED) 1744 while (oc && oc->sid[0] != SECINITSID_UNLABELED)
1694 oc = oc->next; 1745 oc = oc->next;
1746 rc = -EINVAL;
1695 if (!oc) { 1747 if (!oc) {
1696 printk(KERN_ERR "SELinux: unable to look up" 1748 printk(KERN_ERR "SELinux: unable to look up"
1697 " the initial SIDs list\n"); 1749 " the initial SIDs list\n");
@@ -1711,19 +1763,20 @@ static int convert_context(u32 key,
1711 } 1763 }
1712 1764
1713 context_destroy(&oldc); 1765 context_destroy(&oldc);
1766
1714 rc = 0; 1767 rc = 0;
1715out: 1768out:
1716 return rc; 1769 return rc;
1717bad: 1770bad:
1718 /* Map old representation to string and save it. */ 1771 /* Map old representation to string and save it. */
1719 if (context_struct_to_string(&oldc, &s, &len)) 1772 rc = context_struct_to_string(&oldc, &s, &len);
1720 return -ENOMEM; 1773 if (rc)
1774 return rc;
1721 context_destroy(&oldc); 1775 context_destroy(&oldc);
1722 context_destroy(c); 1776 context_destroy(c);
1723 c->str = s; 1777 c->str = s;
1724 c->len = len; 1778 c->len = len;
1725 printk(KERN_INFO 1779 printk(KERN_INFO "SELinux: Context %s became invalid (unmapped).\n",
1726 "SELinux: Context %s became invalid (unmapped).\n",
1727 c->str); 1780 c->str);
1728 rc = 0; 1781 rc = 0;
1729 goto out; 1782 goto out;
@@ -1769,6 +1822,7 @@ int security_load_policy(void *data, size_t len)
1769 return rc; 1822 return rc;
1770 } 1823 }
1771 1824
1825 policydb.len = len;
1772 rc = selinux_set_mapping(&policydb, secclass_map, 1826 rc = selinux_set_mapping(&policydb, secclass_map,
1773 &current_mapping, 1827 &current_mapping,
1774 &current_mapping_size); 1828 &current_mapping_size);
@@ -1791,6 +1845,7 @@ int security_load_policy(void *data, size_t len)
1791 selinux_complete_init(); 1845 selinux_complete_init();
1792 avc_ss_reset(seqno); 1846 avc_ss_reset(seqno);
1793 selnl_notify_policyload(seqno); 1847 selnl_notify_policyload(seqno);
1848 selinux_status_update_policyload(seqno);
1794 selinux_netlbl_cache_invalidate(); 1849 selinux_netlbl_cache_invalidate();
1795 selinux_xfrm_notify_policyload(); 1850 selinux_xfrm_notify_policyload();
1796 return 0; 1851 return 0;
@@ -1804,6 +1859,7 @@ int security_load_policy(void *data, size_t len)
1804 if (rc) 1859 if (rc)
1805 return rc; 1860 return rc;
1806 1861
1862 newpolicydb.len = len;
1807 /* If switching between different policy types, log MLS status */ 1863 /* If switching between different policy types, log MLS status */
1808 if (policydb.mls_enabled && !newpolicydb.mls_enabled) 1864 if (policydb.mls_enabled && !newpolicydb.mls_enabled)
1809 printk(KERN_INFO "SELinux: Disabling MLS support...\n"); 1865 printk(KERN_INFO "SELinux: Disabling MLS support...\n");
@@ -1870,6 +1926,7 @@ int security_load_policy(void *data, size_t len)
1870 1926
1871 avc_ss_reset(seqno); 1927 avc_ss_reset(seqno);
1872 selnl_notify_policyload(seqno); 1928 selnl_notify_policyload(seqno);
1929 selinux_status_update_policyload(seqno);
1873 selinux_netlbl_cache_invalidate(); 1930 selinux_netlbl_cache_invalidate();
1874 selinux_xfrm_notify_policyload(); 1931 selinux_xfrm_notify_policyload();
1875 1932
@@ -1883,6 +1940,17 @@ err:
1883 1940
1884} 1941}
1885 1942
1943size_t security_policydb_len(void)
1944{
1945 size_t len;
1946
1947 read_lock(&policy_rwlock);
1948 len = policydb.len;
1949 read_unlock(&policy_rwlock);
1950
1951 return len;
1952}
1953
1886/** 1954/**
1887 * security_port_sid - Obtain the SID for a port. 1955 * security_port_sid - Obtain the SID for a port.
1888 * @protocol: protocol number 1956 * @protocol: protocol number
@@ -1989,7 +2057,7 @@ int security_node_sid(u16 domain,
1989 u32 addrlen, 2057 u32 addrlen,
1990 u32 *out_sid) 2058 u32 *out_sid)
1991{ 2059{
1992 int rc = 0; 2060 int rc;
1993 struct ocontext *c; 2061 struct ocontext *c;
1994 2062
1995 read_lock(&policy_rwlock); 2063 read_lock(&policy_rwlock);
@@ -1998,10 +2066,9 @@ int security_node_sid(u16 domain,
1998 case AF_INET: { 2066 case AF_INET: {
1999 u32 addr; 2067 u32 addr;
2000 2068
2001 if (addrlen != sizeof(u32)) { 2069 rc = -EINVAL;
2002 rc = -EINVAL; 2070 if (addrlen != sizeof(u32))
2003 goto out; 2071 goto out;
2004 }
2005 2072
2006 addr = *((u32 *)addrp); 2073 addr = *((u32 *)addrp);
2007 2074
@@ -2015,10 +2082,9 @@ int security_node_sid(u16 domain,
2015 } 2082 }
2016 2083
2017 case AF_INET6: 2084 case AF_INET6:
2018 if (addrlen != sizeof(u64) * 2) { 2085 rc = -EINVAL;
2019 rc = -EINVAL; 2086 if (addrlen != sizeof(u64) * 2)
2020 goto out; 2087 goto out;
2021 }
2022 c = policydb.ocontexts[OCON_NODE6]; 2088 c = policydb.ocontexts[OCON_NODE6];
2023 while (c) { 2089 while (c) {
2024 if (match_ipv6_addrmask(addrp, c->u.node6.addr, 2090 if (match_ipv6_addrmask(addrp, c->u.node6.addr,
@@ -2029,6 +2095,7 @@ int security_node_sid(u16 domain,
2029 break; 2095 break;
2030 2096
2031 default: 2097 default:
2098 rc = 0;
2032 *out_sid = SECINITSID_NODE; 2099 *out_sid = SECINITSID_NODE;
2033 goto out; 2100 goto out;
2034 } 2101 }
@@ -2046,6 +2113,7 @@ int security_node_sid(u16 domain,
2046 *out_sid = SECINITSID_NODE; 2113 *out_sid = SECINITSID_NODE;
2047 } 2114 }
2048 2115
2116 rc = 0;
2049out: 2117out:
2050 read_unlock(&policy_rwlock); 2118 read_unlock(&policy_rwlock);
2051 return rc; 2119 return rc;
@@ -2090,24 +2158,22 @@ int security_get_user_sids(u32 fromsid,
2090 2158
2091 context_init(&usercon); 2159 context_init(&usercon);
2092 2160
2161 rc = -EINVAL;
2093 fromcon = sidtab_search(&sidtab, fromsid); 2162 fromcon = sidtab_search(&sidtab, fromsid);
2094 if (!fromcon) { 2163 if (!fromcon)
2095 rc = -EINVAL;
2096 goto out_unlock; 2164 goto out_unlock;
2097 }
2098 2165
2166 rc = -EINVAL;
2099 user = hashtab_search(policydb.p_users.table, username); 2167 user = hashtab_search(policydb.p_users.table, username);
2100 if (!user) { 2168 if (!user)
2101 rc = -EINVAL;
2102 goto out_unlock; 2169 goto out_unlock;
2103 } 2170
2104 usercon.user = user->value; 2171 usercon.user = user->value;
2105 2172
2173 rc = -ENOMEM;
2106 mysids = kcalloc(maxnel, sizeof(*mysids), GFP_ATOMIC); 2174 mysids = kcalloc(maxnel, sizeof(*mysids), GFP_ATOMIC);
2107 if (!mysids) { 2175 if (!mysids)
2108 rc = -ENOMEM;
2109 goto out_unlock; 2176 goto out_unlock;
2110 }
2111 2177
2112 ebitmap_for_each_positive_bit(&user->roles, rnode, i) { 2178 ebitmap_for_each_positive_bit(&user->roles, rnode, i) {
2113 role = policydb.role_val_to_struct[i]; 2179 role = policydb.role_val_to_struct[i];
@@ -2124,12 +2190,11 @@ int security_get_user_sids(u32 fromsid,
2124 if (mynel < maxnel) { 2190 if (mynel < maxnel) {
2125 mysids[mynel++] = sid; 2191 mysids[mynel++] = sid;
2126 } else { 2192 } else {
2193 rc = -ENOMEM;
2127 maxnel += SIDS_NEL; 2194 maxnel += SIDS_NEL;
2128 mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC); 2195 mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);
2129 if (!mysids2) { 2196 if (!mysids2)
2130 rc = -ENOMEM;
2131 goto out_unlock; 2197 goto out_unlock;
2132 }
2133 memcpy(mysids2, mysids, mynel * sizeof(*mysids2)); 2198 memcpy(mysids2, mysids, mynel * sizeof(*mysids2));
2134 kfree(mysids); 2199 kfree(mysids);
2135 mysids = mysids2; 2200 mysids = mysids2;
@@ -2137,7 +2202,7 @@ int security_get_user_sids(u32 fromsid,
2137 } 2202 }
2138 } 2203 }
2139 } 2204 }
2140 2205 rc = 0;
2141out_unlock: 2206out_unlock:
2142 read_unlock(&policy_rwlock); 2207 read_unlock(&policy_rwlock);
2143 if (rc || !mynel) { 2208 if (rc || !mynel) {
@@ -2145,17 +2210,18 @@ out_unlock:
2145 goto out; 2210 goto out;
2146 } 2211 }
2147 2212
2213 rc = -ENOMEM;
2148 mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL); 2214 mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL);
2149 if (!mysids2) { 2215 if (!mysids2) {
2150 rc = -ENOMEM;
2151 kfree(mysids); 2216 kfree(mysids);
2152 goto out; 2217 goto out;
2153 } 2218 }
2154 for (i = 0, j = 0; i < mynel; i++) { 2219 for (i = 0, j = 0; i < mynel; i++) {
2220 struct av_decision dummy_avd;
2155 rc = avc_has_perm_noaudit(fromsid, mysids[i], 2221 rc = avc_has_perm_noaudit(fromsid, mysids[i],
2156 SECCLASS_PROCESS, /* kernel value */ 2222 SECCLASS_PROCESS, /* kernel value */
2157 PROCESS__TRANSITION, AVC_STRICT, 2223 PROCESS__TRANSITION, AVC_STRICT,
2158 NULL); 2224 &dummy_avd);
2159 if (!rc) 2225 if (!rc)
2160 mysids2[j++] = mysids[i]; 2226 mysids2[j++] = mysids[i];
2161 cond_resched(); 2227 cond_resched();
@@ -2188,7 +2254,7 @@ int security_genfs_sid(const char *fstype,
2188 u16 sclass; 2254 u16 sclass;
2189 struct genfs *genfs; 2255 struct genfs *genfs;
2190 struct ocontext *c; 2256 struct ocontext *c;
2191 int rc = 0, cmp = 0; 2257 int rc, cmp = 0;
2192 2258
2193 while (path[0] == '/' && path[1] == '/') 2259 while (path[0] == '/' && path[1] == '/')
2194 path++; 2260 path++;
@@ -2196,6 +2262,7 @@ int security_genfs_sid(const char *fstype,
2196 read_lock(&policy_rwlock); 2262 read_lock(&policy_rwlock);
2197 2263
2198 sclass = unmap_class(orig_sclass); 2264 sclass = unmap_class(orig_sclass);
2265 *sid = SECINITSID_UNLABELED;
2199 2266
2200 for (genfs = policydb.genfs; genfs; genfs = genfs->next) { 2267 for (genfs = policydb.genfs; genfs; genfs = genfs->next) {
2201 cmp = strcmp(fstype, genfs->fstype); 2268 cmp = strcmp(fstype, genfs->fstype);
@@ -2203,11 +2270,9 @@ int security_genfs_sid(const char *fstype,
2203 break; 2270 break;
2204 } 2271 }
2205 2272
2206 if (!genfs || cmp) { 2273 rc = -ENOENT;
2207 *sid = SECINITSID_UNLABELED; 2274 if (!genfs || cmp)
2208 rc = -ENOENT;
2209 goto out; 2275 goto out;
2210 }
2211 2276
2212 for (c = genfs->head; c; c = c->next) { 2277 for (c = genfs->head; c; c = c->next) {
2213 len = strlen(c->u.name); 2278 len = strlen(c->u.name);
@@ -2216,21 +2281,18 @@ int security_genfs_sid(const char *fstype,
2216 break; 2281 break;
2217 } 2282 }
2218 2283
2219 if (!c) { 2284 rc = -ENOENT;
2220 *sid = SECINITSID_UNLABELED; 2285 if (!c)
2221 rc = -ENOENT;
2222 goto out; 2286 goto out;
2223 }
2224 2287
2225 if (!c->sid[0]) { 2288 if (!c->sid[0]) {
2226 rc = sidtab_context_to_sid(&sidtab, 2289 rc = sidtab_context_to_sid(&sidtab, &c->context[0], &c->sid[0]);
2227 &c->context[0],
2228 &c->sid[0]);
2229 if (rc) 2290 if (rc)
2230 goto out; 2291 goto out;
2231 } 2292 }
2232 2293
2233 *sid = c->sid[0]; 2294 *sid = c->sid[0];
2295 rc = 0;
2234out: 2296out:
2235 read_unlock(&policy_rwlock); 2297 read_unlock(&policy_rwlock);
2236 return rc; 2298 return rc;
@@ -2262,8 +2324,7 @@ int security_fs_use(
2262 if (c) { 2324 if (c) {
2263 *behavior = c->v.behavior; 2325 *behavior = c->v.behavior;
2264 if (!c->sid[0]) { 2326 if (!c->sid[0]) {
2265 rc = sidtab_context_to_sid(&sidtab, 2327 rc = sidtab_context_to_sid(&sidtab, &c->context[0],
2266 &c->context[0],
2267 &c->sid[0]); 2328 &c->sid[0]);
2268 if (rc) 2329 if (rc)
2269 goto out; 2330 goto out;
@@ -2286,34 +2347,39 @@ out:
2286 2347
2287int security_get_bools(int *len, char ***names, int **values) 2348int security_get_bools(int *len, char ***names, int **values)
2288{ 2349{
2289 int i, rc = -ENOMEM; 2350 int i, rc;
2290 2351
2291 read_lock(&policy_rwlock); 2352 read_lock(&policy_rwlock);
2292 *names = NULL; 2353 *names = NULL;
2293 *values = NULL; 2354 *values = NULL;
2294 2355
2356 rc = 0;
2295 *len = policydb.p_bools.nprim; 2357 *len = policydb.p_bools.nprim;
2296 if (!*len) { 2358 if (!*len)
2297 rc = 0;
2298 goto out; 2359 goto out;
2299 }
2300 2360
2301 *names = kcalloc(*len, sizeof(char *), GFP_ATOMIC); 2361 rc = -ENOMEM;
2362 *names = kcalloc(*len, sizeof(char *), GFP_ATOMIC);
2302 if (!*names) 2363 if (!*names)
2303 goto err; 2364 goto err;
2304 2365
2305 *values = kcalloc(*len, sizeof(int), GFP_ATOMIC); 2366 rc = -ENOMEM;
2367 *values = kcalloc(*len, sizeof(int), GFP_ATOMIC);
2306 if (!*values) 2368 if (!*values)
2307 goto err; 2369 goto err;
2308 2370
2309 for (i = 0; i < *len; i++) { 2371 for (i = 0; i < *len; i++) {
2310 size_t name_len; 2372 size_t name_len;
2373
2311 (*values)[i] = policydb.bool_val_to_struct[i]->state; 2374 (*values)[i] = policydb.bool_val_to_struct[i]->state;
2312 name_len = strlen(policydb.p_bool_val_to_name[i]) + 1; 2375 name_len = strlen(sym_name(&policydb, SYM_BOOLS, i)) + 1;
2313 (*names)[i] = kmalloc(sizeof(char) * name_len, GFP_ATOMIC); 2376
2377 rc = -ENOMEM;
2378 (*names)[i] = kmalloc(sizeof(char) * name_len, GFP_ATOMIC);
2314 if (!(*names)[i]) 2379 if (!(*names)[i])
2315 goto err; 2380 goto err;
2316 strncpy((*names)[i], policydb.p_bool_val_to_name[i], name_len); 2381
2382 strncpy((*names)[i], sym_name(&policydb, SYM_BOOLS, i), name_len);
2317 (*names)[i][name_len - 1] = 0; 2383 (*names)[i][name_len - 1] = 0;
2318 } 2384 }
2319 rc = 0; 2385 rc = 0;
@@ -2332,24 +2398,23 @@ err:
2332 2398
2333int security_set_bools(int len, int *values) 2399int security_set_bools(int len, int *values)
2334{ 2400{
2335 int i, rc = 0; 2401 int i, rc;
2336 int lenp, seqno = 0; 2402 int lenp, seqno = 0;
2337 struct cond_node *cur; 2403 struct cond_node *cur;
2338 2404
2339 write_lock_irq(&policy_rwlock); 2405 write_lock_irq(&policy_rwlock);
2340 2406
2407 rc = -EFAULT;
2341 lenp = policydb.p_bools.nprim; 2408 lenp = policydb.p_bools.nprim;
2342 if (len != lenp) { 2409 if (len != lenp)
2343 rc = -EFAULT;
2344 goto out; 2410 goto out;
2345 }
2346 2411
2347 for (i = 0; i < len; i++) { 2412 for (i = 0; i < len; i++) {
2348 if (!!values[i] != policydb.bool_val_to_struct[i]->state) { 2413 if (!!values[i] != policydb.bool_val_to_struct[i]->state) {
2349 audit_log(current->audit_context, GFP_ATOMIC, 2414 audit_log(current->audit_context, GFP_ATOMIC,
2350 AUDIT_MAC_CONFIG_CHANGE, 2415 AUDIT_MAC_CONFIG_CHANGE,
2351 "bool=%s val=%d old_val=%d auid=%u ses=%u", 2416 "bool=%s val=%d old_val=%d auid=%u ses=%u",
2352 policydb.p_bool_val_to_name[i], 2417 sym_name(&policydb, SYM_BOOLS, i),
2353 !!values[i], 2418 !!values[i],
2354 policydb.bool_val_to_struct[i]->state, 2419 policydb.bool_val_to_struct[i]->state,
2355 audit_get_loginuid(current), 2420 audit_get_loginuid(current),
@@ -2368,12 +2433,13 @@ int security_set_bools(int len, int *values)
2368 } 2433 }
2369 2434
2370 seqno = ++latest_granting; 2435 seqno = ++latest_granting;
2371 2436 rc = 0;
2372out: 2437out:
2373 write_unlock_irq(&policy_rwlock); 2438 write_unlock_irq(&policy_rwlock);
2374 if (!rc) { 2439 if (!rc) {
2375 avc_ss_reset(seqno); 2440 avc_ss_reset(seqno);
2376 selnl_notify_policyload(seqno); 2441 selnl_notify_policyload(seqno);
2442 selinux_status_update_policyload(seqno);
2377 selinux_xfrm_notify_policyload(); 2443 selinux_xfrm_notify_policyload();
2378 } 2444 }
2379 return rc; 2445 return rc;
@@ -2381,16 +2447,15 @@ out:
2381 2447
2382int security_get_bool_value(int bool) 2448int security_get_bool_value(int bool)
2383{ 2449{
2384 int rc = 0; 2450 int rc;
2385 int len; 2451 int len;
2386 2452
2387 read_lock(&policy_rwlock); 2453 read_lock(&policy_rwlock);
2388 2454
2455 rc = -EFAULT;
2389 len = policydb.p_bools.nprim; 2456 len = policydb.p_bools.nprim;
2390 if (bool >= len) { 2457 if (bool >= len)
2391 rc = -EFAULT;
2392 goto out; 2458 goto out;
2393 }
2394 2459
2395 rc = policydb.bool_val_to_struct[bool]->state; 2460 rc = policydb.bool_val_to_struct[bool]->state;
2396out: 2461out:
@@ -2440,8 +2505,9 @@ int security_sid_mls_copy(u32 sid, u32 mls_sid, u32 *new_sid)
2440 struct context newcon; 2505 struct context newcon;
2441 char *s; 2506 char *s;
2442 u32 len; 2507 u32 len;
2443 int rc = 0; 2508 int rc;
2444 2509
2510 rc = 0;
2445 if (!ss_initialized || !policydb.mls_enabled) { 2511 if (!ss_initialized || !policydb.mls_enabled) {
2446 *new_sid = sid; 2512 *new_sid = sid;
2447 goto out; 2513 goto out;
@@ -2450,19 +2516,20 @@ int security_sid_mls_copy(u32 sid, u32 mls_sid, u32 *new_sid)
2450 context_init(&newcon); 2516 context_init(&newcon);
2451 2517
2452 read_lock(&policy_rwlock); 2518 read_lock(&policy_rwlock);
2519
2520 rc = -EINVAL;
2453 context1 = sidtab_search(&sidtab, sid); 2521 context1 = sidtab_search(&sidtab, sid);
2454 if (!context1) { 2522 if (!context1) {
2455 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", 2523 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2456 __func__, sid); 2524 __func__, sid);
2457 rc = -EINVAL;
2458 goto out_unlock; 2525 goto out_unlock;
2459 } 2526 }
2460 2527
2528 rc = -EINVAL;
2461 context2 = sidtab_search(&sidtab, mls_sid); 2529 context2 = sidtab_search(&sidtab, mls_sid);
2462 if (!context2) { 2530 if (!context2) {
2463 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", 2531 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2464 __func__, mls_sid); 2532 __func__, mls_sid);
2465 rc = -EINVAL;
2466 goto out_unlock; 2533 goto out_unlock;
2467 } 2534 }
2468 2535
@@ -2476,20 +2543,17 @@ int security_sid_mls_copy(u32 sid, u32 mls_sid, u32 *new_sid)
2476 /* Check the validity of the new context. */ 2543 /* Check the validity of the new context. */
2477 if (!policydb_context_isvalid(&policydb, &newcon)) { 2544 if (!policydb_context_isvalid(&policydb, &newcon)) {
2478 rc = convert_context_handle_invalid_context(&newcon); 2545 rc = convert_context_handle_invalid_context(&newcon);
2479 if (rc) 2546 if (rc) {
2480 goto bad; 2547 if (!context_struct_to_string(&newcon, &s, &len)) {
2548 audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
2549 "security_sid_mls_copy: invalid context %s", s);
2550 kfree(s);
2551 }
2552 goto out_unlock;
2553 }
2481 } 2554 }
2482 2555
2483 rc = sidtab_context_to_sid(&sidtab, &newcon, new_sid); 2556 rc = sidtab_context_to_sid(&sidtab, &newcon, new_sid);
2484 goto out_unlock;
2485
2486bad:
2487 if (!context_struct_to_string(&newcon, &s, &len)) {
2488 audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
2489 "security_sid_mls_copy: invalid context %s", s);
2490 kfree(s);
2491 }
2492
2493out_unlock: 2557out_unlock:
2494 read_unlock(&policy_rwlock); 2558 read_unlock(&policy_rwlock);
2495 context_destroy(&newcon); 2559 context_destroy(&newcon);
@@ -2525,6 +2589,8 @@ int security_net_peersid_resolve(u32 nlbl_sid, u32 nlbl_type,
2525 struct context *nlbl_ctx; 2589 struct context *nlbl_ctx;
2526 struct context *xfrm_ctx; 2590 struct context *xfrm_ctx;
2527 2591
2592 *peer_sid = SECSID_NULL;
2593
2528 /* handle the common (which also happens to be the set of easy) cases 2594 /* handle the common (which also happens to be the set of easy) cases
2529 * right away, these two if statements catch everything involving a 2595 * right away, these two if statements catch everything involving a
2530 * single or absent peer SID/label */ 2596 * single or absent peer SID/label */
@@ -2543,40 +2609,37 @@ int security_net_peersid_resolve(u32 nlbl_sid, u32 nlbl_type,
2543 /* we don't need to check ss_initialized here since the only way both 2609 /* we don't need to check ss_initialized here since the only way both
2544 * nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the 2610 * nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the
2545 * security server was initialized and ss_initialized was true */ 2611 * security server was initialized and ss_initialized was true */
2546 if (!policydb.mls_enabled) { 2612 if (!policydb.mls_enabled)
2547 *peer_sid = SECSID_NULL;
2548 return 0; 2613 return 0;
2549 }
2550 2614
2551 read_lock(&policy_rwlock); 2615 read_lock(&policy_rwlock);
2552 2616
2617 rc = -EINVAL;
2553 nlbl_ctx = sidtab_search(&sidtab, nlbl_sid); 2618 nlbl_ctx = sidtab_search(&sidtab, nlbl_sid);
2554 if (!nlbl_ctx) { 2619 if (!nlbl_ctx) {
2555 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", 2620 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2556 __func__, nlbl_sid); 2621 __func__, nlbl_sid);
2557 rc = -EINVAL; 2622 goto out;
2558 goto out_slowpath;
2559 } 2623 }
2624 rc = -EINVAL;
2560 xfrm_ctx = sidtab_search(&sidtab, xfrm_sid); 2625 xfrm_ctx = sidtab_search(&sidtab, xfrm_sid);
2561 if (!xfrm_ctx) { 2626 if (!xfrm_ctx) {
2562 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n", 2627 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2563 __func__, xfrm_sid); 2628 __func__, xfrm_sid);
2564 rc = -EINVAL; 2629 goto out;
2565 goto out_slowpath;
2566 } 2630 }
2567 rc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES); 2631 rc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES);
2632 if (rc)
2633 goto out;
2568 2634
2569out_slowpath: 2635 /* at present NetLabel SIDs/labels really only carry MLS
2636 * information so if the MLS portion of the NetLabel SID
2637 * matches the MLS portion of the labeled XFRM SID/label
2638 * then pass along the XFRM SID as it is the most
2639 * expressive */
2640 *peer_sid = xfrm_sid;
2641out:
2570 read_unlock(&policy_rwlock); 2642 read_unlock(&policy_rwlock);
2571 if (rc == 0)
2572 /* at present NetLabel SIDs/labels really only carry MLS
2573 * information so if the MLS portion of the NetLabel SID
2574 * matches the MLS portion of the labeled XFRM SID/label
2575 * then pass along the XFRM SID as it is the most
2576 * expressive */
2577 *peer_sid = xfrm_sid;
2578 else
2579 *peer_sid = SECSID_NULL;
2580 return rc; 2643 return rc;
2581} 2644}
2582 2645
@@ -2595,10 +2658,11 @@ static int get_classes_callback(void *k, void *d, void *args)
2595 2658
2596int security_get_classes(char ***classes, int *nclasses) 2659int security_get_classes(char ***classes, int *nclasses)
2597{ 2660{
2598 int rc = -ENOMEM; 2661 int rc;
2599 2662
2600 read_lock(&policy_rwlock); 2663 read_lock(&policy_rwlock);
2601 2664
2665 rc = -ENOMEM;
2602 *nclasses = policydb.p_classes.nprim; 2666 *nclasses = policydb.p_classes.nprim;
2603 *classes = kcalloc(*nclasses, sizeof(**classes), GFP_ATOMIC); 2667 *classes = kcalloc(*nclasses, sizeof(**classes), GFP_ATOMIC);
2604 if (!*classes) 2668 if (!*classes)
@@ -2606,7 +2670,7 @@ int security_get_classes(char ***classes, int *nclasses)
2606 2670
2607 rc = hashtab_map(policydb.p_classes.table, get_classes_callback, 2671 rc = hashtab_map(policydb.p_classes.table, get_classes_callback,
2608 *classes); 2672 *classes);
2609 if (rc < 0) { 2673 if (rc) {
2610 int i; 2674 int i;
2611 for (i = 0; i < *nclasses; i++) 2675 for (i = 0; i < *nclasses; i++)
2612 kfree((*classes)[i]); 2676 kfree((*classes)[i]);
@@ -2633,19 +2697,20 @@ static int get_permissions_callback(void *k, void *d, void *args)
2633 2697
2634int security_get_permissions(char *class, char ***perms, int *nperms) 2698int security_get_permissions(char *class, char ***perms, int *nperms)
2635{ 2699{
2636 int rc = -ENOMEM, i; 2700 int rc, i;
2637 struct class_datum *match; 2701 struct class_datum *match;
2638 2702
2639 read_lock(&policy_rwlock); 2703 read_lock(&policy_rwlock);
2640 2704
2705 rc = -EINVAL;
2641 match = hashtab_search(policydb.p_classes.table, class); 2706 match = hashtab_search(policydb.p_classes.table, class);
2642 if (!match) { 2707 if (!match) {
2643 printk(KERN_ERR "SELinux: %s: unrecognized class %s\n", 2708 printk(KERN_ERR "SELinux: %s: unrecognized class %s\n",
2644 __func__, class); 2709 __func__, class);
2645 rc = -EINVAL;
2646 goto out; 2710 goto out;
2647 } 2711 }
2648 2712
2713 rc = -ENOMEM;
2649 *nperms = match->permissions.nprim; 2714 *nperms = match->permissions.nprim;
2650 *perms = kcalloc(*nperms, sizeof(**perms), GFP_ATOMIC); 2715 *perms = kcalloc(*nperms, sizeof(**perms), GFP_ATOMIC);
2651 if (!*perms) 2716 if (!*perms)
@@ -2654,13 +2719,13 @@ int security_get_permissions(char *class, char ***perms, int *nperms)
2654 if (match->comdatum) { 2719 if (match->comdatum) {
2655 rc = hashtab_map(match->comdatum->permissions.table, 2720 rc = hashtab_map(match->comdatum->permissions.table,
2656 get_permissions_callback, *perms); 2721 get_permissions_callback, *perms);
2657 if (rc < 0) 2722 if (rc)
2658 goto err; 2723 goto err;
2659 } 2724 }
2660 2725
2661 rc = hashtab_map(match->permissions.table, get_permissions_callback, 2726 rc = hashtab_map(match->permissions.table, get_permissions_callback,
2662 *perms); 2727 *perms);
2663 if (rc < 0) 2728 if (rc)
2664 goto err; 2729 goto err;
2665 2730
2666out: 2731out:
@@ -2750,7 +2815,7 @@ int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule)
2750 case AUDIT_SUBJ_CLR: 2815 case AUDIT_SUBJ_CLR:
2751 case AUDIT_OBJ_LEV_LOW: 2816 case AUDIT_OBJ_LEV_LOW:
2752 case AUDIT_OBJ_LEV_HIGH: 2817 case AUDIT_OBJ_LEV_HIGH:
2753 /* we do not allow a range, indicated by the presense of '-' */ 2818 /* we do not allow a range, indicated by the presence of '-' */
2754 if (strchr(rulestr, '-')) 2819 if (strchr(rulestr, '-'))
2755 return -EINVAL; 2820 return -EINVAL;
2756 break; 2821 break;
@@ -2772,36 +2837,39 @@ int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule)
2772 switch (field) { 2837 switch (field) {
2773 case AUDIT_SUBJ_USER: 2838 case AUDIT_SUBJ_USER:
2774 case AUDIT_OBJ_USER: 2839 case AUDIT_OBJ_USER:
2840 rc = -EINVAL;
2775 userdatum = hashtab_search(policydb.p_users.table, rulestr); 2841 userdatum = hashtab_search(policydb.p_users.table, rulestr);
2776 if (!userdatum) 2842 if (!userdatum)
2777 rc = -EINVAL; 2843 goto out;
2778 else 2844 tmprule->au_ctxt.user = userdatum->value;
2779 tmprule->au_ctxt.user = userdatum->value;
2780 break; 2845 break;
2781 case AUDIT_SUBJ_ROLE: 2846 case AUDIT_SUBJ_ROLE:
2782 case AUDIT_OBJ_ROLE: 2847 case AUDIT_OBJ_ROLE:
2848 rc = -EINVAL;
2783 roledatum = hashtab_search(policydb.p_roles.table, rulestr); 2849 roledatum = hashtab_search(policydb.p_roles.table, rulestr);
2784 if (!roledatum) 2850 if (!roledatum)
2785 rc = -EINVAL; 2851 goto out;
2786 else 2852 tmprule->au_ctxt.role = roledatum->value;
2787 tmprule->au_ctxt.role = roledatum->value;
2788 break; 2853 break;
2789 case AUDIT_SUBJ_TYPE: 2854 case AUDIT_SUBJ_TYPE:
2790 case AUDIT_OBJ_TYPE: 2855 case AUDIT_OBJ_TYPE:
2856 rc = -EINVAL;
2791 typedatum = hashtab_search(policydb.p_types.table, rulestr); 2857 typedatum = hashtab_search(policydb.p_types.table, rulestr);
2792 if (!typedatum) 2858 if (!typedatum)
2793 rc = -EINVAL; 2859 goto out;
2794 else 2860 tmprule->au_ctxt.type = typedatum->value;
2795 tmprule->au_ctxt.type = typedatum->value;
2796 break; 2861 break;
2797 case AUDIT_SUBJ_SEN: 2862 case AUDIT_SUBJ_SEN:
2798 case AUDIT_SUBJ_CLR: 2863 case AUDIT_SUBJ_CLR:
2799 case AUDIT_OBJ_LEV_LOW: 2864 case AUDIT_OBJ_LEV_LOW:
2800 case AUDIT_OBJ_LEV_HIGH: 2865 case AUDIT_OBJ_LEV_HIGH:
2801 rc = mls_from_string(rulestr, &tmprule->au_ctxt, GFP_ATOMIC); 2866 rc = mls_from_string(rulestr, &tmprule->au_ctxt, GFP_ATOMIC);
2867 if (rc)
2868 goto out;
2802 break; 2869 break;
2803 } 2870 }
2804 2871 rc = 0;
2872out:
2805 read_unlock(&policy_rwlock); 2873 read_unlock(&policy_rwlock);
2806 2874
2807 if (rc) { 2875 if (rc) {
@@ -3016,7 +3084,7 @@ static void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr,
3016 * Description: 3084 * Description:
3017 * Convert the given NetLabel security attributes in @secattr into a 3085 * Convert the given NetLabel security attributes in @secattr into a
3018 * SELinux SID. If the @secattr field does not contain a full SELinux 3086 * SELinux SID. If the @secattr field does not contain a full SELinux
3019 * SID/context then use SECINITSID_NETMSG as the foundation. If possibile the 3087 * SID/context then use SECINITSID_NETMSG as the foundation. If possible the
3020 * 'cache' field of @secattr is set and the CACHE flag is set; this is to 3088 * 'cache' field of @secattr is set and the CACHE flag is set; this is to
3021 * allow the @secattr to be used by NetLabel to cache the secattr to SID 3089 * allow the @secattr to be used by NetLabel to cache the secattr to SID
3022 * conversion for future lookups. Returns zero on success, negative values on 3090 * conversion for future lookups. Returns zero on success, negative values on
@@ -3026,7 +3094,7 @@ static void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr,
3026int security_netlbl_secattr_to_sid(struct netlbl_lsm_secattr *secattr, 3094int security_netlbl_secattr_to_sid(struct netlbl_lsm_secattr *secattr,
3027 u32 *sid) 3095 u32 *sid)
3028{ 3096{
3029 int rc = -EIDRM; 3097 int rc;
3030 struct context *ctx; 3098 struct context *ctx;
3031 struct context ctx_new; 3099 struct context ctx_new;
3032 3100
@@ -3037,16 +3105,15 @@ int security_netlbl_secattr_to_sid(struct netlbl_lsm_secattr *secattr,
3037 3105
3038 read_lock(&policy_rwlock); 3106 read_lock(&policy_rwlock);
3039 3107
3040 if (secattr->flags & NETLBL_SECATTR_CACHE) { 3108 if (secattr->flags & NETLBL_SECATTR_CACHE)
3041 *sid = *(u32 *)secattr->cache->data; 3109 *sid = *(u32 *)secattr->cache->data;
3042 rc = 0; 3110 else if (secattr->flags & NETLBL_SECATTR_SECID)
3043 } else if (secattr->flags & NETLBL_SECATTR_SECID) {
3044 *sid = secattr->attr.secid; 3111 *sid = secattr->attr.secid;
3045 rc = 0; 3112 else if (secattr->flags & NETLBL_SECATTR_MLS_LVL) {
3046 } else if (secattr->flags & NETLBL_SECATTR_MLS_LVL) { 3113 rc = -EIDRM;
3047 ctx = sidtab_search(&sidtab, SECINITSID_NETMSG); 3114 ctx = sidtab_search(&sidtab, SECINITSID_NETMSG);
3048 if (ctx == NULL) 3115 if (ctx == NULL)
3049 goto netlbl_secattr_to_sid_return; 3116 goto out;
3050 3117
3051 context_init(&ctx_new); 3118 context_init(&ctx_new);
3052 ctx_new.user = ctx->user; 3119 ctx_new.user = ctx->user;
@@ -3054,34 +3121,35 @@ int security_netlbl_secattr_to_sid(struct netlbl_lsm_secattr *secattr,
3054 ctx_new.type = ctx->type; 3121 ctx_new.type = ctx->type;
3055 mls_import_netlbl_lvl(&ctx_new, secattr); 3122 mls_import_netlbl_lvl(&ctx_new, secattr);
3056 if (secattr->flags & NETLBL_SECATTR_MLS_CAT) { 3123 if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
3057 if (ebitmap_netlbl_import(&ctx_new.range.level[0].cat, 3124 rc = ebitmap_netlbl_import(&ctx_new.range.level[0].cat,
3058 secattr->attr.mls.cat) != 0) 3125 secattr->attr.mls.cat);
3059 goto netlbl_secattr_to_sid_return; 3126 if (rc)
3127 goto out;
3060 memcpy(&ctx_new.range.level[1].cat, 3128 memcpy(&ctx_new.range.level[1].cat,
3061 &ctx_new.range.level[0].cat, 3129 &ctx_new.range.level[0].cat,
3062 sizeof(ctx_new.range.level[0].cat)); 3130 sizeof(ctx_new.range.level[0].cat));
3063 } 3131 }
3064 if (mls_context_isvalid(&policydb, &ctx_new) != 1) 3132 rc = -EIDRM;
3065 goto netlbl_secattr_to_sid_return_cleanup; 3133 if (!mls_context_isvalid(&policydb, &ctx_new))
3134 goto out_free;
3066 3135
3067 rc = sidtab_context_to_sid(&sidtab, &ctx_new, sid); 3136 rc = sidtab_context_to_sid(&sidtab, &ctx_new, sid);
3068 if (rc != 0) 3137 if (rc)
3069 goto netlbl_secattr_to_sid_return_cleanup; 3138 goto out_free;
3070 3139
3071 security_netlbl_cache_add(secattr, *sid); 3140 security_netlbl_cache_add(secattr, *sid);
3072 3141
3073 ebitmap_destroy(&ctx_new.range.level[0].cat); 3142 ebitmap_destroy(&ctx_new.range.level[0].cat);
3074 } else { 3143 } else
3075 *sid = SECSID_NULL; 3144 *sid = SECSID_NULL;
3076 rc = 0;
3077 }
3078 3145
3079netlbl_secattr_to_sid_return:
3080 read_unlock(&policy_rwlock); 3146 read_unlock(&policy_rwlock);
3081 return rc; 3147 return 0;
3082netlbl_secattr_to_sid_return_cleanup: 3148out_free:
3083 ebitmap_destroy(&ctx_new.range.level[0].cat); 3149 ebitmap_destroy(&ctx_new.range.level[0].cat);
3084 goto netlbl_secattr_to_sid_return; 3150out:
3151 read_unlock(&policy_rwlock);
3152 return rc;
3085} 3153}
3086 3154
3087/** 3155/**
@@ -3103,29 +3171,59 @@ int security_netlbl_sid_to_secattr(u32 sid, struct netlbl_lsm_secattr *secattr)
3103 return 0; 3171 return 0;
3104 3172
3105 read_lock(&policy_rwlock); 3173 read_lock(&policy_rwlock);
3174
3175 rc = -ENOENT;
3106 ctx = sidtab_search(&sidtab, sid); 3176 ctx = sidtab_search(&sidtab, sid);
3107 if (ctx == NULL) { 3177 if (ctx == NULL)
3108 rc = -ENOENT; 3178 goto out;
3109 goto netlbl_sid_to_secattr_failure; 3179
3110 } 3180 rc = -ENOMEM;
3111 secattr->domain = kstrdup(policydb.p_type_val_to_name[ctx->type - 1], 3181 secattr->domain = kstrdup(sym_name(&policydb, SYM_TYPES, ctx->type - 1),
3112 GFP_ATOMIC); 3182 GFP_ATOMIC);
3113 if (secattr->domain == NULL) { 3183 if (secattr->domain == NULL)
3114 rc = -ENOMEM; 3184 goto out;
3115 goto netlbl_sid_to_secattr_failure; 3185
3116 }
3117 secattr->attr.secid = sid; 3186 secattr->attr.secid = sid;
3118 secattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID; 3187 secattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID;
3119 mls_export_netlbl_lvl(ctx, secattr); 3188 mls_export_netlbl_lvl(ctx, secattr);
3120 rc = mls_export_netlbl_cat(ctx, secattr); 3189 rc = mls_export_netlbl_cat(ctx, secattr);
3121 if (rc != 0) 3190out:
3122 goto netlbl_sid_to_secattr_failure;
3123 read_unlock(&policy_rwlock); 3191 read_unlock(&policy_rwlock);
3192 return rc;
3193}
3194#endif /* CONFIG_NETLABEL */
3124 3195
3125 return 0; 3196/**
3197 * security_read_policy - read the policy.
3198 * @data: binary policy data
3199 * @len: length of data in bytes
3200 *
3201 */
3202int security_read_policy(void **data, size_t *len)
3203{
3204 int rc;
3205 struct policy_file fp;
3126 3206
3127netlbl_sid_to_secattr_failure: 3207 if (!ss_initialized)
3208 return -EINVAL;
3209
3210 *len = security_policydb_len();
3211
3212 *data = vmalloc_user(*len);
3213 if (!*data)
3214 return -ENOMEM;
3215
3216 fp.data = *data;
3217 fp.len = *len;
3218
3219 read_lock(&policy_rwlock);
3220 rc = policydb_write(&policydb, &fp);
3128 read_unlock(&policy_rwlock); 3221 read_unlock(&policy_rwlock);
3129 return rc; 3222
3223 if (rc)
3224 return rc;
3225
3226 *len = (unsigned long)fp.data - (unsigned long)*data;
3227 return 0;
3228
3130} 3229}
3131#endif /* CONFIG_NETLABEL */
diff --git a/security/selinux/ss/sidtab.c b/security/selinux/ss/sidtab.c
index e817989764cd..5840a35155fc 100644
--- a/security/selinux/ss/sidtab.c
+++ b/security/selinux/ss/sidtab.c
@@ -147,6 +147,17 @@ out:
147 return rc; 147 return rc;
148} 148}
149 149
150static void sidtab_update_cache(struct sidtab *s, struct sidtab_node *n, int loc)
151{
152 BUG_ON(loc >= SIDTAB_CACHE_LEN);
153
154 while (loc > 0) {
155 s->cache[loc] = s->cache[loc - 1];
156 loc--;
157 }
158 s->cache[0] = n;
159}
160
150static inline u32 sidtab_search_context(struct sidtab *s, 161static inline u32 sidtab_search_context(struct sidtab *s,
151 struct context *context) 162 struct context *context)
152{ 163{
@@ -156,14 +167,33 @@ static inline u32 sidtab_search_context(struct sidtab *s,
156 for (i = 0; i < SIDTAB_SIZE; i++) { 167 for (i = 0; i < SIDTAB_SIZE; i++) {
157 cur = s->htable[i]; 168 cur = s->htable[i];
158 while (cur) { 169 while (cur) {
159 if (context_cmp(&cur->context, context)) 170 if (context_cmp(&cur->context, context)) {
171 sidtab_update_cache(s, cur, SIDTAB_CACHE_LEN - 1);
160 return cur->sid; 172 return cur->sid;
173 }
161 cur = cur->next; 174 cur = cur->next;
162 } 175 }
163 } 176 }
164 return 0; 177 return 0;
165} 178}
166 179
180static inline u32 sidtab_search_cache(struct sidtab *s, struct context *context)
181{
182 int i;
183 struct sidtab_node *node;
184
185 for (i = 0; i < SIDTAB_CACHE_LEN; i++) {
186 node = s->cache[i];
187 if (unlikely(!node))
188 return 0;
189 if (context_cmp(&node->context, context)) {
190 sidtab_update_cache(s, node, i);
191 return node->sid;
192 }
193 }
194 return 0;
195}
196
167int sidtab_context_to_sid(struct sidtab *s, 197int sidtab_context_to_sid(struct sidtab *s,
168 struct context *context, 198 struct context *context,
169 u32 *out_sid) 199 u32 *out_sid)
@@ -174,7 +204,9 @@ int sidtab_context_to_sid(struct sidtab *s,
174 204
175 *out_sid = SECSID_NULL; 205 *out_sid = SECSID_NULL;
176 206
177 sid = sidtab_search_context(s, context); 207 sid = sidtab_search_cache(s, context);
208 if (!sid)
209 sid = sidtab_search_context(s, context);
178 if (!sid) { 210 if (!sid) {
179 spin_lock_irqsave(&s->lock, flags); 211 spin_lock_irqsave(&s->lock, flags);
180 /* Rescan now that we hold the lock. */ 212 /* Rescan now that we hold the lock. */
@@ -259,12 +291,15 @@ void sidtab_destroy(struct sidtab *s)
259void sidtab_set(struct sidtab *dst, struct sidtab *src) 291void sidtab_set(struct sidtab *dst, struct sidtab *src)
260{ 292{
261 unsigned long flags; 293 unsigned long flags;
294 int i;
262 295
263 spin_lock_irqsave(&src->lock, flags); 296 spin_lock_irqsave(&src->lock, flags);
264 dst->htable = src->htable; 297 dst->htable = src->htable;
265 dst->nel = src->nel; 298 dst->nel = src->nel;
266 dst->next_sid = src->next_sid; 299 dst->next_sid = src->next_sid;
267 dst->shutdown = 0; 300 dst->shutdown = 0;
301 for (i = 0; i < SIDTAB_CACHE_LEN; i++)
302 dst->cache[i] = NULL;
268 spin_unlock_irqrestore(&src->lock, flags); 303 spin_unlock_irqrestore(&src->lock, flags);
269} 304}
270 305
diff --git a/security/selinux/ss/sidtab.h b/security/selinux/ss/sidtab.h
index 64ea5b1cdea4..84dc154d9389 100644
--- a/security/selinux/ss/sidtab.h
+++ b/security/selinux/ss/sidtab.h
@@ -26,6 +26,8 @@ struct sidtab {
26 unsigned int nel; /* number of elements */ 26 unsigned int nel; /* number of elements */
27 unsigned int next_sid; /* next SID to allocate */ 27 unsigned int next_sid; /* next SID to allocate */
28 unsigned char shutdown; 28 unsigned char shutdown;
29#define SIDTAB_CACHE_LEN 3
30 struct sidtab_node *cache[SIDTAB_CACHE_LEN];
29 spinlock_t lock; 31 spinlock_t lock;
30}; 32};
31 33
diff --git a/security/selinux/ss/status.c b/security/selinux/ss/status.c
new file mode 100644
index 000000000000..d982365f9d1a
--- /dev/null
+++ b/security/selinux/ss/status.c
@@ -0,0 +1,126 @@
1/*
2 * mmap based event notifications for SELinux
3 *
4 * Author: KaiGai Kohei <kaigai@ak.jp.nec.com>
5 *
6 * Copyright (C) 2010 NEC corporation
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License version 2,
10 * as published by the Free Software Foundation.
11 */
12#include <linux/kernel.h>
13#include <linux/gfp.h>
14#include <linux/mm.h>
15#include <linux/mutex.h>
16#include "avc.h"
17#include "services.h"
18
19/*
20 * The selinux_status_page shall be exposed to userspace applications
21 * using mmap interface on /selinux/status.
22 * It enables to notify applications a few events that will cause reset
23 * of userspace access vector without context switching.
24 *
25 * The selinux_kernel_status structure on the head of status page is
26 * protected from concurrent accesses using seqlock logic, so userspace
27 * application should reference the status page according to the seqlock
28 * logic.
29 *
30 * Typically, application checks status->sequence at the head of access
31 * control routine. If it is odd-number, kernel is updating the status,
32 * so please wait for a moment. If it is changed from the last sequence
33 * number, it means something happen, so application will reset userspace
34 * avc, if needed.
35 * In most cases, application shall confirm the kernel status is not
36 * changed without any system call invocations.
37 */
38static struct page *selinux_status_page;
39static DEFINE_MUTEX(selinux_status_lock);
40
41/*
42 * selinux_kernel_status_page
43 *
44 * It returns a reference to selinux_status_page. If the status page is
45 * not allocated yet, it also tries to allocate it at the first time.
46 */
47struct page *selinux_kernel_status_page(void)
48{
49 struct selinux_kernel_status *status;
50 struct page *result = NULL;
51
52 mutex_lock(&selinux_status_lock);
53 if (!selinux_status_page) {
54 selinux_status_page = alloc_page(GFP_KERNEL|__GFP_ZERO);
55
56 if (selinux_status_page) {
57 status = page_address(selinux_status_page);
58
59 status->version = SELINUX_KERNEL_STATUS_VERSION;
60 status->sequence = 0;
61 status->enforcing = selinux_enforcing;
62 /*
63 * NOTE: the next policyload event shall set
64 * a positive value on the status->policyload,
65 * although it may not be 1, but never zero.
66 * So, application can know it was updated.
67 */
68 status->policyload = 0;
69 status->deny_unknown = !security_get_allow_unknown();
70 }
71 }
72 result = selinux_status_page;
73 mutex_unlock(&selinux_status_lock);
74
75 return result;
76}
77
78/*
79 * selinux_status_update_setenforce
80 *
81 * It updates status of the current enforcing/permissive mode.
82 */
83void selinux_status_update_setenforce(int enforcing)
84{
85 struct selinux_kernel_status *status;
86
87 mutex_lock(&selinux_status_lock);
88 if (selinux_status_page) {
89 status = page_address(selinux_status_page);
90
91 status->sequence++;
92 smp_wmb();
93
94 status->enforcing = enforcing;
95
96 smp_wmb();
97 status->sequence++;
98 }
99 mutex_unlock(&selinux_status_lock);
100}
101
102/*
103 * selinux_status_update_policyload
104 *
105 * It updates status of the times of policy reloaded, and current
106 * setting of deny_unknown.
107 */
108void selinux_status_update_policyload(int seqno)
109{
110 struct selinux_kernel_status *status;
111
112 mutex_lock(&selinux_status_lock);
113 if (selinux_status_page) {
114 status = page_address(selinux_status_page);
115
116 status->sequence++;
117 smp_wmb();
118
119 status->policyload = seqno;
120 status->deny_unknown = !security_get_allow_unknown();
121
122 smp_wmb();
123 status->sequence++;
124 }
125 mutex_unlock(&selinux_status_lock);
126}
diff --git a/security/selinux/xfrm.c b/security/selinux/xfrm.c
index fff78d3b51a2..68178b76a2b3 100644
--- a/security/selinux/xfrm.c
+++ b/security/selinux/xfrm.c
@@ -112,7 +112,7 @@ int selinux_xfrm_policy_lookup(struct xfrm_sec_ctx *ctx, u32 fl_secid, u8 dir)
112 */ 112 */
113 113
114int selinux_xfrm_state_pol_flow_match(struct xfrm_state *x, struct xfrm_policy *xp, 114int selinux_xfrm_state_pol_flow_match(struct xfrm_state *x, struct xfrm_policy *xp,
115 struct flowi *fl) 115 const struct flowi *fl)
116{ 116{
117 u32 state_sid; 117 u32 state_sid;
118 int rc; 118 int rc;
@@ -135,10 +135,10 @@ int selinux_xfrm_state_pol_flow_match(struct xfrm_state *x, struct xfrm_policy *
135 135
136 state_sid = x->security->ctx_sid; 136 state_sid = x->security->ctx_sid;
137 137
138 if (fl->secid != state_sid) 138 if (fl->flowi_secid != state_sid)
139 return 0; 139 return 0;
140 140
141 rc = avc_has_perm(fl->secid, state_sid, SECCLASS_ASSOCIATION, 141 rc = avc_has_perm(fl->flowi_secid, state_sid, SECCLASS_ASSOCIATION,
142 ASSOCIATION__SENDTO, 142 ASSOCIATION__SENDTO,
143 NULL)? 0:1; 143 NULL)? 0:1;
144 144
@@ -208,7 +208,7 @@ static int selinux_xfrm_sec_ctx_alloc(struct xfrm_sec_ctx **ctxp,
208 if (!uctx) 208 if (!uctx)
209 goto not_from_user; 209 goto not_from_user;
210 210
211 if (uctx->ctx_doi != XFRM_SC_ALG_SELINUX) 211 if (uctx->ctx_alg != XFRM_SC_ALG_SELINUX)
212 return -EINVAL; 212 return -EINVAL;
213 213
214 str_len = uctx->ctx_len; 214 str_len = uctx->ctx_len;
diff --git a/security/smack/smack.h b/security/smack/smack.h
index 43ae747a5aa4..2b6c6a516123 100644
--- a/security/smack/smack.h
+++ b/security/smack/smack.h
@@ -51,11 +51,21 @@ struct socket_smack {
51 */ 51 */
52struct inode_smack { 52struct inode_smack {
53 char *smk_inode; /* label of the fso */ 53 char *smk_inode; /* label of the fso */
54 char *smk_task; /* label of the task */
55 char *smk_mmap; /* label of the mmap domain */
54 struct mutex smk_lock; /* initialization lock */ 56 struct mutex smk_lock; /* initialization lock */
55 int smk_flags; /* smack inode flags */ 57 int smk_flags; /* smack inode flags */
56}; 58};
57 59
60struct task_smack {
61 char *smk_task; /* label for access control */
62 char *smk_forked; /* label when forked */
63 struct list_head smk_rules; /* per task access rules */
64 struct mutex smk_rules_lock; /* lock for the rules */
65};
66
58#define SMK_INODE_INSTANT 0x01 /* inode is instantiated */ 67#define SMK_INODE_INSTANT 0x01 /* inode is instantiated */
68#define SMK_INODE_TRANSMUTE 0x02 /* directory is transmuting */
59 69
60/* 70/*
61 * A label access rule. 71 * A label access rule.
@@ -145,12 +155,6 @@ struct smack_known {
145#define SMACK_MAGIC 0x43415d53 /* "SMAC" */ 155#define SMACK_MAGIC 0x43415d53 /* "SMAC" */
146 156
147/* 157/*
148 * A limit on the number of entries in the lists
149 * makes some of the list administration easier.
150 */
151#define SMACK_LIST_MAX 10000
152
153/*
154 * CIPSO defaults. 158 * CIPSO defaults.
155 */ 159 */
156#define SMACK_CIPSO_DOI_DEFAULT 3 /* Historical */ 160#define SMACK_CIPSO_DOI_DEFAULT 3 /* Historical */
@@ -161,11 +165,13 @@ struct smack_known {
161#define SMACK_CIPSO_MAXCATNUM 239 /* CIPSO 2.2 standard */ 165#define SMACK_CIPSO_MAXCATNUM 239 /* CIPSO 2.2 standard */
162 166
163/* 167/*
168 * Flag for transmute access
169 */
170#define MAY_TRANSMUTE 64
171/*
164 * Just to make the common cases easier to deal with 172 * Just to make the common cases easier to deal with
165 */ 173 */
166#define MAY_ANY (MAY_READ | MAY_WRITE | MAY_APPEND | MAY_EXEC)
167#define MAY_ANYREAD (MAY_READ | MAY_EXEC) 174#define MAY_ANYREAD (MAY_READ | MAY_EXEC)
168#define MAY_ANYWRITE (MAY_WRITE | MAY_APPEND)
169#define MAY_READWRITE (MAY_READ | MAY_WRITE) 175#define MAY_READWRITE (MAY_READ | MAY_WRITE)
170#define MAY_NOT 0 176#define MAY_NOT 0
171 177
@@ -191,6 +197,7 @@ struct inode_smack *new_inode_smack(char *);
191/* 197/*
192 * These functions are in smack_access.c 198 * These functions are in smack_access.c
193 */ 199 */
200int smk_access_entry(char *, char *, struct list_head *);
194int smk_access(char *, char *, int, struct smk_audit_info *); 201int smk_access(char *, char *, int, struct smk_audit_info *);
195int smk_curacc(char *, u32, struct smk_audit_info *); 202int smk_curacc(char *, u32, struct smk_audit_info *);
196int smack_to_cipso(const char *, struct smack_cipso *); 203int smack_to_cipso(const char *, struct smack_cipso *);
@@ -234,6 +241,15 @@ static inline void smack_catset_bit(int cat, char *catsetp)
234} 241}
235 242
236/* 243/*
244 * Is the directory transmuting?
245 */
246static inline int smk_inode_transmutable(const struct inode *isp)
247{
248 struct inode_smack *sip = isp->i_security;
249 return (sip->smk_flags & SMK_INODE_TRANSMUTE) != 0;
250}
251
252/*
237 * Present a pointer to the smack label in an inode blob. 253 * Present a pointer to the smack label in an inode blob.
238 */ 254 */
239static inline char *smk_of_inode(const struct inode *isp) 255static inline char *smk_of_inode(const struct inode *isp)
@@ -243,6 +259,30 @@ static inline char *smk_of_inode(const struct inode *isp)
243} 259}
244 260
245/* 261/*
262 * Present a pointer to the smack label in an task blob.
263 */
264static inline char *smk_of_task(const struct task_smack *tsp)
265{
266 return tsp->smk_task;
267}
268
269/*
270 * Present a pointer to the forked smack label in an task blob.
271 */
272static inline char *smk_of_forked(const struct task_smack *tsp)
273{
274 return tsp->smk_forked;
275}
276
277/*
278 * Present a pointer to the smack label in the current task blob.
279 */
280static inline char *smk_of_current(void)
281{
282 return smk_of_task(current_security());
283}
284
285/*
246 * logging functions 286 * logging functions
247 */ 287 */
248#define SMACK_AUDIT_DENIED 0x1 288#define SMACK_AUDIT_DENIED 0x1
@@ -276,22 +316,17 @@ static inline void smk_ad_setfield_u_tsk(struct smk_audit_info *a,
276static inline void smk_ad_setfield_u_fs_path_dentry(struct smk_audit_info *a, 316static inline void smk_ad_setfield_u_fs_path_dentry(struct smk_audit_info *a,
277 struct dentry *d) 317 struct dentry *d)
278{ 318{
279 a->a.u.fs.path.dentry = d; 319 a->a.u.dentry = d;
280}
281static inline void smk_ad_setfield_u_fs_path_mnt(struct smk_audit_info *a,
282 struct vfsmount *m)
283{
284 a->a.u.fs.path.mnt = m;
285} 320}
286static inline void smk_ad_setfield_u_fs_inode(struct smk_audit_info *a, 321static inline void smk_ad_setfield_u_fs_inode(struct smk_audit_info *a,
287 struct inode *i) 322 struct inode *i)
288{ 323{
289 a->a.u.fs.inode = i; 324 a->a.u.inode = i;
290} 325}
291static inline void smk_ad_setfield_u_fs_path(struct smk_audit_info *a, 326static inline void smk_ad_setfield_u_fs_path(struct smk_audit_info *a,
292 struct path p) 327 struct path p)
293{ 328{
294 a->a.u.fs.path = p; 329 a->a.u.path = p;
295} 330}
296static inline void smk_ad_setfield_u_net_sk(struct smk_audit_info *a, 331static inline void smk_ad_setfield_u_net_sk(struct smk_audit_info *a,
297 struct sock *sk) 332 struct sock *sk)
diff --git a/security/smack/smack_access.c b/security/smack/smack_access.c
index f4fac64c4da8..9637e107f7ea 100644
--- a/security/smack/smack_access.c
+++ b/security/smack/smack_access.c
@@ -67,6 +67,46 @@ static u32 smack_next_secid = 10;
67int log_policy = SMACK_AUDIT_DENIED; 67int log_policy = SMACK_AUDIT_DENIED;
68 68
69/** 69/**
70 * smk_access_entry - look up matching access rule
71 * @subject_label: a pointer to the subject's Smack label
72 * @object_label: a pointer to the object's Smack label
73 * @rule_list: the list of rules to search
74 *
75 * This function looks up the subject/object pair in the
76 * access rule list and returns the access mode. If no
77 * entry is found returns -ENOENT.
78 *
79 * NOTE:
80 * Even though Smack labels are usually shared on smack_list
81 * labels that come in off the network can't be imported
82 * and added to the list for locking reasons.
83 *
84 * Therefore, it is necessary to check the contents of the labels,
85 * not just the pointer values. Of course, in most cases the labels
86 * will be on the list, so checking the pointers may be a worthwhile
87 * optimization.
88 */
89int smk_access_entry(char *subject_label, char *object_label,
90 struct list_head *rule_list)
91{
92 int may = -ENOENT;
93 struct smack_rule *srp;
94
95 list_for_each_entry_rcu(srp, rule_list, list) {
96 if (srp->smk_subject == subject_label ||
97 strcmp(srp->smk_subject, subject_label) == 0) {
98 if (srp->smk_object == object_label ||
99 strcmp(srp->smk_object, object_label) == 0) {
100 may = srp->smk_access;
101 break;
102 }
103 }
104 }
105
106 return may;
107}
108
109/**
70 * smk_access - determine if a subject has a specific access to an object 110 * smk_access - determine if a subject has a specific access to an object
71 * @subject_label: a pointer to the subject's Smack label 111 * @subject_label: a pointer to the subject's Smack label
72 * @object_label: a pointer to the object's Smack label 112 * @object_label: a pointer to the object's Smack label
@@ -89,8 +129,7 @@ int log_policy = SMACK_AUDIT_DENIED;
89int smk_access(char *subject_label, char *object_label, int request, 129int smk_access(char *subject_label, char *object_label, int request,
90 struct smk_audit_info *a) 130 struct smk_audit_info *a)
91{ 131{
92 u32 may = MAY_NOT; 132 int may = MAY_NOT;
93 struct smack_rule *srp;
94 int rc = 0; 133 int rc = 0;
95 134
96 /* 135 /*
@@ -142,24 +181,14 @@ int smk_access(char *subject_label, char *object_label, int request,
142 * Beyond here an explicit relationship is required. 181 * Beyond here an explicit relationship is required.
143 * If the requested access is contained in the available 182 * If the requested access is contained in the available
144 * access (e.g. read is included in readwrite) it's 183 * access (e.g. read is included in readwrite) it's
145 * good. 184 * good. A negative response from smk_access_entry()
185 * indicates there is no entry for this pair.
146 */ 186 */
147 rcu_read_lock(); 187 rcu_read_lock();
148 list_for_each_entry_rcu(srp, &smack_rule_list, list) { 188 may = smk_access_entry(subject_label, object_label, &smack_rule_list);
149 if (srp->smk_subject == subject_label ||
150 strcmp(srp->smk_subject, subject_label) == 0) {
151 if (srp->smk_object == object_label ||
152 strcmp(srp->smk_object, object_label) == 0) {
153 may = srp->smk_access;
154 break;
155 }
156 }
157 }
158 rcu_read_unlock(); 189 rcu_read_unlock();
159 /* 190
160 * This is a bit map operation. 191 if (may > 0 && (request & may) == request)
161 */
162 if ((request & may) == request)
163 goto out_audit; 192 goto out_audit;
164 193
165 rc = -EACCES; 194 rc = -EACCES;
@@ -184,23 +213,38 @@ out_audit:
184 */ 213 */
185int smk_curacc(char *obj_label, u32 mode, struct smk_audit_info *a) 214int smk_curacc(char *obj_label, u32 mode, struct smk_audit_info *a)
186{ 215{
216 struct task_smack *tsp = current_security();
217 char *sp = smk_of_task(tsp);
218 int may;
187 int rc; 219 int rc;
188 char *sp = current_security();
189 220
221 /*
222 * Check the global rule list
223 */
190 rc = smk_access(sp, obj_label, mode, NULL); 224 rc = smk_access(sp, obj_label, mode, NULL);
191 if (rc == 0) 225 if (rc == 0) {
192 goto out_audit; 226 /*
227 * If there is an entry in the task's rule list
228 * it can further restrict access.
229 */
230 may = smk_access_entry(sp, obj_label, &tsp->smk_rules);
231 if (may < 0)
232 goto out_audit;
233 if ((mode & may) == mode)
234 goto out_audit;
235 rc = -EACCES;
236 }
193 237
194 /* 238 /*
195 * Return if a specific label has been designated as the 239 * Return if a specific label has been designated as the
196 * only one that gets privilege and current does not 240 * only one that gets privilege and current does not
197 * have that label. 241 * have that label.
198 */ 242 */
199 if (smack_onlycap != NULL && smack_onlycap != current->cred->security) 243 if (smack_onlycap != NULL && smack_onlycap != sp)
200 goto out_audit; 244 goto out_audit;
201 245
202 if (capable(CAP_MAC_OVERRIDE)) 246 if (capable(CAP_MAC_OVERRIDE))
203 return 0; 247 rc = 0;
204 248
205out_audit: 249out_audit:
206#ifdef CONFIG_AUDIT 250#ifdef CONFIG_AUDIT
@@ -387,7 +431,7 @@ char *smk_import(const char *string, int len)
387 * smack_from_secid - find the Smack label associated with a secid 431 * smack_from_secid - find the Smack label associated with a secid
388 * @secid: an integer that might be associated with a Smack label 432 * @secid: an integer that might be associated with a Smack label
389 * 433 *
390 * Returns a pointer to the appropraite Smack label if there is one, 434 * Returns a pointer to the appropriate Smack label if there is one,
391 * otherwise a pointer to the invalid Smack label. 435 * otherwise a pointer to the invalid Smack label.
392 */ 436 */
393char *smack_from_secid(const u32 secid) 437char *smack_from_secid(const u32 secid)
diff --git a/security/smack/smack_lsm.c b/security/smack/smack_lsm.c
index c448d57ae2b7..9831a39c11f6 100644
--- a/security/smack/smack_lsm.c
+++ b/security/smack/smack_lsm.c
@@ -3,12 +3,14 @@
3 * 3 *
4 * This file contains the smack hook function implementations. 4 * This file contains the smack hook function implementations.
5 * 5 *
6 * Author: 6 * Authors:
7 * Casey Schaufler <casey@schaufler-ca.com> 7 * Casey Schaufler <casey@schaufler-ca.com>
8 * Jarkko Sakkinen <ext-jarkko.2.sakkinen@nokia.com>
8 * 9 *
9 * Copyright (C) 2007 Casey Schaufler <casey@schaufler-ca.com> 10 * Copyright (C) 2007 Casey Schaufler <casey@schaufler-ca.com>
10 * Copyright (C) 2009 Hewlett-Packard Development Company, L.P. 11 * Copyright (C) 2009 Hewlett-Packard Development Company, L.P.
11 * Paul Moore <paul.moore@hp.com> 12 * Paul Moore <paul.moore@hp.com>
13 * Copyright (C) 2010 Nokia Corporation
12 * 14 *
13 * This program is free software; you can redistribute it and/or modify 15 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License version 2, 16 * it under the terms of the GNU General Public License version 2,
@@ -31,10 +33,14 @@
31#include <net/cipso_ipv4.h> 33#include <net/cipso_ipv4.h>
32#include <linux/audit.h> 34#include <linux/audit.h>
33#include <linux/magic.h> 35#include <linux/magic.h>
36#include <linux/dcache.h>
34#include "smack.h" 37#include "smack.h"
35 38
36#define task_security(task) (task_cred_xxx((task), security)) 39#define task_security(task) (task_cred_xxx((task), security))
37 40
41#define TRANS_TRUE "TRUE"
42#define TRANS_TRUE_SIZE 4
43
38/** 44/**
39 * smk_fetch - Fetch the smack label from a file. 45 * smk_fetch - Fetch the smack label from a file.
40 * @ip: a pointer to the inode 46 * @ip: a pointer to the inode
@@ -43,7 +49,7 @@
43 * Returns a pointer to the master list entry for the Smack label 49 * Returns a pointer to the master list entry for the Smack label
44 * or NULL if there was no label to fetch. 50 * or NULL if there was no label to fetch.
45 */ 51 */
46static char *smk_fetch(struct inode *ip, struct dentry *dp) 52static char *smk_fetch(const char *name, struct inode *ip, struct dentry *dp)
47{ 53{
48 int rc; 54 int rc;
49 char in[SMK_LABELLEN]; 55 char in[SMK_LABELLEN];
@@ -51,7 +57,7 @@ static char *smk_fetch(struct inode *ip, struct dentry *dp)
51 if (ip->i_op->getxattr == NULL) 57 if (ip->i_op->getxattr == NULL)
52 return NULL; 58 return NULL;
53 59
54 rc = ip->i_op->getxattr(dp, XATTR_NAME_SMACK, in, SMK_LABELLEN); 60 rc = ip->i_op->getxattr(dp, name, in, SMK_LABELLEN);
55 if (rc < 0) 61 if (rc < 0)
56 return NULL; 62 return NULL;
57 63
@@ -79,6 +85,56 @@ struct inode_smack *new_inode_smack(char *smack)
79 return isp; 85 return isp;
80} 86}
81 87
88/**
89 * new_task_smack - allocate a task security blob
90 * @smack: a pointer to the Smack label to use in the blob
91 *
92 * Returns the new blob or NULL if there's no memory available
93 */
94static struct task_smack *new_task_smack(char *task, char *forked, gfp_t gfp)
95{
96 struct task_smack *tsp;
97
98 tsp = kzalloc(sizeof(struct task_smack), gfp);
99 if (tsp == NULL)
100 return NULL;
101
102 tsp->smk_task = task;
103 tsp->smk_forked = forked;
104 INIT_LIST_HEAD(&tsp->smk_rules);
105 mutex_init(&tsp->smk_rules_lock);
106
107 return tsp;
108}
109
110/**
111 * smk_copy_rules - copy a rule set
112 * @nhead - new rules header pointer
113 * @ohead - old rules header pointer
114 *
115 * Returns 0 on success, -ENOMEM on error
116 */
117static int smk_copy_rules(struct list_head *nhead, struct list_head *ohead,
118 gfp_t gfp)
119{
120 struct smack_rule *nrp;
121 struct smack_rule *orp;
122 int rc = 0;
123
124 INIT_LIST_HEAD(nhead);
125
126 list_for_each_entry_rcu(orp, ohead, list) {
127 nrp = kzalloc(sizeof(struct smack_rule), gfp);
128 if (nrp == NULL) {
129 rc = -ENOMEM;
130 break;
131 }
132 *nrp = *orp;
133 list_add_rcu(&nrp->list, nhead);
134 }
135 return rc;
136}
137
82/* 138/*
83 * LSM hooks. 139 * LSM hooks.
84 * We he, that is fun! 140 * We he, that is fun!
@@ -97,23 +153,17 @@ static int smack_ptrace_access_check(struct task_struct *ctp, unsigned int mode)
97{ 153{
98 int rc; 154 int rc;
99 struct smk_audit_info ad; 155 struct smk_audit_info ad;
100 char *sp, *tsp; 156 char *tsp;
101 157
102 rc = cap_ptrace_access_check(ctp, mode); 158 rc = cap_ptrace_access_check(ctp, mode);
103 if (rc != 0) 159 if (rc != 0)
104 return rc; 160 return rc;
105 161
106 sp = current_security(); 162 tsp = smk_of_task(task_security(ctp));
107 tsp = task_security(ctp);
108 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_TASK); 163 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_TASK);
109 smk_ad_setfield_u_tsk(&ad, ctp); 164 smk_ad_setfield_u_tsk(&ad, ctp);
110 165
111 /* we won't log here, because rc can be overriden */ 166 rc = smk_curacc(tsp, MAY_READWRITE, &ad);
112 rc = smk_access(sp, tsp, MAY_READWRITE, NULL);
113 if (rc != 0 && capable(CAP_MAC_OVERRIDE))
114 rc = 0;
115
116 smack_log(sp, tsp, MAY_READWRITE, rc, &ad);
117 return rc; 167 return rc;
118} 168}
119 169
@@ -129,23 +179,17 @@ static int smack_ptrace_traceme(struct task_struct *ptp)
129{ 179{
130 int rc; 180 int rc;
131 struct smk_audit_info ad; 181 struct smk_audit_info ad;
132 char *sp, *tsp; 182 char *tsp;
133 183
134 rc = cap_ptrace_traceme(ptp); 184 rc = cap_ptrace_traceme(ptp);
135 if (rc != 0) 185 if (rc != 0)
136 return rc; 186 return rc;
137 187
188 tsp = smk_of_task(task_security(ptp));
138 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_TASK); 189 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_TASK);
139 smk_ad_setfield_u_tsk(&ad, ptp); 190 smk_ad_setfield_u_tsk(&ad, ptp);
140 191
141 sp = current_security(); 192 rc = smk_curacc(tsp, MAY_READWRITE, &ad);
142 tsp = task_security(ptp);
143 /* we won't log here, because rc can be overriden */
144 rc = smk_access(tsp, sp, MAY_READWRITE, NULL);
145 if (rc != 0 && has_capability(ptp, CAP_MAC_OVERRIDE))
146 rc = 0;
147
148 smack_log(tsp, sp, MAY_READWRITE, rc, &ad);
149 return rc; 193 return rc;
150} 194}
151 195
@@ -157,14 +201,10 @@ static int smack_ptrace_traceme(struct task_struct *ptp)
157 * 201 *
158 * Returns 0 on success, error code otherwise. 202 * Returns 0 on success, error code otherwise.
159 */ 203 */
160static int smack_syslog(int type, bool from_file) 204static int smack_syslog(int typefrom_file)
161{ 205{
162 int rc; 206 int rc = 0;
163 char *sp = current_security(); 207 char *sp = smk_of_current();
164
165 rc = cap_syslog(type, from_file);
166 if (rc != 0)
167 return rc;
168 208
169 if (capable(CAP_MAC_OVERRIDE)) 209 if (capable(CAP_MAC_OVERRIDE))
170 return 0; 210 return 0;
@@ -343,7 +383,7 @@ static int smack_sb_statfs(struct dentry *dentry)
343 int rc; 383 int rc;
344 struct smk_audit_info ad; 384 struct smk_audit_info ad;
345 385
346 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_FS); 386 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_DENTRY);
347 smk_ad_setfield_u_fs_path_dentry(&ad, dentry); 387 smk_ad_setfield_u_fs_path_dentry(&ad, dentry);
348 388
349 rc = smk_curacc(sbp->smk_floor, MAY_READ, &ad); 389 rc = smk_curacc(sbp->smk_floor, MAY_READ, &ad);
@@ -367,7 +407,7 @@ static int smack_sb_mount(char *dev_name, struct path *path,
367 struct superblock_smack *sbp = path->mnt->mnt_sb->s_security; 407 struct superblock_smack *sbp = path->mnt->mnt_sb->s_security;
368 struct smk_audit_info ad; 408 struct smk_audit_info ad;
369 409
370 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_FS); 410 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_PATH);
371 smk_ad_setfield_u_fs_path(&ad, *path); 411 smk_ad_setfield_u_fs_path(&ad, *path);
372 412
373 return smk_curacc(sbp->smk_floor, MAY_WRITE, &ad); 413 return smk_curacc(sbp->smk_floor, MAY_WRITE, &ad);
@@ -385,16 +425,53 @@ static int smack_sb_umount(struct vfsmount *mnt, int flags)
385{ 425{
386 struct superblock_smack *sbp; 426 struct superblock_smack *sbp;
387 struct smk_audit_info ad; 427 struct smk_audit_info ad;
428 struct path path;
388 429
389 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_FS); 430 path.dentry = mnt->mnt_root;
390 smk_ad_setfield_u_fs_path_dentry(&ad, mnt->mnt_root); 431 path.mnt = mnt;
391 smk_ad_setfield_u_fs_path_mnt(&ad, mnt); 432
433 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_PATH);
434 smk_ad_setfield_u_fs_path(&ad, path);
392 435
393 sbp = mnt->mnt_sb->s_security; 436 sbp = mnt->mnt_sb->s_security;
394 return smk_curacc(sbp->smk_floor, MAY_WRITE, &ad); 437 return smk_curacc(sbp->smk_floor, MAY_WRITE, &ad);
395} 438}
396 439
397/* 440/*
441 * BPRM hooks
442 */
443
444static int smack_bprm_set_creds(struct linux_binprm *bprm)
445{
446 struct task_smack *tsp = bprm->cred->security;
447 struct inode_smack *isp;
448 struct dentry *dp;
449 int rc;
450
451 rc = cap_bprm_set_creds(bprm);
452 if (rc != 0)
453 return rc;
454
455 if (bprm->cred_prepared)
456 return 0;
457
458 if (bprm->file == NULL || bprm->file->f_dentry == NULL)
459 return 0;
460
461 dp = bprm->file->f_dentry;
462
463 if (dp->d_inode == NULL)
464 return 0;
465
466 isp = dp->d_inode->i_security;
467
468 if (isp->smk_task != NULL)
469 tsp->smk_task = isp->smk_task;
470
471 return 0;
472}
473
474/*
398 * Inode hooks 475 * Inode hooks
399 */ 476 */
400 477
@@ -406,7 +483,7 @@ static int smack_sb_umount(struct vfsmount *mnt, int flags)
406 */ 483 */
407static int smack_inode_alloc_security(struct inode *inode) 484static int smack_inode_alloc_security(struct inode *inode)
408{ 485{
409 inode->i_security = new_inode_smack(current_security()); 486 inode->i_security = new_inode_smack(smk_of_current());
410 if (inode->i_security == NULL) 487 if (inode->i_security == NULL)
411 return -ENOMEM; 488 return -ENOMEM;
412 return 0; 489 return 0;
@@ -428,6 +505,7 @@ static void smack_inode_free_security(struct inode *inode)
428 * smack_inode_init_security - copy out the smack from an inode 505 * smack_inode_init_security - copy out the smack from an inode
429 * @inode: the inode 506 * @inode: the inode
430 * @dir: unused 507 * @dir: unused
508 * @qstr: unused
431 * @name: where to put the attribute name 509 * @name: where to put the attribute name
432 * @value: where to put the attribute value 510 * @value: where to put the attribute value
433 * @len: where to put the length of the attribute 511 * @len: where to put the length of the attribute
@@ -435,9 +513,12 @@ static void smack_inode_free_security(struct inode *inode)
435 * Returns 0 if it all works out, -ENOMEM if there's no memory 513 * Returns 0 if it all works out, -ENOMEM if there's no memory
436 */ 514 */
437static int smack_inode_init_security(struct inode *inode, struct inode *dir, 515static int smack_inode_init_security(struct inode *inode, struct inode *dir,
438 char **name, void **value, size_t *len) 516 const struct qstr *qstr, char **name,
517 void **value, size_t *len)
439{ 518{
440 char *isp = smk_of_inode(inode); 519 char *isp = smk_of_inode(inode);
520 char *dsp = smk_of_inode(dir);
521 int may;
441 522
442 if (name) { 523 if (name) {
443 *name = kstrdup(XATTR_SMACK_SUFFIX, GFP_KERNEL); 524 *name = kstrdup(XATTR_SMACK_SUFFIX, GFP_KERNEL);
@@ -446,6 +527,19 @@ static int smack_inode_init_security(struct inode *inode, struct inode *dir,
446 } 527 }
447 528
448 if (value) { 529 if (value) {
530 rcu_read_lock();
531 may = smk_access_entry(smk_of_current(), dsp, &smack_rule_list);
532 rcu_read_unlock();
533
534 /*
535 * If the access rule allows transmutation and
536 * the directory requests transmutation then
537 * by all means transmute.
538 */
539 if (may > 0 && ((may & MAY_TRANSMUTE) != 0) &&
540 smk_inode_transmutable(dir))
541 isp = dsp;
542
449 *value = kstrdup(isp, GFP_KERNEL); 543 *value = kstrdup(isp, GFP_KERNEL);
450 if (*value == NULL) 544 if (*value == NULL)
451 return -ENOMEM; 545 return -ENOMEM;
@@ -472,7 +566,7 @@ static int smack_inode_link(struct dentry *old_dentry, struct inode *dir,
472 struct smk_audit_info ad; 566 struct smk_audit_info ad;
473 int rc; 567 int rc;
474 568
475 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_FS); 569 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_DENTRY);
476 smk_ad_setfield_u_fs_path_dentry(&ad, old_dentry); 570 smk_ad_setfield_u_fs_path_dentry(&ad, old_dentry);
477 571
478 isp = smk_of_inode(old_dentry->d_inode); 572 isp = smk_of_inode(old_dentry->d_inode);
@@ -501,7 +595,7 @@ static int smack_inode_unlink(struct inode *dir, struct dentry *dentry)
501 struct smk_audit_info ad; 595 struct smk_audit_info ad;
502 int rc; 596 int rc;
503 597
504 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_FS); 598 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_DENTRY);
505 smk_ad_setfield_u_fs_path_dentry(&ad, dentry); 599 smk_ad_setfield_u_fs_path_dentry(&ad, dentry);
506 600
507 /* 601 /*
@@ -532,7 +626,7 @@ static int smack_inode_rmdir(struct inode *dir, struct dentry *dentry)
532 struct smk_audit_info ad; 626 struct smk_audit_info ad;
533 int rc; 627 int rc;
534 628
535 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_FS); 629 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_DENTRY);
536 smk_ad_setfield_u_fs_path_dentry(&ad, dentry); 630 smk_ad_setfield_u_fs_path_dentry(&ad, dentry);
537 631
538 /* 632 /*
@@ -572,7 +666,7 @@ static int smack_inode_rename(struct inode *old_inode,
572 char *isp; 666 char *isp;
573 struct smk_audit_info ad; 667 struct smk_audit_info ad;
574 668
575 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_FS); 669 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_DENTRY);
576 smk_ad_setfield_u_fs_path_dentry(&ad, old_dentry); 670 smk_ad_setfield_u_fs_path_dentry(&ad, old_dentry);
577 671
578 isp = smk_of_inode(old_dentry->d_inode); 672 isp = smk_of_inode(old_dentry->d_inode);
@@ -595,7 +689,7 @@ static int smack_inode_rename(struct inode *old_inode,
595 * 689 *
596 * Returns 0 if access is permitted, -EACCES otherwise 690 * Returns 0 if access is permitted, -EACCES otherwise
597 */ 691 */
598static int smack_inode_permission(struct inode *inode, int mask) 692static int smack_inode_permission(struct inode *inode, int mask, unsigned flags)
599{ 693{
600 struct smk_audit_info ad; 694 struct smk_audit_info ad;
601 695
@@ -605,7 +699,11 @@ static int smack_inode_permission(struct inode *inode, int mask)
605 */ 699 */
606 if (mask == 0) 700 if (mask == 0)
607 return 0; 701 return 0;
608 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_FS); 702
703 /* May be droppable after audit */
704 if (flags & IPERM_FLAG_RCU)
705 return -ECHILD;
706 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_INODE);
609 smk_ad_setfield_u_fs_inode(&ad, inode); 707 smk_ad_setfield_u_fs_inode(&ad, inode);
610 return smk_curacc(smk_of_inode(inode), mask, &ad); 708 return smk_curacc(smk_of_inode(inode), mask, &ad);
611} 709}
@@ -625,7 +723,7 @@ static int smack_inode_setattr(struct dentry *dentry, struct iattr *iattr)
625 */ 723 */
626 if (iattr->ia_valid & ATTR_FORCE) 724 if (iattr->ia_valid & ATTR_FORCE)
627 return 0; 725 return 0;
628 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_FS); 726 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_DENTRY);
629 smk_ad_setfield_u_fs_path_dentry(&ad, dentry); 727 smk_ad_setfield_u_fs_path_dentry(&ad, dentry);
630 728
631 return smk_curacc(smk_of_inode(dentry->d_inode), MAY_WRITE, &ad); 729 return smk_curacc(smk_of_inode(dentry->d_inode), MAY_WRITE, &ad);
@@ -641,10 +739,13 @@ static int smack_inode_setattr(struct dentry *dentry, struct iattr *iattr)
641static int smack_inode_getattr(struct vfsmount *mnt, struct dentry *dentry) 739static int smack_inode_getattr(struct vfsmount *mnt, struct dentry *dentry)
642{ 740{
643 struct smk_audit_info ad; 741 struct smk_audit_info ad;
742 struct path path;
644 743
645 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_FS); 744 path.dentry = dentry;
646 smk_ad_setfield_u_fs_path_dentry(&ad, dentry); 745 path.mnt = mnt;
647 smk_ad_setfield_u_fs_path_mnt(&ad, mnt); 746
747 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_PATH);
748 smk_ad_setfield_u_fs_path(&ad, path);
648 return smk_curacc(smk_of_inode(dentry->d_inode), MAY_READ, &ad); 749 return smk_curacc(smk_of_inode(dentry->d_inode), MAY_READ, &ad);
649} 750}
650 751
@@ -668,7 +769,9 @@ static int smack_inode_setxattr(struct dentry *dentry, const char *name,
668 769
669 if (strcmp(name, XATTR_NAME_SMACK) == 0 || 770 if (strcmp(name, XATTR_NAME_SMACK) == 0 ||
670 strcmp(name, XATTR_NAME_SMACKIPIN) == 0 || 771 strcmp(name, XATTR_NAME_SMACKIPIN) == 0 ||
671 strcmp(name, XATTR_NAME_SMACKIPOUT) == 0) { 772 strcmp(name, XATTR_NAME_SMACKIPOUT) == 0 ||
773 strcmp(name, XATTR_NAME_SMACKEXEC) == 0 ||
774 strcmp(name, XATTR_NAME_SMACKMMAP) == 0) {
672 if (!capable(CAP_MAC_ADMIN)) 775 if (!capable(CAP_MAC_ADMIN))
673 rc = -EPERM; 776 rc = -EPERM;
674 /* 777 /*
@@ -678,10 +781,16 @@ static int smack_inode_setxattr(struct dentry *dentry, const char *name,
678 if (size == 0 || size >= SMK_LABELLEN || 781 if (size == 0 || size >= SMK_LABELLEN ||
679 smk_import(value, size) == NULL) 782 smk_import(value, size) == NULL)
680 rc = -EINVAL; 783 rc = -EINVAL;
784 } else if (strcmp(name, XATTR_NAME_SMACKTRANSMUTE) == 0) {
785 if (!capable(CAP_MAC_ADMIN))
786 rc = -EPERM;
787 if (size != TRANS_TRUE_SIZE ||
788 strncmp(value, TRANS_TRUE, TRANS_TRUE_SIZE) != 0)
789 rc = -EINVAL;
681 } else 790 } else
682 rc = cap_inode_setxattr(dentry, name, value, size, flags); 791 rc = cap_inode_setxattr(dentry, name, value, size, flags);
683 792
684 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_FS); 793 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_DENTRY);
685 smk_ad_setfield_u_fs_path_dentry(&ad, dentry); 794 smk_ad_setfield_u_fs_path_dentry(&ad, dentry);
686 795
687 if (rc == 0) 796 if (rc == 0)
@@ -704,26 +813,29 @@ static int smack_inode_setxattr(struct dentry *dentry, const char *name,
704static void smack_inode_post_setxattr(struct dentry *dentry, const char *name, 813static void smack_inode_post_setxattr(struct dentry *dentry, const char *name,
705 const void *value, size_t size, int flags) 814 const void *value, size_t size, int flags)
706{ 815{
707 struct inode_smack *isp;
708 char *nsp; 816 char *nsp;
817 struct inode_smack *isp = dentry->d_inode->i_security;
709 818
710 /* 819 if (strcmp(name, XATTR_NAME_SMACK) == 0) {
711 * Not SMACK 820 nsp = smk_import(value, size);
712 */ 821 if (nsp != NULL)
713 if (strcmp(name, XATTR_NAME_SMACK)) 822 isp->smk_inode = nsp;
714 return; 823 else
715 824 isp->smk_inode = smack_known_invalid.smk_known;
716 isp = dentry->d_inode->i_security; 825 } else if (strcmp(name, XATTR_NAME_SMACKEXEC) == 0) {
717 826 nsp = smk_import(value, size);
718 /* 827 if (nsp != NULL)
719 * No locking is done here. This is a pointer 828 isp->smk_task = nsp;
720 * assignment. 829 else
721 */ 830 isp->smk_task = smack_known_invalid.smk_known;
722 nsp = smk_import(value, size); 831 } else if (strcmp(name, XATTR_NAME_SMACKMMAP) == 0) {
723 if (nsp != NULL) 832 nsp = smk_import(value, size);
724 isp->smk_inode = nsp; 833 if (nsp != NULL)
725 else 834 isp->smk_mmap = nsp;
726 isp->smk_inode = smack_known_invalid.smk_known; 835 else
836 isp->smk_mmap = smack_known_invalid.smk_known;
837 } else if (strcmp(name, XATTR_NAME_SMACKTRANSMUTE) == 0)
838 isp->smk_flags |= SMK_INODE_TRANSMUTE;
727 839
728 return; 840 return;
729} 841}
@@ -739,7 +851,7 @@ static int smack_inode_getxattr(struct dentry *dentry, const char *name)
739{ 851{
740 struct smk_audit_info ad; 852 struct smk_audit_info ad;
741 853
742 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_FS); 854 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_DENTRY);
743 smk_ad_setfield_u_fs_path_dentry(&ad, dentry); 855 smk_ad_setfield_u_fs_path_dentry(&ad, dentry);
744 856
745 return smk_curacc(smk_of_inode(dentry->d_inode), MAY_READ, &ad); 857 return smk_curacc(smk_of_inode(dentry->d_inode), MAY_READ, &ad);
@@ -756,22 +868,32 @@ static int smack_inode_getxattr(struct dentry *dentry, const char *name)
756 */ 868 */
757static int smack_inode_removexattr(struct dentry *dentry, const char *name) 869static int smack_inode_removexattr(struct dentry *dentry, const char *name)
758{ 870{
871 struct inode_smack *isp;
759 struct smk_audit_info ad; 872 struct smk_audit_info ad;
760 int rc = 0; 873 int rc = 0;
761 874
762 if (strcmp(name, XATTR_NAME_SMACK) == 0 || 875 if (strcmp(name, XATTR_NAME_SMACK) == 0 ||
763 strcmp(name, XATTR_NAME_SMACKIPIN) == 0 || 876 strcmp(name, XATTR_NAME_SMACKIPIN) == 0 ||
764 strcmp(name, XATTR_NAME_SMACKIPOUT) == 0) { 877 strcmp(name, XATTR_NAME_SMACKIPOUT) == 0 ||
878 strcmp(name, XATTR_NAME_SMACKEXEC) == 0 ||
879 strcmp(name, XATTR_NAME_SMACKTRANSMUTE) == 0 ||
880 strcmp(name, XATTR_NAME_SMACKMMAP)) {
765 if (!capable(CAP_MAC_ADMIN)) 881 if (!capable(CAP_MAC_ADMIN))
766 rc = -EPERM; 882 rc = -EPERM;
767 } else 883 } else
768 rc = cap_inode_removexattr(dentry, name); 884 rc = cap_inode_removexattr(dentry, name);
769 885
770 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_FS); 886 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_DENTRY);
771 smk_ad_setfield_u_fs_path_dentry(&ad, dentry); 887 smk_ad_setfield_u_fs_path_dentry(&ad, dentry);
772 if (rc == 0) 888 if (rc == 0)
773 rc = smk_curacc(smk_of_inode(dentry->d_inode), MAY_WRITE, &ad); 889 rc = smk_curacc(smk_of_inode(dentry->d_inode), MAY_WRITE, &ad);
774 890
891 if (rc == 0) {
892 isp = dentry->d_inode->i_security;
893 isp->smk_task = NULL;
894 isp->smk_mmap = NULL;
895 }
896
775 return rc; 897 return rc;
776} 898}
777 899
@@ -899,7 +1021,7 @@ static int smack_file_permission(struct file *file, int mask)
899 */ 1021 */
900static int smack_file_alloc_security(struct file *file) 1022static int smack_file_alloc_security(struct file *file)
901{ 1023{
902 file->f_security = current_security(); 1024 file->f_security = smk_of_current();
903 return 0; 1025 return 0;
904} 1026}
905 1027
@@ -931,7 +1053,7 @@ static int smack_file_ioctl(struct file *file, unsigned int cmd,
931 int rc = 0; 1053 int rc = 0;
932 struct smk_audit_info ad; 1054 struct smk_audit_info ad;
933 1055
934 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_FS); 1056 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_PATH);
935 smk_ad_setfield_u_fs_path(&ad, file->f_path); 1057 smk_ad_setfield_u_fs_path(&ad, file->f_path);
936 1058
937 if (_IOC_DIR(cmd) & _IOC_WRITE) 1059 if (_IOC_DIR(cmd) & _IOC_WRITE)
@@ -954,8 +1076,8 @@ static int smack_file_lock(struct file *file, unsigned int cmd)
954{ 1076{
955 struct smk_audit_info ad; 1077 struct smk_audit_info ad;
956 1078
957 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_FS); 1079 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_PATH);
958 smk_ad_setfield_u_fs_path_dentry(&ad, file->f_path.dentry); 1080 smk_ad_setfield_u_fs_path(&ad, file->f_path);
959 return smk_curacc(file->f_security, MAY_WRITE, &ad); 1081 return smk_curacc(file->f_security, MAY_WRITE, &ad);
960} 1082}
961 1083
@@ -973,7 +1095,7 @@ static int smack_file_fcntl(struct file *file, unsigned int cmd,
973 struct smk_audit_info ad; 1095 struct smk_audit_info ad;
974 int rc; 1096 int rc;
975 1097
976 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_FS); 1098 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_PATH);
977 smk_ad_setfield_u_fs_path(&ad, file->f_path); 1099 smk_ad_setfield_u_fs_path(&ad, file->f_path);
978 1100
979 switch (cmd) { 1101 switch (cmd) {
@@ -1001,6 +1123,126 @@ static int smack_file_fcntl(struct file *file, unsigned int cmd,
1001} 1123}
1002 1124
1003/** 1125/**
1126 * smack_file_mmap :
1127 * Check permissions for a mmap operation. The @file may be NULL, e.g.
1128 * if mapping anonymous memory.
1129 * @file contains the file structure for file to map (may be NULL).
1130 * @reqprot contains the protection requested by the application.
1131 * @prot contains the protection that will be applied by the kernel.
1132 * @flags contains the operational flags.
1133 * Return 0 if permission is granted.
1134 */
1135static int smack_file_mmap(struct file *file,
1136 unsigned long reqprot, unsigned long prot,
1137 unsigned long flags, unsigned long addr,
1138 unsigned long addr_only)
1139{
1140 struct smack_rule *srp;
1141 struct task_smack *tsp;
1142 char *sp;
1143 char *msmack;
1144 char *osmack;
1145 struct inode_smack *isp;
1146 struct dentry *dp;
1147 int may;
1148 int mmay;
1149 int tmay;
1150 int rc;
1151
1152 /* do DAC check on address space usage */
1153 rc = cap_file_mmap(file, reqprot, prot, flags, addr, addr_only);
1154 if (rc || addr_only)
1155 return rc;
1156
1157 if (file == NULL || file->f_dentry == NULL)
1158 return 0;
1159
1160 dp = file->f_dentry;
1161
1162 if (dp->d_inode == NULL)
1163 return 0;
1164
1165 isp = dp->d_inode->i_security;
1166 if (isp->smk_mmap == NULL)
1167 return 0;
1168 msmack = isp->smk_mmap;
1169
1170 tsp = current_security();
1171 sp = smk_of_current();
1172 rc = 0;
1173
1174 rcu_read_lock();
1175 /*
1176 * For each Smack rule associated with the subject
1177 * label verify that the SMACK64MMAP also has access
1178 * to that rule's object label.
1179 *
1180 * Because neither of the labels comes
1181 * from the networking code it is sufficient
1182 * to compare pointers.
1183 */
1184 list_for_each_entry_rcu(srp, &smack_rule_list, list) {
1185 if (srp->smk_subject != sp)
1186 continue;
1187
1188 osmack = srp->smk_object;
1189 /*
1190 * Matching labels always allows access.
1191 */
1192 if (msmack == osmack)
1193 continue;
1194 /*
1195 * If there is a matching local rule take
1196 * that into account as well.
1197 */
1198 may = smk_access_entry(srp->smk_subject, osmack,
1199 &tsp->smk_rules);
1200 if (may == -ENOENT)
1201 may = srp->smk_access;
1202 else
1203 may &= srp->smk_access;
1204 /*
1205 * If may is zero the SMACK64MMAP subject can't
1206 * possibly have less access.
1207 */
1208 if (may == 0)
1209 continue;
1210
1211 /*
1212 * Fetch the global list entry.
1213 * If there isn't one a SMACK64MMAP subject
1214 * can't have as much access as current.
1215 */
1216 mmay = smk_access_entry(msmack, osmack, &smack_rule_list);
1217 if (mmay == -ENOENT) {
1218 rc = -EACCES;
1219 break;
1220 }
1221 /*
1222 * If there is a local entry it modifies the
1223 * potential access, too.
1224 */
1225 tmay = smk_access_entry(msmack, osmack, &tsp->smk_rules);
1226 if (tmay != -ENOENT)
1227 mmay &= tmay;
1228
1229 /*
1230 * If there is any access available to current that is
1231 * not available to a SMACK64MMAP subject
1232 * deny access.
1233 */
1234 if ((may | mmay) != mmay) {
1235 rc = -EACCES;
1236 break;
1237 }
1238 }
1239
1240 rcu_read_unlock();
1241
1242 return rc;
1243}
1244
1245/**
1004 * smack_file_set_fowner - set the file security blob value 1246 * smack_file_set_fowner - set the file security blob value
1005 * @file: object in question 1247 * @file: object in question
1006 * 1248 *
@@ -1009,7 +1251,7 @@ static int smack_file_fcntl(struct file *file, unsigned int cmd,
1009 */ 1251 */
1010static int smack_file_set_fowner(struct file *file) 1252static int smack_file_set_fowner(struct file *file)
1011{ 1253{
1012 file->f_security = current_security(); 1254 file->f_security = smk_of_current();
1013 return 0; 1255 return 0;
1014} 1256}
1015 1257
@@ -1029,13 +1271,14 @@ static int smack_file_send_sigiotask(struct task_struct *tsk,
1029{ 1271{
1030 struct file *file; 1272 struct file *file;
1031 int rc; 1273 int rc;
1032 char *tsp = tsk->cred->security; 1274 char *tsp = smk_of_task(tsk->cred->security);
1033 struct smk_audit_info ad; 1275 struct smk_audit_info ad;
1034 1276
1035 /* 1277 /*
1036 * struct fown_struct is never outside the context of a struct file 1278 * struct fown_struct is never outside the context of a struct file
1037 */ 1279 */
1038 file = container_of(fown, struct file, f_owner); 1280 file = container_of(fown, struct file, f_owner);
1281
1039 /* we don't log here as rc can be overriden */ 1282 /* we don't log here as rc can be overriden */
1040 rc = smk_access(file->f_security, tsp, MAY_WRITE, NULL); 1283 rc = smk_access(file->f_security, tsp, MAY_WRITE, NULL);
1041 if (rc != 0 && has_capability(tsk, CAP_MAC_OVERRIDE)) 1284 if (rc != 0 && has_capability(tsk, CAP_MAC_OVERRIDE))
@@ -1086,7 +1329,14 @@ static int smack_file_receive(struct file *file)
1086 */ 1329 */
1087static int smack_cred_alloc_blank(struct cred *cred, gfp_t gfp) 1330static int smack_cred_alloc_blank(struct cred *cred, gfp_t gfp)
1088{ 1331{
1089 cred->security = NULL; 1332 struct task_smack *tsp;
1333
1334 tsp = new_task_smack(NULL, NULL, gfp);
1335 if (tsp == NULL)
1336 return -ENOMEM;
1337
1338 cred->security = tsp;
1339
1090 return 0; 1340 return 0;
1091} 1341}
1092 1342
@@ -1095,13 +1345,24 @@ static int smack_cred_alloc_blank(struct cred *cred, gfp_t gfp)
1095 * smack_cred_free - "free" task-level security credentials 1345 * smack_cred_free - "free" task-level security credentials
1096 * @cred: the credentials in question 1346 * @cred: the credentials in question
1097 * 1347 *
1098 * Smack isn't using copies of blobs. Everyone
1099 * points to an immutable list. The blobs never go away.
1100 * There is no leak here.
1101 */ 1348 */
1102static void smack_cred_free(struct cred *cred) 1349static void smack_cred_free(struct cred *cred)
1103{ 1350{
1351 struct task_smack *tsp = cred->security;
1352 struct smack_rule *rp;
1353 struct list_head *l;
1354 struct list_head *n;
1355
1356 if (tsp == NULL)
1357 return;
1104 cred->security = NULL; 1358 cred->security = NULL;
1359
1360 list_for_each_safe(l, n, &tsp->smk_rules) {
1361 rp = list_entry(l, struct smack_rule, list);
1362 list_del(&rp->list);
1363 kfree(rp);
1364 }
1365 kfree(tsp);
1105} 1366}
1106 1367
1107/** 1368/**
@@ -1115,7 +1376,19 @@ static void smack_cred_free(struct cred *cred)
1115static int smack_cred_prepare(struct cred *new, const struct cred *old, 1376static int smack_cred_prepare(struct cred *new, const struct cred *old,
1116 gfp_t gfp) 1377 gfp_t gfp)
1117{ 1378{
1118 new->security = old->security; 1379 struct task_smack *old_tsp = old->security;
1380 struct task_smack *new_tsp;
1381 int rc;
1382
1383 new_tsp = new_task_smack(old_tsp->smk_task, old_tsp->smk_task, gfp);
1384 if (new_tsp == NULL)
1385 return -ENOMEM;
1386
1387 rc = smk_copy_rules(&new_tsp->smk_rules, &old_tsp->smk_rules, gfp);
1388 if (rc != 0)
1389 return rc;
1390
1391 new->security = new_tsp;
1119 return 0; 1392 return 0;
1120} 1393}
1121 1394
@@ -1128,7 +1401,16 @@ static int smack_cred_prepare(struct cred *new, const struct cred *old,
1128 */ 1401 */
1129static void smack_cred_transfer(struct cred *new, const struct cred *old) 1402static void smack_cred_transfer(struct cred *new, const struct cred *old)
1130{ 1403{
1131 new->security = old->security; 1404 struct task_smack *old_tsp = old->security;
1405 struct task_smack *new_tsp = new->security;
1406
1407 new_tsp->smk_task = old_tsp->smk_task;
1408 new_tsp->smk_forked = old_tsp->smk_task;
1409 mutex_init(&new_tsp->smk_rules_lock);
1410 INIT_LIST_HEAD(&new_tsp->smk_rules);
1411
1412
1413 /* cbs copy rule list */
1132} 1414}
1133 1415
1134/** 1416/**
@@ -1140,12 +1422,13 @@ static void smack_cred_transfer(struct cred *new, const struct cred *old)
1140 */ 1422 */
1141static int smack_kernel_act_as(struct cred *new, u32 secid) 1423static int smack_kernel_act_as(struct cred *new, u32 secid)
1142{ 1424{
1425 struct task_smack *new_tsp = new->security;
1143 char *smack = smack_from_secid(secid); 1426 char *smack = smack_from_secid(secid);
1144 1427
1145 if (smack == NULL) 1428 if (smack == NULL)
1146 return -EINVAL; 1429 return -EINVAL;
1147 1430
1148 new->security = smack; 1431 new_tsp->smk_task = smack;
1149 return 0; 1432 return 0;
1150} 1433}
1151 1434
@@ -1161,8 +1444,10 @@ static int smack_kernel_create_files_as(struct cred *new,
1161 struct inode *inode) 1444 struct inode *inode)
1162{ 1445{
1163 struct inode_smack *isp = inode->i_security; 1446 struct inode_smack *isp = inode->i_security;
1447 struct task_smack *tsp = new->security;
1164 1448
1165 new->security = isp->smk_inode; 1449 tsp->smk_forked = isp->smk_inode;
1450 tsp->smk_task = isp->smk_inode;
1166 return 0; 1451 return 0;
1167} 1452}
1168 1453
@@ -1179,7 +1464,7 @@ static int smk_curacc_on_task(struct task_struct *p, int access)
1179 1464
1180 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_TASK); 1465 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_TASK);
1181 smk_ad_setfield_u_tsk(&ad, p); 1466 smk_ad_setfield_u_tsk(&ad, p);
1182 return smk_curacc(task_security(p), access, &ad); 1467 return smk_curacc(smk_of_task(task_security(p)), access, &ad);
1183} 1468}
1184 1469
1185/** 1470/**
@@ -1225,7 +1510,7 @@ static int smack_task_getsid(struct task_struct *p)
1225 */ 1510 */
1226static void smack_task_getsecid(struct task_struct *p, u32 *secid) 1511static void smack_task_getsecid(struct task_struct *p, u32 *secid)
1227{ 1512{
1228 *secid = smack_to_secid(task_security(p)); 1513 *secid = smack_to_secid(smk_of_task(task_security(p)));
1229} 1514}
1230 1515
1231/** 1516/**
@@ -1281,12 +1566,11 @@ static int smack_task_getioprio(struct task_struct *p)
1281 * 1566 *
1282 * Return 0 if read access is permitted 1567 * Return 0 if read access is permitted
1283 */ 1568 */
1284static int smack_task_setscheduler(struct task_struct *p, int policy, 1569static int smack_task_setscheduler(struct task_struct *p)
1285 struct sched_param *lp)
1286{ 1570{
1287 int rc; 1571 int rc;
1288 1572
1289 rc = cap_task_setscheduler(p, policy, lp); 1573 rc = cap_task_setscheduler(p);
1290 if (rc == 0) 1574 if (rc == 0)
1291 rc = smk_curacc_on_task(p, MAY_WRITE); 1575 rc = smk_curacc_on_task(p, MAY_WRITE);
1292 return rc; 1576 return rc;
@@ -1338,14 +1622,15 @@ static int smack_task_kill(struct task_struct *p, struct siginfo *info,
1338 * can write the receiver. 1622 * can write the receiver.
1339 */ 1623 */
1340 if (secid == 0) 1624 if (secid == 0)
1341 return smk_curacc(task_security(p), MAY_WRITE, &ad); 1625 return smk_curacc(smk_of_task(task_security(p)), MAY_WRITE,
1626 &ad);
1342 /* 1627 /*
1343 * If the secid isn't 0 we're dealing with some USB IO 1628 * If the secid isn't 0 we're dealing with some USB IO
1344 * specific behavior. This is not clean. For one thing 1629 * specific behavior. This is not clean. For one thing
1345 * we can't take privilege into account. 1630 * we can't take privilege into account.
1346 */ 1631 */
1347 return smk_access(smack_from_secid(secid), task_security(p), 1632 return smk_access(smack_from_secid(secid),
1348 MAY_WRITE, &ad); 1633 smk_of_task(task_security(p)), MAY_WRITE, &ad);
1349} 1634}
1350 1635
1351/** 1636/**
@@ -1357,12 +1642,12 @@ static int smack_task_kill(struct task_struct *p, struct siginfo *info,
1357static int smack_task_wait(struct task_struct *p) 1642static int smack_task_wait(struct task_struct *p)
1358{ 1643{
1359 struct smk_audit_info ad; 1644 struct smk_audit_info ad;
1360 char *sp = current_security(); 1645 char *sp = smk_of_current();
1361 char *tsp = task_security(p); 1646 char *tsp = smk_of_forked(task_security(p));
1362 int rc; 1647 int rc;
1363 1648
1364 /* we don't log here, we can be overriden */ 1649 /* we don't log here, we can be overriden */
1365 rc = smk_access(sp, tsp, MAY_WRITE, NULL); 1650 rc = smk_access(tsp, sp, MAY_WRITE, NULL);
1366 if (rc == 0) 1651 if (rc == 0)
1367 goto out_log; 1652 goto out_log;
1368 1653
@@ -1383,7 +1668,7 @@ static int smack_task_wait(struct task_struct *p)
1383 out_log: 1668 out_log:
1384 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_TASK); 1669 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_TASK);
1385 smk_ad_setfield_u_tsk(&ad, p); 1670 smk_ad_setfield_u_tsk(&ad, p);
1386 smack_log(sp, tsp, MAY_WRITE, rc, &ad); 1671 smack_log(tsp, sp, MAY_WRITE, rc, &ad);
1387 return rc; 1672 return rc;
1388} 1673}
1389 1674
@@ -1397,7 +1682,7 @@ static int smack_task_wait(struct task_struct *p)
1397static void smack_task_to_inode(struct task_struct *p, struct inode *inode) 1682static void smack_task_to_inode(struct task_struct *p, struct inode *inode)
1398{ 1683{
1399 struct inode_smack *isp = inode->i_security; 1684 struct inode_smack *isp = inode->i_security;
1400 isp->smk_inode = task_security(p); 1685 isp->smk_inode = smk_of_task(task_security(p));
1401} 1686}
1402 1687
1403/* 1688/*
@@ -1416,7 +1701,7 @@ static void smack_task_to_inode(struct task_struct *p, struct inode *inode)
1416 */ 1701 */
1417static int smack_sk_alloc_security(struct sock *sk, int family, gfp_t gfp_flags) 1702static int smack_sk_alloc_security(struct sock *sk, int family, gfp_t gfp_flags)
1418{ 1703{
1419 char *csp = current_security(); 1704 char *csp = smk_of_current();
1420 struct socket_smack *ssp; 1705 struct socket_smack *ssp;
1421 1706
1422 ssp = kzalloc(sizeof(struct socket_smack), gfp_flags); 1707 ssp = kzalloc(sizeof(struct socket_smack), gfp_flags);
@@ -1519,7 +1804,7 @@ static void smack_set_catset(char *catset, struct netlbl_lsm_secattr *sap)
1519 * Casey says that CIPSO is good enough for now. 1804 * Casey says that CIPSO is good enough for now.
1520 * It can be used to effect. 1805 * It can be used to effect.
1521 * It can also be abused to effect when necessary. 1806 * It can also be abused to effect when necessary.
1522 * Appologies to the TSIG group in general and GW in particular. 1807 * Apologies to the TSIG group in general and GW in particular.
1523 */ 1808 */
1524static void smack_to_secattr(char *smack, struct netlbl_lsm_secattr *nlsp) 1809static void smack_to_secattr(char *smack, struct netlbl_lsm_secattr *nlsp)
1525{ 1810{
@@ -1672,10 +1957,13 @@ static int smack_inode_setsecurity(struct inode *inode, const char *name,
1672 ssp->smk_in = sp; 1957 ssp->smk_in = sp;
1673 else if (strcmp(name, XATTR_SMACK_IPOUT) == 0) { 1958 else if (strcmp(name, XATTR_SMACK_IPOUT) == 0) {
1674 ssp->smk_out = sp; 1959 ssp->smk_out = sp;
1675 rc = smack_netlabel(sock->sk, SMACK_CIPSO_SOCKET); 1960 if (sock->sk->sk_family != PF_UNIX) {
1676 if (rc != 0) 1961 rc = smack_netlabel(sock->sk, SMACK_CIPSO_SOCKET);
1677 printk(KERN_WARNING "Smack: \"%s\" netlbl error %d.\n", 1962 if (rc != 0)
1678 __func__, -rc); 1963 printk(KERN_WARNING
1964 "Smack: \"%s\" netlbl error %d.\n",
1965 __func__, -rc);
1966 }
1679 } else 1967 } else
1680 return -EOPNOTSUPP; 1968 return -EOPNOTSUPP;
1681 1969
@@ -1754,7 +2042,7 @@ static int smack_flags_to_may(int flags)
1754 */ 2042 */
1755static int smack_msg_msg_alloc_security(struct msg_msg *msg) 2043static int smack_msg_msg_alloc_security(struct msg_msg *msg)
1756{ 2044{
1757 msg->security = current_security(); 2045 msg->security = smk_of_current();
1758 return 0; 2046 return 0;
1759} 2047}
1760 2048
@@ -1790,7 +2078,7 @@ static int smack_shm_alloc_security(struct shmid_kernel *shp)
1790{ 2078{
1791 struct kern_ipc_perm *isp = &shp->shm_perm; 2079 struct kern_ipc_perm *isp = &shp->shm_perm;
1792 2080
1793 isp->security = current_security(); 2081 isp->security = smk_of_current();
1794 return 0; 2082 return 0;
1795} 2083}
1796 2084
@@ -1913,7 +2201,7 @@ static int smack_sem_alloc_security(struct sem_array *sma)
1913{ 2201{
1914 struct kern_ipc_perm *isp = &sma->sem_perm; 2202 struct kern_ipc_perm *isp = &sma->sem_perm;
1915 2203
1916 isp->security = current_security(); 2204 isp->security = smk_of_current();
1917 return 0; 2205 return 0;
1918} 2206}
1919 2207
@@ -2031,7 +2319,7 @@ static int smack_msg_queue_alloc_security(struct msg_queue *msq)
2031{ 2319{
2032 struct kern_ipc_perm *kisp = &msq->q_perm; 2320 struct kern_ipc_perm *kisp = &msq->q_perm;
2033 2321
2034 kisp->security = current_security(); 2322 kisp->security = smk_of_current();
2035 return 0; 2323 return 0;
2036} 2324}
2037 2325
@@ -2203,9 +2491,11 @@ static void smack_d_instantiate(struct dentry *opt_dentry, struct inode *inode)
2203 struct super_block *sbp; 2491 struct super_block *sbp;
2204 struct superblock_smack *sbsp; 2492 struct superblock_smack *sbsp;
2205 struct inode_smack *isp; 2493 struct inode_smack *isp;
2206 char *csp = current_security(); 2494 char *csp = smk_of_current();
2207 char *fetched; 2495 char *fetched;
2208 char *final; 2496 char *final;
2497 char trattr[TRANS_TRUE_SIZE];
2498 int transflag = 0;
2209 struct dentry *dp; 2499 struct dentry *dp;
2210 2500
2211 if (inode == NULL) 2501 if (inode == NULL)
@@ -2250,7 +2540,7 @@ static void smack_d_instantiate(struct dentry *opt_dentry, struct inode *inode)
2250 switch (sbp->s_magic) { 2540 switch (sbp->s_magic) {
2251 case SMACK_MAGIC: 2541 case SMACK_MAGIC:
2252 /* 2542 /*
2253 * Casey says that it's a little embarassing 2543 * Casey says that it's a little embarrassing
2254 * that the smack file system doesn't do 2544 * that the smack file system doesn't do
2255 * extended attributes. 2545 * extended attributes.
2256 */ 2546 */
@@ -2272,9 +2562,10 @@ static void smack_d_instantiate(struct dentry *opt_dentry, struct inode *inode)
2272 break; 2562 break;
2273 case SOCKFS_MAGIC: 2563 case SOCKFS_MAGIC:
2274 /* 2564 /*
2275 * Casey says sockets get the smack of the task. 2565 * Socket access is controlled by the socket
2566 * structures associated with the task involved.
2276 */ 2567 */
2277 final = csp; 2568 final = smack_known_star.smk_known;
2278 break; 2569 break;
2279 case PROC_SUPER_MAGIC: 2570 case PROC_SUPER_MAGIC:
2280 /* 2571 /*
@@ -2301,7 +2592,16 @@ static void smack_d_instantiate(struct dentry *opt_dentry, struct inode *inode)
2301 /* 2592 /*
2302 * This isn't an understood special case. 2593 * This isn't an understood special case.
2303 * Get the value from the xattr. 2594 * Get the value from the xattr.
2304 * 2595 */
2596
2597 /*
2598 * UNIX domain sockets use lower level socket data.
2599 */
2600 if (S_ISSOCK(inode->i_mode)) {
2601 final = smack_known_star.smk_known;
2602 break;
2603 }
2604 /*
2305 * No xattr support means, alas, no SMACK label. 2605 * No xattr support means, alas, no SMACK label.
2306 * Use the aforeapplied default. 2606 * Use the aforeapplied default.
2307 * It would be curious if the label of the task 2607 * It would be curious if the label of the task
@@ -2313,9 +2613,22 @@ static void smack_d_instantiate(struct dentry *opt_dentry, struct inode *inode)
2313 * Get the dentry for xattr. 2613 * Get the dentry for xattr.
2314 */ 2614 */
2315 dp = dget(opt_dentry); 2615 dp = dget(opt_dentry);
2316 fetched = smk_fetch(inode, dp); 2616 fetched = smk_fetch(XATTR_NAME_SMACK, inode, dp);
2317 if (fetched != NULL) 2617 if (fetched != NULL) {
2318 final = fetched; 2618 final = fetched;
2619 if (S_ISDIR(inode->i_mode)) {
2620 trattr[0] = '\0';
2621 inode->i_op->getxattr(dp,
2622 XATTR_NAME_SMACKTRANSMUTE,
2623 trattr, TRANS_TRUE_SIZE);
2624 if (strncmp(trattr, TRANS_TRUE,
2625 TRANS_TRUE_SIZE) == 0)
2626 transflag = SMK_INODE_TRANSMUTE;
2627 }
2628 }
2629 isp->smk_task = smk_fetch(XATTR_NAME_SMACKEXEC, inode, dp);
2630 isp->smk_mmap = smk_fetch(XATTR_NAME_SMACKMMAP, inode, dp);
2631
2319 dput(dp); 2632 dput(dp);
2320 break; 2633 break;
2321 } 2634 }
@@ -2325,7 +2638,7 @@ static void smack_d_instantiate(struct dentry *opt_dentry, struct inode *inode)
2325 else 2638 else
2326 isp->smk_inode = final; 2639 isp->smk_inode = final;
2327 2640
2328 isp->smk_flags |= SMK_INODE_INSTANT; 2641 isp->smk_flags |= (SMK_INODE_INSTANT | transflag);
2329 2642
2330unlockandout: 2643unlockandout:
2331 mutex_unlock(&isp->smk_lock); 2644 mutex_unlock(&isp->smk_lock);
@@ -2350,7 +2663,7 @@ static int smack_getprocattr(struct task_struct *p, char *name, char **value)
2350 if (strcmp(name, "current") != 0) 2663 if (strcmp(name, "current") != 0)
2351 return -EINVAL; 2664 return -EINVAL;
2352 2665
2353 cp = kstrdup(task_security(p), GFP_KERNEL); 2666 cp = kstrdup(smk_of_task(task_security(p)), GFP_KERNEL);
2354 if (cp == NULL) 2667 if (cp == NULL)
2355 return -ENOMEM; 2668 return -ENOMEM;
2356 2669
@@ -2374,6 +2687,9 @@ static int smack_getprocattr(struct task_struct *p, char *name, char **value)
2374static int smack_setprocattr(struct task_struct *p, char *name, 2687static int smack_setprocattr(struct task_struct *p, char *name,
2375 void *value, size_t size) 2688 void *value, size_t size)
2376{ 2689{
2690 int rc;
2691 struct task_smack *tsp;
2692 struct task_smack *oldtsp;
2377 struct cred *new; 2693 struct cred *new;
2378 char *newsmack; 2694 char *newsmack;
2379 2695
@@ -2403,34 +2719,49 @@ static int smack_setprocattr(struct task_struct *p, char *name,
2403 if (newsmack == smack_known_web.smk_known) 2719 if (newsmack == smack_known_web.smk_known)
2404 return -EPERM; 2720 return -EPERM;
2405 2721
2722 oldtsp = p->cred->security;
2406 new = prepare_creds(); 2723 new = prepare_creds();
2407 if (new == NULL) 2724 if (new == NULL)
2408 return -ENOMEM; 2725 return -ENOMEM;
2409 new->security = newsmack; 2726
2727 tsp = new_task_smack(newsmack, oldtsp->smk_forked, GFP_KERNEL);
2728 if (tsp == NULL) {
2729 kfree(new);
2730 return -ENOMEM;
2731 }
2732 rc = smk_copy_rules(&tsp->smk_rules, &oldtsp->smk_rules, GFP_KERNEL);
2733 if (rc != 0)
2734 return rc;
2735
2736 new->security = tsp;
2410 commit_creds(new); 2737 commit_creds(new);
2411 return size; 2738 return size;
2412} 2739}
2413 2740
2414/** 2741/**
2415 * smack_unix_stream_connect - Smack access on UDS 2742 * smack_unix_stream_connect - Smack access on UDS
2416 * @sock: one socket 2743 * @sock: one sock
2417 * @other: the other socket 2744 * @other: the other sock
2418 * @newsk: unused 2745 * @newsk: unused
2419 * 2746 *
2420 * Return 0 if a subject with the smack of sock could access 2747 * Return 0 if a subject with the smack of sock could access
2421 * an object with the smack of other, otherwise an error code 2748 * an object with the smack of other, otherwise an error code
2422 */ 2749 */
2423static int smack_unix_stream_connect(struct socket *sock, 2750static int smack_unix_stream_connect(struct sock *sock,
2424 struct socket *other, struct sock *newsk) 2751 struct sock *other, struct sock *newsk)
2425{ 2752{
2426 struct inode *sp = SOCK_INODE(sock); 2753 struct socket_smack *ssp = sock->sk_security;
2427 struct inode *op = SOCK_INODE(other); 2754 struct socket_smack *osp = other->sk_security;
2428 struct smk_audit_info ad; 2755 struct smk_audit_info ad;
2756 int rc = 0;
2429 2757
2430 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_NET); 2758 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_NET);
2431 smk_ad_setfield_u_net_sk(&ad, other->sk); 2759 smk_ad_setfield_u_net_sk(&ad, other);
2432 return smk_access(smk_of_inode(sp), smk_of_inode(op), 2760
2433 MAY_READWRITE, &ad); 2761 if (!capable(CAP_MAC_OVERRIDE))
2762 rc = smk_access(ssp->smk_out, osp->smk_in, MAY_WRITE, &ad);
2763
2764 return rc;
2434} 2765}
2435 2766
2436/** 2767/**
@@ -2443,13 +2774,18 @@ static int smack_unix_stream_connect(struct socket *sock,
2443 */ 2774 */
2444static int smack_unix_may_send(struct socket *sock, struct socket *other) 2775static int smack_unix_may_send(struct socket *sock, struct socket *other)
2445{ 2776{
2446 struct inode *sp = SOCK_INODE(sock); 2777 struct socket_smack *ssp = sock->sk->sk_security;
2447 struct inode *op = SOCK_INODE(other); 2778 struct socket_smack *osp = other->sk->sk_security;
2448 struct smk_audit_info ad; 2779 struct smk_audit_info ad;
2780 int rc = 0;
2449 2781
2450 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_NET); 2782 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_NET);
2451 smk_ad_setfield_u_net_sk(&ad, other->sk); 2783 smk_ad_setfield_u_net_sk(&ad, other->sk);
2452 return smk_access(smk_of_inode(sp), smk_of_inode(op), MAY_WRITE, &ad); 2784
2785 if (!capable(CAP_MAC_OVERRIDE))
2786 rc = smk_access(ssp->smk_out, osp->smk_in, MAY_WRITE, &ad);
2787
2788 return rc;
2453} 2789}
2454 2790
2455/** 2791/**
@@ -2634,7 +2970,7 @@ static int smack_socket_getpeersec_stream(struct socket *sock,
2634 2970
2635/** 2971/**
2636 * smack_socket_getpeersec_dgram - pull in packet label 2972 * smack_socket_getpeersec_dgram - pull in packet label
2637 * @sock: the socket 2973 * @sock: the peer socket
2638 * @skb: packet data 2974 * @skb: packet data
2639 * @secid: pointer to where to put the secid of the packet 2975 * @secid: pointer to where to put the secid of the packet
2640 * 2976 *
@@ -2645,41 +2981,39 @@ static int smack_socket_getpeersec_dgram(struct socket *sock,
2645 2981
2646{ 2982{
2647 struct netlbl_lsm_secattr secattr; 2983 struct netlbl_lsm_secattr secattr;
2648 struct sock *sk; 2984 struct socket_smack *sp;
2649 char smack[SMK_LABELLEN]; 2985 char smack[SMK_LABELLEN];
2650 int family = PF_INET; 2986 int family = PF_UNSPEC;
2651 u32 s; 2987 u32 s = 0; /* 0 is the invalid secid */
2652 int rc; 2988 int rc;
2653 2989
2654 /* 2990 if (skb != NULL) {
2655 * Only works for families with packets. 2991 if (skb->protocol == htons(ETH_P_IP))
2656 */ 2992 family = PF_INET;
2657 if (sock != NULL) { 2993 else if (skb->protocol == htons(ETH_P_IPV6))
2658 sk = sock->sk; 2994 family = PF_INET6;
2659 if (sk->sk_family != PF_INET && sk->sk_family != PF_INET6)
2660 return 0;
2661 family = sk->sk_family;
2662 } 2995 }
2663 /* 2996 if (family == PF_UNSPEC && sock != NULL)
2664 * Translate what netlabel gave us. 2997 family = sock->sk->sk_family;
2665 */
2666 netlbl_secattr_init(&secattr);
2667 rc = netlbl_skbuff_getattr(skb, family, &secattr);
2668 if (rc == 0)
2669 smack_from_secattr(&secattr, smack);
2670 netlbl_secattr_destroy(&secattr);
2671 2998
2672 /* 2999 if (family == PF_UNIX) {
2673 * Give up if we couldn't get anything 3000 sp = sock->sk->sk_security;
2674 */ 3001 s = smack_to_secid(sp->smk_out);
2675 if (rc != 0) 3002 } else if (family == PF_INET || family == PF_INET6) {
2676 return rc; 3003 /*
2677 3004 * Translate what netlabel gave us.
2678 s = smack_to_secid(smack); 3005 */
3006 netlbl_secattr_init(&secattr);
3007 rc = netlbl_skbuff_getattr(skb, family, &secattr);
3008 if (rc == 0) {
3009 smack_from_secattr(&secattr, smack);
3010 s = smack_to_secid(smack);
3011 }
3012 netlbl_secattr_destroy(&secattr);
3013 }
3014 *secid = s;
2679 if (s == 0) 3015 if (s == 0)
2680 return -EINVAL; 3016 return -EINVAL;
2681
2682 *secid = s;
2683 return 0; 3017 return 0;
2684} 3018}
2685 3019
@@ -2700,7 +3034,7 @@ static void smack_sock_graft(struct sock *sk, struct socket *parent)
2700 return; 3034 return;
2701 3035
2702 ssp = sk->sk_security; 3036 ssp = sk->sk_security;
2703 ssp->smk_in = ssp->smk_out = current_security(); 3037 ssp->smk_in = ssp->smk_out = smk_of_current();
2704 /* cssp->smk_packet is already set in smack_inet_csk_clone() */ 3038 /* cssp->smk_packet is already set in smack_inet_csk_clone() */
2705} 3039}
2706 3040
@@ -2760,7 +3094,7 @@ static int smack_inet_conn_request(struct sock *sk, struct sk_buff *skb,
2760 /* 3094 /*
2761 * We need to decide if we want to label the incoming connection here 3095 * We need to decide if we want to label the incoming connection here
2762 * if we do we only need to label the request_sock and the stack will 3096 * if we do we only need to label the request_sock and the stack will
2763 * propogate the wire-label to the sock when it is created. 3097 * propagate the wire-label to the sock when it is created.
2764 */ 3098 */
2765 hdr = ip_hdr(skb); 3099 hdr = ip_hdr(skb);
2766 addr.sin_addr.s_addr = hdr->saddr; 3100 addr.sin_addr.s_addr = hdr->saddr;
@@ -2821,7 +3155,7 @@ static void smack_inet_csk_clone(struct sock *sk,
2821static int smack_key_alloc(struct key *key, const struct cred *cred, 3155static int smack_key_alloc(struct key *key, const struct cred *cred,
2822 unsigned long flags) 3156 unsigned long flags)
2823{ 3157{
2824 key->security = cred->security; 3158 key->security = smk_of_task(cred->security);
2825 return 0; 3159 return 0;
2826} 3160}
2827 3161
@@ -2850,6 +3184,7 @@ static int smack_key_permission(key_ref_t key_ref,
2850{ 3184{
2851 struct key *keyp; 3185 struct key *keyp;
2852 struct smk_audit_info ad; 3186 struct smk_audit_info ad;
3187 char *tsp = smk_of_task(cred->security);
2853 3188
2854 keyp = key_ref_to_ptr(key_ref); 3189 keyp = key_ref_to_ptr(key_ref);
2855 if (keyp == NULL) 3190 if (keyp == NULL)
@@ -2863,14 +3198,14 @@ static int smack_key_permission(key_ref_t key_ref,
2863 /* 3198 /*
2864 * This should not occur 3199 * This should not occur
2865 */ 3200 */
2866 if (cred->security == NULL) 3201 if (tsp == NULL)
2867 return -EACCES; 3202 return -EACCES;
2868#ifdef CONFIG_AUDIT 3203#ifdef CONFIG_AUDIT
2869 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_KEY); 3204 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_KEY);
2870 ad.a.u.key_struct.key = keyp->serial; 3205 ad.a.u.key_struct.key = keyp->serial;
2871 ad.a.u.key_struct.key_desc = keyp->description; 3206 ad.a.u.key_struct.key_desc = keyp->description;
2872#endif 3207#endif
2873 return smk_access(cred->security, keyp->security, 3208 return smk_access(tsp, keyp->security,
2874 MAY_READWRITE, &ad); 3209 MAY_READWRITE, &ad);
2875} 3210}
2876#endif /* CONFIG_KEYS */ 3211#endif /* CONFIG_KEYS */
@@ -3005,7 +3340,8 @@ static int smack_secid_to_secctx(u32 secid, char **secdata, u32 *seclen)
3005{ 3340{
3006 char *sp = smack_from_secid(secid); 3341 char *sp = smack_from_secid(secid);
3007 3342
3008 *secdata = sp; 3343 if (secdata)
3344 *secdata = sp;
3009 *seclen = strlen(sp); 3345 *seclen = strlen(sp);
3010 return 0; 3346 return 0;
3011} 3347}
@@ -3071,6 +3407,8 @@ struct security_operations smack_ops = {
3071 .sb_mount = smack_sb_mount, 3407 .sb_mount = smack_sb_mount,
3072 .sb_umount = smack_sb_umount, 3408 .sb_umount = smack_sb_umount,
3073 3409
3410 .bprm_set_creds = smack_bprm_set_creds,
3411
3074 .inode_alloc_security = smack_inode_alloc_security, 3412 .inode_alloc_security = smack_inode_alloc_security,
3075 .inode_free_security = smack_inode_free_security, 3413 .inode_free_security = smack_inode_free_security,
3076 .inode_init_security = smack_inode_init_security, 3414 .inode_init_security = smack_inode_init_security,
@@ -3096,6 +3434,7 @@ struct security_operations smack_ops = {
3096 .file_ioctl = smack_file_ioctl, 3434 .file_ioctl = smack_file_ioctl,
3097 .file_lock = smack_file_lock, 3435 .file_lock = smack_file_lock,
3098 .file_fcntl = smack_file_fcntl, 3436 .file_fcntl = smack_file_fcntl,
3437 .file_mmap = smack_file_mmap,
3099 .file_set_fowner = smack_file_set_fowner, 3438 .file_set_fowner = smack_file_set_fowner,
3100 .file_send_sigiotask = smack_file_send_sigiotask, 3439 .file_send_sigiotask = smack_file_send_sigiotask,
3101 .file_receive = smack_file_receive, 3440 .file_receive = smack_file_receive,
@@ -3207,17 +3546,23 @@ static __init void init_smack_know_list(void)
3207static __init int smack_init(void) 3546static __init int smack_init(void)
3208{ 3547{
3209 struct cred *cred; 3548 struct cred *cred;
3549 struct task_smack *tsp;
3210 3550
3211 if (!security_module_enable(&smack_ops)) 3551 if (!security_module_enable(&smack_ops))
3212 return 0; 3552 return 0;
3213 3553
3554 tsp = new_task_smack(smack_known_floor.smk_known,
3555 smack_known_floor.smk_known, GFP_KERNEL);
3556 if (tsp == NULL)
3557 return -ENOMEM;
3558
3214 printk(KERN_INFO "Smack: Initializing.\n"); 3559 printk(KERN_INFO "Smack: Initializing.\n");
3215 3560
3216 /* 3561 /*
3217 * Set the security state for the initial task. 3562 * Set the security state for the initial task.
3218 */ 3563 */
3219 cred = (struct cred *) current->cred; 3564 cred = (struct cred *) current->cred;
3220 cred->security = &smack_known_floor.smk_known; 3565 cred->security = tsp;
3221 3566
3222 /* initialize the smack_know_list */ 3567 /* initialize the smack_know_list */
3223 init_smack_know_list(); 3568 init_smack_know_list();
diff --git a/security/smack/smackfs.c b/security/smack/smackfs.c
index a2b72d77f926..f93460156dce 100644
--- a/security/smack/smackfs.c
+++ b/security/smack/smackfs.c
@@ -43,6 +43,7 @@ enum smk_inos {
43 SMK_NETLBLADDR = 8, /* single label hosts */ 43 SMK_NETLBLADDR = 8, /* single label hosts */
44 SMK_ONLYCAP = 9, /* the only "capable" label */ 44 SMK_ONLYCAP = 9, /* the only "capable" label */
45 SMK_LOGGING = 10, /* logging */ 45 SMK_LOGGING = 10, /* logging */
46 SMK_LOAD_SELF = 11, /* task specific rules */
46}; 47};
47 48
48/* 49/*
@@ -109,9 +110,12 @@ const char *smack_cipso_option = SMACK_CIPSO_OPTION;
109 * SMK_ACCESSLEN: Maximum length for a rule access field 110 * SMK_ACCESSLEN: Maximum length for a rule access field
110 * SMK_LOADLEN: Smack rule length 111 * SMK_LOADLEN: Smack rule length
111 */ 112 */
112#define SMK_ACCESS "rwxa" 113#define SMK_OACCESS "rwxa"
113#define SMK_ACCESSLEN (sizeof(SMK_ACCESS) - 1) 114#define SMK_ACCESS "rwxat"
114#define SMK_LOADLEN (SMK_LABELLEN + SMK_LABELLEN + SMK_ACCESSLEN) 115#define SMK_OACCESSLEN (sizeof(SMK_OACCESS) - 1)
116#define SMK_ACCESSLEN (sizeof(SMK_ACCESS) - 1)
117#define SMK_OLOADLEN (SMK_LABELLEN + SMK_LABELLEN + SMK_OACCESSLEN)
118#define SMK_LOADLEN (SMK_LABELLEN + SMK_LABELLEN + SMK_ACCESSLEN)
115 119
116/** 120/**
117 * smk_netlabel_audit_set - fill a netlbl_audit struct 121 * smk_netlabel_audit_set - fill a netlbl_audit struct
@@ -121,7 +125,7 @@ static void smk_netlabel_audit_set(struct netlbl_audit *nap)
121{ 125{
122 nap->loginuid = audit_get_loginuid(current); 126 nap->loginuid = audit_get_loginuid(current);
123 nap->sessionid = audit_get_sessionid(current); 127 nap->sessionid = audit_get_sessionid(current);
124 nap->secid = smack_to_secid(current_security()); 128 nap->secid = smack_to_secid(smk_of_current());
125} 129}
126 130
127/* 131/*
@@ -132,102 +136,30 @@ static void smk_netlabel_audit_set(struct netlbl_audit *nap)
132#define SMK_NETLBLADDRMIN 9 136#define SMK_NETLBLADDRMIN 9
133#define SMK_NETLBLADDRMAX 42 137#define SMK_NETLBLADDRMAX 42
134 138
135/*
136 * Seq_file read operations for /smack/load
137 */
138
139static void *load_seq_start(struct seq_file *s, loff_t *pos)
140{
141 if (*pos == SEQ_READ_FINISHED)
142 return NULL;
143 if (list_empty(&smack_rule_list))
144 return NULL;
145 return smack_rule_list.next;
146}
147
148static void *load_seq_next(struct seq_file *s, void *v, loff_t *pos)
149{
150 struct list_head *list = v;
151
152 if (list_is_last(list, &smack_rule_list)) {
153 *pos = SEQ_READ_FINISHED;
154 return NULL;
155 }
156 return list->next;
157}
158
159static int load_seq_show(struct seq_file *s, void *v)
160{
161 struct list_head *list = v;
162 struct smack_rule *srp =
163 list_entry(list, struct smack_rule, list);
164
165 seq_printf(s, "%s %s", (char *)srp->smk_subject,
166 (char *)srp->smk_object);
167
168 seq_putc(s, ' ');
169
170 if (srp->smk_access & MAY_READ)
171 seq_putc(s, 'r');
172 if (srp->smk_access & MAY_WRITE)
173 seq_putc(s, 'w');
174 if (srp->smk_access & MAY_EXEC)
175 seq_putc(s, 'x');
176 if (srp->smk_access & MAY_APPEND)
177 seq_putc(s, 'a');
178 if (srp->smk_access == 0)
179 seq_putc(s, '-');
180
181 seq_putc(s, '\n');
182
183 return 0;
184}
185
186static void load_seq_stop(struct seq_file *s, void *v)
187{
188 /* No-op */
189}
190
191static const struct seq_operations load_seq_ops = {
192 .start = load_seq_start,
193 .next = load_seq_next,
194 .show = load_seq_show,
195 .stop = load_seq_stop,
196};
197
198/**
199 * smk_open_load - open() for /smack/load
200 * @inode: inode structure representing file
201 * @file: "load" file pointer
202 *
203 * For reading, use load_seq_* seq_file reading operations.
204 */
205static int smk_open_load(struct inode *inode, struct file *file)
206{
207 return seq_open(file, &load_seq_ops);
208}
209
210/** 139/**
211 * smk_set_access - add a rule to the rule list 140 * smk_set_access - add a rule to the rule list
212 * @srp: the new rule to add 141 * @srp: the new rule to add
142 * @rule_list: the list of rules
143 * @rule_lock: the rule list lock
213 * 144 *
214 * Looks through the current subject/object/access list for 145 * Looks through the current subject/object/access list for
215 * the subject/object pair and replaces the access that was 146 * the subject/object pair and replaces the access that was
216 * there. If the pair isn't found add it with the specified 147 * there. If the pair isn't found add it with the specified
217 * access. 148 * access.
218 * 149 *
150 * Returns 1 if a rule was found to exist already, 0 if it is new
219 * Returns 0 if nothing goes wrong or -ENOMEM if it fails 151 * Returns 0 if nothing goes wrong or -ENOMEM if it fails
220 * during the allocation of the new pair to add. 152 * during the allocation of the new pair to add.
221 */ 153 */
222static int smk_set_access(struct smack_rule *srp) 154static int smk_set_access(struct smack_rule *srp, struct list_head *rule_list,
155 struct mutex *rule_lock)
223{ 156{
224 struct smack_rule *sp; 157 struct smack_rule *sp;
225 int ret = 0; 158 int found = 0;
226 int found;
227 mutex_lock(&smack_list_lock);
228 159
229 found = 0; 160 mutex_lock(rule_lock);
230 list_for_each_entry_rcu(sp, &smack_rule_list, list) { 161
162 list_for_each_entry_rcu(sp, rule_list, list) {
231 if (sp->smk_subject == srp->smk_subject && 163 if (sp->smk_subject == srp->smk_subject &&
232 sp->smk_object == srp->smk_object) { 164 sp->smk_object == srp->smk_object) {
233 found = 1; 165 found = 1;
@@ -236,19 +168,21 @@ static int smk_set_access(struct smack_rule *srp)
236 } 168 }
237 } 169 }
238 if (found == 0) 170 if (found == 0)
239 list_add_rcu(&srp->list, &smack_rule_list); 171 list_add_rcu(&srp->list, rule_list);
240 172
241 mutex_unlock(&smack_list_lock); 173 mutex_unlock(rule_lock);
242 174
243 return ret; 175 return found;
244} 176}
245 177
246/** 178/**
247 * smk_write_load - write() for /smack/load 179 * smk_write_load_list - write() for any /smack/load
248 * @file: file pointer, not actually used 180 * @file: file pointer, not actually used
249 * @buf: where to get the data from 181 * @buf: where to get the data from
250 * @count: bytes sent 182 * @count: bytes sent
251 * @ppos: where to start - must be 0 183 * @ppos: where to start - must be 0
184 * @rule_list: the list of rules to write to
185 * @rule_lock: lock for the rule list
252 * 186 *
253 * Get one smack access rule from above. 187 * Get one smack access rule from above.
254 * The format is exactly: 188 * The format is exactly:
@@ -258,25 +192,28 @@ static int smk_set_access(struct smack_rule *srp)
258 * 192 *
259 * writes must be SMK_LABELLEN+SMK_LABELLEN+SMK_ACCESSLEN bytes. 193 * writes must be SMK_LABELLEN+SMK_LABELLEN+SMK_ACCESSLEN bytes.
260 */ 194 */
261static ssize_t smk_write_load(struct file *file, const char __user *buf, 195static ssize_t smk_write_load_list(struct file *file, const char __user *buf,
262 size_t count, loff_t *ppos) 196 size_t count, loff_t *ppos,
197 struct list_head *rule_list,
198 struct mutex *rule_lock)
263{ 199{
264 struct smack_rule *rule; 200 struct smack_rule *rule;
265 char *data; 201 char *data;
266 int rc = -EINVAL; 202 int rc = -EINVAL;
267 203
268 /* 204 /*
269 * Must have privilege.
270 * No partial writes. 205 * No partial writes.
271 * Enough data must be present. 206 * Enough data must be present.
272 */ 207 */
273 if (!capable(CAP_MAC_ADMIN)) 208 if (*ppos != 0)
274 return -EPERM; 209 return -EINVAL;
275 210 /*
276 if (*ppos != 0 || count != SMK_LOADLEN) 211 * Minor hack for backward compatibility
212 */
213 if (count < (SMK_OLOADLEN) || count > SMK_LOADLEN)
277 return -EINVAL; 214 return -EINVAL;
278 215
279 data = kzalloc(count, GFP_KERNEL); 216 data = kzalloc(SMK_LOADLEN, GFP_KERNEL);
280 if (data == NULL) 217 if (data == NULL)
281 return -ENOMEM; 218 return -ENOMEM;
282 219
@@ -285,6 +222,12 @@ static ssize_t smk_write_load(struct file *file, const char __user *buf,
285 goto out; 222 goto out;
286 } 223 }
287 224
225 /*
226 * More on the minor hack for backward compatibility
227 */
228 if (count == (SMK_OLOADLEN))
229 data[SMK_OLOADLEN] = '-';
230
288 rule = kzalloc(sizeof(*rule), GFP_KERNEL); 231 rule = kzalloc(sizeof(*rule), GFP_KERNEL);
289 if (rule == NULL) { 232 if (rule == NULL) {
290 rc = -ENOMEM; 233 rc = -ENOMEM;
@@ -345,11 +288,24 @@ static ssize_t smk_write_load(struct file *file, const char __user *buf,
345 goto out_free_rule; 288 goto out_free_rule;
346 } 289 }
347 290
348 rc = smk_set_access(rule); 291 switch (data[SMK_LABELLEN + SMK_LABELLEN + 4]) {
292 case '-':
293 break;
294 case 't':
295 case 'T':
296 rule->smk_access |= MAY_TRANSMUTE;
297 break;
298 default:
299 goto out_free_rule;
300 }
349 301
350 if (!rc) 302 rc = count;
351 rc = count; 303 /*
352 goto out; 304 * smk_set_access returns true if there was already a rule
305 * for the subject/object pair, and false if it was new.
306 */
307 if (!smk_set_access(rule, rule_list, rule_lock))
308 goto out;
353 309
354out_free_rule: 310out_free_rule:
355 kfree(rule); 311 kfree(rule);
@@ -358,6 +314,108 @@ out:
358 return rc; 314 return rc;
359} 315}
360 316
317
318/*
319 * Seq_file read operations for /smack/load
320 */
321
322static void *load_seq_start(struct seq_file *s, loff_t *pos)
323{
324 if (*pos == SEQ_READ_FINISHED)
325 return NULL;
326 if (list_empty(&smack_rule_list))
327 return NULL;
328 return smack_rule_list.next;
329}
330
331static void *load_seq_next(struct seq_file *s, void *v, loff_t *pos)
332{
333 struct list_head *list = v;
334
335 if (list_is_last(list, &smack_rule_list)) {
336 *pos = SEQ_READ_FINISHED;
337 return NULL;
338 }
339 return list->next;
340}
341
342static int load_seq_show(struct seq_file *s, void *v)
343{
344 struct list_head *list = v;
345 struct smack_rule *srp =
346 list_entry(list, struct smack_rule, list);
347
348 seq_printf(s, "%s %s", (char *)srp->smk_subject,
349 (char *)srp->smk_object);
350
351 seq_putc(s, ' ');
352
353 if (srp->smk_access & MAY_READ)
354 seq_putc(s, 'r');
355 if (srp->smk_access & MAY_WRITE)
356 seq_putc(s, 'w');
357 if (srp->smk_access & MAY_EXEC)
358 seq_putc(s, 'x');
359 if (srp->smk_access & MAY_APPEND)
360 seq_putc(s, 'a');
361 if (srp->smk_access & MAY_TRANSMUTE)
362 seq_putc(s, 't');
363 if (srp->smk_access == 0)
364 seq_putc(s, '-');
365
366 seq_putc(s, '\n');
367
368 return 0;
369}
370
371static void load_seq_stop(struct seq_file *s, void *v)
372{
373 /* No-op */
374}
375
376static const struct seq_operations load_seq_ops = {
377 .start = load_seq_start,
378 .next = load_seq_next,
379 .show = load_seq_show,
380 .stop = load_seq_stop,
381};
382
383/**
384 * smk_open_load - open() for /smack/load
385 * @inode: inode structure representing file
386 * @file: "load" file pointer
387 *
388 * For reading, use load_seq_* seq_file reading operations.
389 */
390static int smk_open_load(struct inode *inode, struct file *file)
391{
392 return seq_open(file, &load_seq_ops);
393}
394
395/**
396 * smk_write_load - write() for /smack/load
397 * @file: file pointer, not actually used
398 * @buf: where to get the data from
399 * @count: bytes sent
400 * @ppos: where to start - must be 0
401 *
402 */
403static ssize_t smk_write_load(struct file *file, const char __user *buf,
404 size_t count, loff_t *ppos)
405{
406
407 /*
408 * Must have privilege.
409 * No partial writes.
410 * Enough data must be present.
411 */
412 if (!capable(CAP_MAC_ADMIN))
413 return -EPERM;
414
415 return smk_write_load_list(file, buf, count, ppos, &smack_rule_list,
416 &smack_list_lock);
417}
418
361static const struct file_operations smk_load_ops = { 419static const struct file_operations smk_load_ops = {
362 .open = smk_open_load, 420 .open = smk_open_load,
363 .read = seq_read, 421 .read = seq_read,
@@ -869,7 +927,7 @@ static ssize_t smk_write_netlbladdr(struct file *file, const char __user *buf,
869 } 927 }
870 } else { 928 } else {
871 /* we delete the unlabeled entry, only if the previous label 929 /* we delete the unlabeled entry, only if the previous label
872 * wasnt the special CIPSO option */ 930 * wasn't the special CIPSO option */
873 if (skp->smk_label != smack_cipso_option) 931 if (skp->smk_label != smack_cipso_option)
874 rc = netlbl_cfg_unlbl_static_del(&init_net, NULL, 932 rc = netlbl_cfg_unlbl_static_del(&init_net, NULL,
875 &skp->smk_host.sin_addr, &skp->smk_mask, 933 &skp->smk_host.sin_addr, &skp->smk_mask,
@@ -968,6 +1026,7 @@ static ssize_t smk_write_doi(struct file *file, const char __user *buf,
968static const struct file_operations smk_doi_ops = { 1026static const struct file_operations smk_doi_ops = {
969 .read = smk_read_doi, 1027 .read = smk_read_doi,
970 .write = smk_write_doi, 1028 .write = smk_write_doi,
1029 .llseek = default_llseek,
971}; 1030};
972 1031
973/** 1032/**
@@ -1031,6 +1090,7 @@ static ssize_t smk_write_direct(struct file *file, const char __user *buf,
1031static const struct file_operations smk_direct_ops = { 1090static const struct file_operations smk_direct_ops = {
1032 .read = smk_read_direct, 1091 .read = smk_read_direct,
1033 .write = smk_write_direct, 1092 .write = smk_write_direct,
1093 .llseek = default_llseek,
1034}; 1094};
1035 1095
1036/** 1096/**
@@ -1112,6 +1172,7 @@ static ssize_t smk_write_ambient(struct file *file, const char __user *buf,
1112static const struct file_operations smk_ambient_ops = { 1172static const struct file_operations smk_ambient_ops = {
1113 .read = smk_read_ambient, 1173 .read = smk_read_ambient,
1114 .write = smk_write_ambient, 1174 .write = smk_write_ambient,
1175 .llseek = default_llseek,
1115}; 1176};
1116 1177
1117/** 1178/**
@@ -1157,7 +1218,7 @@ static ssize_t smk_write_onlycap(struct file *file, const char __user *buf,
1157 size_t count, loff_t *ppos) 1218 size_t count, loff_t *ppos)
1158{ 1219{
1159 char in[SMK_LABELLEN]; 1220 char in[SMK_LABELLEN];
1160 char *sp = current->cred->security; 1221 char *sp = smk_of_task(current->cred->security);
1161 1222
1162 if (!capable(CAP_MAC_ADMIN)) 1223 if (!capable(CAP_MAC_ADMIN))
1163 return -EPERM; 1224 return -EPERM;
@@ -1191,6 +1252,7 @@ static ssize_t smk_write_onlycap(struct file *file, const char __user *buf,
1191static const struct file_operations smk_onlycap_ops = { 1252static const struct file_operations smk_onlycap_ops = {
1192 .read = smk_read_onlycap, 1253 .read = smk_read_onlycap,
1193 .write = smk_write_onlycap, 1254 .write = smk_write_onlycap,
1255 .llseek = default_llseek,
1194}; 1256};
1195 1257
1196/** 1258/**
@@ -1255,6 +1317,113 @@ static ssize_t smk_write_logging(struct file *file, const char __user *buf,
1255static const struct file_operations smk_logging_ops = { 1317static const struct file_operations smk_logging_ops = {
1256 .read = smk_read_logging, 1318 .read = smk_read_logging,
1257 .write = smk_write_logging, 1319 .write = smk_write_logging,
1320 .llseek = default_llseek,
1321};
1322
1323/*
1324 * Seq_file read operations for /smack/load-self
1325 */
1326
1327static void *load_self_seq_start(struct seq_file *s, loff_t *pos)
1328{
1329 struct task_smack *tsp = current_security();
1330
1331 if (*pos == SEQ_READ_FINISHED)
1332 return NULL;
1333 if (list_empty(&tsp->smk_rules))
1334 return NULL;
1335 return tsp->smk_rules.next;
1336}
1337
1338static void *load_self_seq_next(struct seq_file *s, void *v, loff_t *pos)
1339{
1340 struct task_smack *tsp = current_security();
1341 struct list_head *list = v;
1342
1343 if (list_is_last(list, &tsp->smk_rules)) {
1344 *pos = SEQ_READ_FINISHED;
1345 return NULL;
1346 }
1347 return list->next;
1348}
1349
1350static int load_self_seq_show(struct seq_file *s, void *v)
1351{
1352 struct list_head *list = v;
1353 struct smack_rule *srp =
1354 list_entry(list, struct smack_rule, list);
1355
1356 seq_printf(s, "%s %s", (char *)srp->smk_subject,
1357 (char *)srp->smk_object);
1358
1359 seq_putc(s, ' ');
1360
1361 if (srp->smk_access & MAY_READ)
1362 seq_putc(s, 'r');
1363 if (srp->smk_access & MAY_WRITE)
1364 seq_putc(s, 'w');
1365 if (srp->smk_access & MAY_EXEC)
1366 seq_putc(s, 'x');
1367 if (srp->smk_access & MAY_APPEND)
1368 seq_putc(s, 'a');
1369 if (srp->smk_access & MAY_TRANSMUTE)
1370 seq_putc(s, 't');
1371 if (srp->smk_access == 0)
1372 seq_putc(s, '-');
1373
1374 seq_putc(s, '\n');
1375
1376 return 0;
1377}
1378
1379static void load_self_seq_stop(struct seq_file *s, void *v)
1380{
1381 /* No-op */
1382}
1383
1384static const struct seq_operations load_self_seq_ops = {
1385 .start = load_self_seq_start,
1386 .next = load_self_seq_next,
1387 .show = load_self_seq_show,
1388 .stop = load_self_seq_stop,
1389};
1390
1391
1392/**
1393 * smk_open_load_self - open() for /smack/load-self
1394 * @inode: inode structure representing file
1395 * @file: "load" file pointer
1396 *
1397 * For reading, use load_seq_* seq_file reading operations.
1398 */
1399static int smk_open_load_self(struct inode *inode, struct file *file)
1400{
1401 return seq_open(file, &load_self_seq_ops);
1402}
1403
1404/**
1405 * smk_write_load_self - write() for /smack/load-self
1406 * @file: file pointer, not actually used
1407 * @buf: where to get the data from
1408 * @count: bytes sent
1409 * @ppos: where to start - must be 0
1410 *
1411 */
1412static ssize_t smk_write_load_self(struct file *file, const char __user *buf,
1413 size_t count, loff_t *ppos)
1414{
1415 struct task_smack *tsp = current_security();
1416
1417 return smk_write_load_list(file, buf, count, ppos, &tsp->smk_rules,
1418 &tsp->smk_rules_lock);
1419}
1420
1421static const struct file_operations smk_load_self_ops = {
1422 .open = smk_open_load_self,
1423 .read = seq_read,
1424 .llseek = seq_lseek,
1425 .write = smk_write_load_self,
1426 .release = seq_release,
1258}; 1427};
1259/** 1428/**
1260 * smk_fill_super - fill the /smackfs superblock 1429 * smk_fill_super - fill the /smackfs superblock
@@ -1272,23 +1441,26 @@ static int smk_fill_super(struct super_block *sb, void *data, int silent)
1272 struct inode *root_inode; 1441 struct inode *root_inode;
1273 1442
1274 static struct tree_descr smack_files[] = { 1443 static struct tree_descr smack_files[] = {
1275 [SMK_LOAD] = 1444 [SMK_LOAD] = {
1276 {"load", &smk_load_ops, S_IRUGO|S_IWUSR}, 1445 "load", &smk_load_ops, S_IRUGO|S_IWUSR},
1277 [SMK_CIPSO] = 1446 [SMK_CIPSO] = {
1278 {"cipso", &smk_cipso_ops, S_IRUGO|S_IWUSR}, 1447 "cipso", &smk_cipso_ops, S_IRUGO|S_IWUSR},
1279 [SMK_DOI] = 1448 [SMK_DOI] = {
1280 {"doi", &smk_doi_ops, S_IRUGO|S_IWUSR}, 1449 "doi", &smk_doi_ops, S_IRUGO|S_IWUSR},
1281 [SMK_DIRECT] = 1450 [SMK_DIRECT] = {
1282 {"direct", &smk_direct_ops, S_IRUGO|S_IWUSR}, 1451 "direct", &smk_direct_ops, S_IRUGO|S_IWUSR},
1283 [SMK_AMBIENT] = 1452 [SMK_AMBIENT] = {
1284 {"ambient", &smk_ambient_ops, S_IRUGO|S_IWUSR}, 1453 "ambient", &smk_ambient_ops, S_IRUGO|S_IWUSR},
1285 [SMK_NETLBLADDR] = 1454 [SMK_NETLBLADDR] = {
1286 {"netlabel", &smk_netlbladdr_ops, S_IRUGO|S_IWUSR}, 1455 "netlabel", &smk_netlbladdr_ops, S_IRUGO|S_IWUSR},
1287 [SMK_ONLYCAP] = 1456 [SMK_ONLYCAP] = {
1288 {"onlycap", &smk_onlycap_ops, S_IRUGO|S_IWUSR}, 1457 "onlycap", &smk_onlycap_ops, S_IRUGO|S_IWUSR},
1289 [SMK_LOGGING] = 1458 [SMK_LOGGING] = {
1290 {"logging", &smk_logging_ops, S_IRUGO|S_IWUSR}, 1459 "logging", &smk_logging_ops, S_IRUGO|S_IWUSR},
1291 /* last one */ {""} 1460 [SMK_LOAD_SELF] = {
1461 "load-self", &smk_load_self_ops, S_IRUGO|S_IWUGO},
1462 /* last one */
1463 {""}
1292 }; 1464 };
1293 1465
1294 rc = simple_fill_super(sb, SMACK_MAGIC, smack_files); 1466 rc = simple_fill_super(sb, SMACK_MAGIC, smack_files);
@@ -1305,27 +1477,25 @@ static int smk_fill_super(struct super_block *sb, void *data, int silent)
1305} 1477}
1306 1478
1307/** 1479/**
1308 * smk_get_sb - get the smackfs superblock 1480 * smk_mount - get the smackfs superblock
1309 * @fs_type: passed along without comment 1481 * @fs_type: passed along without comment
1310 * @flags: passed along without comment 1482 * @flags: passed along without comment
1311 * @dev_name: passed along without comment 1483 * @dev_name: passed along without comment
1312 * @data: passed along without comment 1484 * @data: passed along without comment
1313 * @mnt: passed along without comment
1314 * 1485 *
1315 * Just passes everything along. 1486 * Just passes everything along.
1316 * 1487 *
1317 * Returns what the lower level code does. 1488 * Returns what the lower level code does.
1318 */ 1489 */
1319static int smk_get_sb(struct file_system_type *fs_type, 1490static struct dentry *smk_mount(struct file_system_type *fs_type,
1320 int flags, const char *dev_name, void *data, 1491 int flags, const char *dev_name, void *data)
1321 struct vfsmount *mnt)
1322{ 1492{
1323 return get_sb_single(fs_type, flags, data, smk_fill_super, mnt); 1493 return mount_single(fs_type, flags, data, smk_fill_super);
1324} 1494}
1325 1495
1326static struct file_system_type smk_fs_type = { 1496static struct file_system_type smk_fs_type = {
1327 .name = "smackfs", 1497 .name = "smackfs",
1328 .get_sb = smk_get_sb, 1498 .mount = smk_mount,
1329 .kill_sb = kill_litter_super, 1499 .kill_sb = kill_litter_super,
1330}; 1500};
1331 1501
diff --git a/security/tomoyo/common.c b/security/tomoyo/common.c
index c668b447c725..a0d09e56874b 100644
--- a/security/tomoyo/common.c
+++ b/security/tomoyo/common.c
@@ -108,10 +108,9 @@ static bool tomoyo_flush(struct tomoyo_io_buffer *head)
108 head->read_user_buf += len; 108 head->read_user_buf += len;
109 w += len; 109 w += len;
110 } 110 }
111 if (*w) { 111 head->r.w[0] = w;
112 head->r.w[0] = w; 112 if (*w)
113 return false; 113 return false;
114 }
115 /* Add '\0' for query. */ 114 /* Add '\0' for query. */
116 if (head->poll) { 115 if (head->poll) {
117 if (!head->read_user_buf_avail || 116 if (!head->read_user_buf_avail ||
@@ -459,8 +458,16 @@ static int tomoyo_write_profile(struct tomoyo_io_buffer *head)
459 if (profile == &tomoyo_default_profile) 458 if (profile == &tomoyo_default_profile)
460 return -EINVAL; 459 return -EINVAL;
461 if (!strcmp(data, "COMMENT")) { 460 if (!strcmp(data, "COMMENT")) {
462 const struct tomoyo_path_info *old_comment = profile->comment; 461 static DEFINE_SPINLOCK(lock);
463 profile->comment = tomoyo_get_name(cp); 462 const struct tomoyo_path_info *new_comment
463 = tomoyo_get_name(cp);
464 const struct tomoyo_path_info *old_comment;
465 if (!new_comment)
466 return -ENOMEM;
467 spin_lock(&lock);
468 old_comment = profile->comment;
469 profile->comment = new_comment;
470 spin_unlock(&lock);
464 tomoyo_put_name(old_comment); 471 tomoyo_put_name(old_comment);
465 return 0; 472 return 0;
466 } 473 }
@@ -768,8 +775,10 @@ static bool tomoyo_select_one(struct tomoyo_io_buffer *head, const char *data)
768 return true; /* Do nothing if open(O_WRONLY). */ 775 return true; /* Do nothing if open(O_WRONLY). */
769 memset(&head->r, 0, sizeof(head->r)); 776 memset(&head->r, 0, sizeof(head->r));
770 head->r.print_this_domain_only = true; 777 head->r.print_this_domain_only = true;
771 head->r.eof = !domain; 778 if (domain)
772 head->r.domain = &domain->list; 779 head->r.domain = &domain->list;
780 else
781 head->r.eof = 1;
773 tomoyo_io_printf(head, "# select %s\n", data); 782 tomoyo_io_printf(head, "# select %s\n", data);
774 if (domain && domain->is_deleted) 783 if (domain && domain->is_deleted)
775 tomoyo_io_printf(head, "# This is a deleted domain.\n"); 784 tomoyo_io_printf(head, "# This is a deleted domain.\n");
@@ -2051,13 +2060,22 @@ void tomoyo_check_profile(void)
2051 const u8 profile = domain->profile; 2060 const u8 profile = domain->profile;
2052 if (tomoyo_profile_ptr[profile]) 2061 if (tomoyo_profile_ptr[profile])
2053 continue; 2062 continue;
2063 printk(KERN_ERR "You need to define profile %u before using it.\n",
2064 profile);
2065 printk(KERN_ERR "Please see http://tomoyo.sourceforge.jp/2.3/ "
2066 "for more information.\n");
2054 panic("Profile %u (used by '%s') not defined.\n", 2067 panic("Profile %u (used by '%s') not defined.\n",
2055 profile, domain->domainname->name); 2068 profile, domain->domainname->name);
2056 } 2069 }
2057 tomoyo_read_unlock(idx); 2070 tomoyo_read_unlock(idx);
2058 if (tomoyo_profile_version != 20090903) 2071 if (tomoyo_profile_version != 20090903) {
2072 printk(KERN_ERR "You need to install userland programs for "
2073 "TOMOYO 2.3 and initialize policy configuration.\n");
2074 printk(KERN_ERR "Please see http://tomoyo.sourceforge.jp/2.3/ "
2075 "for more information.\n");
2059 panic("Profile version %u is not supported.\n", 2076 panic("Profile version %u is not supported.\n",
2060 tomoyo_profile_version); 2077 tomoyo_profile_version);
2078 }
2061 printk(KERN_INFO "TOMOYO: 2.3.0\n"); 2079 printk(KERN_INFO "TOMOYO: 2.3.0\n");
2062 printk(KERN_INFO "Mandatory Access Control activated.\n"); 2080 printk(KERN_INFO "Mandatory Access Control activated.\n");
2063} 2081}
diff --git a/security/tomoyo/file.c b/security/tomoyo/file.c
index 9d32f182301e..d64e8ecb6fb3 100644
--- a/security/tomoyo/file.c
+++ b/security/tomoyo/file.c
@@ -927,7 +927,7 @@ int tomoyo_check_open_permission(struct tomoyo_domain_info *domain,
927 struct path *path, const int flag) 927 struct path *path, const int flag)
928{ 928{
929 const u8 acc_mode = ACC_MODE(flag); 929 const u8 acc_mode = ACC_MODE(flag);
930 int error = -ENOMEM; 930 int error = 0;
931 struct tomoyo_path_info buf; 931 struct tomoyo_path_info buf;
932 struct tomoyo_request_info r; 932 struct tomoyo_request_info r;
933 int idx; 933 int idx;
@@ -938,9 +938,6 @@ int tomoyo_check_open_permission(struct tomoyo_domain_info *domain,
938 buf.name = NULL; 938 buf.name = NULL;
939 r.mode = TOMOYO_CONFIG_DISABLED; 939 r.mode = TOMOYO_CONFIG_DISABLED;
940 idx = tomoyo_read_lock(); 940 idx = tomoyo_read_lock();
941 if (!tomoyo_get_realpath(&buf, path))
942 goto out;
943 error = 0;
944 /* 941 /*
945 * If the filename is specified by "deny_rewrite" keyword, 942 * If the filename is specified by "deny_rewrite" keyword,
946 * we need to check "allow_rewrite" permission when the filename is not 943 * we need to check "allow_rewrite" permission when the filename is not
@@ -1014,7 +1011,6 @@ int tomoyo_path_perm(const u8 operation, struct path *path)
1014 break; 1011 break;
1015 case TOMOYO_TYPE_RMDIR: 1012 case TOMOYO_TYPE_RMDIR:
1016 case TOMOYO_TYPE_CHROOT: 1013 case TOMOYO_TYPE_CHROOT:
1017 case TOMOYO_TYPE_UMOUNT:
1018 tomoyo_add_slash(&buf); 1014 tomoyo_add_slash(&buf);
1019 break; 1015 break;
1020 } 1016 }
diff --git a/security/tomoyo/load_policy.c b/security/tomoyo/load_policy.c
index bbada7ca1b91..3312e5624f24 100644
--- a/security/tomoyo/load_policy.c
+++ b/security/tomoyo/load_policy.c
@@ -23,7 +23,7 @@ static bool tomoyo_policy_loader_exists(void)
23 * If the initrd includes /sbin/init but real-root-dev has not 23 * If the initrd includes /sbin/init but real-root-dev has not
24 * mounted on / yet, activating MAC will block the system since 24 * mounted on / yet, activating MAC will block the system since
25 * policies are not loaded yet. 25 * policies are not loaded yet.
26 * Thus, let do_execve() call this function everytime. 26 * Thus, let do_execve() call this function every time.
27 */ 27 */
28 struct path path; 28 struct path path;
29 29
diff --git a/security/tomoyo/memory.c b/security/tomoyo/memory.c
index 297612669c74..42a7b1ba8cbf 100644
--- a/security/tomoyo/memory.c
+++ b/security/tomoyo/memory.c
@@ -75,6 +75,7 @@ void *tomoyo_commit_ok(void *data, const unsigned int size)
75 memset(data, 0, size); 75 memset(data, 0, size);
76 return ptr; 76 return ptr;
77 } 77 }
78 kfree(ptr);
78 return NULL; 79 return NULL;
79} 80}
80 81
diff --git a/security/tomoyo/mount.c b/security/tomoyo/mount.c
index 82bf8c2390bc..9fc2e15841c9 100644
--- a/security/tomoyo/mount.c
+++ b/security/tomoyo/mount.c
@@ -138,11 +138,12 @@ static int tomoyo_mount_acl(struct tomoyo_request_info *r, char *dev_name,
138 } 138 }
139 if (need_dev) { 139 if (need_dev) {
140 /* Get mount point or device file. */ 140 /* Get mount point or device file. */
141 if (kern_path(dev_name, LOOKUP_FOLLOW, &path)) { 141 if (!dev_name || kern_path(dev_name, LOOKUP_FOLLOW, &path)) {
142 error = -ENOENT; 142 error = -ENOENT;
143 goto out; 143 goto out;
144 } 144 }
145 requested_dev_name = tomoyo_realpath_from_path(&path); 145 requested_dev_name = tomoyo_realpath_from_path(&path);
146 path_put(&path);
146 if (!requested_dev_name) { 147 if (!requested_dev_name) {
147 error = -ENOENT; 148 error = -ENOENT;
148 goto out; 149 goto out;
diff --git a/security/tomoyo/realpath.c b/security/tomoyo/realpath.c
index ed8ccd680102..d1e05b047715 100644
--- a/security/tomoyo/realpath.c
+++ b/security/tomoyo/realpath.c
@@ -14,6 +14,7 @@
14#include <linux/slab.h> 14#include <linux/slab.h>
15#include <net/sock.h> 15#include <net/sock.h>
16#include "common.h" 16#include "common.h"
17#include "../../fs/internal.h"
17 18
18/** 19/**
19 * tomoyo_encode: Convert binary string to ascii string. 20 * tomoyo_encode: Convert binary string to ascii string.
@@ -127,10 +128,8 @@ char *tomoyo_realpath_from_path(struct path *path)
127 /* If we don't have a vfsmount, we can't calculate. */ 128 /* If we don't have a vfsmount, we can't calculate. */
128 if (!path->mnt) 129 if (!path->mnt)
129 break; 130 break;
130 spin_lock(&dcache_lock);
131 /* go to whatever namespace root we are under */ 131 /* go to whatever namespace root we are under */
132 pos = __d_path(path, &ns_root, buf, buf_len); 132 pos = __d_path(path, &ns_root, buf, buf_len);
133 spin_unlock(&dcache_lock);
134 /* Prepend "/proc" prefix if using internal proc vfs mount. */ 133 /* Prepend "/proc" prefix if using internal proc vfs mount. */
135 if (!IS_ERR(pos) && (path->mnt->mnt_flags & MNT_INTERNAL) && 134 if (!IS_ERR(pos) && (path->mnt->mnt_flags & MNT_INTERNAL) &&
136 (path->mnt->mnt_sb->s_magic == PROC_SUPER_MAGIC)) { 135 (path->mnt->mnt_sb->s_magic == PROC_SUPER_MAGIC)) {
diff --git a/security/tomoyo/util.c b/security/tomoyo/util.c
index 9bfc1ee8222d..6d5393204d95 100644
--- a/security/tomoyo/util.c
+++ b/security/tomoyo/util.c
@@ -390,7 +390,7 @@ bool tomoyo_correct_domain(const unsigned char *domainname)
390 if (!cp) 390 if (!cp)
391 break; 391 break;
392 if (*domainname != '/' || 392 if (*domainname != '/' ||
393 !tomoyo_correct_word2(domainname, cp - domainname - 1)) 393 !tomoyo_correct_word2(domainname, cp - domainname))
394 goto out; 394 goto out;
395 domainname = cp + 1; 395 domainname = cp + 1;
396 } 396 }