Saltar a contenido

Hashcat

Hashcat Cheat Sheet

__HTML_TAG_19_ Todos los comandos

Overview

Hashcat es la herramienta de recuperación de contraseñas más rápida y avanzada del mundo, diseñada para aprovechar el poder computacional de las CPUs y GPU modernas para la comprobación de contraseñas de alto rendimiento y la auditoría de seguridad. Desarrollado como sucesor de las tradicionales galletas de contraseña basadas en CPU, Hashcat revoluciona las pruebas de seguridad de contraseña utilizando las capacidades de procesamiento paralelo de tarjetas gráficas para lograr velocidades de grieta sin precedentes. La herramienta admite más de 300 algoritmos de hash y modos de ataque, lo que lo convierte en la plataforma de recuperación de contraseñas más completa disponible para profesionales de seguridad, probadores de penetración e investigadores que realizan evaluaciones de políticas de contraseña y auditorías de seguridad.

La fuerza central de Hashcat reside en su sofisticada arquitectura de aceleración GPU, que puede aprovechar el poder de múltiples tarjetas gráficas simultáneamente para realizar miles de millones de pruebas de candidatos por segundo. Esta enorme capacidad computacional, combinada con algoritmos inteligentes de optimización de ataque, permite a Hashcat romper contraseñas complejas que serían poco prácticas para atacar con herramientas tradicionales basadas en CPU. La plataforma es compatible con todos los principales proveedores de GPU, incluyendo NVIDIA CUDA y AMD OpenCL, optimizando automáticamente el rendimiento para configuraciones de hardware disponibles y proporcionando métricas de rendimiento detalladas para la planificación de capacidades y optimización de ataques.

El conjunto avanzado de funciones de Hashcat incluye múltiples modos de ataque que van desde ataques de diccionarios y transformaciones basadas en reglas a sofisticados ataques de máscaras y combinaciones híbridas. La arquitectura modular de la herramienta es compatible con el desarrollo de reglas personalizadas, computación distribuida en múltiples sistemas, e integración con generadores externos de lista de palabras y herramientas de preprocesamiento. Con su gestión integral del período de sesiones, información detallada sobre los progresos y amplias opciones de personalización, Hashcat proporciona capacidades automatizadas de auditoría de contraseñas y control fino para aplicaciones especializadas de investigación de seguridad. La comunidad de desarrollo activa de la plataforma y la optimización continua para las arquitecturas de hardware emergentes garantizan que permanezca a la vanguardia de la tecnología de pruebas de seguridad de contraseñas.

Instalación

Ubuntu/Debian Instalación

Instalar Hashcat en los sistemas Ubuntu/Debian:

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

# Install Hashcat from repositories
sudo apt install -y hashcat

# Install additional dependencies
sudo apt install -y opencl-headers ocl-icd-opencl-dev

# Install GPU drivers for optimal performance
# For NVIDIA GPUs:
sudo apt install -y nvidia-driver-470 nvidia-opencl-dev

# For AMD GPUs:
sudo apt install -y mesa-opencl-icd

# Verify installation
hashcat --version
hashcat --benchmark

# Install latest version from source
sudo apt install -y git build-essential
git clone https://github.com/hashcat/hashcat.git
cd hashcat
make
sudo make install

# Verify GPU detection
hashcat -I

CentOS/RHEL Instalación

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

# Install development tools
sudo yum groupinstall -y "Development Tools"

# Install dependencies
sudo yum install -y opencl-headers ocl-icd-devel

# Install GPU drivers
# For NVIDIA:
sudo yum install -y nvidia-driver nvidia-opencl

# Build from source
git clone https://github.com/hashcat/hashcat.git
cd hashcat
make
sudo make install

# Verify installation
hashcat --version
hashcat -I

Instalación de Windows

# Download pre-compiled binaries
# https://hashcat.net/hashcat/

# Extract to desired location
# Example: C:\hashcat

# Install GPU drivers
# NVIDIA: Download from nvidia.com
# AMD: Download from amd.com

# Add to PATH environment variable
# System Properties > Environment Variables
# Add C:\hashcat to PATH

# Verify installation
hashcat.exe --version
hashcat.exe -I

# Alternative: Install with Chocolatey
choco install hashcat

macOS Instalación

# Install using Homebrew
brew install hashcat

# Install GPU support (limited on macOS)
# Metal performance shaders for Apple Silicon

# Verify installation
hashcat --version
hashcat -I

# Build from source for latest features
brew install git
git clone https://github.com/hashcat/hashcat.git
cd hashcat
make
sudo make install

Docker Instalación

Hashcat en Docker con soporte GPU:

# Create Dockerfile for Hashcat
cat > Dockerfile.hashcat << 'EOF'
FROM nvidia/cuda:11.8-devel-ubuntu22.04

