Saltar a contenido

hashcat hoja de trucos

Overview

hashcat is the world's fastest and most advanced contraseña recovery tool, designed to leverage the computational power of modern CPUs and GPUs for high-performance cracking de contraseñas and security auditing. Developed as a successor to traditional CPU-based contraseña crackers, hashcat revolutionizes contraseña security testing by utilizing the parallel procesoing capabilities of graphics cards to achieve unprecedented cracking speeds. The tool suppuertos over 300 hash algoritmos and attack modes, making it the most comprehensive contraseña recovery platform available for security professionals, penetration testers, and researchers conducting contraseña policy assessments and security audits.

The core strength of hashcat lies in its sophisticated GPU acceleration architecture, which can harness the power of multiple graphics cards simultaneously to perform billions of contraseña candidate tests per second. This massive computational capability, combined with intelligent attack optimization algoritmos, enables hashcat to crack complex contraseñas that would be impractical to attack with traditional CPU-based tools. The platform suppuertos all major GPU vendors including NVIDIA CUDA and AMD OpenCL, automatically optimizing performance for available hardware configuracións and providing detailed performance metrics for capacity planning and attack optimization.

hashcat's advanced feature set includes multiple attack modes ranging from ataque de diccionarios and rule-based transformations to sophisticated mask attacks and hybrid combinations. The tool's modular architecture suppuertos custom rule development, distributed computing across multiple systems, and integration with external wordlist generators and preprocesoing tools. With its comprehensive sesión management, detailed progress repuertoing, and extensive customization opcións, hashcat provides both automated contraseña auditing capabilities and fine-grained control for specialized security research applications. The platform's active development community and continuous optimization for emerging hardware architectures ensure it remains at the forefront of contraseña security testing technology.

instalación

Ubuntu/Debian instalación

Installing hashcat on Ubuntu/Debian systems:

# 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 instalación
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 instalación
hashcat --version
hashcat -I

Windows instalación

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

# Extract to desired location
# ejemplo: 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 instalación
hashcat.exe --version
hashcat.exe -I

# Alternative: Install with Chocolatey
choco install hashcat

macOS instalación

# Install using Homebrew
brew install hashcat

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

# Verify instalación
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

Running hashcat in Docker with GPU suppuerto:

# 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 suppuerto (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

Basic uso

hash Identification

Identifying hash types and formats:

# List suppuertoed 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

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

Basic Attacks

Performing basic contraseña attacks:

# ataque de diccionario
hashcat -m 0 -a 0 hash.txt wordlist.txt

# ataque de diccionario with rules
hashcat -m 0 -a 0 hash.txt wordlist.txt -r rules/best64.rule

# fuerza bruta 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 contraseñas
hashcat -m 0 hash.txt --show

# Resume sesión
hashcat --sesión=mysesión --restore

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

Performance Optimization

Optimizing hashcat performance:

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

Advanced Features

Mask Attacks

Advanced mask-based attacks:

# 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 contraseña 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

Rule-Based Attacks

Advanced rule-based transformations:

# 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

sesión Management

Managing long-running sesións:

# Start named sesión
hashcat --sesión=audit2023 -m 1000 -a 0 hash.txt wordlist.txt

# Check sesión status
hashcat --sesión=audit2023 --status

# Restore sesión
hashcat --sesión=audit2023 --restore

# Remove sesión
hashcat --sesión=audit2023 --remove

# sesión with checkpoint
hashcat --sesión=audit2023 -m 1000 -a 0 hash.txt wordlist.txt --status-timer=60

# Quit sesión gracefully
# Press 'q' during execution or send SIGTERM

# sesión configuración
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 configuración file
hashcat --sesión=audit2023 --config=hashcat.conf -m 1000 -a 0 hash.txt wordlist.txt

Distributed Cracking

Setting up distributed cracking de contraseñas:

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

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

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

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

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

# Distribute clavespace
# 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 --sesión=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 contraseña Audit Script

#!/usr/bin/env python3
# Comprehensive contraseña audit using hashcat

impuerto subproceso
impuerto os
impuerto sys
impuerto time
impuerto json
impuerto argparse
from datetime impuerto datetime
impuerto hiloing
impuerto queue
impuerto re

