Re: [PATCH v3] selinux: lsm: fix a missing-check bug in selinux_add_mnt_opt( )

From: Ondrej Mosnacek
Date: Fri Jun 07 2019 - 04:43:30 EST


On Thu, Jun 6, 2019 at 11:23 AM Gen Zhang <blackgod016574@xxxxxxxxx> wrote:
> In selinux_add_mnt_opt(), 'val' is allocated by kmemdup_nul(). It returns
> NULL when fails. So 'val' should be checked. And 'mnt_opts' should be
> freed when error.
>
> Signed-off-by: Gen Zhang <blackgod016574@xxxxxxxxx>
> Fixes: 757cbe597fe8 ("LSM: new method: ->sb_add_mnt_opt()")
> ---
> diff --git a/security/selinux/hooks.c b/security/selinux/hooks.c
> index 3ec702c..4e4c1c6 100644
> --- a/security/selinux/hooks.c
> +++ b/security/selinux/hooks.c
> @@ -1052,15 +1052,23 @@ static int selinux_add_mnt_opt(const char *option, const char *val, int len,
> if (token == Opt_error)
> return -EINVAL;
>
> - if (token != Opt_seclabel)
> - val = kmemdup_nul(val, len, GFP_KERNEL);
> + if (token != Opt_seclabel) {
> + val = kmemdup_nul(val, len, GFP_KERNEL);
> + if (!val) {
> + rc = -ENOMEM;
> + goto free_opt;
> + }
> + }
> rc = selinux_add_opt(token, val, mnt_opts);
> if (unlikely(rc)) {
> kfree(val);
> - if (*mnt_opts) {
> - selinux_free_mnt_opts(*mnt_opts);
> - *mnt_opts = NULL;
> - }
> + goto free_opt;
> + }
> + return rc;

At this point rc is guaranteed to be 0, so you can just 'return 0' for
clarity. Also, I visually prefer an empty line between a return
statement and a goto label, but I'm not sure what is the
general/maintainer's preference.

Also, you should drop the "lsm: " from the subject - it is redundant
and doesn't follow the SELinux convention. See `git log --oneline --
security/selinux/` for what the subjects usually look like - mostly we
just go with "selinux: <description>" (or "LSM: <description>" when
the changes affect the shared LSM interface).

> +free_opt:
> + if (*mnt_opts) {
> + selinux_free_mnt_opts(*mnt_opts);
> + *mnt_opts = NULL;
> }
> return rc;
> }

--
Ondrej Mosnacek <omosnace at redhat dot com>
Software Engineer, Security Technologies
Red Hat, Inc.