Unsanitized dynamic input in OS command

Description

OS command injection is a severe security vulnerability that occurs when an application incorrectly processes external input. This flaw can allow attackers to execute arbitrary commands on the host operating system, potentially leading to a full system compromise.

Remediations

Prevent OS command injection by adhering to the following practices:

❌ Avoid Direct External Input

Do not use externally-supplied information for constructing OS commands or command-line arguments, as this can lead to command injection vulnerabilities.

✅ Implement Input Validation

Ensure that any external input is validated against a set of strict rules to ensure it does not contain malicious characters or patterns.

✅ Use Hardcoded Arguments

When invoking OS commands, use a hardcoded set of arguments to ensure that external input cannot alter the command's behavior.

✅ Utilize Temporary Files Securely

When dealing with files, create temporary files in a restricted directory, avoiding the use of user-supplied filenames.

✅ Employ Native Libraries

Where possible, use native libraries or features of the programming language instead of invoking shell commands, which can be safer and more efficient.

import (
"io/ioutil"
"os/exec"
"log"
)

func main() {
userData := []byte("user data")

// Create a temporary file in a secure, application-specific directory
f, err := ioutil.TempFile("/var/app/restricted", "temp-*.dat")
if err != nil {
log.Fatal(err)
}

// Write user data to the temporary file
if _, err := f.Write(userData); err != nil {
f.Close()
log.Fatal(err)
}

// Close the file handle
if err := f.Close(); err != nil {
log.Fatal(err)
}

// Execute a command using the temporary file, avoiding direct external input for filenames
out, err := exec.Command("/bin/cat", f.Name()).Output()
if err != nil {
log.Fatal(err)
}
// Output can be used for further processing
}

Resources

Associated CWE

OWASP Top 10

Configuration

To skip this rule during a scan, use the following flag

bearer scan /path/to/your-project/ --skip-rule=go_gosec_injection_subproc_injection

To run only this rule during a scan, use the following flag

bearer scan /path/to/your-project/ --only-rule=go_gosec_injection_subproc_injection