RustScan Cheat Sheet
"Clase de la hoja" id="copy-btn" class="copy-btn" onclick="copyAllCommands()" Copiar todos los comandos id="pdf-btn" class="pdf-btn" onclick="generatePDF()" Generar PDF seleccionado/button ■/div titulada
Sinopsis
RustScan es un escáner de puerto moderno y de alto rendimiento escrito en Rust que pretende ser más rápido y más eficiente que las herramientas tradicionales de escaneo portuario como Nmap. Desarrollado por Bee-San, RustScan aprovecha La seguridad de memoria de Rust y las características de rendimiento para ofrecer capacidades de escaneo de puertos extremadamente rápidas manteniendo la precisión y fiabilidad. La herramienta está diseñada para complementar en lugar de reemplazar Nmap, a menudo utilizando Nmap para la detección de servicios detallados después de que RustScan identifica puertos abiertos a alta velocidad.
La principal ventaja de RustScan radica en su velocidad de escaneo excepcional, alcanzada a través de operaciones de I/O asincrónicas eficientes y abstracciones de coste cero de Rust. Mientras que los escáneres de puertos tradicionales pueden tardar minutos o horas en escanear grandes rangos de puertos, RustScan puede completar escaneos completos en segundos o minutos. Esta mejora de la velocidad hace que sea particularmente valiosa para las fases de reconocimiento de las pruebas de penetración, descubrimiento de redes y evaluaciones de infraestructura a gran escala donde la eficiencia del tiempo es crítica.
RustScan cuenta con una interfaz intuitiva de línea de comandos con defectos sensibles, lo que hace que sea accesible tanto para principiantes como para profesionales experimentados de seguridad. La herramienta admite diversas técnicas de escaneo, rangos de puertos personalizados e integración con otras herramientas de seguridad. Su capacidad de filtrar automáticamente los resultados a Nmap para la enumeración detallada del servicio crea un poderoso flujo de trabajo que combina la velocidad con el análisis integral, lo que lo convierte en una herramienta esencial para el reconocimiento moderno de la red.
Instalación
Instalación binaria
Instalar RustScan de binarios precompilados:
# Download latest release (Linux)
wget https://github.com/RustScan/RustScan/releases/latest/download/rustscan_2.1.1_amd64.deb
sudo dpkg -i rustscan_2.1.1_amd64.deb
# Install via package manager (Arch Linux)
yay -S rustscan
# Install via Homebrew (macOS)
brew install rustscan
# Install via Chocolatey (Windows)
choco install rustscan
# Verify installation
rustscan --version
Instalación de carga
Instalar RustScan usando el administrador de paquetes de Rust:
# Install Rust and Cargo
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs|sh
source ~/.cargo/env
# Install RustScan from crates.io
cargo install rustscan
# Install development version
cargo install --git https://github.com/RustScan/RustScan.git
# Update RustScan
cargo install rustscan --force
Docker Instalación
# Pull RustScan Docker image
docker pull rustscan/rustscan:latest
# Run RustScan in container
docker run -it --rm rustscan/rustscan:latest
# Create alias for easier usage
alias rustscan='docker run -it --rm rustscan/rustscan:latest'
# Scan with Docker
docker run -it --rm rustscan/rustscan:latest -a 192.168.1.1
Compilación de fuentes
# Clone repository
git clone https://github.com/RustScan/RustScan.git
cd RustScan
# Build release version
cargo build --release
# Install locally
cargo install --path .
# Run tests
cargo test
# Build with specific features
cargo build --release --features "web"
Uso básico
Escáner simple
Operaciones básicas de escaneo RustScan:
# Scan single host
rustscan -a 192.168.1.1
# Scan multiple hosts
rustscan -a 192.168.1.1,192.168.1.2,192.168.1.3
# Scan IP range
rustscan -a 192.168.1.1-192.168.1.254
# Scan subnet
rustscan -a 192.168.1.0/24
# Scan with domain name
rustscan -a example.com
Especificación de rango de puerto
Controlar rangos de puertos para escanear:
# Scan specific ports
rustscan -a 192.168.1.1 -p 22,80,443
# Scan port range
rustscan -a 192.168.1.1 -p 1-1000
# Scan common ports (default)
rustscan -a 192.168.1.1
# Scan all ports
rustscan -a 192.168.1.1 -p 1-65535
# Scan top ports
rustscan -a 192.168.1.1 --top-ports 1000
Performance Tuning
Optimización del rendimiento de RustScan:
# Increase batch size for faster scanning
rustscan -a 192.168.1.1 -b 4000
# Set timeout (milliseconds)
rustscan -a 192.168.1.1 -t 2000
# Limit concurrent connections
rustscan -a 192.168.1.1 --ulimit 5000
# Adjust scan order
rustscan -a 192.168.1.1 --scan-order "Random"
# Use specific number of threads
rustscan -a 192.168.1.1 --threads 1000
Características avanzadas
Integración de Nmap
Integrando RustScan con Nmap para el análisis detallado:
# Pipe to Nmap for service detection
rustscan -a 192.168.1.1 -- -sV -sC
# Use Nmap scripts
rustscan -a 192.168.1.1 -- --script vuln
# Aggressive Nmap scan
rustscan -a 192.168.1.1 -- -A
# Custom Nmap options
rustscan -a 192.168.1.1 -- -O -sS -T4
# Save Nmap output
rustscan -a 192.168.1.1 -- -oA scan_results
Formato de salida
Controlar el formato de salida RustScan:
# JSON output
rustscan -a 192.168.1.1 --output json
# Save to file
rustscan -a 192.168.1.1 -o results.txt
# Quiet mode
rustscan -a 192.168.1.1 -q
# Verbose output
rustscan -a 192.168.1.1 -v
# Custom output format
rustscan -a 192.168.1.1 --format "Host: \\\\{host\\\\}, Port: \\\\{port\\\\}"
Archivos de configuración
Usando archivos de configuración para el escaneo consistente:
# Create config file
cat > ~/.rustscan.toml << 'EOF'
[default]
batch_size = 4000
timeout = 1500
ulimit = 5000
ports = "1-65535"
addresses = ["192.168.1.0/24"]
[fast]
batch_size = 8000
timeout = 1000
ulimit = 10000
[stealth]
batch_size = 100
timeout = 5000
ulimit = 1000
EOF
# Use config profile
rustscan --config fast -a 192.168.1.1
# Override config options
rustscan --config stealth -a 192.168.1.1 -b 200
Soporte de scripts
Utilizando RustScan con scripts personalizados:
# Custom script execution
rustscan -a 192.168.1.1 --scripts /path/to/custom_script.py
# Script with arguments
rustscan -a 192.168.1.1 --scripts "python3 /path/to/script.py --target \\\\{host\\\\} --port \\\\{port\\\\}"
# Multiple scripts
rustscan -a 192.168.1.1 --scripts "script1.py,script2.sh"
# Conditional script execution
rustscan -a 192.168.1.1 --scripts "if [ \\\\{port\\\\} -eq 22 ]; then ssh_enum.py \\\\{host\\\\}; fi"
Técnicas de exploración
Network Discovery
Red de descubrimiento y reconocimiento:
# Ping sweep
rustscan -a 192.168.1.0/24 -p 0 --ping
# ARP scan (local network)
rustscan -a 192.168.1.0/24 --arp
# DNS resolution
rustscan -a example.com --resolve
# Reverse DNS lookup
rustscan -a 192.168.1.1 --reverse-dns
# IPv6 scanning
rustscan -a 2001:db8::/32 -6
Escáner de integridad
Implementando técnicas de escaneo de sigilo:
# Slow scan to avoid detection
rustscan -a 192.168.1.1 -b 50 -t 5000
# Random port order
rustscan -a 192.168.1.1 --scan-order Random
# Source port spoofing
rustscan -a 192.168.1.1 --source-port 53
# Decoy scanning
rustscan -a 192.168.1.1 --decoys 192.168.1.10,192.168.1.11
# Fragment packets
rustscan -a 192.168.1.1 --fragment
Escáner de gran escala
Escaneando redes grandes de manera eficiente:
# Scan multiple subnets
rustscan -a 192.168.0.0/16 -p 22,80,443
# Parallel subnet scanning
for subnet in 192.168.\\\\{1..10\\\\}.0/24; do
rustscan -a $subnet -p 22,80,443 &
done
wait
# Distributed scanning
rustscan -a 10.0.0.0/8 --split 4 --part 1
# Resume interrupted scan
rustscan -a 192.168.1.0/24 --resume scan_state.json
Scripts de automatización
Red de masas
#!/bin/bash
# RustScan mass network scanning script
NETWORKS_FILE="networks.txt"
OUTPUT_DIR="rustscan_results"
COMMON_PORTS="22,23,25,53,80,110,111,135,139,143,443,993,995,1723,3306,3389,5432,5900,8080"
mkdir -p $OUTPUT_DIR
echo "Starting mass network scanning with RustScan"
while IFS= read -r network; do
echo "Scanning network: $network"
# Create network-specific output file
output_file="$OUTPUT_DIR/rustscan_$(echo $network|tr '/' '_').txt"
# Perform RustScan
rustscan -a $network -p $COMMON_PORTS -b 4000 -t 1500 > $output_file
# Extract open ports and pipe to Nmap for detailed analysis
if [ -s $output_file ]; then
echo "Found open ports in $network, running detailed Nmap scan"
nmap_output="$OUTPUT_DIR/nmap_$(echo $network|tr '/' '_').xml"
rustscan -a $network -p $COMMON_PORTS -- -sV -sC -oX $nmap_output
fi
echo "Completed scanning: $network"
sleep 2
done < "$NETWORKS_FILE"
echo "Mass scanning completed"
Supervisión continua
#!/usr/bin/env python3
# RustScan continuous monitoring script
import subprocess
import json
import time
import smtplib
from email.mime.text import MIMEText
from datetime import datetime
class RustScanMonitor:
def __init__(self, targets, ports, interval=3600):
self.targets = targets
self.ports = ports
self.interval = interval
self.baseline = \\\\{\\\\}
self.alerts = []
def run_rustscan(self, target):
"""Run RustScan against target"""
cmd = [
"rustscan",
"-a", target,
"-p", self.ports,
"-b", "4000",
"-t", "1500",
"--output", "json"
]
try:
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
return self.parse_rustscan_output(result.stdout)
else:
print(f"Error scanning \\\\{target\\\\}: \\\\{result.stderr\\\\}")
return None
except Exception as e:
print(f"Exception scanning \\\\{target\\\\}: \\\\{e\\\\}")
return None
def parse_rustscan_output(self, output):
"""Parse RustScan JSON output"""
try:
# RustScan output parsing logic
lines = output.strip().split('\n')
open_ports = []
for line in lines:
if "Open" in line and ":" in line:
port = line.split(':')[1].strip().split()[0]
open_ports.append(int(port))
return sorted(open_ports)
except Exception as e:
print(f"Error parsing output: \\\\{e\\\\}")
return []
def establish_baseline(self):
"""Establish baseline for all targets"""
print("Establishing baseline...")
for target in self.targets:
ports = self.run_rustscan(target)
if ports is not None:
self.baseline[target] = ports
print(f"Baseline for \\\\{target\\\\}: \\\\{len(ports)\\\\} open ports")
print("Baseline established")
def detect_changes(self):
"""Detect changes from baseline"""
changes = \\\\{\\\\}
for target in self.targets:
current_ports = self.run_rustscan(target)
if current_ports is not None and target in self.baseline:
baseline_ports = set(self.baseline[target])
current_ports_set = set(current_ports)
new_ports = current_ports_set - baseline_ports
closed_ports = baseline_ports - current_ports_set
if new_ports or closed_ports:
changes[target] = \\\\{
'new_ports': list(new_ports),
'closed_ports': list(closed_ports),
'timestamp': datetime.now().isoformat()
\\\\}
return changes
def send_alert(self, changes):
"""Send alert for detected changes"""
if not changes:
return
alert_message = "RustScan Monitoring Alert\n\n"
for target, change in changes.items():
alert_message += f"Target: \\\\{target\\\\}\n"
alert_message += f"Timestamp: \\\\{change['timestamp']\\\\}\n"
if change['new_ports']:
alert_message += f"New open ports: \\\\{change['new_ports']\\\\}\n"
if change['closed_ports']:
alert_message += f"Closed ports: \\\\{change['closed_ports']\\\\}\n"
alert_message += "\n"
print(alert_message)
# Add email notification logic here if needed
def monitor(self):
"""Start continuous monitoring"""
self.establish_baseline()
print(f"Starting continuous monitoring (interval: \\\\{self.interval\\\\}s)")
while True:
try:
changes = self.detect_changes()
if changes:
self.send_alert(changes)
# Update baseline with changes
for target, change in changes.items():
current_ports = self.run_rustscan(target)
if current_ports is not None:
self.baseline[target] = current_ports
time.sleep(self.interval)
except KeyboardInterrupt:
print("Monitoring stopped")
break
except Exception as e:
print(f"Monitoring error: \\\\{e\\\\}")
time.sleep(60)
# Usage
if __name__ == "__main__":
targets = ["192.168.1.1", "192.168.1.10", "192.168.1.20"]
ports = "22,80,443,3389,5900"
monitor = RustScanMonitor(targets, ports, interval=1800)
monitor.monitor()
Integración con Herramientas de Seguridad
#!/usr/bin/env python3
# RustScan integration with security tools
import subprocess
import json
import requests
class RustScanIntegration:
def __init__(self):
self.results = \\\\{\\\\}
def run_rustscan(self, target, ports="1-65535"):
"""Run RustScan and return results"""
cmd = ["rustscan", "-a", target, "-p", ports, "-b", "4000"]
try:
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
open_ports = self.parse_ports(result.stdout)
self.results[target] = open_ports
return open_ports
else:
print(f"RustScan error: \\\\{result.stderr\\\\}")
return []
except Exception as e:
print(f"Error running RustScan: \\\\{e\\\\}")
return []
def parse_ports(self, output):
"""Parse RustScan output for open ports"""
open_ports = []
for line in output.split('\n'):
if "Open" in line and ":" in line:
try:
port = int(line.split(':')[1].strip().split()[0])
open_ports.append(port)
except:
continue
return sorted(open_ports)
def integrate_with_nmap(self, target, ports):
"""Run detailed Nmap scan on discovered ports"""
if not ports:
return None
port_list = ",".join(map(str, ports))
cmd = [
"nmap", "-sV", "-sC", "-O",
"-p", port_list,
target,
"-oX", f"nmap_\\\\{target.replace('.', '_')\\\\}.xml"
]
try:
result = subprocess.run(cmd, capture_output=True, text=True)
return result.stdout
except Exception as e:
print(f"Nmap integration error: \\\\{e\\\\}")
return None
def integrate_with_nuclei(self, target, ports):
"""Run Nuclei vulnerability scan"""
if not ports:
return None
# Create target list for Nuclei
targets = []
for port in ports:
if port in [80, 8080, 8000]:
targets.append(f"http://\\\\{target\\\\}:\\\\{port\\\\}")
elif port in [443, 8443]:
targets.append(f"https://\\\\{target\\\\}:\\\\{port\\\\}")
if not targets:
return None
target_file = f"nuclei_targets_\\\\{target.replace('.', '_')\\\\}.txt"
with open(target_file, 'w') as f:
f.write('\n'.join(targets))
cmd = [
"nuclei",
"-l", target_file,
"-t", "/path/to/nuclei-templates/",
"-o", f"nuclei_\\\\{target.replace('.', '_')\\\\}.txt"
]
try:
result = subprocess.run(cmd, capture_output=True, text=True)
return result.stdout
except Exception as e:
print(f"Nuclei integration error: \\\\{e\\\\}")
return None
def integrate_with_masscan(self, target_range):
"""Use Masscan for initial discovery, then RustScan for verification"""
cmd = [
"masscan",
target_range,
"-p1-65535",
"--rate=1000",
"--output-format", "list"
]
try:
result = subprocess.run(cmd, capture_output=True, text=True)
# Parse Masscan results
discovered_targets = set()
for line in result.stdout.split('\n'):
if line.strip():
parts = line.split()
if len(parts) >= 4:
ip = parts[3]
discovered_targets.add(ip)
# Run RustScan on discovered targets
for target in discovered_targets:
print(f"Running RustScan verification on \\\\{target\\\\}")
self.run_rustscan(target)
return list(discovered_targets)
except Exception as e:
print(f"Masscan integration error: \\\\{e\\\\}")
return []
def generate_report(self):
"""Generate comprehensive scan report"""
report = \\\\{
"scan_timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
"total_targets": len(self.results),
"targets": self.results
\\\\}
with open("rustscan_report.json", "w") as f:
json.dump(report, f, indent=2)
return report
# Usage example
if __name__ == "__main__":
integration = RustScanIntegration()
# Scan target
target = "192.168.1.100"
ports = integration.run_rustscan(target)
# Run additional tools
if ports:
integration.integrate_with_nmap(target, ports)
integration.integrate_with_nuclei(target, ports)
# Generate report
report = integration.generate_report()
print(f"Scan completed. Found \\\\{len(ports)\\\\} open ports on \\\\{target\\\\}")
Optimización del rendimiento
Sistema de Tuning
Optimización del sistema para el rendimiento de RustScan:
# Increase file descriptor limits
echo "* soft nofile 65535" >> /etc/security/limits.conf
echo "* hard nofile 65535" >> /etc/security/limits.conf
# Optimize network stack
echo 'net.core.rmem_default = 262144' >> /etc/sysctl.conf
echo 'net.core.rmem_max = 16777216' >> /etc/sysctl.conf
echo 'net.core.wmem_default = 262144' >> /etc/sysctl.conf
echo 'net.core.wmem_max = 16777216' >> /etc/sysctl.conf
# Apply changes
sysctl -p
ulimit -n 65535
Pruebas de Benchmark
#!/bin/bash
# RustScan performance benchmark
TARGET="192.168.1.1"
PORTS="1-1000"
echo "RustScan Performance Benchmark"
echo "=============================="
# Test different batch sizes
for batch_size in 1000 2000 4000 8000; do
echo "Testing batch size: $batch_size"
start_time=$(date +%s.%N)
rustscan -a $TARGET -p $PORTS -b $batch_size -q
end_time=$(date +%s.%N)
duration=$(echo "$end_time - $start_time"|bc)
echo "Duration: $\\\\{duration\\\\}s"
echo ""
done
# Test different timeout values
for timeout in 1000 1500 2000 3000; do
echo "Testing timeout: $\\\\{timeout\\\\}ms"
start_time=$(date +%s.%N)
rustscan -a $TARGET -p $PORTS -t $timeout -q
end_time=$(date +%s.%N)
duration=$(echo "$end_time - $start_time"|bc)
echo "Duration: $\\\\{duration\\\\}s"
echo ""
done
Solución de problemas
Cuestiones comunes
** Errores de permiso:**
# Check ulimit settings
ulimit -n
# Increase ulimit for current session
ulimit -n 65535
# Run with sudo if needed
sudo rustscan -a 192.168.1.1
# Check firewall rules
sudo iptables -L
Conectividad de red:
# Test basic connectivity
ping 192.168.1.1
# Check routing
traceroute 192.168.1.1
# Verify DNS resolution
nslookup example.com
# Test with different source interface
rustscan -a 192.168.1.1 --interface eth0
** Cuestiones de desempeño**
# Monitor system resources
top
htop
# Check network utilization
iftop
nethogs
# Reduce batch size for stability
rustscan -a 192.168.1.1 -b 1000
# Increase timeout for slow networks
rustscan -a 192.168.1.1 -t 5000
Debugging
Permite depurar y registrar:
# Enable verbose output
rustscan -a 192.168.1.1 -v
# Debug mode
RUST_LOG=debug rustscan -a 192.168.1.1
# Trace mode
RUST_LOG=trace rustscan -a 192.168.1.1
# Save debug output
RUST_LOG=debug rustscan -a 192.168.1.1 2> debug.log
Consideraciones de seguridad
Seguridad operacional
** Impacto de la red:** - Supervisar el uso del ancho de banda durante los escaneos - Utilice los tamaños apropiados para la capacidad de red - Ejecutar la programación del escaneo para evitar las horas pico - Considerar los efectos en los sistemas de destino - Monitor para respuestas defensivas
Evitación de la detección: - Usa técnicas de escaneo de sigilo - Tiempo y patrones de exploración aleatorios - Implementar la rotación IP fuente - Monitor for IDS/IPS alerts - Use patrones de escaneo legítimos
Consideraciones jurídicas y éticas
Escaneamiento de alta velocidad Sólo: - Obtener la autorización escrita adecuada - Definir el alcance y las limitaciones claras - Documentar todas las actividades de escaneo - Seguir las prácticas de divulgación responsables - Respetar la disponibilidad y el rendimiento del sistema
Las mejores prácticas: - Uso en entornos controlados - Evaluaciones periódicas de seguridad - Limitación de la tasa de ejecución - Monitor para uso no autorizado - Mantener pistas de auditoría completas