Go

Go

Made by DeepSource

File path traversal when extracting zip archive GSC-G305

Security
Minor
a03 cwe-22 sans top 25 owasp top 10

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

References