Skip to content

Commit

Permalink
Merge pull request openshift#17 from alexlarsson/fix-close-race
Browse files Browse the repository at this point in the history
Fix invalid fd race
  • Loading branch information
Michael Crosby committed Jun 16, 2014
2 parents 4145356 + f602821 commit e00eadd
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
6 changes: 5 additions & 1 deletion namespaces/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down Expand Up @@ -217,6 +220,7 @@ func FinalizeNamespace(container *libcontainer.Container) error {
return fmt.Errorf("chdir to %s %s", container.WorkingDir, err)
}
}

return nil
}

Expand Down
27 changes: 27 additions & 0 deletions utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
}

0 comments on commit e00eadd

Please sign in to comment.