Delete System Directory

ID

go.delete_system_directory

Severity

high

Remediation Complexity

simple

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Go

Tags

CWE:22, data-loss, filesystem, reliability

Description

Reports os.RemoveAll(x) where x holds a bare system or user directory obtained from os.TempDir(), os.UserHomeDir(), os.UserCacheDir() or os.UserConfigDir(). Removing one of those directories recursively deletes the user’s entire temp/home/cache/config tree.

Rationale

os.RemoveAll removes a path and everything under it. Pointed at a top-level system or user directory it destroys the whole tree — all of the user’s temporary files, their home directory, or the application data of every program on the machine. That is almost never intended; the code usually means to remove a specific subdirectory it created. The check is conservative: it fires only when the argument is a variable assigned directly from one of the system-directory functions and not subsequently narrowed (for example by filepath.Join).

func cleanup() {
    x := os.TempDir()
    os.RemoveAll(x) // FLAW — deletes the entire temporary directory
}

func ok() {
    x := os.TempDir()
    dir := filepath.Join(x, "myapp")
    os.RemoveAll(dir) // OK — removes only the application's own subdirectory
}

Remediation

Join the system directory with an application-specific subdirectory and remove only that, never the bare system directory itself.