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
17 changes: 16 additions & 1 deletion sdks/go/pkg/beam/core/runtime/xlangx/expansionx/download.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,18 @@ func getLocalJar(url string) (string, error) {
return jarPath, nil
}

func validatePath(dest, filename string) (string, error) {
destPath := filepath.Join(dest, filename)
cleanDest := filepath.Clean(dest)
cleanPath := filepath.Clean(destPath)

rel, err := filepath.Rel(cleanDest, cleanPath)
if err != nil || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || rel == ".." {
return "", fmt.Errorf("file path %q is outside destination directory %q", filename, dest)
}
return cleanPath, nil
}

func extractJar(source, dest string) error {
reader, err := zip.OpenReader(source)
if err != nil {
Expand All @@ -150,7 +162,10 @@ func extractJar(source, dest string) error {
}

for _, file := range reader.File {
fileName := filepath.Join(dest, file.Name)
fileName, err := validatePath(dest, file.Name)
if err != nil {
return fmt.Errorf("error validating file path (%s, %s): %w", dest, file.Name, err)
}
if file.FileInfo().IsDir() {
os.MkdirAll(fileName, 0700)
continue
Expand Down
25 changes: 25 additions & 0 deletions sdks/go/pkg/beam/core/runtime/xlangx/expansionx/download_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,3 +249,28 @@ func TestGetPythonVersion(t *testing.T) {
}
}
}

func TestValidatePath(t *testing.T) {
dest := filepath.Clean("/tmp/cache")
tests := []struct {
name string
filename string
wantErr bool
}{
{"valid simple file", "Foo.class", false},
{"valid nested file", "org/apache/beam/Foo.class", false},
{"traversal attack", "../../etc/passwd", true},
{"partial directory prefix attack", "../cache_evil/evil.sh", true},
{"parent directory traversal", "..", true},
{"nested traversal attack", "foo/bar/../../../etc/passwd", true},
}

for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
_, err := validatePath(dest, tc.filename)
if (err != nil) != tc.wantErr {
t.Errorf("validatePath(%q, %q) error = %v, wantErr %v", dest, tc.filename, err, tc.wantErr)
}
})
}
}
Loading