# Install dependencies
RUN apt-get update && apt-get install -y \
    git \
    build-essential \
    opencl-headers \
    ocl-icd-opencl-dev \
    && rm -rf /var/lib/apt/lists/*

# Clone and build Hashcat
RUN git clone https://github.com/hashcat/hashcat.git /opt/hashcat
WORKDIR /opt/hashcat
RUN make && make install

# Create working directory
WORKDIR /work

# Set PATH
ENV PATH="/opt/hashcat:$\\\\{PATH\\\\}"

CMD ["hashcat", "--help"]
EOF

# Build Docker image
docker build -f Dockerfile.hashcat -t hashcat-gpu .

# Run with GPU support (NVIDIA)
docker run --gpus all -it --rm \
    -v $(pwd):/work \
    hashcat-gpu hashcat --benchmark

# Run with specific GPU
docker run --gpus '"device=0"' -it --rm \
    -v $(pwd):/work \
    hashcat-gpu hashcat -I

Uso básico

Hash Identification

Identificar tipos y formatos de hash:

# List supported hash modes
hashcat --help|grep -A 500 "Hash modes"

# Common hash mode numbers
# 0     = MD5
# 100   = SHA1
# 1000  = NTLM
# 1400  = SHA256
# 1700  = SHA512
# 1800  = sha512crypt
# 3200  = bcrypt
# 7500  = Kerberos 5 AS-REQ Pre-Auth

# Identify hash automatically
hashcat --identify hash.txt

# Example hash formats
echo "5d41402abc4b2a76b9719d911017c592" > md5_hash.txt  # MD5
echo "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d" > sha1_hash.txt  # SHA1
echo "admin:1000:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::" > ntlm_hash.txt  # NTLM

# Verify hash format
hashcat -m 0 --identify md5_hash.txt
hashcat -m 100 --identify sha1_hash.txt
hashcat -m 1000 --identify ntlm_hash.txt

Ataques básicos

Realización de ataques básicos de contraseña:

# Dictionary attack
hashcat -m 0 -a 0 hash.txt wordlist.txt

# Dictionary attack with rules
hashcat -m 0 -a 0 hash.txt wordlist.txt -r rules/best64.rule

# Brute force attack
hashcat -m 0 -a 3 hash.txt ?a?a?a?a?a?a

# Mask attack (specific pattern)
hashcat -m 0 -a 3 hash.txt ?u?l?l?l?l?d?d?d

# Combination attack
hashcat -m 0 -a 1 hash.txt wordlist1.txt wordlist2.txt

# Hybrid attack (wordlist + mask)
hashcat -m 0 -a 6 hash.txt wordlist.txt ?d?d?d

# Hybrid attack (mask + wordlist)
hashcat -m 0 -a 7 hash.txt ?d?d?d wordlist.txt

# Show cracked passwords
hashcat -m 0 hash.txt --show

# Resume session
hashcat --session=mysession --restore

# Attack with time limit
timeout 3600 hashcat -m 0 -a 0 hash.txt wordlist.txt

Performance Optimization

Optimizando el rendimiento de Hashcat:

# Benchmark system performance
hashcat -b

# Benchmark specific hash mode
hashcat -b -m 1000

# Show device information
hashcat -I

# Use specific GPU devices
hashcat -m 0 -a 0 hash.txt wordlist.txt -d 1,2

# Optimize workload
hashcat -m 0 -a 0 hash.txt wordlist.txt -w 3

# Workload profiles:
# -w 1 = Low (desktop use)
# -w 2 = Default
# -w 3 = High (dedicated cracking)
# -w 4 = Nightmare (maximum performance)

# Optimize kernel loops
hashcat -m 0 -a 0 hash.txt wordlist.txt -n 1024 -u 256

# Monitor temperature and performance
watch -n 1 'hashcat --status --machine-readable'

Características avanzadas

Mask Attacks

Ataques avanzados basados en máscaras:

# Character sets
# ?l = lowercase letters (a-z)
# ?u = uppercase letters (A-Z)
# ?d = digits (0-9)
# ?h = hex digits (0-9a-f)
# ?H = hex digits (0-9A-F)
# ?s = special characters
# ?a = all characters (?l?u?d?s)
# ?b = all bytes (0x00-0xff)

# Common password patterns
# 8-character mixed case with numbers
hashcat -m 0 -a 3 hash.txt ?u?l?l?l?l?d?d?d

# Phone number pattern
hashcat -m 0 -a 3 hash.txt ?d?d?d-?d?d?d-?d?d?d?d

# Date pattern (MMDDYYYY)
hashcat -m 0 -a 3 hash.txt ?d?d?d?d?d?d?d?d

# Custom character set
hashcat -m 0 -a 3 hash.txt -1 ?l?d ?1?1?1?1?1?1?1?1

# Multiple custom character sets
hashcat -m 0 -a 3 hash.txt -1 ?l?u -2 ?d?s ?1?1?1?1?2?2

# Increment mode
hashcat -m 0 -a 3 hash.txt --increment --increment-min=6 --increment-max=8 ?a?a?a?a?a?a?a?a

# Position-specific masks
hashcat -m 0 -a 3 hash.txt ?u?l?l?l?l?l?d?d

# Mask file
cat > masks.txt << 'EOF'
?u?l?l?l?l?d?d
?u?l?l?l?l?d?d?d
?u?l?l?l?l?l?d?d
?l?l?l?l?d?d?d?d
EOF

hashcat -m 0 -a 3 hash.txt masks.txt

Ataques basados en reglas

Transformaciones avanzadas basadas en reglas:

# Built-in rule files
ls /usr/share/hashcat/rules/

# Common rule files
# best64.rule - Most effective 64 rules
# leetspeak.rule - Leet speak transformations
# rockyou-30000.rule - Rules based on RockYou analysis
# dive.rule - Comprehensive rule set

# Use specific rule file
hashcat -m 0 -a 0 hash.txt wordlist.txt -r /usr/share/hashcat/rules/best64.rule

# Multiple rule files
hashcat -m 0 -a 0 hash.txt wordlist.txt -r rules/best64.rule -r rules/leetspeak.rule

# Create custom rules
cat > custom.rule ``<< 'EOF'
# Append numbers
$0 $1 $2 $3 $4 $5 $6 $7 $8 $9

# Prepend numbers
^0 ^1 ^2 ^3 ^4 ^5 ^6 ^7 ^8 ^9

# Capitalize first letter
c

# Toggle case
t

# Duplicate word
d

# Reverse word
r

# Leetspeak substitutions
sa@ se3 si1 so0 ss$

# Append common suffixes
$! $@ $# $ $% $1 $2 $3

# Complex transformations
c $1 $2 $3
c $! $@
sa@ se3 si1 so0 $!
EOF

# Use custom rules
hashcat -m 0 -a 0 hash.txt wordlist.txt -r custom.rule

# Generate rule statistics
hashcat -m 0 -a 0 hash.txt wordlist.txt -r rules/best64.rule --debug-mode=1 --debug-file=debug.log

# Test rules without cracking
hashcat -a 0 --stdout wordlist.txt -r custom.rule|head -20

Session Management

Gestión de sesiones de larga duración:

# Start named session
hashcat --session=audit2023 -m 1000 -a 0 hash.txt wordlist.txt

# Check session status
hashcat --session=audit2023 --status

# Restore session
hashcat --session=audit2023 --restore

# Remove session
hashcat --session=audit2023 --remove

# Session with checkpoint
hashcat --session=audit2023 -m 1000 -a 0 hash.txt wordlist.txt --status-timer=60

# Quit session gracefully
# Press 'q' during execution or send SIGTERM

# Session configuration
cat >`` hashcat.conf << 'EOF'
# Status timer (seconds)
status-timer = 60

# Checkpoint interval (seconds)
checkpoint-disable = false

# Restore timer (seconds)
restore-timer = 60

# Quiet mode
quiet = false

# Force mode
force = false
EOF

# Use configuration file
hashcat --session=audit2023 --config=hashcat.conf -m 1000 -a 0 hash.txt wordlist.txt

Distributed Cracking

Configuración de la contraseña distribuida:

# Split wordlist for distribution
split -l 1000000 rockyou.txt wordlist_part_

# Distribute across multiple machines
# Machine 1:
hashcat --session=node1 -m 1000 -a 0 hash.txt wordlist_part_aa

# Machine 2:
hashcat --session=node2 -m 1000 -a 0 hash.txt wordlist_part_ab

# Machine 3:
hashcat --session=node3 -m 1000 -a 0 hash.txt wordlist_part_ac

# Keyspace distribution for mask attacks
# Total keyspace calculation
hashcat -m 0 -a 3 --keyspace ?a?a?a?a?a?a

# Distribute keyspace
# Machine 1 (first quarter):
hashcat -m 0 -a 3 hash.txt ?a?a?a?a?a?a --skip=0 --limit=1000000

# Machine 2 (second quarter):
hashcat -m 0 -a 3 hash.txt ?a?a?a?a?a?a --skip=1000000 --limit=1000000

# Automated distribution script
cat > distribute_hashcat.sh ``<< 'EOF'
#!/bin/bash

HOSTS=("server1" "server2" "server3" "server4")
HASH_FILE="hashes.txt"
WORDLIST="rockyou.txt"
HASH_MODE="1000"

# Calculate total lines
TOTAL_LINES=$(wc -l < $WORDLIST)
LINES_PER_HOST=$((TOTAL_LINES / $\\\{#HOSTS[@]\\\}))

for i in "$\\\{!HOSTS[@]\\\}"; do
    HOST="$\\\{HOSTS[$i]\\\}"
    SKIP=$((i * LINES_PER_HOST))

    echo "Starting node $((i+1)) on $HOST"
    ssh $HOST "hashcat --session=node$((i+1)) -m $HASH_MODE -a 0 $HASH_FILE $WORDLIST --skip=$SKIP --limit=$LINES_PER_HOST" &
done

wait
echo "All nodes completed"
EOF

chmod +x distribute_hashcat.sh
./distribute_hashcat.sh

Automation Scripts

Comprehensive Password Audit Script

#!/usr/bin/env python3
# Comprehensive password audit using Hashcat

import subprocess
import os
import sys
import time
import json
import argparse
from datetime import datetime
import threading
import queue
import re

class HashcatAuditor:
    def __init__(self, hashcat_path="hashcat"):
        self.hashcat_path = hashcat_path
        self.results = \\\{\\\}
        self.sessions = \\\{\\\}

    def verify_hashcat_installation(self):
        """Verify Hashcat installation and GPU support"""
        try:
            result = subprocess.run([self.hashcat_path, "--version"],
                                  capture_output=True, text=True)
            if result.returncode == 0:
                print(f"Hashcat version: \\\{result.stdout.strip()\\\}")

                # Check GPU devices
                gpu_result = subprocess.run([self.hashcat_path, "-I"],
                                          capture_output=True, text=True)
                if gpu_result.returncode == 0:
                    print("GPU devices detected:")
                    print(gpu_result.stdout)
                    return True
                else:
                    print("Warning: No GPU devices detected")
                    return True
            else:
                print("Hashcat not found or not working")
                return False
        except Exception as e:
            print(f"Error checking Hashcat installation: \\\{e\\\}")
            return False

    def identify_hash_type(self, hash_file):
        """Identify hash types in file"""
        try:
            result = subprocess.run([self.hashcat_path, "--identify", hash_file],
                                  capture_output=True, text=True)
            if result.returncode == 0:
                return self.parse_hash_identification(result.stdout)
            else:
                print(f"Hash identification failed: \\\{result.stderr\\\}")
                return \\\{\\\}
        except Exception as e:
            print(f"Error identifying hashes: \\\{e\\\}")
            return \\\{\\\}

    def parse_hash_identification(self, output):
        """Parse hash identification output"""
        hash_types = \\\{\\\}
        lines = output.strip().split('\n')

        for line in lines:
            if 'possible' in line.lower():
                # Parse hash type information
                parts = line.split()
                if len(parts) >``= 3:
                    hash_mode = parts[0]
                    hash_name = ' '.join(parts[1:])
                    hash_types[hash_mode] = hash_name

        return hash_types

    def benchmark_performance(self):
        """Benchmark system performance"""
        try:
            result = subprocess.run([self.hashcat_path, "-b"],
                                  capture_output=True, text=True, timeout=300)
            if result.returncode == 0:
                return self.parse_benchmark_results(result.stdout)
            else:
                print(f"Benchmark failed: \\\\{result.stderr\\\\}")
                return \\\\{\\\\}
        except subprocess.TimeoutExpired:
            print("Benchmark timed out")
            return \\\\{\\\\}
        except Exception as e:
            print(f"Error running benchmark: \\\\{e\\\\}")
            return \\\\{\\\\}

    def parse_benchmark_results(self, output):
        """Parse benchmark results"""
        benchmarks = \\\\{\\\\}
        lines = output.strip().split('\n')

        for line in lines:
            if 'H/s' in line:
                # Parse benchmark line
                parts = line.split()
                if len(parts) >= 4:
                    hash_mode = parts[0]
                    speed = parts[-2]
                    unit = parts[-1]
                    benchmarks[hash_mode] = f"\\\\{speed\\\\} \\\\{unit\\\\}"

        return benchmarks

    def crack_passwords(self, hash_file, attack_config):
        """Crack passwords with specified configuration"""
        session_name = f"audit_\\\\{int(time.time())\\\\}"

        cmd = [self.hashcat_path, "--session", session_name]

        # Add hash mode
        if attack_config.get('mode'):
            cmd.extend(["-m", str(attack_config['mode'])])

        # Add attack type
        if attack_config.get('attack'):
            cmd.extend(["-a", str(attack_config['attack'])])

        # Add attack-specific parameters
        if attack_config.get('attack') == 0:  # Dictionary attack
            if attack_config.get('wordlist'):
                cmd.append(attack_config['wordlist'])
            if attack_config.get('rules'):
                cmd.extend(["-r", attack_config['rules']])
        elif attack_config.get('attack') == 3:  # Mask attack
            if attack_config.get('mask'):
                cmd.append(attack_config['mask'])
            if attack_config.get('increment'):
                cmd.append("--increment")
                if attack_config.get('increment_min'):
                    cmd.extend(["--increment-min", str(attack_config['increment_min'])])
                if attack_config.get('increment_max'):
                    cmd.extend(["--increment-max", str(attack_config['increment_max'])])

        # Add performance options
        if attack_config.get('workload'):
            cmd.extend(["-w", str(attack_config['workload'])])

        if attack_config.get('devices'):
            cmd.extend(["-d", attack_config['devices']])

        # Add hash file
        cmd.append(hash_file)

        print(f"Starting password cracking: \\\\{' '.join(cmd)\\\\}")

        try:
            # Start cracking process
            process = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE, text=True)

            self.sessions[session_name] = \\\\{
                'process': process,
                'start_time': time.time(),
                'config': attack_config,
                'cmd': cmd
            \\\\}

            return session_name
        except Exception as e:
            print(f"Error starting crack: \\\\{e\\\\}")
            return None

    def monitor_session(self, session_name, timeout=None):
        """Monitor cracking session"""
        if session_name not in self.sessions:
            print(f"Session \\\\{session_name\\\\} not found")
            return None

        session = self.sessions[session_name]
        process = session['process']
        start_time = session['start_time']

        try:
            if timeout:
                stdout, stderr = process.communicate(timeout=timeout)
            else:
                stdout, stderr = process.communicate()

            end_time = time.time()
            duration = end_time - start_time

            result = \\\\{
                'session': session_name,
                'duration': duration,
                'returncode': process.returncode,
                'stdout': stdout,
                'stderr': stderr,
                'cmd': session['cmd']
            \\\\}

            return result
        except subprocess.TimeoutExpired:
            print(f"Session \\\\{session_name\\\\} timed out")
            process.terminate()
            return None
        except Exception as e:
            print(f"Error monitoring session: \\\\{e\\\\}")
            return None

    def get_cracked_passwords(self, hash_file, hash_mode=None):
        """Retrieve cracked passwords"""
        cmd = [self.hashcat_path, "--show"]

        if hash_mode:
            cmd.extend(["-m", str(hash_mode)])

        cmd.append(hash_file)

        try:
            result = subprocess.run(cmd, capture_output=True, text=True)

            if result.returncode == 0:
                lines = result.stdout.strip().split('\n')
                cracked = []

                for line in lines:
                    if ':' in line and line.strip():
                        parts = line.split(':')
                        if len(parts) >= 2:
                            cracked.append(\\\\{
                                'hash': parts[0],
                                'password': parts[1],
                                'full_line': line
                            \\\\})

                return cracked
            else:
                print(f"Error getting cracked passwords: \\\\{result.stderr\\\\}")
                return []
        except Exception as e:
            print(f"Error retrieving passwords: \\\\{e\\\\}")
            return []

    def analyze_password_strength(self, cracked_passwords):
        """Analyze password strength patterns"""
        analysis = \\\\{
            'total_cracked': len(cracked_passwords),
            'length_distribution': \\\\{\\\\},
            'character_analysis': \\\\{
                'lowercase_only': 0,
                'uppercase_only': 0,
                'digits_only': 0,
                'mixed_case': 0,
                'with_digits': 0,
                'with_symbols': 0,
                'alphanumeric': 0
            \\\\},
            'pattern_analysis': \\\\{
                'dictionary_words': 0,
                'keyboard_patterns': 0,
                'repeated_characters': 0,
                'sequential_patterns': 0
            \\\\},
            'complexity_score': 0,
            'weak_passwords': []
        \\\\}

        if not cracked_passwords:
            return analysis

        for entry in cracked_passwords:
            password = entry['password']
            length = len(password)

            # Length distribution
            if length not in analysis['length_distribution']:
                analysis['length_distribution'][length] = 0
            analysis['length_distribution'][length] += 1

            # Character analysis
            has_lower = bool(re.search(r'[a-z]', password))
            has_upper = bool(re.search(r'[A-Z]', password))
            has_digit = bool(re.search(r'[0-9]', password))
            has_symbol = bool(re.search(r'[^a-zA-Z0-9]', password))

            if password.islower():
                analysis['character_analysis']['lowercase_only'] += 1
            elif password.isupper():
                analysis['character_analysis']['uppercase_only'] += 1
            elif password.isdigit():
                analysis['character_analysis']['digits_only'] += 1
            elif has_lower and has_upper:
                analysis['character_analysis']['mixed_case'] += 1

            if has_digit:
                analysis['character_analysis']['with_digits'] += 1
            if has_symbol:
                analysis['character_analysis']['with_symbols'] += 1
            if password.isalnum():
                analysis['character_analysis']['alphanumeric'] += 1

            # Pattern analysis
            if re.search(r'(password|admin|user|test|guest|login)', password.lower()):
                analysis['pattern_analysis']['dictionary_words'] += 1

            if re.search(r'(qwerty|asdf|zxcv|1234|abcd)', password.lower()):
                analysis['pattern_analysis']['keyboard_patterns'] += 1

            if re.search(r'(.)\1\\\\{2,\\\\}', password):
                analysis['pattern_analysis']['repeated_characters'] += 1

            if re.search(r'(012|123|234|345|456|567|678|789|abc|bcd|cde)', password.lower()):
                analysis['pattern_analysis']['sequential_patterns'] += 1

            # Weakness assessment
            weakness_score = 0
            if length < 8:
                weakness_score += 3
            if password.lower() in ['password', '123456', 'admin', 'user', 'guest']:
                weakness_score += 5
            if password.isdigit() or password.islower() or password.isupper():
                weakness_score += 2
            if not has_symbol:
                weakness_score += 1

            if weakness_score >= 3:
                analysis['weak_passwords'].append(\\\\{
                    'password': password,
                    'hash': entry['hash'],
                    'weakness_score': weakness_score
                \\\\})

        # Calculate overall complexity score
        total = len(cracked_passwords)
        if total > 0:
            complexity_factors = [
                (analysis['character_analysis']['mixed_case'] / total) * 20,
                (analysis['character_analysis']['with_symbols'] / total) * 30,
                (sum(1 for l in analysis['length_distribution'] if l >= 12) / total) * 25,
                (1 - (len(analysis['weak_passwords']) / total)) * 25
            ]
            analysis['complexity_score'] = sum(complexity_factors)

        return analysis

    def generate_comprehensive_report(self, audit_results, output_file="hashcat_audit_report.html"):
        """Generate comprehensive audit report"""
        html_content = f"""
<!DOCTYPE html>
<html>
<head>
    <title>Hashcat Password Security Audit Report</title>
    <style>
        body \\\\{\\\\{ font-family: Arial, sans-serif; margin: 20px; \\\\}\\\\}
        .section \\\\{\\\\{ margin: 20px 0; padding: 15px; border: 1px solid #ddd; \\\\}\\\\}
        .critical \\\\{\\\\{ color: red; font-weight: bold; \\\\}\\\\}
        .warning \\\\{\\\\{ color: orange; font-weight: bold; \\\\}\\\\}
        .info \\\\{\\\\{ color: blue; \\\\}\\\\}
        .success \\\\{\\\\{ color: green; font-weight: bold; \\\\}\\\\}
        table \\\\{\\\\{ border-collapse: collapse; width: 100%; \\\\}\\\\}
        th, td \\\\{\\\\{ border: 1px solid #ddd; padding: 8px; text-align: left; \\\\}\\\\}
        th \\\\{\\\\{ background-color: #f2f2f2; \\\\}\\\\}
        .score \\\\{\\\\{ font-size: 24px; font-weight: bold; \\\\}\\\\}
        .score.high \\\\{\\\\{ color: green; \\\\}\\\\}
        .score.medium \\\\{\\\\{ color: orange; \\\\}\\\\}
        .score.low \\\\{\\\\{ color: red; \\\\}\\\\}
    </style>
</head>
<body>
    <h1>Hashcat Password Security Audit Report</h1>
    <p>Generated: \\\\{datetime.now().isoformat()\\\\}</p>
    <p>Hash File: \\\\{audit_results.get('hash_file', 'N/A')\\\\}</p>

    <div class="section">
        <h2>Executive Summary</h2>
        <ul>
            <li>Total Hashes Analyzed: \\\\{audit_results.get('total_hashes', 0)\\\\}</li>
            <li>Passwords Cracked: \\\\{audit_results.get('total_cracked', 0)\\\\}</li>
            <li>Crack Rate: \\\\{(audit_results.get('total_cracked', 0) / max(audit_results.get('total_hashes', 1), 1) * 100):.2f\\\\}%</li>
            <li>Weak Passwords: \\\\{len(audit_results.get('weak_passwords', []))\\\\}</li>
        </ul>

        <h3>Password Complexity Score</h3>
        <div class="score \\\\{self.get_score_class(audit_results.get('complexity_score', 0))\\\\}">
            \\\\{audit_results.get('complexity_score', 0):.1f\\\\}/100
        </div>
    </div>

    <div class="section">
        <h2 class="critical">Critical Findings</h2>
        <h3>Weak Passwords</h3>
        <table>
            <tr><th>Hash</th><th>Password</th><th>Weakness Score</th></tr>
"""

        for weak in audit_results.get('weak_passwords', [])[:20]:
            html_content += f"""
            <tr>
                <td>\\\\{weak['hash'][:20]\\\\}...</td>
                <td>\\\\{weak['password']\\\\}</td>
                <td>\\\\{weak['weakness_score']\\\\}</td>
            </tr>"""

        html_content += """
        </table>
    </div>

    <div class="section">
        <h2>Performance Analysis</h2>
        <table>
            <tr><th>Attack Method</th><th>Duration</th><th>Passwords Found</th><th>Rate</th></tr>
"""

        for session in audit_results.get('sessions', []):
            duration = session.get('duration', 0)
            passwords_found = session.get('passwords_found', 0)
            rate = passwords_found / duration if duration > 0 else 0

            html_content += f"""
            <tr>
                <td>\\\\{session.get('attack_method', 'Unknown')\\\\}</td>
                <td>\\\\{duration:.2f\\\\}s</td>
                <td>\\\\{passwords_found\\\\}</td>
                <td>\\\\{rate:.2f\\\\} p/s</td>
            </tr>"""

        html_content += """
        </table>
    </div>

    <div class="section">
        <h2>Recommendations</h2>
        <ul>
            <li>Implement minimum password length of 14 characters</li>
            <li>Require complex passwords with mixed case, numbers, and symbols</li>
            <li>Prohibit common dictionary words and keyboard patterns</li>
            <li>Implement password history to prevent reuse</li>
            <li>Enable multi-factor authentication</li>
            <li>Regular password audits and user training</li>
            <li>Consider passphrase-based authentication</li>
        </ul>
    </div>
</body>
</html>
"""

        with open(output_file, 'w') as f:
            f.write(html_content)

        print(f"Report generated: \\\\{output_file\\\\}")
        return output_file

    def get_score_class(self, score):
        """Get CSS class for complexity score"""
        if score >= 70:
            return "high"
        elif score >= 40:
            return "medium"
        else:
            return "low"

    def run_comprehensive_audit(self, hash_file, wordlists, output_dir="/tmp/hashcat_audit"):
        """Run comprehensive password audit"""
        print("Starting comprehensive Hashcat audit...")

        # Create output directory
        os.makedirs(output_dir, exist_ok=True)

        audit_results = \\\\{
            'start_time': time.time(),
            'hash_file': hash_file,
            'wordlists': wordlists,
            'sessions': [],
            'total_hashes': 0,
            'total_cracked': 0
        \\\\}

        # Identify hash types
        print("Identifying hash types...")
        hash_types = self.identify_hash_type(hash_file)
        audit_results['hash_types'] = hash_types

        # Count total hashes
        try:
            with open(hash_file, 'r') as f:
                audit_results['total_hashes'] = len(f.readlines())
        except Exception as e:
            print(f"Error reading hash file: \\\\{e\\\\}")
            return None

        # Determine best hash mode
        if hash_types:
            best_mode = list(hash_types.keys())[0]
            print(f"Using hash mode: \\\\{best_mode\\\\} (\\\\{hash_types[best_mode]\\\\})")
        else:
            best_mode = "0"  # Default to MD5
            print("Using default hash mode: MD5")

        # Run multiple attack strategies
        attack_configs = [
            \\\\{
                'name': 'Quick Dictionary',
                'mode': best_mode,
                'attack': 0,
                'wordlist': wordlists[0] if wordlists else '/usr/share/wordlists/rockyou.txt',
                'timeout': 1800  # 30 minutes
            \\\\},
            \\\\{
                'name': 'Dictionary with Rules',
                'mode': best_mode,
                'attack': 0,
                'wordlist': wordlists[0] if wordlists else '/usr/share/wordlists/rockyou.txt',
                'rules': '/usr/share/hashcat/rules/best64.rule',
                'timeout': 3600  # 1 hour
            \\\\},
            \\\\{
                'name': 'Mask Attack (8 chars)',
                'mode': best_mode,
                'attack': 3,
                'mask': '?a?a?a?a?a?a?a?a',
                'increment': True,
                'increment_min': 6,
                'increment_max': 8,
                'timeout': 1800  # 30 minutes
            \\\\}
        ]

        # Execute attacks
        for config in attack_configs:
            print(f"Running \\\\{config['name']\\\\} attack...")

            session_name = self.crack_passwords(hash_file, config)
            if session_name:
                result = self.monitor_session(session_name, config.get('timeout'))
                if result:
                    result['attack_method'] = config['name']
                    audit_results['sessions'].append(result)

        # Get final results
        cracked_passwords = self.get_cracked_passwords(hash_file, best_mode)
        audit_results['total_cracked'] = len(cracked_passwords)

        # Analyze password strength
        if cracked_passwords:
            strength_analysis = self.analyze_password_strength(cracked_passwords)
            audit_results.update(strength_analysis)

        # Generate report
        report_file = os.path.join(output_dir, "hashcat_audit_report.html")
        self.generate_comprehensive_report(audit_results, report_file)

        audit_results['end_time'] = time.time()
        audit_results['duration'] = audit_results['end_time'] - audit_results['start_time']

        print(f"Audit completed in \\\\{audit_results['duration']:.2f\\\\} seconds")
        print(f"Cracked \\\\{audit_results['total_cracked']\\\\} of \\\\{audit_results['total_hashes']\\\\} passwords")

        return audit_results

def main():
    parser = argparse.ArgumentParser(description='Hashcat Password Audit')
    parser.add_argument('--hash-file', required=True, help='Hash file to crack')
    parser.add_argument('--wordlists', nargs='+', help='Wordlist files')
    parser.add_argument('--hash-mode', help='Hash mode (auto-detect if not specified)')
    parser.add_argument('--output', default='/tmp/hashcat_audit', help='Output directory')
    parser.add_argument('--hashcat-path', default='hashcat', help='Path to Hashcat executable')

    args = parser.parse_args()

    # Initialize auditor
    auditor = HashcatAuditor(args.hashcat_path)

    # Verify installation
    if not auditor.verify_hashcat_installation():
        print("Hashcat not properly installed or configured")
        sys.exit(1)

    # Run audit
    results = auditor.run_comprehensive_audit(
        args.hash_file,
        args.wordlists or [],
        args.output
    )

    if results:
        print("Password audit completed successfully")
    else:
        print("Password audit failed")
        sys.exit(1)

if __name__ == "__main__":
    main()

Integración Ejemplos

CI/CD Integration

# Jenkins Pipeline for Hashcat Integration
pipeline \\\\{
    agent \\\\{
        label 'gpu-enabled'
    \\\\}

    environment \\\\{
        HASH_FILE = 'extracted_hashes.txt'
        WORDLIST = '/opt/wordlists/rockyou.txt'
        HASHCAT_PATH = '/usr/local/bin/hashcat'
    \\\\}

    stages \\\\{
        stage('Extract Hashes') \\\\{
            steps \\\\{
                script \\\\{
                    // Extract hashes from application
                    sh '''
                        # Extract user password hashes
                        python3 extract_hashes.py --output $\\\\{HASH_FILE\\\\}

                        # Verify hash file
                        if [ ! -s $\\\\{HASH_FILE\\\\} ]; then
                            echo "No hashes extracted"
                            exit 1
                        fi

                        echo "Extracted $(wc -l < $\\\\{HASH_FILE\\\\}) hashes"
                    '''
                \\\\}
            \\\\}
        \\\\}

        stage('Password Audit') \\\\{
            steps \\\\{
                script \\\\{
                    // Run Hashcat audit
                    sh '''
                        python3 hashcat_audit.py \
                            --hash-file $\\\\{HASH_FILE\\\\} \
                            --wordlists $\\\\{WORDLIST\\\\} \
                            --output ./hashcat-results \
                            --hashcat-path $\\\\{HASHCAT_PATH\\\\}
                    '''
                \\\\}
            \\\\}
        \\\\}

        stage('Process Results') \\\\{
            steps \\\\{
                // Archive results
                archiveArtifacts artifacts: 'hashcat-results/**/*', fingerprint: true

                // Publish report
                publishHTML([
                    allowMissing: false,
                    alwaysLinkToLastBuild: true,
                    keepAll: true,
                    reportDir: 'hashcat-results',
                    reportFiles: '*.html',
                    reportName: 'Hashcat Audit Report'
                ])

                // Check for weak passwords
                script \\\\{
                    def weakPasswords = sh(
                        script: "grep -c 'weakness_score.*[3-9]' hashcat-results/*.html||true",
                        returnStdout: true
                    ).trim()

                    if (weakPasswords.toInteger() > 0) \\\\{
                        currentBuild.result = 'UNSTABLE'
                        echo "Found $\\\\{weakPasswords\\\\} weak passwords"
                    \\\\}
                \\\\}
            \\\\}
        \\\\}
    \\\\}

    post \\\\{
        always \\\\{
            // Clean up sensitive data
            sh 'rm -f $\\\\{HASH_FILE\\\\} hashcat-results/*.potfile'
        \\\\}

        failure \\\\{
            // Send notification
            emailext (
                subject: "Password Audit Failed: $\\\\{env.JOB_NAME\\\\} - $\\\\{env.BUILD_NUMBER\\\\}",
                body: "Password audit failed. Check console output for details.",
                to: "$\\\\{env.SECURITY_TEAM_EMAIL\\\\}"
            )
        \\\\}
    \\\\}
