Skip to content
Open
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
6 changes: 5 additions & 1 deletion cgi.go
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,11 @@ func sanitizedPathJoin(root, reqPath string) string {

// Clean with "path", not "filepath": on Windows filepath.Clean keeps the
// ".." behind a leading "//" (UNC prefix), letting reqPath escape root.
relPath := path.Clean("/" + reqPath)[1:]
rootedPath := reqPath
if !strings.HasPrefix(rootedPath, "/") {
rootedPath = "/" + rootedPath
}
relPath := path.Clean(rootedPath)[1:]
// A cleaned rooted path is always local on POSIX: only Windows needs the check
if runtime.GOOS == "windows" && relPath != "" && !filepath.IsLocal(relPath) {
// path is unsafe (see https://github.com/golang/go/issues/56336#issuecomment-1416214885)
Expand Down
25 changes: 25 additions & 0 deletions cgi_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ func TestSanitizedPathJoin(t *testing.T) {
expected string
}{
{"leading slash", "/index.php", filepath.Join(root, "index.php")},
{"multiple leading slashes", "///index.php", filepath.Join(root, "index.php")},
{"multiple root slashes", "//", filepath.Clean(root) + separator},
{"rooted nested traversal", "//foo/../../bar/", filepath.Join(root, "bar") + separator},
{"no leading slash", "index.php", filepath.Join(root, "index.php")},
{"nested", "/foo/bar/index.php", filepath.Join(root, "foo", "bar", "index.php")},
{"empty req path returns root", "", filepath.Clean(root)},
Expand Down Expand Up @@ -617,3 +620,25 @@ func BenchmarkSplitRawHeader(b *testing.B) {
})
}
}

var sanitizedPathJoinResult string

func BenchmarkSanitizedPathJoin(b *testing.B) {
for _, tc := range []struct {
name string
path string
}{
{"index", "/index.php"},
{"nested", "/products/catalog/index.php"},
{"long", "/" + strings.Repeat("products/", 16) + "index.php"},
{"relative", "index.php"},
{"traversal", "/foo/../../etc/passwd"},
} {
b.Run(tc.name, func(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
sanitizedPathJoinResult = sanitizedPathJoin("/srv/app/public", tc.path)
}
})
}
}
Loading