Appearance
RustScan Cheat Sheet
Overview
RustScan is a modern, high-performance port scanner written in Rust that aims to be faster and more efficient than traditional port scanning tools like Nmap. Developed by Bee-San, RustScan leverages Rust's memory safety and performance characteristics to deliver extremely fast port scanning capabilities while maintaining accuracy and reliability. The tool is designed to complement rather than replace Nmap, often using Nmap for detailed service detection after RustScan identifies open ports at high speed.
The primary advantage of RustScan lies in its exceptional scanning speed, achieved through efficient asynchronous I/O operations and Rust's zero-cost abstractions. While traditional port scanners may take minutes or hours to scan large port ranges, RustScan can complete comprehensive scans in seconds or minutes. This speed improvement makes it particularly valuable for reconnaissance phases of penetration testing, network discovery, and large-scale infrastructure assessments where time efficiency is critical.
RustScan features an intuitive command-line interface with sensible defaults, making it accessible to both beginners and experienced security professionals. The tool supports various scanning techniques, custom port ranges, and integration with other security tools. Its ability to automatically pipe results to Nmap for detailed service enumeration creates a powerful workflow that combines speed with comprehensive analysis, making it an essential tool for modern network reconnaissance.
Installation
Binary Installation
Installing RustScan from pre-compiled binaries:
bash
# 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
Cargo Installation
Installing RustScan using Rust's package manager:
bash
# 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 Installation
bash
# 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
Source Compilation
bash
# 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"
Basic Usage
Simple Scanning
Basic RustScan scanning operations:
bash
# 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
Port Range Specification
Controlling port ranges for scanning:
bash
# 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
Optimizing RustScan performance:
bash
# 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
Advanced Features
Nmap Integration
Integrating RustScan with Nmap for detailed analysis:
bash
# 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
Output Formatting
Controlling RustScan output format:
bash
# 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}"
Configuration Files
Using configuration files for consistent scanning:
bash
# 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
Scripting Support
Using RustScan with custom scripts:
bash
# 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"
Scanning Techniques
Network Discovery
Network discovery and reconnaissance:
bash
# 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
Stealth Scanning
Implementing stealth scanning techniques:
bash
# 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
Large-Scale Scanning
Scanning large networks efficiently:
bash
# 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
Automation Scripts
Mass Network Scanning
bash
#!/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"
Continuous Monitoring
python
#!/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()
Integration with Security Tools
python
#!/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}")
Performance Optimization
System Tuning
Optimizing system for RustScan performance:
bash
# 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
Benchmark Testing
bash
#!/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
Troubleshooting
Common Issues
Permission Errors:
bash
# 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
Network Connectivity:
bash
# 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
Performance Issues:
bash
# 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
Enable debugging and logging:
bash
# 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
Security Considerations
Operational Security
Network Impact:
- Monitor bandwidth usage during scans
- Use appropriate batch sizes for network capacity
- Implement scan scheduling to avoid peak hours
- Consider impact on target systems
- Monitor for defensive responses
Detection Avoidance:
- Use stealth scanning techniques
- Randomize scan timing and patterns
- Implement source IP rotation
- Monitor for IDS/IPS alerts
- Use legitimate-looking scan patterns
Legal and Ethical Considerations
Authorized Scanning Only:
- Obtain proper written authorization
- Define clear scope and limitations
- Document all scanning activities
- Follow responsible disclosure practices
- Respect system availability and performance
Best Practices:
- Use in controlled environments
- Regular security assessments
- Implement rate limiting
- Monitor for unauthorized use
- Maintain comprehensive audit trails