class hashcatAuditor:
    def __init__(self, hashcat_path="hashcat"):
        self.hashcat_path = hashcat_path
        self.results = \\\{\\\}
        self.sesións = \\\{\\\}

    def verify_hashcat_instalación(self):
        """Verify hashcat instalación and GPU suppuerto"""
        try:
            result = subproceso.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 = subproceso.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 instalación: \\\{e\\\}")
            return False

    def identify_hash_type(self, hash_file):
        """Identify hash types in file"""
        try:
            result = subproceso.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 = subproceso.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 subproceso.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_contraseñas(self, hash_file, attack_config):
        """Crack contraseñas with specified configuración"""
        sesión_name = f"audit_\\\\{int(time.time())\\\\}"

        cmd = [self.hashcat_path, "--sesión", sesión_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 parámetros
        if attack_config.get('attack') == 0:  # ataque de diccionario
            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 opcións
        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 cracking de contraseñas: \\\\{' '.join(cmd)\\\\}")

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

            self.sesións[sesión_name] = \\\\{
                'proceso': proceso,
                'start_time': time.time(),
                'config': attack_config,
                'cmd': cmd
            \\\\}

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

    def monitor_sesión(self, sesión_name, timeout=None):
        """Monitor cracking sesión"""
        if sesión_name not in self.sesións:
            print(f"sesión \\\\{sesión_name\\\\} not found")
            return None

        sesión = self.sesións[sesión_name]
        proceso = sesión['proceso']
        start_time = sesión['start_time']

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

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

            result = \\\\{
                'sesión': sesión_name,
                'duration': duration,
                'returncode': proceso.returncode,
                'stdout': stdout,
                'stderr': stderr,
                'cmd': sesión['cmd']
            \\\\}

            return result
        except subproceso.TimeoutExpired:
            print(f"sesión \\\\{sesión_name\\\\} timed out")
            proceso.terminate()
            return None
        except Exception as e:
            print(f"Error monitoring sesión: \\\\{e\\\\}")
            return None

    def get_cracked_contraseñas(self, hash_file, hash_mode=None):
        """Retrieve cracked contraseñas"""
        cmd = [self.hashcat_path, "--show"]

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

        cmd.append(hash_file)

        try:
            result = subproceso.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],
                                'contraseña': parts[1],
                                'full_line': line
                            \\\\})

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

    def analyze_contraseña_strength(self, cracked_contraseñas):
        """Analyze contraseña strength patterns"""
        analysis = \\\\{
            'total_cracked': len(cracked_contraseñas),
            '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,
                'claveboard_patterns': 0,
                'repeated_characters': 0,
                'sequential_patterns': 0
            \\\\},
            'complexity_score': 0,
            'weak_contraseñas': []
        \\\\}

        if not cracked_contraseñas:
            return analysis

        for entry in cracked_contraseñas:
            contraseña = entry['contraseña']
            length = len(contraseña)

            # 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]', contraseña))
            has_upper = bool(re.search(r'[A-Z]', contraseña))
            has_digit = bool(re.search(r'[0-9]', contraseña))
            has_symbol = bool(re.search(r'[^a-zA-Z0-9]', contraseña))

            if contraseña.islower():
                analysis['character_analysis']['lowercase_only'] += 1
            elif contraseña.isupper():
                analysis['character_analysis']['uppercase_only'] += 1
            elif contraseña.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 contraseña.isalnum():
                analysis['character_analysis']['alphanumeric'] += 1

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

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

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

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

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

            if weakness_score >= 3:
                analysis['weak_contraseñas'].append(\\\\{
                    'contraseña': contraseña,
                    'hash': entry['hash'],
                    'weakness_score': weakness_score
                \\\\})

        # Calculate overall complexity score
        total = len(cracked_contraseñas)
        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_contraseñas']) / total)) * 25
            ]
            analysis['complexity_score'] = sum(complexity_factors)

        return analysis

    def generate_comprehensive_repuerto(self, audit_results, output_file="hashcat_audit_repuerto.html"):
        """Generate comprehensive audit repuerto"""
        html_content = f"""
<!DOCTYPE html>
<html>
<head>
    <title>hashcat contraseña Security Audit Repuerto</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 contraseña Security Audit Repuerto</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>contraseñas 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 contraseñas: \\\\{len(audit_results.get('weak_contraseñas', []))\\\\}</li>
        </ul>

        <h3>contraseña 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 contraseñas</h3>
        <table>
            <tr><th>hash</th><th>contraseña</th><th>Weakness Score</th></tr>
"""

        for weak in audit_results.get('weak_contraseñas', [])[:20]:
            html_content += f"""
            <tr>
                <td>\\\\{weak['hash'][:20]\\\\}...</td>
                <td>\\\\{weak['contraseña']\\\\}</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>contraseñas Found</th><th>Rate</th></tr>
"""

        for sesión in audit_results.get('sesións', []):
            duration = sesión.get('duration', 0)
            contraseñas_found = sesión.get('contraseñas_found', 0)
            rate = contraseñas_found / duration if duration > 0 else 0

            html_content += f"""
            <tr>
                <td>\\\\{sesión.get('attack_method', 'Unknown')\\\\}</td>
                <td>\\\\{duration:.2f\\\\}s</td>
                <td>\\\\{contraseñas_found\\\\}</td>
                <td>\\\\{rate:.2f\\\\} p/s</td>
            </tr>"""

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

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

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

        print(f"Repuerto 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 contraseña 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,
            'sesións': [],
            '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.claves())[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...")

            sesión_name = self.crack_contraseñas(hash_file, config)
            if sesión_name:
                result = self.monitor_sesión(sesión_name, config.get('timeout'))
                if result:
                    result['attack_method'] = config['name']
                    audit_results['sesións'].append(result)

        # Get final results
        cracked_contraseñas = self.get_cracked_contraseñas(hash_file, best_mode)
        audit_results['total_cracked'] = len(cracked_contraseñas)

        # Analyze contraseña strength
        if cracked_contraseñas:
            strength_analysis = self.analyze_contraseña_strength(cracked_contraseñas)
            audit_results.update(strength_analysis)

        # Generate repuerto
        repuerto_file = os.path.join(output_dir, "hashcat_audit_repuerto.html")
        self.generate_comprehensive_repuerto(audit_results, repuerto_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']\\\\} contraseñas")

        return audit_results

def main():
    parser = argparse.ArgumentParser(Descripción='hashcat contraseña 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 instalación
    if not auditor.verify_hashcat_instalación():
        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("contraseña audit completed successfully")
    else:
        print("contraseña audit failed")
        sys.exit(1)

if __name__ == "__main__":
    main()

Integration 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 contraseña 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('contraseña 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('proceso Results') \\\\{
            steps \\\\{
                // Archive results
                archiveArtifacts artifacts: 'hashcat-results/**/*', huella digital: true

                // Publish repuerto
                publishHTML([
                    allowMissing: false,
                    alwaysLinkToLastBuild: true,
                    keepAll: true,
                    repuertoDir: 'hashcat-results',
                    repuertoFiles: '*.html',
                    repuertoName: 'hashcat Audit Repuerto'
                ])

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

                    if (weakcontraseñas.toInteger() > 0) \\\\{
                        currentBuild.result = 'UNSTABLE'
                        echo "Found $\\\\{weakcontraseñas\\\\} weak contraseñas"
                    \\\\}
                \\\\}
            \\\\}
        \\\\}
    \\\\}

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

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

solución de problemas

Common Issues

GPU Detection Issues:

# 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

Performance Issues:

# Check system resources
nvidia-smi
htop
free -h

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

# Adjust kernel parámetros
hashcat -n 1024 -u 256

# Monitor temperature
watch -n 1 nvidia-smi

Memory Issues:

# Reduce memory uso
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

Optimizing hashcat performance:

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

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

# Tune kernel parámetros
hashcat -n 1024 -u 256

# Memory Optimization
hashcat --segment-size=1024

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

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

Security Considerations

Operational Security

Data Protection: - Encrypt hash files and cracked contraseña databases - Implement secure data retention policies for audit results - Control access to cracking de contraseñas tools and results - Secure transmission of hash files and audit repuertos - Regular cleanup of temporary files and sesión data

Legal and Ethical Considerations: - Only crack contraseñas you own or have explicit permission to test - Understand legal requirements for contraseña security testing - Implement proper data handling procedures for sensitive information - Respect privacy and confidentiality of user credenciales - Document contraseña auditing activities for compliance purposes

Hardware Security

GPU Security: - Monitor GPU temperature and performance - Implement proper cooling for extended operations - Regular maintenance of GPU hardware - Secure physical access to cracking systems - Backup and recovery procedures for hardware failures

referencias

  1. hashcat Official documentación
  2. hashcat GitHub Repository
  3. GPU cracking de contraseñas
  4. contraseña Security Guidelines
  5. hash algoritmo Reference