\\\\}

Troubleshooting

Common Issues

** Cuestiones de detección de GPU:**

# Check GPU drivers
nvidia-smi  # For NVIDIA
clinfo      # For OpenCL

# Verify Hashcat GPU detection
hashcat -I

# Install missing drivers
# NVIDIA:
sudo apt install nvidia-driver-470 nvidia-opencl-dev

# AMD:
sudo apt install mesa-opencl-icd

# Test GPU functionality
hashcat -b -m 0

** Cuestiones de desempeño**

# Check system resources
nvidia-smi
htop
free -h

# Optimize workload
hashcat -w 3  # High workload
hashcat -w 4  # Nightmare mode

# Adjust kernel parameters
hashcat -n 1024 -u 256

# Monitor temperature
watch -n 1 nvidia-smi

** Cuestiones de memoria:**

# Reduce memory usage
hashcat --segment-size=32

# Use smaller wordlists
head -1000000 rockyou.txt > small_wordlist.txt

# Split large hash files
split -l 1000 large_hashes.txt hash_part_

Performance Optimization

Optimizando el rendimiento de Hashcat:

# GPU Optimization
# Use all available GPUs
hashcat -d 1,2,3,4

# Optimize workload for GPU
hashcat -w 4  # Maximum performance

# Tune kernel parameters
hashcat -n 1024 -u 256

