Skip to contentSkip to conversation

selinux: fix variable scope issue in live sidtab conversion

PATCH In review Ondrej Mosnacek 2 participants 4 messages Feb 8, 2021 – Feb 10, 2021 SELinux security module

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 selinux: fix variable scope issue in live sidtab conversion

Commit 02a52c5c8c3b ("selinux: move policy commit after updating selinuxfs") moved the selinux_policy_commit() call out of security_load_policy() into sel_write_load(), which caused a subtle yet rather serious bug.

The problem is that security_load_policy() passes a reference to the convert_params local variable to sidtab_convert(), which stores it in the sidtab, where it may be accessed until the policy is swapped over and RCU synchronized. Before 02a52c5c8c3b, selinux_policy_commit() was called directly from security_load_policy(), so the convert_params pointer remained valid all the way until the old sidtab was destroyed, but now that's no longer the case and calls to sidtab_context_to_sid() on the old sidtab after security_load_policy() returns may cause invalid memory accesses.

This can be easily triggered using the stress test from commit ee1a84fdfeed ("selinux: overhaul sidtab to fix bug and improve performance"):

```
function rand_cat() {
	echo $(( $RANDOM % 1024 ))
}

function do_work() {
	while true; do
		echo -n "system_u:system_r:kernel_t:s0:c$(rand_cat),c$(rand_cat)" \
			>/sys/fs/selinux/context 2>/dev/null || true
	done
}

do_work >/dev/null &
do_work >/dev/null &
do_work >/dev/null &

while load_policy; do echo -n .; sleep 0.1; done

kill %1
kill %2
kill %3
```

There are several ways to fix this:
1. Move the sidtab convert parameters to struct selinux_policy. Pros:
* simple change
Cons:
* added fields not used during most of the object's lifetime
2. Move the sidtab convert params to sel_write_load().
Pros:
* (nothing specific)
Cons:
* layering violation, a lot of types would have to be exposed to selinuxfs.c
3. Merge policy load functions back into one and call sel_make_policy_nodes() as a callback.
Pros:
* results in simpler code
Cons:
* introduces an indirect call (not in hot path, so should be okay)

I chose to implement option (3.), because IMHO it results in the least ugly code and has the least bad drawback.

Note that this commit also fixes the minor issue of logging a MAC_POLICY_LOAD audit record in case sel_make_policy_nodes() fails (in which case the new policy isn't actually loaded).

Fixes 02a52c5c8c3b ("selinux: move policy commit after updating selinuxfs")
---
 security/selinux/include/security.h |  10 +-
 security/selinux/selinuxfs.c        |  18 +---
 security/selinux/ss/services.c      | 159 ++++++++++++----------------
 3 files changed, 78 insertions(+), 109 deletions(-)
security/selinux/include/security.h +4 -6
index 765a258a899e..9b1bcecad6ef 100644
@@ -221,12 +221,10 @@ static inline bool selinux_policycap_genfs_seclabel_symlinks(void)
 
 int security_mls_enabled(struct selinux_state *state);
 int security_load_policy(struct selinux_state *state,
-			void *data, size_t len,
-			struct selinux_policy **newpolicyp);
-void selinux_policy_commit(struct selinux_state *state,
-			struct selinux_policy *newpolicy);
-void selinux_policy_cancel(struct selinux_state *state,
-			struct selinux_policy *policy);
+			 void *data, size_t len,
+			 int (*setup_func)(struct selinux_policy *newpolicy,
+					   void *args),
+			 void *args);
 int security_read_policy(struct selinux_state *state,
 			 void **data, size_t *len);
 
security/selinux/selinuxfs.c +5 -13
index 01a7d50ed39b..1a9ef1a010e6 100644
@@ -533,9 +533,9 @@ static void sel_remove_old_bool_data(unsigned int bool_num, char **bool_names,
 	kfree(bool_values);
 }
 
