Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions safeopen_nix.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@ func unixRelativePathDoesntTraverse(path string) bool {
if path == "" {
return false
}

// Strip leading slashes so an absolute-looking input is treated as relative
// to the base directory, matching the Linux implementation
// (canTraverseUnixRelPath). Without this, filepath.Clean("/../x") == "/x"
// hides the leading "../", so a traversal such as "/../x" is accepted here
// and escapes the base directory in openFileBeneath.
path = strings.TrimLeft(path, "/")

hasDots := false
for p := path; p != ""; {
var part string
Expand Down
44 changes: 44 additions & 0 deletions safeopen_nix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,3 +166,47 @@ func TestUnixDirTraversal(t *testing.T) {
t.Errorf("io.ReadAll() = %v, want = %v", string(actualData), fileContent)
}
}

func TestUnixBeneathLeadingSlashTraversal(t *testing.T) {
// The base directory is a subdirectory; a secret file lives in its parent,
// outside the base. A leading-slash argument must not escape the base
// directory, for either reads or writes. Regression test for a missing
// strings.TrimLeft in unixRelativePathDoesntTraverse: filepath.Clean("/../x")
// == "/x" hid the leading "../", so "/../x" was accepted and escaped base.
parent := t.TempDir()
base := path.Join(parent, "base")
if err := os.Mkdir(base, 0777); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(path.Join(base, "d"), 0777); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path.Join(parent, "secret.txt"), []byte("outside"), 0600); err != nil {
t.Fatal(err)
}

escapes := []string{
"/../secret.txt",
"/./../secret.txt",
"/d/../../secret.txt",
}
for _, file := range escapes {
if fd, err := OpenBeneath(base, file); err == nil {
fd.Close()
t.Errorf("OpenBeneath(%q, %q) = nil error; want rejection (escaped the base directory)", base, file)
}
if err := WriteFileBeneath(base, file, []byte("pwn"), 0600); err == nil {
t.Errorf("WriteFileBeneath(%q, %q) = nil error; want rejection (escaped the base directory)", base, file)
}
}

// A legitimate leading-slash path that stays within base must still succeed.
if err := os.WriteFile(path.Join(base, "ok.txt"), []byte("in"), 0600); err != nil {
t.Fatal(err)
}
if fd, err := OpenBeneath(base, "/ok.txt"); err != nil {
t.Errorf("OpenBeneath(%q, %q) = %v; want success (in-base leading slash)", base, "/ok.txt", err)
} else {
fd.Close()
}
}