Skip to contentSkip to conversation

security/selinux: fix potential memleak in error branch

PATCH In review Bernard Zhao 2 participants 2 messages Dec 10, 2021 – Dec 21, 2021 SELinux security module

lore
Share & tools
lore
#0 lore raw

PATCH v3 1/1 security/selinux: fix potential memleak in error branch

This patch try to fix potential memleak in error branch.

Changes since V1:
*make it to be simpler to do the "(!s)" check before the "(!opts)" check.

Changes since v2:
*add *mnt_opts = NULL after kfree(opt) to avoid double free risk.

---
 security/selinux/hooks.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
security/selinux/hooks.c +10 -2
index 62d30c0a30c2..0d018f054dfb 100644
@@ -983,18 +983,22 @@ static int selinux_sb_clone_mnt_opts(const struct super_block *oldsb,
 static int selinux_add_opt(int token, const char *s, void **mnt_opts)
 {
 	struct selinux_mnt_opts *opts = *mnt_opts;
+	bool is_alloc_opts = false;
 
 	if (token == Opt_seclabel)	/* eaten and completely ignored */
 		return 0;
 
+	if (!s)
+		return -ENOMEM;
+
 	if (!opts) {
 		opts = kzalloc(sizeof(struct selinux_mnt_opts), GFP_KERNEL);
 		if (!opts)
 			return -ENOMEM;
 		*mnt_opts = opts;
+		is_alloc_opts = true;
 	}
-	if (!s)
-		return -ENOMEM;
+
 	switch (token) {
 	case Opt_context:
 		if (opts->context || opts->defcontext)
@@ -1019,6 +1023,10 @@ static int selinux_add_opt(int token, const char *s, void **mnt_opts)
 	}
 	return 0;
 Einval:
+	if (is_alloc_opts) {
+		kfree(opts);
+		*mnt_opts = NULL;
+	}
 	pr_warn(SEL_MOUNT_FAIL_MSG);
 	return -EINVAL;
 }
Signature · 1 line
2.33.1
maintainer
#1 lore raw
Quoted 5 lines · Bernard Zhao

This patch try to fix potential memleak in error branch.

Quoted 8 lines

Changes since V1:
*make it to be simpler to do the "(!s)" check before the "(!opts)" check.

Changes since v2:
*add *mnt_opts = NULL after kfree(opt) to avoid double free risk.

---
 security/selinux/hooks.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)

Hi Bernard,

I apologize for the late response, this was lost in my inbox for some reason. Regardless, this looks fine to me so I'm merging it into selinux/next; thanks for your help.

However, Ondrej made a few good suggestions about further improvements that could be made up at the LSM layer, I think it would be nice if you could look into that too.

Thanks again for your help.

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