diff mbox series

[v3] security/selinux: fix potential memleak in error branch

Message ID 20211210120359.394986-1-bernard@vivo.com (mailing list archive)
State Accepted
Delegated to: Paul Moore
Headers show
Series [v3] security/selinux: fix potential memleak in error branch | expand

Commit Message

Bernard Zhao Dec. 10, 2021, 12:03 p.m. UTC
This patch try to fix potential memleak in error branch.

Signed-off-by: Bernard Zhao <bernard@vivo.com>

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(-)

Comments

Paul Moore Dec. 21, 2021, 8 p.m. UTC | #1
On Fri, Dec 10, 2021 at 7:04 AM Bernard Zhao <bernard@vivo.com> wrote:
>
> This patch try to fix potential memleak in error branch.
>
> Signed-off-by: Bernard Zhao <bernard@vivo.com>
>
> 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.
diff mbox series

Patch

diff --git a/security/selinux/hooks.c b/security/selinux/hooks.c
index 62d30c0a30c2..0d018f054dfb 100644
--- a/security/selinux/hooks.c
+++ b/security/selinux/hooks.c
@@ -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;
 }