Engineer working on a laptop connected to a device test rig, surrounded by wiring harnesses and test hardware

Firmware vulnerabilities & fixes

How to fix command injection in embedded firmware

Last updated:

Command injection (MITRE CWE-78 for the OS shell, CWE-77 for any product-specific command language) happens when firmware builds a command string from attacker-influenced input — a hostname, filename, SSID, or CLI argument — and passes it to a shell or command interpreter without neutralizing the characters that change its meaning. Both MITRE pages are read as of 2026-10-29. The fix is largely architectural: stop invoking a shell at all where a library call will do, and treat every remaining shell invocation as a parameterized call plus allowlist, not as a string to sanitize.

Key takeaways

  • MITRE's 2025 CWE Top 25 ranks CWE-78 ninth, with a score of 7.85 and 20 CVEs mapped to it in CISA's Known Exploited Vulnerabilities catalog.
  • Flag any handler where a user-supplied string (device name, SSID, filename, email address) is concatenated into that command line rather than passed as a discrete, already-separated argument.
  • The grep list above is only useful if you know which calls hand their string to sh.
  • Remove the shell call.

Why does command injection matter for device makers?

MITRE's 2025 CWE Top 25 ranks CWE-78 ninth, with a score of 7.85 and 20 CVEs mapped to it in CISA's Known Exploited Vulnerabilities catalog. CWE-77 ranks 23rd. The CWE-78 entry rates the likelihood of exploit as High. In a device, the injected command usually runs with the rights of the web server or management daemon, which on many embedded builds is root, so one diagnostic field can hand over the whole unit. See our CWE Top 25 guide for how the ranking is computed.

1. Detect

  • Grep the firmware's web UI and CLI handlers (diagnostics, ping/traceroute, firmware upgrade, Wi-Fi/VPN configuration, log export) for calls into system(), popen(), exec*(), backticks, or an equivalent shell-invoking call in your language/SDK, and trace every argument back to its source.
  • Flag any handler where a user-supplied string (device name, SSID, filename, email address) is concatenated into that command line rather than passed as a discrete, already-separated argument.
  • Run static analysis with a rule set that maps to CWE-77/78 (most commercial and open-source SAST tools ship one), and treat a hit on firmware CLI/web-UI code as higher priority than the same hit in a build script, since the former is attacker-reachable over the network.
  • Check CLI protocol parsers (not just the shell) for the CWE-77 case: a device's own management protocol or scripting language can carry the same risk if it does not separate commands from data.

Which calls run a shell, and which do not?

The grep list above is only useful if you know which calls hand their string to sh. The table covers the calls found most often in embedded Linux firmware:

Call Runs a shell? What the specification says
C system() Yes POSIX system() behaves as if the child ran execl(<shell path>, "sh", "-c", command, (char *)0)
C popen() Yes POSIX popen() invokes the sh utility with the same sh -c call
C posix_spawn(), execv(), execve() No The program path and an argument array go straight to the new process; see POSIX posix_spawn()
C posix_spawnp(), execvp() No, but they search PATH A relative program name is looked up in PATH; use an absolute path
Lua os.execute() Yes The Lua 5.4 manual says it "passes command to be executed by an operating system shell"
Lua io.popen() Treat as yes The manual calls it system dependent; on POSIX builds it normally sits on C popen()
Shell eval, sh -c "$x" Yes, a second time The value is parsed again as shell code

Interpreted firmware code (Lua web UIs, PHP on some NAS and router builds, shell CGI) follows the same rule: any call that takes one command string usually goes through a shell.

2. How do you fix it?

  1. Remove the shell callOWASP's primary defense is to "avoid calling OS commands directly" and use a built-in library function instead — a filesystem function for mkdir/rm, a DNS resolver library for a ping-equivalent check, a native Wi-Fi configuration API instead of shelling out to wpa_cli. MITRE's own architecture-and-design mitigation for CWE-78 says the same: use library calls "rather than external processes to recreate the desired functionality."
  2. If a shell call cannot be removed, parameterize itCall the exec-family function with the command and each argument as separate list elements (so the OS invokes the binary directly, with no shell parsing step in between), rather than building one interpolated string that a shell then re-parses.
  3. Add allowlist validation on top of parameterization, not instead of it: validate the command itself against a fixed allowlist, and validate each argument against a strict pattern (for example, a hostname regex) that rejects shell metacharacters (ampersand, pipe, semicolon, dollar sign, angle brackets, backtick, backslash, quotes and parentheses). OWASP is explicit that "argument separation does not replace argument validation" — the two layers address different attack paths.
  4. Treat OS-specific escaping (e.g. `escapeshellarg()`) as a last resort only, when neither of the above is possible — it still allows an attacker to control which arguments reach an otherwise-fixed command.
  5. Run with least privilegeIf the firmware process that shells out does not need root, drop privileges first, so a missed case is contained rather than a full compromise.

Worked example: how do you fix a ping diagnostic handler?

