Skip to contentSkip to conversation

Make selinux_check_access() thread-safe

RFC PATCH Superseded Stephen Smalley 1 participant 4 messages Jun 12 SELinux security module

v2 of 3 Superseded Latest is v3 →

lore
Share & tools
lore

Stephen Smalley

author maintainer
#0 lore raw

v2 cover Make selinux_check_access() thread-safe

This is a RFC-only series targeting merge after the 3.11 release.

This series tries to address the same thread-safety issues for selinux_check_access(3) previously raised in 2021 by the following mailing list links and GitHub issues/pull requests:

[1] https://github.com/SELinuxProject/selinux/issues/287
[2] https://lore.kernel.org/selinux/CAJsHiNx1E7x1jaBkS0i4L1nBWXp8YXLHRWcCaDaH4LOn=zm+Zw@mail.gmail.com/
[3] https://github.com/SELinuxProject/selinux/issues/335
[4] https://github.com/SELinuxProject/selinux/pull/336
[5] https://lore.kernel.org/selinux/[email protected]/

v2 makes some improvements to each of the three patches, noted in each one.

Stephen Smalley (3):
libselinux: avc: use pthread mutexes by default when no lock callbacks
set
libselinux: stringrep: serialize access to the discover_class_cache
libselinux: sestatus: serialize selinux status updates

 libselinux/src/avc_internal.h |  19 +++++-
 libselinux/src/sestatus.c     |  49 +++++++++++---
 libselinux/src/stringrep.c    | 120 ++++++++++++++++++++++++----------
 3 files changed, 144 insertions(+), 44 deletions(-)
Signature · 1 line
2.54.0
author maintainer
#1 lore raw

RFC PATCH v2 1/3 libselinux: avc: use pthread mutexes by default when no lock callbacks set

The AVC has a set of locking calls but defaults to no locking, and only the deprecated avc_init() allowed applications to set their own locking callbacks. Since selinux_check_access() is now commonly used by applications implementing userspace SELinux permission checks and it uses avc_open() internally, such calls are currently not thread-safe. Provide fallbacks to using pthread mutexes by default. Single-threaded programs that do not link -lpthread will be unaffected due to the existing __pthread_mutex() helpers. Applications that explicitly specify locking callbacks via the deprecated avc_init() will also be unaffected.

This is the first step toward a thread-safe selinux_check_access(); the class-string cache and status-page transition handling are addressed in follow-up changes.

---
v2 uses avc_malloc/avc_free when allocating the lock rather than direct malloc/free; this only makes a difference if the caller set their own avc malloc/free callbacks.

 libselinux/src/avc_internal.h | 19 ++++++++++++++++++-
 1 file changed, 18 insertions(+), 1 deletion(-)
libselinux/src/avc_internal.h +18 -1
index 719be934..3c21ffef 100644
@@ -14,6 +14,7 @@
 #include <string.h>
 #include <selinux/avc.h>
 #include "callbacks.h"
+#include "selinux_internal.h"
 
 /* callback pointers */
 extern void *(*avc_func_malloc)(size_t);
@@ -115,25 +116,41 @@ static inline void avc_stop_thread(void *thread)
 
 static inline void *avc_alloc_lock(void)
 {
-	return avc_func_alloc_lock ? avc_func_alloc_lock() : NULL;
+	pthread_mutex_t *m;
+
+	if (avc_func_alloc_lock)
+		return avc_func_alloc_lock();
+
+	m = avc_malloc(sizeof(*m));
+	if (m)
+		__pthread_mutex_init(m, NULL);
+	return m;
 }
 
 static inline void avc_get_lock(void *lock)
 {
 	if (avc_func_get_lock)
 		avc_func_get_lock(lock);
+	else if (lock)
+		__pthread_mutex_lock((pthread_mutex_t *)lock);
 }
 
 static inline void avc_release_lock(void *lock)
 {
 	if (avc_func_release_lock)
 		avc_func_release_lock(lock);
+	else if (lock)
+		__pthread_mutex_unlock((pthread_mutex_t *)lock);
 }
 
 static inline void avc_free_lock(void *lock)
 {
 	if (avc_func_free_lock)
 		avc_func_free_lock(lock);
+	else if (lock) {
+		__pthread_mutex_destroy((pthread_mutex_t *)lock);
+		avc_free(lock);
+	}
 }
 
 /* statistics helper routines */
