Saltar a contenido

John the Ripper hoja de trucos

Overview

John the Ripper is one of the most powerful and versatile cracking de contraseñas tools available, designed to detect weak contraseñas and perform comprehensive contraseña security auditing across multiple platforms and hash formats. Originally developed by Solar Designer, John the Ripper has evolved into a sophisticated contraseña recovery and security testing platform that suppuertos hundreds of hash and cipher types, making it an essential tool for security professionals, penetration testers, and system administrators conducting contraseña policy assessments. The tool's modular architecture and extensive customization capabilities enable both automated contraseña auditing and advanced manual contraseña recovery operations.

The core strength of John the Ripper lies in its comprehensive approach to cracking de contraseñas, combining multiple attack modes including ataque de diccionarios, fuerza bruta attacks, hybrid attacks, and advanced rule-based transformations. The tool's intelligent contraseña candidate generation system can efficiently explore contraseña spaces using wordlists, character sets, and sophisticated mutation rules that simulate common contraseña creation patterns. John's multi-format suppuerto encompasses traditional Unix crypt formats, modern bcrypt and scrypt hashes, Windows NTLM hashes, application-specific formats, and encrypted file formats, making it suitable for diverse contraseña recovery scenarios across different systems and applications.

John the Ripper's advanced features include distributed computing suppuerto for large-scale contraseña recovery operations, GPU acceleration for high-performance cracking, custom rule development for objetivoed attacks, and comprehensive sesión management for long-running operations. The tool's extensible plugin architecture allows for custom hash format suppuerto and specialized attack implementations, while its detailed progress repuertoing and statistics provide insights into contraseña strength patterns and security policy effectiveness. With its active development community, regular updates, and proven track record in security assessments, John the Ripper remains the gold standard for contraseña security testing and an indispensable component of any comprehensive security toolkit.

instalación

Ubuntu/Debian instalación

Installing John the Ripper on Ubuntu/Debian systems:

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

# Install John the Ripper from repositories
sudo apt install -y john

# Install additional tools and dependencies
sudo apt install -y john-data hashcat-utils

# Verify instalación
john --version
john --list=formats|head -20

# Install development version (Jumbo)
sudo apt install -y git build-essential libssl-dev zlib1g-dev \
    yasm libgmp-dev libpcap-dev pkg-config libbz2-dev

# Clone and build John the Ripper Jumbo
cd /opt
sudo git clone https://github.com/openwall/john.git
cd john/src
sudo ./configure
sudo make -j$(nproc)

# Create symlinks for system-wide access
sudo ln -sf /opt/john/run/john /usr/local/bin/john
sudo ln -sf /opt/john/run/john /usr/local/bin/john-jumbo

# Verify Jumbo instalación
john --version
john --list=formats|wc -l

CentOS/RHEL instalación

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

# Install John the Ripper
sudo yum install -y john

# Install development tools for Jumbo version
sudo yum groupinstall -y "Development Tools"
sudo yum install -y openssl-devel zlib-devel gmp-devel libpcap-devel \
    bzip2-devel git

# Build John the Ripper Jumbo
cd /opt
sudo git clone https://github.com/openwall/john.git
cd john/src
sudo ./configure
sudo make -j$(nproc)

# Install system-wide
sudo make install

# Alternative: Install from source with optimizations
sudo ./configure --enable-simd=avx2 --enable-openmp
sudo make -j$(nproc)

macOS instalación

# Install using Homebrew
brew install john

# Install Jumbo version
brew install john-jumbo

# Alternative: Build from source
brew install openssl gmp libpcap
git clone https://github.com/openwall/john.git
cd john/src
./configure --with-openssl=$(brew --prefix openssl)
make -j$(sysctl -n hw.ncpu)

# Verify instalación
john --version

Windows instalación

# Download pre-compiled binaries
# https://www.openwall.com/john/

# Extract to desired location
# ejemplo: C:\john

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

