From 9a2fec0a9a261b5f9ed987584bb2862a39bdd7fb Mon Sep 17 00:00:00 2001 From: lifubang Date: Sat, 16 May 2026 04:40:37 +0000 Subject: [PATCH] libct: close rootFd ASAP in maskPaths Close the root file descriptor immediately after use in maskPaths to reduce the window during which an attacker could potentially exploit an open fd to access or manipulate the root filesystem. This follows the principle of least privilege and mitigates risks in compromised or malicious container scenarios. Co-authored-by: Kir Kolyshkin Signed-off-by: lifubang (cherry picked from commit b88635e57ec51c83a4b3d2ef281e3cfb692e30ca) Signed-off-by: lifubang --- libcontainer/rootfs_linux.go | 7 +++++-- libcontainer/standard_init_linux.go | 13 +++---------- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/libcontainer/rootfs_linux.go b/libcontainer/rootfs_linux.go index 0b13866b2..0bd49c4d1 100644 --- a/libcontainer/rootfs_linux.go +++ b/libcontainer/rootfs_linux.go @@ -1345,7 +1345,10 @@ func maskDir(path, mountLabel string) error { // mounts ( proc/kcore ). // For files, maskPath bind mounts /dev/null over the top of the specified path. // For directories, maskPath mounts read-only tmpfs over the top of the specified path. -func maskPaths(rootFd *os.File, paths []string, mountLabel string) error { +func maskPaths(rootFs string, paths []string, mountLabel string) error { + if len(paths) == 0 { + return nil + } devNull, err := os.OpenFile("/dev/null", unix.O_PATH, 0) if err != nil { return fmt.Errorf("can't mask paths: %w", err) @@ -1403,7 +1406,7 @@ func maskPaths(rootFd *os.File, paths []string, mountLabel string) error { // resolves the underlying inode via procfs and re-opens it through // rootFd, so the resulting fd is anchored to the real path inside the // container rootfs even if path was a /proc/self/fd/N alias. - reopened, err := reopenAfterMount(rootFd, dstFh, unix.O_PATH|unix.O_CLOEXEC) + reopened, err := reopenAfterMount(rootFs, dstFh, unix.O_PATH|unix.O_CLOEXEC) if err != nil { return fmt.Errorf("can't reopen shared directory mask: %w", err) } diff --git a/libcontainer/standard_init_linux.go b/libcontainer/standard_init_linux.go index f73bc740e..0e96dcf23 100644 --- a/libcontainer/standard_init_linux.go +++ b/libcontainer/standard_init_linux.go @@ -141,17 +141,10 @@ func (l *linuxStandardInit) Init() error { } } - if len(l.config.Config.MaskPaths) > 0 { - rootFd, err := os.OpenFile("/", unix.O_DIRECTORY|unix.O_CLOEXEC|unix.O_PATH, 0) - if err != nil { - return fmt.Errorf("open rootfs handle for masked paths: %w", err) - } - err = maskPaths(rootFd, l.config.Config.MaskPaths, l.config.Config.MountLabel) - rootFd.Close() - if err != nil { - return err - } + if err := maskPaths("/", l.config.Config.MaskPaths, l.config.Config.MountLabel); err != nil { + return err } + pdeath, err := system.GetParentDeathSignal() if err != nil { return fmt.Errorf("can't get pdeath signal: %w", err)