Signature · 1 line
2.54.0
author maintainer
#2 lore raw

RFC PATCH v2 2/3 libselinux: stringrep: serialize access to the discover_class_cache

In reply to Stephen Smalley

The discover_class_cache list is accessed without locking by the string_to_*() and *_to_string() functions in libselinux for translating between string names and class/perm values, and returns pointers to strings within this list to callers. selinux_flush_class_cache() frees the list upon a policy reload, called by avc_process_policyload() from selinux_status_updated() and avc_netlink_process().

Make this safe for multi-threaded users by introducing and taking a mutex around the list accesses, and by moving flushed nodes to a retired list rather than freeing them so that returned string pointers remain valid. Given the infrequency of policy reloads, the relative stability of the class/perm mapping even across policy reloads, and the small amount of memory required, this seems a worthwhile tradeoff. If it becomes an issue, there are several options:
1. Only load/refresh new/modified class/permission names and values upon policy reload rather than flushing and reloading them all,
2. Provide a way to drain the retired list safely when the application knows it is no longer using any returned strings.

---
v2 fixes string_to_security_class() to return the value saved prior to unlocking, and to retry the cache lookup after taking the lock and free the new node if a match is found rather than inserting a duplicate.

 libselinux/src/stringrep.c | 120 +++++++++++++++++++++++++++----------
 1 file changed, 87 insertions(+), 33 deletions(-)
libselinux/src/stringrep.c +87 -33
index ec6fc637..cd9841ca 100644
@@ -27,7 +27,9 @@ struct discover_class_node {
 	struct discover_class_node *next;
 };
 
+static pthread_mutex_t discover_class_lock = PTHREAD_MUTEX_INITIALIZER;
 static struct discover_class_node *discover_class_cache = NULL;
+static struct discover_class_node *discover_class_retired = NULL;
 
 static struct discover_class_node *get_class_cache_entry_name(const char *s)
 {
@@ -156,9 +158,6 @@ static struct discover_class_node *discover_class(const char *s)
 	}
 	closedir(dir);
 
-	node->next = discover_class_cache;
-	discover_class_cache = node;
-
 	return node;
 
 err4:
