Path Traversal in Archive Extraction
Description
The application may be vulnerable to a path traversal if it extracts untrusted archive files. Archive files may contain folders which, when extracted, may write outside of the intended directory. This is exploited by including path traversal characters such as `../../other/directory` to overwrite or place files in system or application directories.
Examples
Insecure Code
r, err := zip.OpenReader("untrusted.zip")
if err != nil {
log.Fatal(err)
}
for _, f := range r.File {
resolvedPath := filepath.Join("/var/", f.Name)
// process / work with file
}Secure Code
r, err := zip.OpenReader("trusted.zip")
if err != nil {
log.Fatal(err)
}
const basePath = "/var/restricted/"
for _, f := range r.File {
name := filepath.Base(f.Name)
resolvedPath := filepath.Join(basePath, name)
if !strings.HasPrefix(resolvedPath, basePath) {
log.Fatal("path does not start with basePath")
}
// process / work with file
}Remediation
Validate file paths are written with a prefixed, known trusted directory. Ensure archive contains only the expected number of files and sum up all files before attempting to process them. Configure a max size per file allowed and set a restricted base path. Iterate over the files in the archive, ensuring uncompressed size does not exceed the allowed file size and the file is a regular file and not a symbolic link.
Rule Details
| Field | Value |
|---|---|
| ID | CODE-0787 |
| Category | Injection |
| Severity | MEDIUM |
| CWE | CWE-22 |
| Confidence | HIGH |
| Impact | HIGH |
| Likelihood | MEDIUM |
| Exploitability | EASY |
| Tags | path traversal, archive extraction, zip slip |
| OWASP | A5:2017-Broken Access Control, A01:2021-Broken Access Control |