Synthetic example. The device, handler and code are invented for this guide and are not taken from any product.

A hypothetical industrial gateway has a "Ping host" field on its diagnostics page. The handler builds a command string and reads the output:

/* SYNTHETIC - vulnerable */
char cmd[256];
snprintf(cmd, sizeof cmd, "ping -c 4 %s", host);
FILE *p = popen(cmd, "r");

Entering 127.0.0.1;id runs id after the ping, as the web server's user. So do $(id), a backtick pair, or a URL-encoded newline (%0a) followed by a command. The fixed handler never builds a command string:

/* SYNTHETIC - fixed */
static int host_ok(const char *h) {
    struct in_addr a4; struct in6_addr a6;
    if (inet_pton(AF_INET, h, &a4) == 1 || inet_pton(AF_INET6, h, &a6) == 1) return 1;
    size_t n = strlen(h);
    if (n == 0 || n > 253 || h[0] == '-' || h[0] == '.') return 0;
    for (size_t i = 0; i < n; i++)
        if (!isalnum((unsigned char)h[i]) && h[i] != '-' && h[i] != '.') return 0;
    return 1;
}

int run_ping(const char *host, int out_fd, pid_t *pid) {
    if (!host_ok(host)) return -1;
    char *argv[] = { "/bin/ping", "-c", "4", "--", (char *)host, NULL };
    posix_spawn_file_actions_t fa;
    posix_spawn_file_actions_init(&fa);
    posix_spawn_file_actions_adddup2(&fa, out_fd, STDOUT_FILENO);
    int rc = posix_spawn(pid, argv[0], &fa, NULL, argv, environ);
    posix_spawn_file_actions_destroy(&fa);
    return rc;   /* caller reads out_fd, then waitpid(*pid) */
}

What each part does, and why:

  • No shell. posix_spawn() passes argv as separate strings, so ;, | and $(...) are plain bytes in one argument that ping will reject as an unknown host.
  • An absolute program path. /bin/ping avoids a PATH lookup. MITRE's CWE-78 notes cover untrusted search paths (CWE-426) as a related way to run an attacker's program.
  • An allowlist for the one argument. An IP address must parse with inet_pton(); a hostname may contain only letters, digits, hyphens and dots, and may not start with -.
  • -- before the operand. Without a shell, the remaining risk is argument injection (CWE-88): a value such as -f becomes an option. OWASP's cheat sheet shows the same problem with curl --help. POSIX Utility Syntax Guideline 10 makes the first -- end the options for utilities that follow the guideline. Check your BusyBox build's applets before you rely on it; the leading-hyphen rule above covers the case either way.
  • The test list for this handler: 127.0.0.1;id, $(id), a backtick pair, 127.0.0.1%0aid, -f, --help, a 300-character name, and a normal hostname that must still work.

If the page only needs "reachable or not", an ICMP socket in the daemon itself removes the child process entirely, which is OWASP's first choice.

What about CGI and init scripts written in shell?

Many device web UIs are shell CGI scripts that read QUERY_STRING, and many settings end up in init scripts. The POSIX Shell Command Language explains where they go wrong. The shell does not re-parse the result of a variable expansion for ; or $(...). An unquoted expansion is still split into fields and expanded as a filename pattern, and eval or sh -c parses its input as code again.

  • Never pass request data to eval, sh -c or a generated script.
  • Always double-quote expansions: "$host", not $host.
  • Validate with a case pattern before use, for example rejecting *[!A-Za-z0-9.-]*, -* and the empty string.
  • Put -- before operands taken from input.
  • Apply the same rule to stored values. An SSID or device name saved safely today becomes an injection when a boot script later pastes it into a command string.

3. Verify

  • Re-run the original report's proof-of-concept input, and a short fuzz list of shell metacharacters, against the patched handler and confirm the command no longer executes unexpected behaviour.
  • Add the test case to your regression suite so a future refactor cannot silently reintroduce the same concatenation pattern.
  • Re-run SAST/static analysis across the firmware image and confirm the CWE-77/78 finding is gone, not just suppressed.

What are the common pitfalls?

  • Escaping instead of removing the shell. OWASP notes escaping still lets an attacker choose arguments to the command.
  • A metacharacter denylist that misses newline, $(...) or backticks. Allowlist the expected format instead.
  • Forgetting argument injection. Removing the shell does not stop a value that starts with -.
  • Validating only in the browser. The device must repeat every check; see how to fix authentication bypass for the client-side trust problem.
  • Relative program names that depend on PATH.
  • Second-order injection through stored settings used later by scripts or cron jobs.
  • Fixing ping but not traceroute, nslookup or the Wi-Fi scan handler that copy the same pattern.
  • Leaving the daemon as root when it only needs to run a few utilities.

4. Ship an update

Build and sign a new firmware image carrying the fix, and distribute it through your normal secure-update channel (signed image, integrity check, rollback protection). See our firmware SBOM guide to confirm which shipped models and versions actually contain the vulnerable handler before you scope the release.

