[PATCH RFC 05/19] selinux: close inherited files that can't be replaced

Serge Hallyn (AMD) sergeh at kernel.org
Thu Dec 3 20:19:08 UTC 2026


On Tue, Nov 24, 2026 at 11:58:28PM +0100, Christian Brauner wrote:
> When an exec transitions to a new SID flush_unauthorized_files()
> replaces the inherited files the new SID isn't allowed to use with the
> null device. It uses replace_fd() for that and ignores the return value.
> 
> replace_fd() refuses a file descriptor at or above RLIMIT_NOFILE. And a
> task can lower its own soft limit as it likes. So a task that sets
> RLIMIT_NOFILE to the number of a file descriptor right before the exec
> keeps that file open in the new image:
> 
> 	fd = open(path, O_RDONLY);	/* 3 */
> 	getrlimit(RLIMIT_NOFILE, &rl);
> 	rl.rlim_cur = fd;
> 	setrlimit(RLIMIT_NOFILE, &rl);
> 	execve(...);
> 
> The new SID still can't read from the file as that is checked again on
> every use. But it holds on to the file and what isn't checked on use
> like lseek() works.
> 
> Before commit ee97cd872d08 ("switch flush_unauthorized_files() to
> replace_fd()") the file was closed first and stayed closed if its file
> descriptor couldn't be allocated again. So close the file if it can't be
> replaced.
> 
> Fixes: ee97cd872d08 ("switch flush_unauthorized_files() to replace_fd()")
> Cc: stable at vger.kernel.org
> Signed-off-by: Christian Brauner (Amutable) <brauner at kernel.org>

Reviewed-by: Serge Hallyn (AMD) <sergeh at kernel.org>

> ---
>  security/selinux/hooks.c | 4 +++-
>  1 file changed, 3 insertions(+), 1 deletion(-)
> 
> diff --git a/security/selinux/hooks.c b/security/selinux/hooks.c
> index 9950f89dfaa23..4ec9ec723cacc 100644
> --- a/security/selinux/hooks.c
> +++ b/security/selinux/hooks.c
> @@ -2521,7 +2521,9 @@ static inline void flush_unauthorized_files(const struct cred *cred,
>  		devnull = NULL;
>  	/* replace all the matching ones with this */
>  	do {
> -		replace_fd(n - 1, devnull, 0);
> +		/* replace_fd() fails for an fd at or above RLIMIT_NOFILE. */
> +		if (replace_fd(n - 1, devnull, 0) < 0)
> +			close_fd(n - 1);
>  	} while ((n = iterate_fd(files, n, match_file, cred)) != 0);
>  	if (devnull)
>  		fput(devnull);
> 
> -- 
> 2.53.0
> 



More information about the Linux-security-module-archive mailing list