Skip to content

Commit

Permalink
[security] Fix path injection
Browse files Browse the repository at this point in the history
  • Loading branch information
quentinguidee committed Sep 25, 2023
1 parent 2c770d4 commit 27ae834
Showing 1 changed file with 23 additions and 10 deletions.
33 changes: 23 additions & 10 deletions pkg/varchiver/tar.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,16 @@ import (
"io"
"os"
"path"
"path/filepath"
"strings"
)

var (
ErrMustBeLocal = errors.New("security: src must be a local file")
ErrZipSlipAttack = errors.New("security: paths must be local")
)

func Unzip(src string, dest string) error {
if !filepath.IsLocal(src) || !filepath.IsLocal(dest) {
return ErrMustBeLocal
if zipSlipAttack(src) || zipSlipAttack(dest) {
return ErrZipSlipAttack
}

reader, err := zip.OpenReader(src)
Expand All @@ -27,12 +27,16 @@ func Unzip(src string, dest string) error {
}

for _, header := range reader.File {
if !filepath.IsLocal(header.Name) {
return ErrMustBeLocal
if zipSlipAttack(header.Name) {
return ErrZipSlipAttack
}

p := path.Join(dest, header.Name)

if zipSlipAttack(p) {
return ErrZipSlipAttack
}

if header.FileInfo().IsDir() {
err = os.MkdirAll(p, os.ModePerm)
if err != nil {
Expand Down Expand Up @@ -74,8 +78,8 @@ func Unzip(src string, dest string) error {
// Untar a tarball to a destination. src is the path to
// the tarball, and dest is the path to the destination directory.
func Untar(src string, dest string) error {
if !filepath.IsLocal(src) || !filepath.IsLocal(dest) {
return ErrMustBeLocal
if zipSlipAttack(src) || zipSlipAttack(dest) {
return ErrZipSlipAttack
}

archive, err := os.Open(src)
Expand All @@ -102,12 +106,16 @@ func Untar(src string, dest string) error {
return err
}

if !filepath.IsLocal(header.Name) {
return ErrMustBeLocal
if zipSlipAttack(header.Name) {
return ErrZipSlipAttack
}

p := path.Join(dest, header.Name)

if zipSlipAttack(p) {
return ErrZipSlipAttack
}

switch header.Typeflag {
case tar.TypeDir:
err = os.MkdirAll(p, os.ModePerm)
Expand Down Expand Up @@ -143,3 +151,8 @@ func Untar(src string, dest string) error {

return nil
}

// CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
func zipSlipAttack(path string) bool {
return strings.Contains(path, "..")
}

0 comments on commit 27ae834

Please sign in to comment.