From 1ff3ba036bfe8898b04820f0f79fe87835948183 Mon Sep 17 00:00:00 2001 From: Kevin Wan Date: Sun, 26 Jan 2025 00:40:37 +0800 Subject: [PATCH 1/2] Potential fix for code scanning alert no. 57: Arbitrary file access during archive extraction ("Zip Slip") Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> --- tools/goctl/util/zipx/zipx.go | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/tools/goctl/util/zipx/zipx.go b/tools/goctl/util/zipx/zipx.go index 0071150d1b3a..1cf6f6ce6916 100644 --- a/tools/goctl/util/zipx/zipx.go +++ b/tools/goctl/util/zipx/zipx.go @@ -2,9 +2,11 @@ package zipx import ( "archive/zip" + "fmt" "io" "os" "path/filepath" + "strings" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) @@ -39,13 +41,22 @@ func fileCopy(file *zip.File, destPath string) error { return err } defer rc.Close() - abs, err := filepath.Abs(file.Name) + // Ensure the file path does not contain directory traversal elements + if strings.Contains(file.Name, "..") { + return fmt.Errorf("invalid file path: %s", file.Name) + } + + abs, err := filepath.Abs(filepath.Join(destPath, file.Name)) if err != nil { return err } - filename := filepath.Join(destPath, filepath.Base(abs)) - dir := filepath.Dir(filename) + // Ensure the destination path is within the intended directory + if !strings.HasPrefix(abs, destPath) { + return fmt.Errorf("file path is outside the destination directory: %s", abs) + } + + dir := filepath.Dir(abs) err = pathx.MkdirIfNotExist(dir) if err != nil { return err From 90e9c1d9efecb064d1f22ca8eca332684cf4c75a Mon Sep 17 00:00:00 2001 From: kevin Date: Sun, 26 Jan 2025 20:41:15 +0800 Subject: [PATCH 2/2] chore: file compile error --- tools/goctl/util/zipx/zipx.go | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/tools/goctl/util/zipx/zipx.go b/tools/goctl/util/zipx/zipx.go index 1cf6f6ce6916..e41d42d8774b 100644 --- a/tools/goctl/util/zipx/zipx.go +++ b/tools/goctl/util/zipx/zipx.go @@ -41,22 +41,19 @@ func fileCopy(file *zip.File, destPath string) error { return err } defer rc.Close() + // Ensure the file path does not contain directory traversal elements if strings.Contains(file.Name, "..") { return fmt.Errorf("invalid file path: %s", file.Name) } - abs, err := filepath.Abs(filepath.Join(destPath, file.Name)) + abs, err := filepath.Abs(file.Name) if err != nil { return err } - // Ensure the destination path is within the intended directory - if !strings.HasPrefix(abs, destPath) { - return fmt.Errorf("file path is outside the destination directory: %s", abs) - } - - dir := filepath.Dir(abs) + filename := filepath.Join(destPath, filepath.Base(abs)) + dir := filepath.Dir(filename) err = pathx.MkdirIfNotExist(dir) if err != nil { return err