JavaScript

JavaScript

By DeepSource

Audit: Unsanitized user input supplied to cat command is prone to command injection JS-A1003

Security

The cat command allows you to view the contents of a file. However, if you use cat with unsanitized user input, you may be vulnerable to injection attacks.

If the file name supplied to cat comes from an external entity, the file name can have some malicious commands along with it. In this case, cat would not only display you the contents of the file but will also execute the injected commands.

Moreover, if your application has elevated privileges, a user can use cat to view the contents of sensitive files as well.

Example of how a user can construct their input to inject malicious commands in your application:

const fileName = getFileNameFromUser()

// If the user input is `fileName.txt; rm -rf ./someImportantDirectory`, the `rm -rf` command will be executed as well.
const out = execSync(`cat ${fileName}`)

Bad Practice

import { execSync } from 'child_process'
app.get((req, res) => {
  execSync('cat ' + req.body.fileName) // The user input can be vulnerable
})

Recommended

import { execSync } from 'child_process'
app.get((req, res) => {
  const sanitizedFileName = sanitize(req.body.fileName)
  execSync('cat ' + sanitizedFileName) // The user input is sanitized and safe to use
})

References