From 7078ed1e0b8a197aa9e5103986bce927abef87a4 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Christian=20G=C3=B6ttsche?= <cgzones@googlemail.com>
Date: Sat, 1 Apr 2023 14:11:06 +0200
Subject: [PATCH] semanage: disconnect to free libsemanage internals

Destroying the handle does not actually disconnect, see [1].
Also free the key on user removal.

[1]: https://github.com/SELinuxProject/selinux/blob/e9072e7d45f4559887d11b518099135cbe564163/libsemanage/src/direct_api.c#L330

Example adduser leak:

    Direct leak of 1008 byte(s) in 14 object(s) allocated from:
        #0 0x5638f2e782ae in __interceptor_malloc (./src/useradd+0xee2ae)
        #1 0x7fb5cfffad09 in dbase_file_init src/database_file.c:170:45

    Direct leak of 392 byte(s) in 7 object(s) allocated from:
        #0 0x5638f2e782ae in __interceptor_malloc (./src/useradd+0xee2ae)
        #1 0x7fb5cfffc929 in dbase_policydb_init src/database_policydb.c:187:27

    Direct leak of 144 byte(s) in 2 object(s) allocated from:
        #0 0x5638f2e782ae in __interceptor_malloc (./src/useradd+0xee2ae)
        #1 0x7fb5cfffb519 in dbase_join_init src/database_join.c:249:28

    [...]

Conflict: NA
Reference: https://github.com/shadow-maint/shadow/commit/7078ed1e0b8a197aa9e5103986bce927abef87a4
---
 lib/semanage.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/lib/semanage.c b/lib/semanage.c
index 5d336b08..d412186c 100644
--- a/lib/semanage.c
+++ b/lib/semanage.c
@@ -97,6 +97,8 @@ static semanage_handle_t *semanage_init (void)
 	return handle;
 
 fail:
+	if (handle)
+		semanage_disconnect (handle);
 	semanage_handle_destroy (handle);
 	return NULL;
 }
@@ -156,7 +158,7 @@ done:
 
 
 static int semanage_user_add (semanage_handle_t *handle,
-                             semanage_seuser_key_t *key,
+                             const semanage_seuser_key_t *key,
                              const char *login_name,
                              const char *seuser_name)
 {
@@ -279,6 +281,8 @@ int set_seuser (const char *login_name, const char *seuser_name)
 
 done:
 	semanage_seuser_key_free (key);
+	if (handle)
+		semanage_disconnect (handle);
 	semanage_handle_destroy (handle);
 	return ret;
 }
@@ -353,6 +357,9 @@ int del_seuser (const char *login_name)
 
 	ret = 0;
 done:
+	semanage_seuser_key_free (key);
+	if (handle)
+		semanage_disconnect (handle);
 	semanage_handle_destroy (handle);
 	return ret;
 }
-- 
2.27.0

