join_linux.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. package safepath
  2. import (
  3. "context"
  4. "os"
  5. "path/filepath"
  6. "runtime"
  7. "strconv"
  8. "github.com/containerd/log"
  9. "github.com/moby/sys/mount"
  10. "github.com/pkg/errors"
  11. "golang.org/x/sys/unix"
  12. )
  13. // Join makes sure that the concatenation of path and subpath doesn't
  14. // resolve to a path outside of path and returns a path to a temporary file that is
  15. // a bind mount to the the exact same file/directory that was validated.
  16. //
  17. // After use, it is the caller's responsibility to call Close on the returned
  18. // SafePath object, which will unmount the temporary file/directory
  19. // and remove it.
  20. func Join(path, subpath string) (*SafePath, error) {
  21. base, subpart, err := evaluatePath(path, subpath)
  22. if err != nil {
  23. return nil, err
  24. }
  25. runtime.LockOSThread()
  26. defer runtime.UnlockOSThread()
  27. fd, err := safeOpenFd(base, subpart)
  28. if err != nil {
  29. return nil, err
  30. }
  31. defer unix.Close(fd)
  32. tmpMount, err := tempMountPoint(fd)
  33. if err != nil {
  34. return nil, errors.Wrap(err, "failed to create temporary file for safe mount")
  35. }
  36. pid := strconv.Itoa(unix.Gettid())
  37. // Using explicit pid path, because /proc/self/fd/<fd> fails with EACCES
  38. // when running under "Enhanced Container Isolation" in Docker Desktop
  39. // which uses sysbox runtime under the hood.
  40. // TODO(vvoland): Investigate.
  41. mountSource := "/proc/" + pid + "/fd/" + strconv.Itoa(fd)
  42. if err := unix.Mount(mountSource, tmpMount, "none", unix.MS_BIND, ""); err != nil {
  43. os.Remove(tmpMount)
  44. return nil, errors.Wrap(err, "failed to mount resolved path")
  45. }
  46. return &SafePath{
  47. path: tmpMount,
  48. sourceBase: base,
  49. sourceSubpath: subpart,
  50. cleanup: cleanupSafePath(tmpMount),
  51. }, nil
  52. }
  53. // safeOpenFd opens the file at filepath.Join(path, subpath) in O_PATH
  54. // mode and returns the file descriptor if subpath is within the subtree
  55. // rooted at path. It is an error if any of components of path or subpath
  56. // are symbolic links.
  57. //
  58. // It is a caller's responsibility to close the returned file descriptor, if no
  59. // error was returned.
  60. func safeOpenFd(path, subpath string) (int, error) {
  61. // Open base volume path (_data directory).
  62. prevFd, err := unix.Open(path, unix.O_PATH|unix.O_DIRECTORY|unix.O_CLOEXEC|unix.O_NOFOLLOW, 0)
  63. if err != nil {
  64. return -1, &ErrNotAccessible{Path: path, Cause: err}
  65. }
  66. defer unix.Close(prevFd)
  67. // Try to use the Openat2 syscall first (available on Linux 5.6+).
  68. fd, err := unix.Openat2(prevFd, subpath, &unix.OpenHow{
  69. Flags: unix.O_PATH | unix.O_CLOEXEC,
  70. Mode: 0,
  71. Resolve: unix.RESOLVE_BENEATH | unix.RESOLVE_NO_MAGICLINKS | unix.RESOLVE_NO_SYMLINKS,
  72. })
  73. switch {
  74. case errors.Is(err, unix.ENOSYS):
  75. // Openat2 is not available, fallback to Openat loop.
  76. return softOpenat2(prevFd, subpath)
  77. case errors.Is(err, unix.EXDEV):
  78. return -1, &ErrEscapesBase{Base: path, Subpath: subpath}
  79. case errors.Is(err, unix.ENOENT), errors.Is(err, unix.ELOOP):
  80. return -1, &ErrNotAccessible{Path: filepath.Join(path, subpath), Cause: err}
  81. case err != nil:
  82. return -1, &os.PathError{Op: "openat2", Path: subpath, Err: err}
  83. }
  84. // Openat2 is available and succeeded.
  85. return fd, nil
  86. }
  87. func softOpenat2(baseFd int, subpath string) (int, error) {
  88. return -1, errors.New("temporary stub, will be removed in later commit")
  89. }
  90. // tempMountPoint creates a temporary file/directory to act as mount
  91. // point for the file descriptor.
  92. func tempMountPoint(sourceFd int) (string, error) {
  93. var stat unix.Stat_t
  94. err := unix.Fstat(sourceFd, &stat)
  95. if err != nil {
  96. return "", errors.Wrap(err, "failed to Fstat mount source fd")
  97. }
  98. isDir := (stat.Mode & unix.S_IFMT) == unix.S_IFDIR
  99. if isDir {
  100. return os.MkdirTemp("", "safe-mount")
  101. }
  102. f, err := os.CreateTemp("", "safe-mount")
  103. if err != nil {
  104. return "", err
  105. }
  106. p := f.Name()
  107. if err := f.Close(); err != nil {
  108. return "", err
  109. }
  110. return p, nil
  111. }
  112. // cleanupSafePaths returns a function that unmounts the path and removes the
  113. // mountpoint.
  114. func cleanupSafePath(path string) func() error {
  115. return func() error {
  116. log.G(context.TODO()).WithField("path", path).Debug("removing safe temp mount")
  117. if err := unix.Unmount(path, unix.MNT_DETACH); err != nil {
  118. if errors.Is(err, unix.EINVAL) {
  119. log.G(context.TODO()).WithField("path", path).Warn("safe temp mount no longer exists?")
  120. return nil
  121. }
  122. return errors.Wrapf(err, "error unmounting safe mount %s", path)
  123. }
  124. if err := os.Remove(path); err != nil {
  125. if errors.Is(err, os.ErrNotExist) {
  126. log.G(context.TODO()).WithField("path", path).Warn("safe temp mount no longer exists?")
  127. return nil
  128. }
  129. return errors.Wrapf(err, "failed to delete temporary safe mount")
  130. }
  131. return nil
  132. }
  133. }