Command injection: keep input out of the shell and out of the command
Command injection happens when an application builds an operating system command from input and the input changes what the command does.
This guide shows what a shell does with a command string, what an argument array changes, what the environment and working directory still decide, and gives you a local Node.js lab whose marker tests check that shell metacharacters stay data.
In this guide
Process-execution lab: shell strings, argument arrays and marker tests
An illustration written for this page, not client code. Six runners hand the same file name to a stand-in program, a comparison script prints what the program received, and a regression test on Node.js's built-in test runner fails for the four unsafe runners and passes for the two safe ones.
How to use itHide the instructions
It needs Node.js only, and a POSIX shell at /bin/sh for the unsafe steps. Every marker only prints a fixed word or changes a harmless option. Use it on your own machine to learn, and to test code you own.
command-injection.txt
ILLUSTRATION ONLY. The thumbnail feature, the stand-in program and every input below were written for this page. They are not a client's code or a client's result. Use the lab on your own machine to learn, and to test code you own. Do not point any part of it at a system you do not own or are not authorised in writing to test.
WHAT IT NEEDS
Node.js, with nothing to install. The lab uses only built-in modules: node:child_process, node:util, node:fs, node:os, node:path, node:url, node:assert and node:test. The Node.js documentation marks the test runner stable, and util.parseArgs no longer experimental, from version 20.0.0. Steps 1 to 3 hand a string to /bin/sh, the shell Node.js uses on Unix, so run the lab on macOS or Linux, or under WSL on Windows.
The outputs below were recorded on Node.js 26.0.0 on macOS. The comparison printed the same lines on Node.js 22.14.0, without the step 3 warning.
WHAT IT DOES NOT DO
Markers F1 to F5 only print a fixed word, such as CMDI-MARKER-F1, if a shell reads them as syntax. Marker F6 only changes an option that the stand-in program reports. Nothing reads a file, opens a network connection or changes your system. The only programs started are Node.js and, in steps 1 to 3, /bin/sh running echo. compare.mjs and the test move their own process into your temporary folder and set a made-up variable, LAB_FAKE_SECRET, inside that process.
SET-UP
Create an empty folder with a plain name, such as cmdi-lab, on a path with no quote marks or dollar signs in it, because steps 1 to 3 put the folder's path inside a shell string. Save the five files below into it under the names shown, then run the commands under RUN IT from that folder.
==== File 1 of 5: fake-tool.mjs ====
// fake-tool.mjs: a stand-in for a command-line program, such as a
// thumbnail maker. It changes nothing on your machine. It prints one line
// of JSON saying what it received, so the lab can compare that with what
// the runner meant to send.
import { parseArgs } from 'node:util'
const parsed = parseArgs({
options: { 'out-dir': { type: 'string' } },
allowPositionals: true,
strict: false,
})
const report = {
outDir: parsed.values['out-dir'],
files: parsed.positionals,
cwd: process.cwd(),
seesFakeSecret: 'LAB_FAKE_SECRET' in process.env,
}
console.log(JSON.stringify(report))
==== File 2 of 5: runners.mjs ====
// runners.mjs: six ways to hand a customer's file name to the same
// program. Steps 1 to 4 are wrong on purpose. Run them only on your own
// machine, and never copy them into an application.
import { execFileSync, execSync } from 'node:child_process'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
export const LAB_DIR = path.dirname(fileURLToPath(import.meta.url))
const TOOL = path.join(LAB_DIR, 'fake-tool.mjs')
const NODE = process.execPath
// Wraps a path in double quotes so a folder name with spaces still works.
function quoted(text) {
return '"' + text + '"'
}
// Step 1 (unsafe): one string, handed to /bin/sh to parse.
export function shellString(fileName) {
const command = quoted(NODE) + ' ' + quoted(TOOL) + ' --out-dir=thumbs ' + fileName
return execSync(command, { encoding: 'utf8' })
}
// Step 2 (unsafe): the same string with quotes added around the input.
export function quotedShellString(fileName) {
const command = quoted(NODE) + ' ' + quoted(TOOL) + ' --out-dir=thumbs "' + fileName + '"'
return execSync(command, { encoding: 'utf8' })
}
// Step 3 (unsafe): an argument array, but with the shell switched on.
export function arrayWithShell(fileName) {
const args = [quoted(TOOL), '--out-dir=thumbs', fileName]
return execFileSync(quoted(NODE), args, { encoding: 'utf8', shell: true })
}
// Step 4 (better, not finished): an argument array with no shell.
export function argumentArray(fileName) {
const args = [TOOL, '--out-dir=thumbs', fileName]
return execFileSync(NODE, args, { encoding: 'utf8' })
}
// Step 5 (the launch to copy): no shell, the input after "--" so it
// cannot be read as an option, and a working folder and environment
// chosen by the code rather than inherited from the caller.
export function controlledLaunch(fileName) {
const args = [TOOL, '--out-dir=thumbs', '--', fileName]
return execFileSync(NODE, args, {
encoding: 'utf8',
shell: false,
cwd: LAB_DIR,
env: { PATH: '/usr/bin:/bin' },
})
}
// Step 6 (the whole pattern): an allow-list check, then step 5.
const ALLOWED_NAME = /^[a-z0-9][a-z0-9-]{0,62}\.pdf$/
export function safeRunner(fileName) {
if (!ALLOWED_NAME.test(fileName)) {
throw new Error('REJECTED: the file name is not on the allow-list')
}
return controlledLaunch(fileName)
}
export const RUNNERS = {
shellString,
quotedShellString,
arrayWithShell,
argumentArray,
controlledLaunch,
safeRunner,
}
==== File 3 of 5: markers.mjs ====
// markers.mjs: the marker inputs and the check that reads what came back.
// F1 to F5 only print a fixed word if a shell treats them as syntax. F6
// only changes the option the stand-in program reports. Nothing here reads
// files, opens connections or changes your system.
import fs from 'node:fs'
import { LAB_DIR } from './runners.mjs'
export const FIXTURES = [
{ id: 'F1', label: '; separator', input: 'invoice-17.pdf; echo CMDI-MARKER-F1' },
{ id: 'F2', label: '&& chain', input: 'invoice-17.pdf && echo CMDI-MARKER-F2' },
{ id: 'F3', label: '| pipe', input: 'invoice-17.pdf | echo CMDI-MARKER-F3' },
{ id: 'F4', label: '$( ) substitution', input: 'invoice-$(echo CMDI-MARKER-F4).pdf' },
{ id: 'F5', label: '" closes a quote', input: 'invoice-17.pdf"; echo CMDI-MARKER-F5; echo "' },
{ id: 'F6', label: 'option flag', input: '--out-dir=CMDI-MARKER-F6' },
{ id: 'B1', label: 'plain name', input: 'invoice-17.pdf' },
]
// Runs one input and returns a verdict plus the program's own report.
export function runAndCheck(runner, input) {
let stdout
try {
stdout = runner(input)
} catch (error) {
if (error.message.startsWith('REJECTED')) return { verdict: 'REJECTED', report: null }
return { verdict: 'COMMAND FAILED', report: null }
}
return checkOutput(input, stdout)
}
function checkOutput(input, stdout) {
const lines = stdout.split('\n').filter((line) => line.trim() !== '')
const reportLine = lines.find((line) => line.startsWith('{'))
const markerLine = lines.find((line) => !line.startsWith('{') && line.includes('CMDI-MARKER'))
if (markerLine) return { verdict: 'EXTRA COMMAND RAN: printed ' + markerLine, report: null }
if (!reportLine) return { verdict: 'COMMAND FAILED', report: null }
const report = JSON.parse(reportLine)
if (report.outDir !== 'thumbs') {
return { verdict: 'BECAME AN OPTION: out-dir is now ' + report.outDir, report }
}
if (report.files.length !== 1 || report.files[0] !== input) {
return { verdict: 'ARGUMENT CHANGED: received ' + JSON.stringify(report.files), report }
}
return { verdict: 'DATA', report }
}
// True when the program ran in the lab folder rather than the caller's folder.
export function ranInLabFolder(report) {
return fs.realpathSync(report.cwd) === fs.realpathSync(LAB_DIR)
}
==== File 4 of 5: compare.mjs ====
// compare.mjs: runs every marker through every step and prints a verdict.
// It starts from a temporary folder, as a server can be started from a
// folder other than the one holding your code, and it gives itself a
// made-up secret to see whether the program inherits it.
import os from 'node:os'
import { FIXTURES, ranInLabFolder, runAndCheck } from './markers.mjs'
import { RUNNERS } from './runners.mjs'
process.chdir(os.tmpdir())
process.env.LAB_FAKE_SECRET = 'not-a-real-secret'
let step = 1
for (const [name, runner] of Object.entries(RUNNERS)) {
console.log('Step ' + step + ': ' + name)
for (const fixture of FIXTURES) {
const result = runAndCheck(runner, fixture.input)
console.log(' ' + fixture.id + ' ' + fixture.label.padEnd(20) + result.verdict)
}
const plain = runAndCheck(runner, 'invoice-17.pdf').report
console.log(' Program saw LAB_FAKE_SECRET: ' + (plain.seesFakeSecret ? 'yes' : 'no'))
console.log(' Program ran in: ' + (ranInLabFolder(plain) ? 'the lab folder' : 'the caller\'s folder'))
console.log('')
step = step + 1
}
==== File 5 of 5: marker.test.mjs ====
// marker.test.mjs: a regression test for whichever runner LAB_RUNNER names.
// It passes for controlledLaunch and safeRunner and fails for steps 1 to 4.
import assert from 'node:assert/strict'
import os from 'node:os'
import { test } from 'node:test'
import { FIXTURES, ranInLabFolder, runAndCheck } from './markers.mjs'
import { RUNNERS } from './runners.mjs'
const runnerName = process.env.LAB_RUNNER || 'safeRunner'
const runner = RUNNERS[runnerName]
process.chdir(os.tmpdir())
process.env.LAB_FAKE_SECRET = 'not-a-real-secret'
for (const fixture of FIXTURES) {
test(fixture.id + ' ' + fixture.label + ' stays data', () => {
const { verdict } = runAndCheck(runner, fixture.input)
const allowed = fixture.id === 'B1' ? ['DATA'] : ['DATA', 'REJECTED']
assert.ok(allowed.includes(verdict), runnerName + ' gave ' + verdict)
})
}
test('the program does not see the caller\'s secret', () => {
const { report } = runAndCheck(runner, 'invoice-17.pdf')
assert.equal(report.seesFakeSecret, false)
})
test('the program runs in the lab folder', () => {
const { report } = runAndCheck(runner, 'invoice-17.pdf')
assert.equal(ranInLabFolder(report), true)
})
==== RUN IT ====
node compare.mjs
node --test marker.test.mjs
LAB_RUNNER=controlledLaunch node --test marker.test.mjs
LAB_RUNNER=argumentArray node --test marker.test.mjs
LAB_RUNNER=quotedShellString node --test marker.test.mjs
LAB_RUNNER=shellString node --test marker.test.mjs
LAB_RUNNER=arrayWithShell node --test marker.test.mjs
==== OUTPUT OF node compare.mjs (Node.js 26.0.0, macOS) ====
Step 1: shellString
F1 ; separator EXTRA COMMAND RAN: printed CMDI-MARKER-F1
F2 && chain EXTRA COMMAND RAN: printed CMDI-MARKER-F2
F3 | pipe EXTRA COMMAND RAN: printed CMDI-MARKER-F3
F4 $( ) substitution ARGUMENT CHANGED: received ["invoice-CMDI-MARKER-F4.pdf"]
F5 " closes a quote ARGUMENT CHANGED: received ["invoice-17.pdf; echo CMDI-MARKER-F5; echo "]
F6 option flag BECAME AN OPTION: out-dir is now CMDI-MARKER-F6
B1 plain name DATA
Program saw LAB_FAKE_SECRET: yes
Program ran in: the caller's folder
Step 2: quotedShellString
F1 ; separator DATA
F2 && chain DATA
F3 | pipe DATA
F4 $( ) substitution ARGUMENT CHANGED: received ["invoice-CMDI-MARKER-F4.pdf"]
F5 " closes a quote EXTRA COMMAND RAN: printed CMDI-MARKER-F5
F6 option flag BECAME AN OPTION: out-dir is now CMDI-MARKER-F6
B1 plain name DATA
Program saw LAB_FAKE_SECRET: yes
Program ran in: the caller's folder
Step 3: arrayWithShell
F1 ; separator EXTRA COMMAND RAN: printed CMDI-MARKER-F1
F2 && chain EXTRA COMMAND RAN: printed CMDI-MARKER-F2
F3 | pipe EXTRA COMMAND RAN: printed CMDI-MARKER-F3
F4 $( ) substitution ARGUMENT CHANGED: received ["invoice-CMDI-MARKER-F4.pdf"]
F5 " closes a quote ARGUMENT CHANGED: received ["invoice-17.pdf; echo CMDI-MARKER-F5; echo "]
F6 option flag BECAME AN OPTION: out-dir is now CMDI-MARKER-F6
B1 plain name DATA
Program saw LAB_FAKE_SECRET: yes
Program ran in: the caller's folder
Step 4: argumentArray
F1 ; separator DATA
F2 && chain DATA
F3 | pipe DATA
F4 $( ) substitution DATA
F5 " closes a quote DATA
F6 option flag BECAME AN OPTION: out-dir is now CMDI-MARKER-F6
B1 plain name DATA
Program saw LAB_FAKE_SECRET: yes
Program ran in: the caller's folder
Step 5: controlledLaunch
F1 ; separator DATA
F2 && chain DATA
F3 | pipe DATA
F4 $( ) substitution DATA
F5 " closes a quote DATA
F6 option flag DATA
B1 plain name DATA
Program saw LAB_FAKE_SECRET: no
Program ran in: the lab folder
Step 6: safeRunner
F1 ; separator REJECTED
F2 && chain REJECTED
F3 | pipe REJECTED
F4 $( ) substitution REJECTED
F5 " closes a quote REJECTED
F6 option flag REJECTED
B1 plain name DATA
Program saw LAB_FAKE_SECRET: no
Program ran in: the lab folder
During step 3, Node.js 26.0.0 also wrote this warning to stderr, followed by a line on how to trace it. The number after "node:" is the process id and changes with each run:
(node:89251) [DEP0190] DeprecationWarning: Passing args to a child process with shell option true can lead to security vulnerabilities, as the arguments are not escaped, only concatenated.
==== REGRESSION TEST RESULTS (Node.js 26.0.0) ====
Each run reported 9 tests. The pass and fail counts are copied from the test runner's summary lines.
LAB_RUNNER pass fail exit code
safeRunner (default) 9 0 0
controlledLaunch 9 0 0
argumentArray 6 3 1
quotedShellString 4 5 1
shellString 1 8 1
arrayWithShell 1 8 1
A failed check names its verdict. The first failure for shellString read:
AssertionError [ERR_ASSERTION]: shellString gave EXTRA COMMAND RAN: printed CMDI-MARKER-F1
==== READING THE VERDICTS ====
DATA: the program received exactly the text that was sent, as one file name, with --out-dir unchanged, and nothing else ran. A pass.
REJECTED: the runner refused the input before any process started. A pass for F1 to F6, and a fail for B1, which must arrive.
EXTRA COMMAND RAN: a marker word was printed outside the program's own output, so the shell ran a second command.
ARGUMENT CHANGED: the program received different text from what was sent, so the shell rewrote the input before the program saw it.
BECAME AN OPTION: the input replaced the program's --out-dir setting, so a value was read as an option.
COMMAND FAILED: the shell or the program exited with an error, so the input broke the command.
==== USING THE TEST ON YOUR OWN CODE ====
1. Find each place your code starts a process: exec, execSync, spawn or execFile with a shell option, and any .bat or .cmd file on Windows.
2. Make each one a function that takes the untrusted value, like the runners above, and point it at a stand-in program that prints what it received.
3. Copy markers.mjs and marker.test.mjs, add your function to RUNNERS, and run the test with LAB_RUNNER set to its name.
4. Add markers built from the characters your own allow-list accepts, such as a value that starts with a hyphen if hyphens are allowed, and a benign value from real use, such as a real file name, so the test also shows when validation is stricter than it needs to be.
5. Keep the test in your suite, so a later change that brings the shell back fails a build instead of reaching production.What command injection is
Command injection, also called OS command injection, is what happens when an application builds an operating system command from input it does not control, and the input changes the command.
OWASP's OS Command Injection Defense Cheat Sheet defines it as a type of injection where software that constructs a system command using externally influenced input does not correctly neutralise the input from special elements that can modify the initially intended command. MITRE catalogues the weakness as CWE-78 and gives shell injection and shell metacharacters as alternate terms.
CWE-78 describes two forms. In the first, the application means to run one fixed program and passes input as its arguments; if command separators in that input are not removed, an attacker can run a program of their own after the intended one finishes. In the second, the input selects which program runs, so whoever controls it can run arbitrary commands.
CWE-78 calls these distinct programmer errors: in the first the developer meant untrusted input to become arguments, and in the second the developer did not intend the command to be reachable by any untrusted party.
The harm comes from the command running as your application. CWE-78 says attackers could execute unauthorised operating system commands, which could be used to disable the product or to read and modify data they have no permission to access directly, and that because the application runs the commands, the activity may appear to come from the application or its owner.
The standards place it in the injection family. OWASP's Top 10:2025 entry A05:2025 Injection names OS command injection among what it calls the more common injections, and its mapped weaknesses include CWE-77, CWE-78 and CWE-88. ASVS 5.0 requirement 1.2.5, a Level 1 requirement, asks that the application protects against OS command injection and that operating system calls use parameterised OS queries or contextual command line output encoding.
This guide covers how a command is built from input and handed to the operating system. What the resulting process can reach once it runs, and the privileges behind it, belong to the remote code execution guide in this library.
Shell injection: what a shell does with a command string
There are two ways to ask the operating system to start a program.
One hands a single string to a shell, which reads it as a small script. The other names the program and passes its arguments as a list. CWE-78 draws the same line with C: system() accepts a string that contains the entire command, whereas execl(), execve() and others require an array of strings, one for each argument.
Its advice is, where possible, to identify any function that invokes a command shell using a single string and replace it with one that requires individual arguments.
OWASP's cheat sheet explains why the difference matters. C's system function passes its arguments to the shell, /bin/sh, to be parsed. Its note on Java's Runtime.exec(String), which does not invoke a shell, says that much of the shell functionality that could be used for mischief, chaining commands with &, &&, | and || and redirecting input and output, would end up as a parameter passed to the first command, likely causing a syntax error or being thrown out as an invalid parameter.
The characters to watch are shell syntax. The cheat sheet's Note A lists & | ; $ > < ` \ ! ' " ( ) as metacharacters to keep out of an allow-list pattern. The WSTG test for command injection, WSTG-INPV-12, describes what several of them do: with | or ; a second command runs whether or not the first succeeded, || runs it only if the first fails and && only if the first succeeds, and it lists $(cmd) among the other forms.
Adding quotes around the input does not turn a shell string into an argument list. In step 2 of the lab on this page, the input invoice-$(echo CMDI-MARKER-F4).pdf still reached the program as invoice-CMDI-MARKER-F4.pdf inside double quotes, because the shell ran the echo and pasted in its output, and a double quote in another input ended the quoted section early so its marker command ran.
Argument injection: when input becomes an option
Removing the shell closes one route and leaves another.
The cheat sheet says every OS command injection is also an argument injection, in which user input can be passed as arguments while executing a specific command. Its example escapes a URL before handing it to curl, which stops other commands from running, but an input of --help is still read as curl's help option.
Depending on the command, it says, the impact can range from information disclosure to critical remote code execution.
MITRE tracks this as CWE-88, a command string that does not properly delimit the intended arguments, options or switches. CWE-78's relationships list CWE-88 as a weakness it can also be, and its terminology note says that when argument injection inserts alternate command-line switches, CWE-88 could be regarded as the primary weakness in a chain with CWE-78.
The fix lives in the code that builds the call. The cheat sheet's PHP section recommends hardcoding the command, so the user never chooses which executable runs, and hardcoding required options such as --directory-prefix in the code rather than in user input.
For commands that support it, it recommends -- to end option parsing, and warns that in curl later arguments are still URL operands, so -- does not prevent additional transfers, and that argument separation does not validate the destination.
In the lab, the input --out-dir=CMDI-MARKER-F6 replaced the program's output folder setting in every step that passed it before a --, including step 4, which uses no shell at all.
How Node.js starts a process: exec, execFile and spawn
Node.js offers both styles in node:child_process.
Its documentation says child_process.exec() spawns a shell and runs a command within that shell, that the command string is processed directly by the shell, and that special characters vary based on the shell. The default shell is /bin/sh on Unix and process.env.ComSpec on Windows. For exec() and execSync() it says never to pass unsanitised user input, because any input containing shell metacharacters may be used to trigger arbitrary command execution.
child_process.execFile() does not spawn a shell by default. The documentation says the executable is spawned directly as a new process, and that because no shell is spawned, behaviours such as I/O redirection and file globbing are not supported. child_process.spawn() takes the command and a separate list of string arguments, and its shell option defaults to false.
Both accept a shell option, and the documentation repeats its warning for each when that option is on.
Switching the shell on undoes the argument list. Node.js deprecation DEP0190 says that when an args array is passed to execFile or spawn with shell: true, or with a path to a shell, the values are not escaped, only space-separated, which can lead to shell injection.
It became a runtime deprecation in Node.js 24.0.0. In the lab, step 3 passes a tidy array with the shell on, gives the same results as the raw string in step 1, and makes Node.js 26.0.0 print a DEP0190 warning.
Windows needs its own care. The documentation says .bat and .cmd files are not executable on their own without a terminal, so execFile() cannot launch them. They can be run with exec(), by spawning cmd.exe with the file as an argument, which is what exec() does internally, or with spawn() and the shell option, which it does not recommend.
Each route puts a command interpreter between your code and the script. The cheat sheet's .NET advice applies here too: do not pass untrusted input to command interpreters such as cmd.exe, powershell.exe or sh -c.
What the environment and working directory still decide
An argument list settles what the program receives as arguments.
Two more inputs travel with every process start. The Node.js documentation says the env option defaults to process.env, so a child sees every variable the parent holds, including any keys kept in environment variables, unless your code passes its own object. Without a cwd option, the child inherits the current working directory.
The environment also decides which program a bare name refers to. Node.js looks the command up using options.env.PATH when env is given and process.env.PATH otherwise, and when env is set without PATH, lookup on Unix uses a default search path of /usr/bin:/bin.
CWE-78's terminology note says that for some people OS command injection covers any attack that lets the attacker run OS commands of their own choosing, a usage that could include untrusted search path weaknesses, which cause the application to find and run an attacker-controlled program.
The cheat sheet's .NET advice is a fixed, fully qualified executable path; the lab does the same in Node.js by naming process.execPath.
The working directory decides where relative paths land. The lab's program is told --out-dir=thumbs, a relative path, so the folder it starts in decides where a real tool would write. Steps 1 to 4 inherited whichever folder the caller happened to be in; steps 5 and 6 named the lab folder.
Both become injection routes when request data reaches them. If a locale, a folder name, a setting copied from a form or any other request value flows into the environment or the working directory, an attacker can change what the program does without touching its arguments.
CWE-88 lists environment variables among the places untrusted input can enter a product. If the program you call reads settings from its working directory or from environment variables, check its documentation for both, and give it a folder and an environment your code chooses.
A working directory built from a path the user supplied is also a path traversal question, which has its own guide in this library.
Walking through the process-execution lab
The lab is an illustration written for this page, not a client's code.
An invented web application makes a thumbnail of a customer's uploaded PDF by passing the file name to a command-line program. To keep everything on your own machine, the program is a stand-in, fake-tool.mjs, that changes nothing and prints one line of JSON: the file names and the --out-dir value it received, the folder it ran in, and whether it can see a variable called LAB_FAKE_SECRET.
Six runners hand it the same seven inputs.
Six are markers: five only print a fixed word if a shell reads them as syntax, and one only changes an option the stand-in reports. The seventh is an ordinary file name.
Step 1 joins the program's path, a fixed option and the file name into one string and hands it to execSync(), which passes it to /bin/sh. The separator, chain and pipe markers each printed their marker word, because the shell read ;, && and | as instructions to start echo.
The substitution marker reached the program as invoice-CMDI-MARKER-F4.pdf, because the shell ran the echo inside $( ) and pasted its output into the name. The plain file name passed, so a test that only tries ordinary names would pass on this code.
Step 2 wraps the file name in double quotes, a fix that looks reasonable in review. It stopped the first three markers and missed the other two: the substitution still ran inside the quotes, and the quote marker closed the developer's quotes early so its echo ran as a second command. Both steps also let --out-dir=CMDI-MARKER-F6 replace the output folder setting.
Step 3 looks like the fix: execFileSync() with the arguments in an array. It also sets shell: true, the option the Node.js documentation lists for spawn(), without recommending it, as one way to run a Windows .bat or .cmd file. The results matched step 1 line for line, which is what DEP0190 describes: the array values are not escaped, only space-separated, before the shell reads them.
The deprecation warning was the only visible difference on Node.js 26.0.0, and on Node.js 22.14.0 the same run printed no warning at all.
Step 4 removes the shell. All five shell markers arrived at the program exactly as sent, metacharacters included, as one file name. That is the central result: without a shell, there is nothing to read ;, |, $( ) or a quote mark as syntax. The option marker still became --out-dir, because the program, not the shell, decides what a leading -- means.
The program could also still see LAB_FAKE_SECRET and ran in the caller's folder, which compare.mjs sets to a temporary folder before it starts, standing in for a server started from somewhere other than its code.
Step 5 keeps step 4 and adds three things: a -- before the file name, so the stand-in treats everything after it as a file name, a cwd naming the lab folder, and an env object holding only PATH. Every marker now arrived as data, including --out-dir=CMDI-MARKER-F6 as a file name, the fake secret was no longer visible, and the program ran in the lab folder.
Step 6 puts an allow-list in front of step 5: lowercase letters, digits and hyphens, ending in .pdf, starting with a letter or digit. Every marker was rejected before any process started, and the plain name still arrived. The allow-list is the first check, and the controlled launch is the one that still holds if someone loosens the pattern later, which is why both pass the same test.
marker.test.mjs runs nine checks against the runner LAB_RUNNER names: one per input, one for the secret and one for the folder. On Node.js 26.0.0, safeRunner and controlledLaunch passed all nine. argumentArray failed three: the option marker, the secret and the folder. quotedShellString failed five, and shellString and arrayWithShell each failed eight, passing only the plain file name. Each failure message names the verdict, so a red build says which kind of injection came back.
Command injection prevention in a real code base
The lab's step 6 is the shape to copy, but a real code base can do better than validating a customer's file name.
These are the changes to make, starting with the ones that remove the external program or the customer's text from the call altogether.
- Avoid the external program where a library does the job. The cheat sheet's primary defence is to avoid calling OS commands directly, using built-in library functions such as mkdir() in place of system("mkdir /dir_name"), and CWE-78 says, if at all possible, to use library calls rather than external processes. The file, image and archive work that tempts code into a shell call is worth checking for a library first.
- Never pass the customer's text when an identifier will do. Under enforcement by conversion, CWE-78 says that when the set of acceptable objects, such as filenames or URLs, is limited or known, map fixed input values such as numeric IDs to the actual filenames and reject all other inputs. Store each upload under a name your code generates, look it up by ID, and pass that name. CWE-78 also says to keep as much of the data used to build a command out of external control as possible, for example in the session's state rather than a hidden form field.
- When a process is necessary, start it without a shell. In Node.js that is execFile() or spawn() with the shell option left off, the program named by a fixed path, and every value as its own array element.
- Hardcode the program and its options, and put the untrusted value after --. The cheat sheet says to hardcode the command so the user never chooses which executable runs, to keep required flags in the code rather than in user input, and to use -- to end option parsing for commands that support it. Check that your program honours --, and never let input supply an option flag.
- Allow-list the value as well. The cheat sheet asks for the command to be validated against a list of allowed commands, and for each argument to be validated by an explicit list of allowed values, or by an allow-list pattern that defines the allowed characters and a maximum length and leaves out metacharacters and whitespace. Its example allows only lowercase letters and numbers, three to ten characters long. Its Java section adds that separating arguments does not replace validating them.
- Set the working directory and the environment yourself. Pass cwd as a folder your code owns, never one built from a request, and pass env as the variables the program needs rather than everything the server holds.
- Treat escaping as a fallback. The cheat sheet lists escaping per operating system, such as PHP's escapeshellarg(), and notes an attacker can still pass a single argument to the command. OWASP's A05:2025 entry warns that escaping techniques are error-prone, and offers them for when data cannot be separated from commands.
- Give the process the least it needs. Both the cheat sheet and CWE-78 recommend running with the lowest privileges required, and isolated accounts with limited privileges used for a single task where possible. The WSTG adds that the web application and its components should run under strict permissions that do not allow operating system command execution. The remote code execution guide covers what a process can reach once it runs.
- Keep error messages short. CWE-78 notes that error information passed back to the user might reveal whether an OS command is being executed and possibly which command is used. Log the detail on the server instead.
- Treat a web application firewall as a stopgap, not the fix. CWE-78 rates an application firewall's effectiveness as moderate, says it can help where the code cannot be fixed or as an emergency measure, and notes it might not cover all input vectors and that bypass techniques might be available.
Command injection testing in code and on a running build
WSTG-INPV-12, Testing for Command Injection, has one objective: identify and assess the command injection points.
Its examples add a pipe or a semicolon and a command to a parameter, such as a document name in a URL or a form field, and its remediation asks for an allow list of allowable characters or commands to validate user input.
In code, start from the calls. The WSTG's list of dangerous APIs covers Java, C and C++, Python and PHP and does not name Node.js, so for a Node.js code base add the calls this guide has covered: exec() and execSync(), spawn() or execFile() with a shell option, and any .bat or .cmd file launched on Windows.
For each call, trace where the program name, every argument, the environment and the working directory come from, back to the request that can influence them. CWE-78 says automated static analysis can often detect this weakness, but might not recognise proper input validation, which produces false positives, and might miss custom API functions or third-party libraries that invoke OS commands indirectly, which produces false negatives. A library that starts a process for you is still a process call to trace.
Against a running build, use markers like the lab's: inputs that only print a fixed word, or change a harmless option, if something reads them as syntax, sent only to an application you own or are authorised in writing to test.
The evidence is a marker word where it should not appear, or a value that arrives changed. Nothing beyond that is needed to show the flaw, and nothing in the lab reads files, opens connections or changes a system.
Then add the case to a regression test like marker.test.mjs, so a later change that brings the shell back fails a build.
Where an outside review fits
The lab tests the calls you know about.
A review looks for the ones you do not. Clever Ops reviews code for applications such as Next.js, React and Node with read-only access to the repository, and a secure code review follows the paths in scope, looking at untrusted input along the way. Code findings are confirmed against a running build where the scope allows, and the report marks any that rest on the code alone.
A web application and API penetration test exercises the running application, and read-only code access to named areas can be added to confirm how a control is enforced. If Clever Ops built or hosts your application, the work is a security review rather than an independent test, and the report says who built it and who hosts it.
Frequently asked questions
For practical purposes, yes. MITRE lists shell injection, shell metacharacters and OS command injection as alternate terms for CWE-78. CWE-78 sits under CWE-77, the broader weakness for special elements in any command, and beside CWE-88, argument injection, where the input changes a program's options rather than starting another command.
Step 1 of the lab on this page is one. A thumbnail feature joins a fixed command and a customer's file name into one string and hands it to /bin/sh. The file name invoice-17.pdf; echo CMDI-MARKER-F1 makes the shell run echo after the program, and the marker word appears in the output. OWASP's cheat sheet gives a Windows example: a value of calc opens the Calculator, and calc & echo "test" opens it and prints test as well.
It reduces the risk and leaves some behind. OWASP's cheat sheet says PHP's escapeshellarg() prevents OS command injection, but an attacker can still pass a single argument to the command, and OWASP's A05:2025 entry calls escaping techniques error-prone. Run the program without a shell, pass values as separate arguments after --, and allow-list them. Step 2 of the lab shows that adding quotes inside the command string stops some markers and misses others.
It removes the shell, which closes the route the lab's shell markers use. In the lab, execFileSync() with an argument array delivered every shell marker as plain data. It did not stop --out-dir=CMDI-MARKER-F6 from changing the program's option, and the program still inherited the parent's environment and working folder. Turning the shell option on undoes the rest: Node.js deprecation DEP0190 says array values are then only space-separated, not escaped.
Use markers that only print a fixed word if a shell reads them, or that change a harmless option, never inputs that read files, open connections or change a system. Run them on your own machine or against an application you own or are authorised in writing to test, and keep a regression test that fails if a marker comes back. The lab on this page is built that way.
It can reduce exposure while code is fixed. CWE-78 rates an application firewall's effectiveness as moderate, says it can be useful where the code cannot be fixed or as an emergency measure, and notes it might not cover all input vectors and that bypass techniques might be available. The fix belongs in the code that builds the command.
Scope the right test for your application
Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.