Description
In a shared directory such as /tmp, a fixed temporary name can refer to an existing file or symbolic link. Broad permissions can also let other users read or change the contents.
Potential impact
The process may overwrite configuration or logs, or expose sensitive temporary data. A privileged process may also overwrite protected system files.
Remediation
- Pass a directory and a prefix to
os.CreateTemp. It supplies a random suffix and opens a new file. The olderioutil.TempFiledelegates toos.CreateTemp. - Check that other users cannot replace the path or modify the file. On POSIX, creation requests mode
0o600before theumask. Close the file and callos.Removewhen you finish. - Where possible, keep passwords, tokens and personal data in memory or in protected storage.
Examples
Before
go
package main
import (
"fmt"
"os"
)
func unsafeTemp() {
// Before: use a fixed filename under /tmp
path := "/tmp/report.log"
// Another user or process may create this filename first
// or place a symbolic link at that path
f, err := os.Create(path)
if err != nil {
fmt.Println("failed to create temp file:", err)
return
}
defer f.Close()
// Default permissions, such as 0644, may allow
// other users to read the contents
if _, err := f.WriteString("user session token: abc123\n"); err != nil {
fmt.Println("failed to write:", err)
return
}
}
func main() {
unsafeTemp()
}
After
go
package main
import (
"fmt"
"os"
)
func safeTemp() {
// Create a temporary file in /tmp using the report- prefix
// A random suffix reduces filename collisions
f, err := os.CreateTemp("/tmp", "report-")
if err != nil {
fmt.Println("failed to create temp file:", err)
return
}
// Save the name and schedule removal with defer
tempName := f.Name()
defer os.Remove(tempName)
defer f.Close()
// Restrict permissions for sensitive data, for example to 0600
if err := os.Chmod(tempName, 0o600); err != nil {
fmt.Println("failed to chmod temp file:", err)
return
}
if _, err := f.WriteString("temporary processing data\n"); err != nil {
fmt.Println("failed to write:", err)
return
}
fmt.Println("temp file created:", tempName)
}
func main() {
safeTemp()
}
The example uses the report- prefix. os.Chmod sets 0o600 after creation. On return, calls registered with defer run in reverse order, closing the file before attempting removal.