5. Disclose via PSIRT

Publish an advisory describing the affected products, versions and fix, following ISO/IEC 29147/30111's receive-verify-remediate-disclose shape — see our CVD process guide — and, for EU-market products, check whether the Cyber Resilience Act's 24-/72-hour reporting duty applies if the flaw was being actively exploited; see CRA 24h/72h reporting. If you do not have a standing PSIRT process yet, our PSIRT setup guide covers what a small device maker needs.

Unauthenticated command injection in a network-facing device is a frequent KEV entry once public, so check exploitation signals before you set the disclosure date; see KEV + EPSS prioritization.

CISA's Secure by Design Pledge lists "reducing the prevalence of one or more vulnerability classes" as one of its seven measurable goals — command injection in a repeated code pattern (every diagnostic handler shelling out the same way) is a good candidate for exactly that kind of class-wide fix; see our CISA Secure by Design guide.

What can SoftWSP check, and what needs code review?

Command injection in your own handlers is found by the grep, review and tests above. SoftWSP covers the third-party components in the image. It extracts a software bill of materials from the firmware as CycloneDX JSON and matches components against NVD, CISA KEV, FIRST EPSS and CISA ICS advisories. A published CWE-78 CVE in a BusyBox version, web server or management daemon you ship then appears together with its exploitation signals. An AI-drafted report cites each source, and an engineer reviews it before you receive it. SoftWSP does not trace input into system() calls in your code and does not judge reachability. See device & firmware security.

This guide summarises public MITRE CWE and OWASP guidance; it is not a substitute for a full source-code review and does not constitute legal advice.

Put this guide to work

Frequently asked questions

What is command injection?

MITRE's CWE-78 (OS Command Injection) defines it as a product that "constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command before it is sent to a downstream component." CWE-77 covers the broader case of any custom command language, not just the OS shell — MITRE notes that "developers may not realize that these other command languages might also be vulnerable to attacks," which matters for firmware CLIs and management-protocol parsers that implement their own command syntax.

Why is command injection common in device firmware specifically?

Firmware web UIs and CLI handlers frequently shell out to BusyBox or system binaries for ping, traceroute, firmware upgrade, Wi-Fi configuration or diagnostics, passing a user-supplied hostname, filename or SSID straight into a shell string. MITRE's demonstrative examples for CWE-78 show exactly this pattern — a PHP or C handler building a command line by string concatenation — which is how most router, camera and industrial-gateway OS-command-injection CVEs in this site's advisories arise.

What is the single most effective fix?

Per OWASP's OS Command Injection Defense Cheat Sheet, "the primary defense is to avoid calling OS commands directly" and instead use a built-in library function for the same task (its example: replace `system("mkdir /dir_name")` with the language's own `mkdir()` call), because a library function "cannot be manipulated to perform tasks other than those it is intended to do." This removes the shell parser — and the injection risk — entirely, rather than trying to filter dangerous input to it.

If we cannot avoid shelling out, what is the fallback?

OWASP describes two more layers, to be used together rather than as alternatives: parameterization — "structured mechanisms that automatically enforce the separation between data and command," i.e. pass arguments as a list/array to an exec-family call that does not invoke a shell, not as one interpolated string — plus allowlist validation of both the command and each argument, rejecting metacharacters such as ampersand, pipe, semicolon, dollar sign, angle brackets, backtick, backslash, quotes and parentheses. OS-specific escaping functions (for example PHP's `escapeshellarg()`) are a weaker last resort: OWASP notes they still let an attacker pass arbitrary arguments to the allowed command.

How do we verify the fix actually closes the hole?

Re-test with the same shell metacharacters the original report or your own fuzzing used (`; & | \n` and backticks) against every input that reaches the changed code path, confirm the firmware's command-injection static-analysis or SAST rule for the relevant CWE no longer fires, and keep the test case in your regression suite — CISA's Secure by Design pledge asks signatories to show a measurable reduction in a vulnerability class over time, not a single one-off fix; see our [CISA Secure by Design guide](/guides/cisa-secure-by-design-pledge/).

Sources

  1. MITRE CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
  2. MITRE CWE-77: Improper Neutralization of Special Elements used in a Command
  3. OWASP Cheat Sheet Series: OS Command Injection Defense Cheat Sheet
  4. CISA: Secure by Design
  5. MITRE: 2025 CWE Top 25 Most Dangerous Software Weaknesses
  6. MITRE CWE-88: Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')
  7. MITRE CWE-426: Untrusted Search Path
  8. The Open Group: system() — POSIX.1-2017 function specification
  9. The Open Group: popen() — POSIX.1-2017 function specification
  10. The Open Group: posix_spawn() — POSIX.1-2017 function specification
  11. The Open Group: Utility Conventions (Utility Syntax Guidelines) — POSIX.1-2017
  12. The Open Group: Shell Command Language — POSIX.1-2017
  13. Lua 5.4 Reference Manual (os.execute, io.popen)
Was this guide helpful?

In this cluster