Skip to content
This repository was archived by the owner on May 9, 2025. It is now read-only.
Merged
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
24 changes: 22 additions & 2 deletions pkg/gogit/tar.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"io"
"os"
"path/filepath"
"strings"
)

// Untar writes a tar stream to a filesystem.
Expand All @@ -22,15 +23,24 @@ func Untar(in io.Reader, dir string) error {
return err
}

abs := filepath.Join(dir, header.Name) //nolint:gosec // tar
fp, err := sanitizeArchivePath(dir, header.Name)
if err != nil {
return fmt.Errorf("illegal file path: %s", header.Name)
}

abs := filepath.Join(dir, fp)

switch header.Typeflag {
case tar.TypeDir:
if err := os.MkdirAll(abs, os.FileMode(header.Mode)); err != nil {
return fmt.Errorf("unable to create directory %s: %w", header.Name, err)
}
case tar.TypeReg:
file, err := os.OpenFile(abs, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(header.Mode))
file, err := os.OpenFile(
abs,
os.O_WRONLY|os.O_CREATE|os.O_TRUNC,
os.FileMode(header.Mode),
)
if err != nil {
return fmt.Errorf("unable to open file %s: %w", header.Name, err)
}
Expand All @@ -49,3 +59,13 @@ func Untar(in io.Reader, dir string) error {
}
}
}

// mitigate "G305: Zip Slip vulnerability".
func sanitizeArchivePath(dir, path string) (v string, err error) {
v = filepath.Join(dir, path)
if !strings.HasPrefix(v, filepath.Clean(dir)) {
return "", fmt.Errorf("illegal filepath: %s", path)
}

return v, nil
}