# Memory Optimization
hashcat --segment-size=1024

# CPU Optimization
# Disable CPU usage for GPU-only attacks
hashcat --opencl-device-types=2

# Benchmark optimization
hashcat -b -m 1000 --runtime=60

Security Considerations

Operational Security

Protección de datos** - Encrypt hash files and cracked password databases - Aplicar políticas de retención de datos seguras para los resultados de auditoría - Control de acceso a herramientas y resultados de cracking contraseña - Transmisión segura de archivos de hash e informes de auditoría - Limpieza regular de archivos temporales y datos de sesión

** Consideraciones jurídicas y éticas:** - Sólo contraseñas de crack que posees o tienes permiso explícito para probar - Comprender los requisitos legales para las pruebas de seguridad de contraseñas - Aplicar procedimientos adecuados de tratamiento de datos para información confidencial - Respetar la privacidad y la confidencialidad de las credenciales de usuario - Actividades de auditoría de contraseñas para fines de cumplimiento

Hardware Security

GPU Seguridad - Control de temperatura y rendimiento de GPU - Implementar un enfriamiento adecuado para operaciones extendidas - Mantenimiento regular del hardware GPU - Acceso físico seguro a sistemas de cracking - Procedimientos de respaldo y recuperación para fallos de hardware

Referencias

  1. [Documentación Oficial de Hashcat](URL_24__
  2. [Repositorio Hashcat GitHub](URL_25__
  3. [GPU Password Cracking](URL_26___
  4. [Password Security Guidelines](URL_27__
  5. [Referencia Hash Algorithm](URL_28_