diff --git a/namespaces/init.go b/namespaces/init.go index 9bad7cc9b..e89afdb47 100644 --- a/namespaces/init.go +++ b/namespaces/init.go @@ -185,7 +185,10 @@ func setupRoute(container *libcontainer.Container) error { // and working dir, and closes any leaky file descriptors // before execing the command inside the namespace func FinalizeNamespace(container *libcontainer.Container) error { - if err := system.CloseFdsFrom(3); err != nil { + // Ensure that all non-standard fds we may have accidentally + // inherited are marked close-on-exec so they stay out of the + // container + if err := utils.CloseExecFrom(3); err != nil { return fmt.Errorf("close open file descriptors %s", err) } @@ -217,6 +220,7 @@ func FinalizeNamespace(container *libcontainer.Container) error { return fmt.Errorf("chdir to %s %s", container.WorkingDir, err) } } + return nil } diff --git a/utils/utils.go b/utils/utils.go index 0d919bc43..76184ce00 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -4,7 +4,10 @@ import ( "crypto/rand" "encoding/hex" "io" + "io/ioutil" "path/filepath" + "strconv" + "syscall" ) // GenerateRandomName returns a new name joined with a prefix. This size @@ -26,3 +29,27 @@ func ResolveRootfs(uncleanRootfs string) (string, error) { } return filepath.EvalSymlinks(rootfs) } + +func CloseExecFrom(minFd int) error { + fdList, err := ioutil.ReadDir("/proc/self/fd") + if err != nil { + return err + } + for _, fi := range fdList { + fd, err := strconv.Atoi(fi.Name()) + if err != nil { + // ignore non-numeric file names + continue + } + + if fd < minFd { + // ignore descriptors lower than our specified minimum + continue + } + + // intentionally ignore errors from syscall.CloseOnExec + syscall.CloseOnExec(fd) + // the cases where this might fail are basically file descriptors that have already been closed (including and especially the one that was created when ioutil.ReadDir did the "opendir" syscall) + } + return nil +}