From 2cfed99cf5b89e06692bebb67007a9a0ace8a91e Mon Sep 17 00:00:00 2001 From: Mateusz Filipowicz Date: Fri, 7 Feb 2025 15:44:53 +0100 Subject: [PATCH] fix: arbitrary file access during archive extraction Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> --- fields/download.go | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/fields/download.go b/fields/download.go index a5bdb5c..f60bcd2 100644 --- a/fields/download.go +++ b/fields/download.go @@ -20,6 +20,24 @@ import ( "github.com/xor-gate/ar" ) +func sanitizeExtractedPath(filePath, destinationDir string) (string, error) { + absDestinationDir, err := filepath.Abs(destinationDir) + if err != nil { + return "", err + } + + absFilePath, err := filepath.Abs(filepath.Join(destinationDir, filePath)) + if err != nil { + return "", err + } + + if !strings.HasPrefix(absFilePath, absDestinationDir) { + return "", fmt.Errorf("invalid file path: %s", filePath) + } + + return absFilePath, nil +} + func DownloadAndExtract(downloadUrl url.URL, outputDir string) error { targetInfo, err := os.Stat(outputDir) if err != nil { @@ -147,7 +165,12 @@ func extractJSON(jarFile, fieldsDir string) error { return err } - dst, err := os.Create(filepath.Join(fieldsDir, filepath.Base(f.Name))) + dstPath, err := sanitizeExtractedPath(f.Name, fieldsDir) + if err != nil { + return err + } + + dst, err := os.Create(dstPath) if err != nil { return err }