@@ -176,41 +175,84 @@ err1:
 
 void selinux_flush_class_cache(void)
 {
-	struct discover_class_node *cur = discover_class_cache, *prev = NULL;
-	size_t i;
-
-	while (cur != NULL) {
-		free(cur->name);
-
-		for (i = 0; i < MAXVECTORS; i++)
-			free(cur->perms[i]);
-
-		free(cur->perms);
+	struct discover_class_node *head, *tail;
 
-		prev = cur;
-		cur = cur->next;
+	__pthread_mutex_lock(&discover_class_lock);
+	head = discover_class_cache;
+	discover_class_cache = NULL;
 
-		free(prev);
+	/*
+	 * Move old list to the retired chain rather than
+	 * freeing it; other threads may hold pointers to
+	 * class/perm strings within it returned by
+	 * security_class_to_string() and
+	 * security_av_perm_to_string(). This incurs a small
+	 * memory cost but given the infrequency of policy
+	 * reloads, it should never be significant. If
+	 * required, a new interface could be introduced to
+	 * allow the application to safely drain the retired
+	 * list when it knows it is safe to do so.
+	 */
+	if (head) {
+		tail = head;
+		while (tail->next)
+			tail = tail->next;
+		tail->next = discover_class_retired;
+		discover_class_retired = head;
 	}
-
-	discover_class_cache = NULL;
+	__pthread_mutex_unlock(&discover_class_lock);
 }
 
 security_class_t string_to_security_class(const char *s)
 {
-	struct discover_class_node *node;
+	struct discover_class_node *node, *retry;
+	security_class_t value;
+	size_t i;
 
+	__pthread_mutex_lock(&discover_class_lock);
 	node = get_class_cache_entry_name(s);
-	if (node == NULL) {
-		node = discover_class(s);
+	if (node) {
+		value = node->value;
+		__pthread_mutex_unlock(&discover_class_lock);
+		return map_class(value);
+	}
+	__pthread_mutex_unlock(&discover_class_lock);
 
-		if (node == NULL) {
-			errno = EINVAL;
-			return 0;
-		}
+	/* Discover outside of lock; reads selinuxfs */
+	node = discover_class(s);
+	if (node == NULL) {
+		errno = EINVAL;
+		return 0;
 	}
+	value = node->value;
+
+	/*
+	 * Retry cache lookup with lock held in case
+	 * another thread raced with us. If we don't
+	 * find it, add the new one; else use
+	 * the old one and free the new one.
+	 */
+	__pthread_mutex_lock(&discover_class_lock);
+	retry = get_class_cache_entry_name(s);
+	if (!retry) {
+		node->next = discover_class_cache;
+		discover_class_cache = node;
+	} else {
+		value = retry->value;
+		/*
+		 * We can only safely free node here
+		 * because it wasn't yet added to the cache.
+		 */
+		free(node->name);
+		for (i = 0; i < MAXVECTORS; i++)
+			free(node->perms[i]);
+		free(node->perms);
+		free(node);
+		node = NULL;
+	}
+	__pthread_mutex_unlock(&discover_class_lock);
 
-	return map_class(node->value);
+	return map_class(value);
 }
 
 security_class_t mode_to_security_class(mode_t m)
@@ -239,13 +281,17 @@ access_vector_t string_to_av_perm(security_class_t tclass, const char *s)
 	struct discover_class_node *node;
 	security_class_t kclass = unmap_class(tclass);
 
+	__pthread_mutex_lock(&discover_class_lock);
 	node = get_class_cache_entry_value(kclass);
 	if (node != NULL) {
 		size_t i;
 		for (i = 0; i < MAXVECTORS && node->perms[i] != NULL; i++)
-			if (strcmp(node->perms[i], s) == 0)
+			if (strcmp(node->perms[i], s) == 0) {
+				__pthread_mutex_unlock(&discover_class_lock);
 				return map_perm(tclass, UINT32_C(1) << i);
+			}
 	}
+	__pthread_mutex_unlock(&discover_class_lock);
 
 	errno = EINVAL;
 	return 0;
@@ -254,14 +300,16 @@ access_vector_t string_to_av_perm(security_class_t tclass, const char *s)
 const char *security_class_to_string(security_class_t tclass)
 {
 	struct discover_class_node *node;
+	const char *name;
 
 	tclass = unmap_class(tclass);
 
+	__pthread_mutex_lock(&discover_class_lock);
 	node = get_class_cache_entry_value(tclass);
-	if (node == NULL)
-		return NULL;
-	else
-		return node->name;
+	name = node ? node->name : NULL;
+	__pthread_mutex_unlock(&discover_class_lock);
+
+	return name;
 }
 
 const char *security_av_perm_to_string(security_class_t tclass,
@@ -269,16 +317,22 @@ const char *security_av_perm_to_string(security_class_t tclass,
 {
 	struct discover_class_node *node;
 	size_t i;
+	const char *name;
 
 	av = unmap_perm(tclass, av);
 	tclass = unmap_class(tclass);
 
+	__pthread_mutex_lock(&discover_class_lock);
 	node = get_class_cache_entry_value(tclass);
 	if (av && node)
 		for (i = 0; i < MAXVECTORS; i++)
-			if ((UINT32_C(1) << i) & av)
-				return node->perms[i];
+			if ((UINT32_C(1) << i) & av) {
+				name = node->perms[i];
+				__pthread_mutex_unlock(&discover_class_lock);
+				return name;
+			}
 
+	__pthread_mutex_unlock(&discover_class_lock);
 	return NULL;
 }
 
Signature · 1 line
2.54.0
author maintainer
#3 lore raw

RFC PATCH v2 3/3 libselinux: sestatus: serialize selinux status updates

In reply to Stephen Smalley

When selinux_check_access() is used by a multi-threaded application and calls selinux_status_updated(), every thread that observes the same sequence number bump races to run the avc_process_*() functions, so avc_ss_reset() and selinux_flush_class_cache() fire once per thread instead of once per event, and writes to the last_seqno/policyload can tear.

Introduce and take a status_lock mutex across the last_seqno compare-and-update and the update actions so that exactly one thread services each event. The kernel status page itself is a seqlock and is still read unlocked via the existing read_sequence() loop.

Lock ordering:
1. status_lock is never taken when another libselinux lock is held.
2. Under status_lock, the code may take avc_lock (via avc_ss_reset) or discover_class_lock (via selinux_flush_class_cache), but neither of these ever nest back into status_lock.

---
v2 restores a lockless fast path for the common case where no policy change has occurred since the last check.

 libselinux/src/sestatus.c | 49 +++++++++++++++++++++++++++++++--------
 1 file changed, 39 insertions(+), 10 deletions(-)
libselinux/src/sestatus.c +39 -10
index bb69fe90..e30380ae 100644
@@ -36,6 +36,7 @@ struct selinux_status_t {
  * Valid Pointer : opened and mapped correctly
  */
 static struct selinux_status_t *selinux_status = NULL;
+static pthread_mutex_t status_lock = PTHREAD_MUTEX_INITIALIZER;
 static uint32_t last_seqno;
 static uint32_t last_policyload;
 
@@ -98,9 +99,25 @@ int selinux_status_updated(void)
 		return -1;
 	}
 
+	/*
+	 * Fast path with no locking is only possible when the status page
+	 * is mapped, the last_seqno is even (stable) and it matches the
+	 * curr_seqno.
+	 */
+	if (selinux_status != MAP_FAILED) {
+		curr_seqno = read_sequence(selinux_status);
+		if ((last_seqno & 0x0001) == 0 && curr_seqno == last_seqno)
+			return 0;
+	}
+
+	/* Otherwise we have to take the mutex and re-check */
+	__pthread_mutex_lock(&status_lock);
+
 	if (selinux_status == MAP_FAILED) {
-		if (avc_netlink_check_nb() < 0)
+		if (avc_netlink_check_nb() < 0) {
+			__pthread_mutex_unlock(&status_lock);
 			return -1;
+		}
 
 		curr_seqno = fallback_sequence;
 	} else {
@@ -117,11 +134,14 @@ int selinux_status_updated(void)
 	if (last_seqno & 0x0001)
 		last_seqno = curr_seqno;
 
-	if (last_seqno == curr_seqno)
+	if (last_seqno == curr_seqno) {
+		__pthread_mutex_unlock(&status_lock);
 		return 0;
+	}
 
 	if (selinux_status == MAP_FAILED) {
 		last_seqno = curr_seqno;
+		__pthread_mutex_unlock(&status_lock);
 		return 1;
 	}
 
@@ -134,16 +154,21 @@ int selinux_status_updated(void)
 	} while (tmp_seqno != curr_seqno);
 
 	if (avc_enforcing != (int)enforcing) {
-		if (avc_process_setenforce(enforcing) < 0)
+		if (avc_process_setenforce(enforcing) < 0) {
+			__pthread_mutex_unlock(&status_lock);
 			return -1;
+		}
 	}
 	if (last_policyload != policyload) {
-		if (avc_process_policyload(policyload) < 0)
+		if (avc_process_policyload(policyload) < 0) {
+			__pthread_mutex_unlock(&status_lock);
 			return -1;
+		}
 		last_policyload = policyload;
 	}
 	last_seqno = curr_seqno;
 
+	__pthread_mutex_unlock(&status_lock);
 	return 1;
 }
 
@@ -164,10 +189,12 @@ int selinux_status_getenforce(void)
 	}
 
 	if (selinux_status == MAP_FAILED) {
-		if (avc_netlink_check_nb() < 0)
-			return -1;
+		int rc;
 
-		return fallback_enforcing;
+		__pthread_mutex_lock(&status_lock);
+		rc = (avc_netlink_check_nb() < 0) ? -1 : fallback_enforcing;
+		__pthread_mutex_unlock(&status_lock);
+		return rc;
 	}
 
 	/* sequence must not be changed during references */
@@ -201,10 +228,12 @@ int selinux_status_policyload(void)
 	}
 
 	if (selinux_status == MAP_FAILED) {
-		if (avc_netlink_check_nb() < 0)
-			return -1;
+		int rc;
 
-		return fallback_policyload;
+		__pthread_mutex_lock(&status_lock);
+		rc = (avc_netlink_check_nb() < 0) ? -1 : fallback_policyload;
+		__pthread_mutex_unlock(&status_lock);
+		return rc;
 	}
 
 	/* sequence must not be changed during references */
Signature · 1 line
2.54.0