File traversal when extracting zip/tar archive
50}
51
52func extractZipArchiveFile(file *zip.File, dest string, input io.Reader) error {
53 filePath := filepath.Join(dest, file.Name)54 fileInfo := file.FileInfo()
55
56 if fileInfo.IsDir() {
File traversal when extracting zip/tar archive
73 return BreakoutError{header.Name, header.Linkname}
74 }
75
76 err := os.Link(filepath.Join(dest, header.Linkname), filePath) 77 if err != nil {
78 return err
79 }
File traversal when extracting zip/tar archive
67
68 switch header.Typeflag {
69 case tar.TypeLink:
70 targetPath := filepath.Join(dest, header.Linkname) 71
72 if !strings.HasPrefix(targetPath, dest) {
73 return BreakoutError{header.Name, header.Linkname}
File traversal when extracting zip/tar archive
56}
57
58func ExtractEntry(header *tar.Header, dest string, input io.Reader, chown bool) error {
59 filePath := filepath.Join(dest, header.Name) 60 fileInfo := header.FileInfo()
61 fileMode := fileInfo.Mode()
62
Description
A path traversal attack (also known as directory traversal) aims to access files and directories that are stored outside the web root folder.
Manipulating variables that reference files with “dot-dot (..)” sequences and their variations or using absolute file paths may be possible to access arbitrary files and directories stored on the file system, including application source code or configuration and critical system files.
Bad practice
package main
import (
"archive/zip"
"io/ioutil"
"path/filepath"
)
func unzip(f string) {
r, _ := zip.OpenReader(f)
for _, f := range r.File {
p, _ := filepath.Abs(f.Name)
// Bad: Could overwrite any file on the file system
ioutil.WriteFile(p, []byte("dummy"), 0666)
}
}
Recommended
package main
import (
"archive/zip"
"io/ioutil"
"path/filepath"
"strings"
)
func unzipGood(f string) {
r, _ := zip.OpenReader(f)
for _, f := range r.File {
p, _ := filepath.Abs(f.Name)
// Good: Check that path does not contain ".." before using it
// If this check is ignored then there's a possibility of
// arbitrary file write during zip extraction - "zip slip".
if !strings.Contains(p, "..") {
ioutil.WriteFile(p, []byte("present"), 0666)
}
}
}