-static int sel_make_policy_nodes(struct selinux_fs_info *fsi,
-				struct selinux_policy *newpolicy)
+static int sel_make_policy_nodes(struct selinux_policy *newpolicy, void *args)
 {
+	struct selinux_fs_info *fsi = args;
 	int ret = 0;
 	struct dentry *tmp_parent, *tmp_bool_dir, *tmp_class_dir, *old_dentry;
 	unsigned int tmp_bool_num, old_bool_num;
@@ -616,7 +616,6 @@ static ssize_t sel_write_load(struct file *file, const char __user *buf,
 
 {
 	struct selinux_fs_info *fsi = file_inode(file)->i_sb->s_fs_info;
-	struct selinux_policy *newpolicy;
 	ssize_t length;
 	void *data = NULL;
 
@@ -642,27 +641,20 @@ static ssize_t sel_write_load(struct file *file, const char __user *buf,
 	if (copy_from_user(data, buf, count) != 0)
 		goto out;
 
-	length = security_load_policy(fsi->state, data, count, &newpolicy);
+	length = security_load_policy(fsi->state, data, count,
+				      sel_make_policy_nodes, fsi);
 	if (length) {
 		pr_warn_ratelimited("SELinux: failed to load policy\n");
 		goto out;
 	}
 
-	length = sel_make_policy_nodes(fsi, newpolicy);
-	if (length) {
-		selinux_policy_cancel(fsi->state, newpolicy);
-		goto out1;
-	}
-
-	selinux_policy_commit(fsi->state, newpolicy);
-
 	length = count;
 
-out1:
 	audit_log(audit_context(), GFP_KERNEL, AUDIT_MAC_POLICY_LOAD,
 		"auid=%u ses=%u lsm=selinux res=1",
 		from_kuid(&init_user_ns, audit_get_loginuid(current)),
 		audit_get_sessionid(current));
+
 out:
 	mutex_unlock(&fsi->state->policy_mutex);
 	vfree(data);
security/selinux/ss/services.c +69 -90

197 lines not on this page · raw message

Signature · 1 line
2.29.2
maintainer
#1 lore raw
Quoted 68 lines · Ondrej Mosnacek

Commit 02a52c5c8c3b ("selinux: move policy commit after updating selinuxfs") moved the selinux_policy_commit() call out of security_load_policy() into sel_write_load(), which caused a subtle yet rather serious bug.

The problem is that security_load_policy() passes a reference to the convert_params local variable to sidtab_convert(), which stores it in the sidtab, where it may be accessed until the policy is swapped over and RCU synchronized. Before 02a52c5c8c3b, selinux_policy_commit() was called directly from security_load_policy(), so the convert_params pointer remained valid all the way until the old sidtab was destroyed, but now that's no longer the case and calls to sidtab_context_to_sid() on the old sidtab after security_load_policy() returns may cause invalid memory accesses.

This can be easily triggered using the stress test from commit ee1a84fdfeed ("selinux: overhaul sidtab to fix bug and improve performance"):

```
function rand_cat() {
        echo $(( $RANDOM % 1024 ))
}

function do_work() {
        while true; do
                echo -n "system_u:system_r:kernel_t:s0:c$(rand_cat),c$(rand_cat)" \
                        >/sys/fs/selinux/context 2>/dev/null || true
        done
}

do_work >/dev/null &
do_work >/dev/null &
do_work >/dev/null &

while load_policy; do echo -n .; sleep 0.1; done

kill %1
kill %2
kill %3
```

There are several ways to fix this:
1. Move the sidtab convert parameters to struct selinux_policy. Pros:
* simple change
Cons:
* added fields not used during most of the object's lifetime
2. Move the sidtab convert params to sel_write_load().
Pros:
* (nothing specific)
Cons:
* layering violation, a lot of types would have to be exposed to selinuxfs.c
3. Merge policy load functions back into one and call sel_make_policy_nodes() as a callback.
Pros:
* results in simpler code
Cons:
* introduces an indirect call (not in hot path, so should be okay)

I chose to implement option (3.), because IMHO it results in the least ugly code and has the least bad drawback.

Note that this commit also fixes the minor issue of logging a MAC_POLICY_LOAD audit record in case sel_make_policy_nodes() fails (in which case the new policy isn't actually loaded).

Quoted 7 lines
Fixes 02a52c5c8c3b ("selinux: move policy commit after updating selinuxfs")
---
 security/selinux/include/security.h |  10 +-
 security/selinux/selinuxfs.c        |  18 +---
 security/selinux/ss/services.c      | 159 ++++++++++++----------------
 3 files changed, 78 insertions(+), 109 deletions(-)

My concern is that this is something that should be backported to -stable and I wonder if there is an easier way. Since the core issue appears to be the scope/lifetime of the stdtab->convert field, and since the ->convert field is a struct with only three pointers, why not either embed a copy of the sidtab_convert_params struct in the sidtab struct (net increase in two pointers), or do a memdup() (or similar) into the sidtab->convert in sidtab_convert(). There would need to be some minor additional work in the latter case, but I imagine adding a kfree() to sidtab_cancel_convert() and calling sidtab_cancel_convert() in selinux_policy_commit() should be the bulk of the changes.

Am I missing something, is there a good reason why it isn't that easy?

Signature · 2 lines
paul moore
www.paul-moore.com
#2 lore raw
Quoted 77 lines · Paul Moore
Quoted 68 lines · Ondrej Mosnacek

Commit 02a52c5c8c3b ("selinux: move policy commit after updating selinuxfs") moved the selinux_policy_commit() call out of security_load_policy() into sel_write_load(), which caused a subtle yet rather serious bug.

The problem is that security_load_policy() passes a reference to the convert_params local variable to sidtab_convert(), which stores it in the sidtab, where it may be accessed until the policy is swapped over and RCU synchronized. Before 02a52c5c8c3b, selinux_policy_commit() was called directly from security_load_policy(), so the convert_params pointer remained valid all the way until the old sidtab was destroyed, but now that's no longer the case and calls to sidtab_context_to_sid() on the old sidtab after security_load_policy() returns may cause invalid memory accesses.

This can be easily triggered using the stress test from commit ee1a84fdfeed ("selinux: overhaul sidtab to fix bug and improve performance"):

```
function rand_cat() {
        echo $(( $RANDOM % 1024 ))
}

function do_work() {
        while true; do
                echo -n "system_u:system_r:kernel_t:s0:c$(rand_cat),c$(rand_cat)" \
                        >/sys/fs/selinux/context 2>/dev/null || true
        done
}

do_work >/dev/null &
do_work >/dev/null &
do_work >/dev/null &

while load_policy; do echo -n .; sleep 0.1; done

kill %1
kill %2
kill %3
```

There are several ways to fix this:
1. Move the sidtab convert parameters to struct selinux_policy. Pros:
* simple change
Cons:
* added fields not used during most of the object's lifetime
2. Move the sidtab convert params to sel_write_load().
Pros:
* (nothing specific)
Cons:
* layering violation, a lot of types would have to be exposed to selinuxfs.c
3. Merge policy load functions back into one and call sel_make_policy_nodes() as a callback.
Pros:
* results in simpler code
Cons:
* introduces an indirect call (not in hot path, so should be okay)

I chose to implement option (3.), because IMHO it results in the least ugly code and has the least bad drawback.

Note that this commit also fixes the minor issue of logging a MAC_POLICY_LOAD audit record in case sel_make_policy_nodes() fails (in which case the new policy isn't actually loaded).

Quoted 7 lines
Fixes 02a52c5c8c3b ("selinux: move policy commit after updating selinuxfs")
---
 security/selinux/include/security.h |  10 +-
 security/selinux/selinuxfs.c        |  18 +---
 security/selinux/ss/services.c      | 159 ++++++++++++----------------
 3 files changed, 78 insertions(+), 109 deletions(-)
Quoted 2 lines

My concern is that this is something that should be backported to -stable and I wonder if there is an easier way.

This would need to go only into 5.10 (and 5.11 depending on the timing), so I think it should still apply cleanly. But there is additional value in having small patches for stable (less likelihood of mistake), so I'll try to revisit it...

Quoted 5 lines

Since the core issue
appears to be the scope/lifetime of the stdtab->convert field, and since the ->convert field is a struct with only three pointers, why not either embed a copy of the sidtab_convert_params struct in the sidtab struct (net increase in two pointers),

This has a hidden catch - also the convert_context_args would need to be embedded and that has pointers to policydb and selinux_state, which sidtab currently doesn't "know about" (i.e. it would slightly break the abstraction).

Quoted 6 lines

or do a memdup() (or
similar) into the sidtab->convert in sidtab_convert(). There would need to be some minor additional work in the latter case, but I imagine adding a kfree() to sidtab_cancel_convert() and calling sidtab_cancel_convert() in selinux_policy_commit() should be the bulk of the changes.

This should be possible and relatively easy. I forgot to list it in the options - my only problem with that was the unnecessary dynamic allocation, but i concur that keeping the patch small is more important in this case. I'll try to do it this way in v2.

Signature · 3 lines
Ondrej Mosnacek
Software Engineer, Linux Security - SELinux kernel
Red Hat, Inc.
maintainer
#3 lore raw
Quoted 78 lines · Ondrej Mosnacek
Quoted 77 lines · Paul Moore
Quoted 75 lines · Ondrej Mosnacek

Commit 02a52c5c8c3b ("selinux: move policy commit after updating selinuxfs") moved the selinux_policy_commit() call out of security_load_policy() into sel_write_load(), which caused a subtle yet rather serious bug.

The problem is that security_load_policy() passes a reference to the convert_params local variable to sidtab_convert(), which stores it in the sidtab, where it may be accessed until the policy is swapped over and RCU synchronized. Before 02a52c5c8c3b, selinux_policy_commit() was called directly from security_load_policy(), so the convert_params pointer remained valid all the way until the old sidtab was destroyed, but now that's no longer the case and calls to sidtab_context_to_sid() on the old sidtab after security_load_policy() returns may cause invalid memory accesses.

This can be easily triggered using the stress test from commit ee1a84fdfeed ("selinux: overhaul sidtab to fix bug and improve performance"):

```
function rand_cat() {
        echo $(( $RANDOM % 1024 ))
}

function do_work() {
        while true; do
                echo -n "system_u:system_r:kernel_t:s0:c$(rand_cat),c$(rand_cat)" \
                        >/sys/fs/selinux/context 2>/dev/null || true
        done
}

do_work >/dev/null &
do_work >/dev/null &
do_work >/dev/null &

while load_policy; do echo -n .; sleep 0.1; done

kill %1
kill %2
kill %3
```

There are several ways to fix this:
1. Move the sidtab convert parameters to struct selinux_policy. Pros:
* simple change
Cons:
* added fields not used during most of the object's lifetime
2. Move the sidtab convert params to sel_write_load().
Pros:
* (nothing specific)
Cons:
* layering violation, a lot of types would have to be exposed to selinuxfs.c
3. Merge policy load functions back into one and call sel_make_policy_nodes() as a callback.
Pros:
* results in simpler code
Cons:
* introduces an indirect call (not in hot path, so should be okay)

I chose to implement option (3.), because IMHO it results in the least ugly code and has the least bad drawback.

Note that this commit also fixes the minor issue of logging a MAC_POLICY_LOAD audit record in case sel_make_policy_nodes() fails (in which case the new policy isn't actually loaded).

Fixes 02a52c5c8c3b ("selinux: move policy commit after updating selinuxfs")
---
 security/selinux/include/security.h |  10 +-
 security/selinux/selinuxfs.c        |  18 +---
 security/selinux/ss/services.c      | 159 ++++++++++++----------------
 3 files changed, 78 insertions(+), 109 deletions(-)
Quoted 7 lines
Quoted 2 lines

My concern is that this is something that should be backported to -stable and I wonder if there is an easier way.

This would need to go only into 5.10 (and 5.11 depending on the timing), so I think it should still apply cleanly. But there is additional value in having small patches for stable (less likelihood of mistake), so I'll try to revisit it...

Aiming for a simple solution first is generally a good first approach; things almost always get more complex as they progress :)

Quoted 10 lines
Quoted 5 lines

Since the core issue
appears to be the scope/lifetime of the stdtab->convert field, and since the ->convert field is a struct with only three pointers, why not either embed a copy of the sidtab_convert_params struct in the sidtab struct (net increase in two pointers),

This has a hidden catch - also the convert_context_args would need to be embedded and that has pointers to policydb and selinux_state, which sidtab currently doesn't "know about" (i.e. it would slightly break the abstraction).

Fair point.

Quoted 11 lines
Quoted 6 lines

or do a memdup() (or
similar) into the sidtab->convert in sidtab_convert(). There would need to be some minor additional work in the latter case, but I imagine adding a kfree() to sidtab_cancel_convert() and calling sidtab_cancel_convert() in selinux_policy_commit() should be the bulk of the changes.

This should be possible and relatively easy. I forgot to list it in the options - my only problem with that was the unnecessary dynamic allocation, but i concur that keeping the patch small is more important in this case. I'll try to do it this way in v2.

I'm not that worried about the allocation, in security_load_policy() we're already allocating both a new policy and a new sidtab with GFP_KERNEL so we are already looking at delays when under memory pressure (which is okay in this case). I view this as more desirable than the approach taken in your first patch.

If we wanted to try and reduce our calls to kzalloc() we could always allocate the new policy, sidtab, and convert_context_args structs in one block via one kzalloc() call. The drawback would be that we would be allocating a bit more memory than we would need for normal usage (the convert struct space would generally be wasted), and I guess there might be an increased chance of the allocation taking the slow path since the chunk would be larger. Likely not worth pursuing unless we see real memory problems in the future.

Signature · 2 lines
paul moore
www.paul-moore.com