Skip to content

Commit

Permalink
sec: zip-slip fix
Browse files Browse the repository at this point in the history
  • Loading branch information
phoban01 committed Dec 11, 2023
1 parent 4ab0cf1 commit e1d13f3
Showing 1 changed file with 22 additions and 2 deletions.
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
}

0 comments on commit e1d13f3

Please sign in to comment.