Go

Go

Made by DeepSource

Creating tempfile using a predictable path GSC-G303

Security
Major
cwe-377

Use os.TempDir, ioutil.TempDir and ioutil.TempFile() to ensure filepath generated is correct and not predictable.

Malicious users that can predict the file name and write to the directory containing the temporary file can effectively hijack the temporary file by creating a symlink with the name of the temporary file before the program creates the file itself. This allows a malicious user to supply malicious data or cause actions by the program to affect the attacker chosen files. The Go standard library provides several secure ways to create temporary files and directories. As a recommended practice when creating a temporary file, use os.TempDir()/ioutil.TempDir() to get the name of the directory and ioutil.TempFile() to create a file - instead of os.Create. Please note that it’s the caller’s responsibility to remove the file. Using the recommended functions from the standard library creates the temporary directory in the correct temporary directories of the target Operating System the program is running on, and the file name is also randomized.

Bad practice

package samples

import (
    "fmt"
    "io/ioutil"
)

func main() {
    err := ioutil.WriteFile("/tmp/demo2", []byte("This is some data"), 0644)
    if err != nil {
        fmt.Println("Error while writing!")
    }
}

Recommended

package main

import (
    "fmt"
    "io/ioutil"
    "os"
)

func main() {
    content := []byte("This is some data")

    dir, err := ioutil.TempDir(os.TempDir(), "")
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }

    tmp, err := ioutil.TempFile(dir, "demo2")
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
    defer tmp.Close()

    _, _ = tmp.Write(content)
}

References