Skip to contentSkip to conversation

libselinux: Do not clobber errno of the world

PATCH Superseded Stephen Smalley 1 participant 1 message Jun 9 SELinux security module

v2 of 3 Superseded Latest is v3 →

lore
Share & tools
lore

Stephen Smalley

author maintainer
#0 lore raw

PATCH v2 1/1 libselinux: Do not clobber errno of the world

From: Cristian Rodríguez <[email protected]>

libselinux clobbers errno of all consumers (systemd, sshd you name it) because its constructors do not properly save and restore errno. The following program demonstrates it.

int main(void)

{
        assert(errno == 0);
	/* Just a test, it doesn't matter already clobbered */
        if(is_selinux_enabled() < 0) {
                perror("not enabled");
                return 1;
        }
}

if any function sets errno, it is not switched back to the original value and standards DO NOT require errno to the set to zero before entering main

---
v2 drops the extraneous saved_errno < 0 guard and drops the extraenous __selinux prefix of _saved_errno.

 libselinux/src/init.c             | 1 +
 libselinux/src/selinux_internal.h | 8 ++++++++
 2 files changed, 9 insertions(+)
libselinux/src/init.c +1 -0
index 499e4e44..abed3088 100644
@@ -145,6 +145,7 @@ void set_selinuxmnt(const char *mnt)
 static void init_lib(void) __attribute__((constructor));
 static void init_lib(void)
 {
+	SELINUX_PROTECT_ERRNO;
 	selinux_page_size = sysconf(_SC_PAGE_SIZE);
 	init_selinuxmnt();
 #ifndef ANDROID
libselinux/src/selinux_internal.h +8 -0
index 6089463d..39d57bd8 100644
@@ -147,4 +147,12 @@ static inline void fclose_errno_safe(FILE *stream)
 
 #define spaceship_cmp(a, b) (((a) > (b)) - ((a) < (b)))
 
+static inline void selinux_reset_errno(int *saved_errno)
+{
+        errno = *saved_errno;
+}
+
+#define SELINUX_PROTECT_ERRNO __attribute__((__cleanup__(selinux_reset_errno))) \
+                         __attribute__((__unused__)) int _saved_errno = errno
+
 #endif /* SELINUX_INTERNAL_H_ */
Signature · 1 line
2.54.0