# Verify instalación
john.exe --version

# Alternative: Build with Cygwin
# Install Cygwin with development tools
# Follow Unix build instructions

Docker instalación

Running John the Ripper in Docker:

# Create Dockerfile for John the Ripper
cat > Dockerfile.john << 'EOF'
FROM ubuntu:22.04

# Install dependencies
RUN apt-get update && apt-get install -y \
    git \
    build-essential \
    libssl-dev \
    zlib1g-dev \
    yasm \
    libgmp-dev \
    libpcap-dev \
    pkg-config \
    libbz2-dev \
    && rm -rf /var/lib/apt/lists/*

# Clone and build John the Ripper Jumbo
RUN git clone https://github.com/openwall/john.git /opt/john
WORKDIR /opt/john/src
RUN ./configure && make -j$(nproc)

# Create working directory
WORKDIR /work

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

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

# Build Docker image
docker build -f Dockerfile.john -t john-the-ripper .

# Run John the Ripper in Docker
docker run -it --rm \
    -v $(pwd):/work \
    john-the-ripper john --version

# Run with GPU suppuerto (NVIDIA)
docker run --gpus all -it --rm \
    -v $(pwd):/work \
    john-the-ripper john --list=opencl-devices

Basic uso

hash Extraction

Extracting hashes from various sources:

# Extract hashes from /etc/passwd and /etc/shadow
sudo unshadow /etc/passwd /etc/shadow > hashes.txt

# Extract Windows hashes from SAM
# Use tools like pwdump, fgdump, or Metasploit
# ejemplo output format: nombre de usuario:RID:LM_hash:NTLM_hash:::

# Extract hashes from various file formats
# ZIP files
zip2john encrypted.zip > zip_hashes.txt

# RAR files
rar2john encrypted.rar > rar_hashes.txt

# PDF files
pdf2john encrypted.pdf > pdf_hashes.txt

# SSH private claves
ssh2john id_rsa > ssh_hashes.txt

# Office documents
office2john document.docx > office_hashes.txt

# 7-Zip files
7z2john encrypted.7z > 7z_hashes.txt

# TrueCrypt/VeraCrypt volumes
truecrypt2john encrypted.tc > tc_hashes.txt

# Bitcoin wallets
bitcoin2john wallet.dat > bitcoin_hashes.txt

# Verify hash format
john --list=formats|grep -i ntlm
john --list=formats|grep -i md5

Basic Cracking

Performing basic cracking de contraseñas:

# Simple ataque de diccionario
john --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt

# Crack specific hash format
john --format=NT hashes.txt
john --format=md5crypt hashes.txt
john --format=bcrypt hashes.txt

# Show cracked contraseñas
john --show hashes.txt

# Show cracked contraseñas with specific format
john --show --format=NT hashes.txt

# Resume interrupted sesión
john --restore

# Crack with time limit
timeout 3600 john --wordlist=wordlist.txt hashes.txt

# Crack single hash
echo "user:$1$salt$hash"|john --stdin --format=md5crypt

# Incremental mode (fuerza bruta)
john --incremental hashes.txt

# Incremental with specific charset
john --incremental=alpha hashes.txt
john --incremental=digits hashes.txt
john --incremental=alnum hashes.txt

# Custom incremental mode
john --incremental=custom --min-length=6 --max-length=8 hashes.txt

Wordlist Attacks

Advanced wordlist-based attacks:

# Basic wordlist attack
john --wordlist=rockyou.txt hashes.txt

# Multiple wordlists
john --wordlist=wordlist1.txt,wordlist2.txt,wordlist3.txt hashes.txt

# Wordlist with rules
john --wordlist=rockyou.txt --rules hashes.txt

# Specific rule set
john --wordlist=rockyou.txt --rules=best64 hashes.txt
john --wordlist=rockyou.txt --rules=wordlist hashes.txt

# Custom rules
john --wordlist=rockyou.txt --rules=custom hashes.txt

# Pipe wordlist from stdin
cat wordlist.txt|john --stdin hashes.txt

# Generate wordlist variations
john --wordlist=base.txt --stdout --rules=best64 > expanded.txt

# Mask attack (hybrid)
john --mask=?l?l?l?l?d?d?d?d hashes.txt

# Mask with wordlist
john --wordlist=names.txt --mask=?w?d?d?d?d hashes.txt

# External mode (custom algoritmos)
john --external=double hashes.txt

Advanced Features

Rule-Based Attacks

Creating and using custom rules:

# View available rules
john --list=rules

# Create custom rule file
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$ st7

# Common substitutions
| sa4 se3 si! so0 su | _ |  |

# Append common suffixes
$! $@ $# $ $% $1 $2 $3 $01 $02 $03 $123

# Prepend common prefixes
^! ^@ ^# ^$ ^% ^1 ^2 ^3

# Complex rules
c $1 $2 $3
c $! $@
c $2 $0 $1 $9
EOF

# Use custom rules
john --wordlist=wordlist.txt --rules=custom hashes.txt

# Test rules without cracking
john --wordlist=test.txt --rules=custom --stdout

# Rule debugging
john --wordlist=test.txt --rules=custom --stdout|head -20

# Combine multiple rule sets
john --wordlist=wordlist.txt --rules=best64,custom hashes.txt

sesión Management

Managing long-running sesións:

# Start named sesión
john --sesión=mysesión --wordlist=rockyou.txt hashes.txt

# Resume named sesión
john --restore=mysesión

# List active sesións
john --list=sesións

# sesión status
john --status=mysesión

# Abort sesión
john --abort=mysesión

# sesión configuración
cat >`` john.conf << 'EOF'
[opcións]
# sesión save interval (seconds)
Save = 600

# Idle time before sesión save
Idle = 1800

# Beep when contraseña found
Beep = Y

# Log file
LogFile = john.log
EOF

# Use custom configuración
john --config=john.conf --wordlist=wordlist.txt hashes.txt

Performance Optimization

Optimizing John the Ripper performance:

# Multi-core procesoing
john --fork=4 --wordlist=rockyou.txt hashes.txt

# OpenMP suppuerto (if compiled)
expuerto OMP_NUM_hiloS=8
john --wordlist=rockyou.txt hashes.txt

# GPU acceleration (OpenCL)
john --list=opencl-devices
john --format=ntlm-opencl --wordlist=rockyou.txt hashes.txt

# CUDA suppuerto
john --format=ntlm-cuda --wordlist=rockyou.txt hashes.txt

# Memory optimization
john --mem-file-size=1024 --wordlist=rockyou.txt hashes.txt

# Benchmark different formats
john --test
john --test=60  # 60-second benchmark

# Format-specific benchmark
john --test --format=md5crypt
john --test --format=bcrypt

# Node-specific optimization
john --node=1/4 --wordlist=rockyou.txt hashes.txt  # Node 1 of 4
john --node=2/4 --wordlist=rockyou.txt hashes.txt  # Node 2 of 4

# Priority settings
nice -n 19 john --wordlist=rockyou.txt hashes.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:
john --node=1/4 --wordlist=rockyou.txt hashes.txt

# Machine 2:
john --node=2/4 --wordlist=rockyou.txt hashes.txt

# Machine 3:
john --node=3/4 --wordlist=rockyou.txt hashes.txt

# Machine 4:
john --node=4/4 --wordlist=rockyou.txt hashes.txt

# Combine results
john --show hashes.txt > results_machine1.txt
# Copy results from all machines and combine

# Network-based distribution script
cat > distribute_john.sh ``<< 'EOF'
#!/bin/bash

hostS=("server1" "server2" "server3" "server4")
WORDLIST="rockyou.txt"
hashES="hashes.txt"
TOTAL_NODES=$\\\{#hostS[@]\\\}

for i in "$\\\{!hostS[@]\\\}"; do
    NODE=$((i + 1))
    host="$\\\{hostS[$i]\\\}"

    echo "Starting node $NODE on $host"
    ssh $host "john --node=$NODE/$TOTAL_NODES --wordlist=$WORDLIST $hashES" &
done

wait
echo "All nodes completed"
EOF

chmod +x distribute_john.sh
./distribute_john.sh

Automation Scripts

Comprehensive contraseña Audit Script

#!/usr/bin/env python3
# Comprehensive contraseña audit using John the Ripper

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

class JohnTheRipperAuditor:
    def __init__(self, john_path="john"):
        self.john_path = john_path
        self.results = \\\{\\\}
        self.sesións = \\\{\\\}

    def verify_john_instalación(self):
        """Verify John the Ripper instalación"""
        try:
            result = subproceso.run([self.john_path, "--version"],
                                  capture_output=True, text=True)
            if result.returncode == 0:
                print(f"John the Ripper version: \\\{result.stdout.strip()\\\}")
                return True
            else:
                print("John the Ripper not found or not working")
                return False
        except Exception as e:
            print(f"Error checking John instalación: \\\{e\\\}")
            return False

    def list_suppuertoed_formats(self):
        """List suppuertoed hash formats"""
        try:
            result = subproceso.run([self.john_path, "--list=formats"],
                                  capture_output=True, text=True)
            if result.returncode == 0:
                formats = result.stdout.strip().split('\n')
                return [f.strip() for f in formats if f.strip()]
            return []
        except Exception as e:
            print(f"Error listing formats: \\\{e\\\}")
            return []

    def extract_hashes(self, source_type, source_path, output_file):
        """Extract hashes from various sources"""
        extractors = \\\{
            'zip': 'zip2john',
            'rar': 'rar2john',
            'pdf': 'pdf2john',
            'ssh': 'ssh2john',
            'office': 'office2john',
            '7z': '7z2john',
            'truecrypt': 'truecrypt2john',
            'bitcoin': 'bitcoin2john'
        \\\}

        if source_type not in extractors:
            print(f"Unsuppuertoed source type: \\\{source_type\\\}")
            return False

        extractor = extractors[source_type]

        try:
            with open(output_file, 'w') as f:
                result = subproceso.run([extractor, source_path],
                                      stdout=f, stderr=subproceso.PIPE, text=True)

            if result.returncode == 0:
                print(f"hashes extracted to: \\\{output_file\\\}")
                return True
            else:
                print(f"hash extraction failed: \\\{result.stderr\\\}")
                return False
        except Exception as e:
            print(f"Error extracting hashes: \\\{e\\\}")
            return False

    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.john_path, "--sesión=" + sesión_name]

        # Add format if specified
        if attack_config.get('format'):
            cmd.extend(["--format=" + attack_config['format']])

        # Add attack mode
        if attack_config.get('mode') == 'wordlist':
            if attack_config.get('wordlist'):
                cmd.extend(["--wordlist=" + attack_config['wordlist']])
            if attack_config.get('rules'):
                cmd.extend(["--rules=" + attack_config['rules']])
        elif attack_config.get('mode') == 'incremental':
            cmd.extend(["--incremental"])
            if attack_config.get('charset'):
                cmd.extend(["--incremental=" + attack_config['charset']])
        elif attack_config.get('mode') == 'mask':
            if attack_config.get('mask'):
                cmd.extend(["--mask=" + attack_config['mask']])

        # Add performance opcións
        if attack_config.get('fork'):
            cmd.extend(["--fork=" + str(attack_config['fork'])])

        # 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
            \\\}

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

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

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

        if format_type:
            cmd.extend(["--format=" + format_type])

        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 not line.startswith('0 contraseña'):
                        parts = line.split(':')
                        if len(parts) >``= 2:
                            cracked.append(\\\\{
                                'nombre de usuario': 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_patterns(self, cracked_contraseñas):
        """Analyze contraseña patterns and weaknesses"""
        analysis = \\\\{
            'total_cracked': len(cracked_contraseñas),
            'length_distribution': \\\\{\\\\},
            'character_sets': \\\\{
                'lowercase_only': 0,
                'uppercase_only': 0,
                'digits_only': 0,
                'mixed_case': 0,
                'with_digits': 0,
                'with_symbols': 0
            \\\\},
            'common_patterns': \\\\{
                'dictionary_words': 0,
                'claveboard_patterns': 0,
                'date_patterns': 0,
                'name_patterns': 0
            \\\\},
            'weak_contraseñas': []
        \\\\}

        impuerto re

        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 set 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_sets']['lowercase_only'] += 1
            elif contraseña.isupper():
                analysis['character_sets']['uppercase_only'] += 1
            elif contraseña.isdigit():
                analysis['character_sets']['digits_only'] += 1
            elif has_lower and has_upper:
                analysis['character_sets']['mixed_case'] += 1

            if has_digit:
                analysis['character_sets']['with_digits'] += 1
            if has_symbol:
                analysis['character_sets']['with_symbols'] += 1

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

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

            if re.search(r'(19|20)\d\\\\{2\\\\}', contraseña):
                analysis['common_patterns']['date_patterns'] += 1

            # Weak contraseña identification
            if (length < 8 or
                contraseña.lower() in ['contraseña', '123456', 'admin', 'user'] or
                contraseña.isdigit() or
                contraseña.islower()):
                analysis['weak_contraseñas'].append(entry)

        return analysis

    def generate_repuerto(self, audit_results, output_file="contraseña_audit_repuerto.html"):
        """Generate comprehensive audit repuerto"""
        html_content = f"""
<!DOCTYPE html>
<html>
<head>
    <title>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; \\\\}\\\\}
        table \\\\{\\\\{ border-collapse: collapse; width: 100%; \\\\}\\\\}
        th, td \\\\{\\\\{ border: 1px solid #ddd; padding: 8px; text-align: left; \\\\}\\\\}
        th \\\\{\\\\{ background-color: #f2f2f2; \\\\}\\\\}
        .chart \\\\{\\\\{ width: 100%; height: 300px; \\\\}\\\\}
    </style>
</head>
<body>
    <h1>contraseña Security Audit Repuerto</h1>
    <p>Generated: \\\\{datetime.now().isoformat()\\\\}</p>

    <div class="section">
        <h2>Executive Summary</h2>
        <ul>
            <li>Total contraseñas Analyzed: \\\\{audit_results.get('total_analyzed', 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_analyzed', 1), 1) * 100):.2f\\\\}%</li>
            <li>Weak contraseñas: \\\\{len(audit_results.get('weak_contraseñas', []))\\\\}</li>
        </ul>
    </div>

    <div class="section">
        <h2 class="critical">Critical Findings</h2>
        <h3>Weak contraseñas</h3>
        <table>
            <tr><th>nombre de usuario</th><th>contraseña</th><th>Weakness</th></tr>
"""

        for weak in audit_results.get('weak_contraseñas', [])[:20]:
            weakness = "Short/Common/Simple"
            html_content += f"""
            <tr>
                <td>\\\\{weak['nombre de usuario']\\\\}</td>
                <td>\\\\{weak['contraseña']\\\\}</td>
                <td>\\\\{weakness\\\\}</td>
            </tr>"""

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

    <div class="section">
        <h2>contraseña Length Distribution</h2>
        <table>
            <tr><th>Length</th><th>Count</th><th>Percentage</th></tr>
"""

        length_dist = audit_results.get('length_distribution', \\\\{\\\\})
        total = sum(length_dist.values())

        for length, count in sorted(length_dist.items()):
            percentage = (count / total * 100) if total > 0 else 0
            html_content += f"""
            <tr>
                <td>\\\\{length\\\\}</td>
                <td>\\\\{count\\\\}</td>
                <td>\\\\{percentage:.2f\\\\}%</td>
            </tr>"""

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

    <div class="section">
        <h2>Character Set Analysis</h2>
        <table>
            <tr><th>Character Set</th><th>Count</th><th>Percentage</th></tr>
"""

        char_sets = audit_results.get('character_sets', \\\\{\\\\})
        total_cracked = audit_results.get('total_cracked', 1)

        for char_set, count in char_sets.items():
            percentage = (count / total_cracked * 100) if total_cracked > 0 else 0
            html_content += f"""
            <tr>
                <td>\\\\{char_set.replace('_', ' ').title()\\\\}</td>
                <td>\\\\{count\\\\}</td>
                <td>\\\\{percentage:.2f\\\\}%</td>
            </tr>"""

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

    <div class="section">
        <h2>Recommendations</h2>
        <ul>
            <li>Implement minimum contraseña length of 12 characters</li>
            <li>Require mixed case, numbers, and symbols</li>
            <li>Prohibit common dictionary words and patterns</li>
            <li>Implement account lockout policies</li>
            <li>Enable multi-factor autenticación</li>
            <li>Regular contraseña audits and user education</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 run_comprehensive_audit(self, hash_file, wordlists, output_dir="/tmp/john_audit"):
        """Run comprehensive contraseña audit"""
        print("Starting comprehensive contraseña 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_analyzed': 0,
            'total_cracked': 0
        \\\\}

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

        # Run multiple attack modes
        attack_configs = [
            \\\\{
                'name': 'Quick Dictionary',
                'mode': 'wordlist',
                'wordlist': wordlists[0] if wordlists else '/usr/share/wordlists/rockyou.txt',
                'rules': 'best64',
                'timeout': 1800  # 30 minutes
            \\\\},
            \\\\{
                'name': 'Extended Dictionary',
                'mode': 'wordlist',
                'wordlist': wordlists[0] if wordlists else '/usr/share/wordlists/rockyou.txt',
                'rules': 'wordlist',
                'timeout': 3600  # 1 hour
            \\\\},
            \\\\{
                'name': 'Incremental Alpha',
                'mode': 'incremental',
                'charset': 'alpha',
                '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:
                    audit_results['sesións'].append(result)

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

        # Analyze patterns
        if cracked_contraseñas:
            pattern_analysis = self.analyze_contraseña_patterns(cracked_contraseñas)
            audit_results.update(pattern_analysis)

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

        return audit_results

def main():
    parser = argparse.ArgumentParser(Descripción='John the Ripper 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('--format', help='hash format')
    parser.add_argument('--output', default='/tmp/john_audit', help='Output directory')
    parser.add_argument('--john-path', default='john', help='Path to John executable')

    args = parser.parse_args()

    # Initialize auditor
    auditor = JohnTheRipperAuditor(args.john_path)

    # Verify instalación
    if not auditor.verify_john_instalación():
        print("John the Ripper not properly installed")
        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

SIEM Integration

#!/bin/bash
# John the Ripper SIEM integration script

# configuración
hash_DIR="/var/log/contraseña_hashes"
WORDLIST="/usr/share/wordlists/rockyou.txt"
SPLUNK_HEC_URL="https://splunk.company.com:8088/servicios/collector/event"
SPLUNK_token="your-hec-token"
ELASTICSEARCH_URL="http://elasticsearch.company.com:9200"

# Function to send events to Splunk
send_to_splunk() \\\\{
    local event_data="$1"

    curl -k -X POST "$SPLUNK_HEC_URL" \
        -H "autorización: Splunk $SPLUNK_token" \
        -H "Content-Type: application/json" \
        -d "$event_data"
\\\\}

# Function to audit contraseñas and send results
audit_and_repuerto() \\\\{
    local hash_file="$1"
    local timestamp=$(date +%Y%m%d_%H%M%S)
    local sesión_name="audit_$timestamp"

    echo "Starting contraseña audit: $hash_file"

    # Start John the Ripper
    john --sesión=$sesión_name --wordlist=$WORDLIST --rules=best64 $hash_file &
    JOHN_PID=$!

    # Monitor for 30 minutes
    sleep 1800

    # Stop John if still running
    if kill -0 $JOHN_PID 2>/dev/null; then
        kill $JOHN_PID
    fi

    # Get results
    cracked_contraseñas=$(john --show $hash_file)

    # Parse results and send to SIEM
    echo "$cracked_contraseñas"|while IFS=':' read -r nombre de usuario contraseña rest; do
        if [ -n "$nombre de usuario" ] && [ -n "$contraseña" ]; then
            event_json=$(cat << EOF
\\\\{
    "time": "$(date -Iseconds)",
    "source": "john_the_ripper",
    "sourcetype": "contraseña_audit",
    "event": \\\\{
        "timestamp": "$(date -Iseconds)",
        "nombre de usuario": "$nombre de usuario",
        "contraseña_cracked": true,
        "contraseña_length": $\\\\{#contraseña\\\\},
        "hash_file": "$hash_file",
        "sesión": "$sesión_name",
        "event_type": "weak_contraseña_detected"
    \\\\}
\\\\}
EOF
            )

            send_to_splunk "$event_json"
        fi
    done

    echo "contraseña audit completed: $hash_file"
\\\\}

# Monitor hash directory for new files
inotifywait -m -e create -e moved_to "$hash_DIR"|
while read path action file; do
    if [[ "$file" == *.txt ]]; then
        audit_and_repuerto "$path$file"
    fi
done

solución de problemas

Common Issues

Permission Issues:

# Ensure proper permissions for hash files
chmod 600 hashes.txt

# Run with appropriate privileges
sudo john --wordlist=rockyou.txt hashes.txt

# Check file ownership
ls -la hashes.txt
chown user:user hashes.txt

Memory Issues:

# Reduce memory uso
john --mem-file-size=100 --wordlist=wordlist.txt hashes.txt

# Use external mode for large wordlists
john --external=wordlist --wordlist=huge_wordlist.txt hashes.txt

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

Performance Issues:

# Check system resources
top
htop
free -h

# Optimize for CPU
john --fork=$(nproc) --wordlist=wordlist.txt hashes.txt

# Use GPU acceleration
john --list=opencl-devices
john --format=ntlm-opencl --wordlist=wordlist.txt hashes.txt

# Benchmark performance
john --test=60

Performance Optimization

Optimizing John the Ripper performance:

# CPU Optimization
expuerto OMP_NUM_hiloS=$(nproc)
john --fork=$(nproc) --wordlist=wordlist.txt hashes.txt

# Memory Optimization
john --mem-file-size=1024 --wordlist=wordlist.txt hashes.txt

# I/O Optimization
# Use SSD for wordlists and hash files
# Preload wordlists into memory
cat wordlist.txt > /dev/null

# GPU Optimization
john --list=opencl-devices
john --format=ntlm-opencl --wordlist=wordlist.txt hashes.txt

# Network Optimization for distributed cracking
john --node=1/4 --wordlist=wordlist.txt hashes.txt

Security Considerations

Operational Security

Data Protection: - Encrypt hash files and cracked contraseña databases - Implement secure data retention policies for contraseña 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

contraseña Security

Audit Best Practices: - Regular contraseña strength assessments - Implementation of strong contraseña policies - User education on contraseña security - Multi-factor autenticación deployment - Monitoring for compromised credenciales

referencias

  1. John the Ripper Official documentación
  2. John the Ripper Jumbo
  3. cracking de contraseñas Techniques
  4. hash Formats Reference
  5. contraseña Security Best Practices