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.
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)
}
}
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)
}
}
}