SecPrep logoSecPrep

What is wrong with how this code runs a shell command?

Vulnerable code

javascript
const { exec } = require('child_process');
exec(`ping -c 1 ${req.query.host}`, (e, out) => res.send(out));
OS Command Injection

Fixed

javascript
const { execFile } = require('child_process');
execFile('ping', ['-c', '1', req.query.host], (e, out) => res.send(out));

Building a shell string from user input enables OS command injection (e.g. ; rm -rf /). Avoid the shell: pass arguments as an array to execFile/spawn without shell: true, and validate/allow-list input.

Practice this in the app →