Vai al contenuto

FRONTMATTER_29_# John the Ripper Cheat Sheet

HTML_TAG_18_ __HTML_TAG_23_

Panoramica

John the Ripper è uno degli strumenti di cracking password più potenti e versatili disponibili, progettato per rilevare le password deboli e eseguire un controllo completo della sicurezza delle password su più piattaforme e formati hash. Originariamente sviluppato da Solar Designer, John the Ripper si è evoluto in una sofisticata piattaforma di recupero password e test di sicurezza che supporta centinaia di tipi di hash e cifrari, rendendolo uno strumento essenziale per i professionisti della sicurezza, i tester di penetrazione e gli amministratori di sistema che conducono le valutazioni di policy delle password. L'architettura modulare dello strumento e le ampie capacità di personalizzazione consentono sia l'auditing automatico delle password sia le operazioni di recupero manuale avanzate delle password.

La forza principale di John lo Squartatore si trova nel suo approccio completo di cracking password, combinando più modalità di attacco tra cui attacchi di dizionario, attacchi di forza bruta, attacchi ibridi, e trasformazioni basate su regole avanzate. Il sistema di generazione intelligente di password dello strumento può esplorare in modo efficiente gli spazi di password utilizzando wordlist, set di caratteri e sofisticate regole di mutazione che simulano i modelli di creazione di password comuni. Il supporto multi-format di John comprende i formati tradizionali di crittografia Unix, le moderne ciglia di bcrypt e scrypt, le ciglia di Windows NTLM, i formati specifici per le applicazioni e i formati di file crittografati, rendendolo adatto per diversi scenari di recupero password in diversi sistemi e applicazioni.

Le funzioni avanzate di John the Ripper includono il supporto informatico distribuito per le operazioni di recupero di password su larga scala, l'accelerazione GPU per la cracking ad alte prestazioni, lo sviluppo di regole personalizzate per attacchi mirati e la gestione completa delle sessioni per operazioni di lungo periodo. L'estesa architettura del plugin dello strumento consente il supporto del formato hash personalizzato e le implementazioni di attacco specializzate, mentre il suo dettagliato report dei progressi e le statistiche forniscono informazioni sui modelli di forza della password e sull'efficacia della politica di sicurezza. Con la sua comunità attiva di sviluppo, gli aggiornamenti regolari e la comprovata registrazione delle tracce nelle valutazioni di sicurezza, John the Ripper rimane lo standard d'oro per i test di sicurezza delle password e un componente indispensabile di qualsiasi toolkit di sicurezza completo.

Installazione

## Ubuntu/Debian Installazione

Installazione di John the Ripper sui sistemi Ubuntu/Debian:

# 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 installation
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 installation
john --version
john --list=formats|wc -l

CentOS/RHEL Installazione

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

# 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 installation
john --version

Installazione di Windows

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

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

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

# Verify installation
john.exe --version

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

Installazione Docker

Gestire John lo Squartatore a 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 support (NVIDIA)
docker run --gpus all -it --rm \
    -v $(pwd):/work \
    john-the-ripper john --list=opencl-devices

Uso di base

Hash Extraction

Estratto di ceneri da varie fonti:

# 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
# Example output format: username: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 keys
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

Effettuare cracking password di base:

# Simple dictionary attack
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 passwords
john --show hashes.txt

# Show cracked passwords with specific format
john --show --format=NT hashes.txt

# Resume interrupted session
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 (brute force)
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

Attacchi di Wordlist

Attacchi basati su wordlist avanzati:

# 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 algorithms)
john --external=double hashes.txt

Caratteristiche avanzate

Attacchi basati sulla regola

Creazione e utilizzo di regole personalizzate:

# 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

Gestione sessione

Gestione di sessioni di lungo periodo:

# Start named session
john --session=mysession --wordlist=rockyou.txt hashes.txt

# Resume named session
john --restore=mysession

# List active sessions
john --list=sessions

# Session status
john --status=mysession

# Abort session
john --abort=mysession

# Session configuration
cat >`` john.conf << 'EOF'
[Options]
# Session save interval (seconds)
Save = 600

# Idle time before session save
Idle = 1800

# Beep when password found
Beep = Y

# Log file
LogFile = john.log
EOF

# Use custom configuration
john --config=john.conf --wordlist=wordlist.txt hashes.txt

Ottimizzazione delle prestazioni

Ottimizzazione delle prestazioni di John the Ripper:

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

# OpenMP support (if compiled)
export OMP_NUM_THREADS=8
john --wordlist=rockyou.txt hashes.txt

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

# CUDA support
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

Distribuito Cracking

Impostazione di cracking password distribuito:

# 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

Comprensiva password Audit Script

#!/usr/bin/env python3
# Comprehensive password audit using John the Ripper

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

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

    def verify_john_installation(self):
        """Verify John the Ripper installation"""
        try:
            result = subprocess.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 installation: \\\{e\\\}")
            return False

    def list_supported_formats(self):
        """List supported hash formats"""
        try:
            result = subprocess.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"Unsupported source type: \\\{source_type\\\}")
            return False

        extractor = extractors[source_type]

        try:
            with open(output_file, 'w') as f:
                result = subprocess.run([extractor, source_path],
                                      stdout=f, stderr=subprocess.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_passwords(self, hash_file, attack_config):
        """Crack passwords with specified configuration"""
        session_name = f"audit_\\\{int(time.time())\\\}"

        cmd = [self.john_path, "--session=" + session_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 options
        if attack_config.get('fork'):
            cmd.extend(["--fork=" + str(attack_config['fork'])])

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

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

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

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

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

        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 not line.startswith('0 password'):
                        parts = line.split(':')
                        if len(parts) >``= 2:
                            cracked.append(\\\\{
                                'username': 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_patterns(self, cracked_passwords):
        """Analyze password patterns and weaknesses"""
        analysis = \\\\{
            'total_cracked': len(cracked_passwords),
            '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,
                'keyboard_patterns': 0,
                'date_patterns': 0,
                'name_patterns': 0
            \\\\},
            'weak_passwords': []
        \\\\}

        import re

        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 set 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_sets']['lowercase_only'] += 1
            elif password.isupper():
                analysis['character_sets']['uppercase_only'] += 1
            elif password.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'(password|admin|user|test|guest)', password.lower()):
                analysis['common_patterns']['dictionary_words'] += 1

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

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

            # Weak password identification
            if (length < 8 or
                password.lower() in ['password', '123456', 'admin', 'user'] or
                password.isdigit() or
                password.islower()):
                analysis['weak_passwords'].append(entry)

        return analysis

    def generate_report(self, audit_results, output_file="password_audit_report.html"):
        """Generate comprehensive audit report"""
        html_content = f"""
<!DOCTYPE html>
<html>
<head>
    <title>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; \\\\}\\\\}
        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>Password Security Audit Report</h1>
    <p>Generated: \\\\{datetime.now().isoformat()\\\\}</p>

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

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

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

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

    <div class="section">
        <h2>Password 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 password 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 authentication</li>
            <li>Regular password audits and user education</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 run_comprehensive_audit(self, hash_file, wordlists, output_dir="/tmp/john_audit"):
        """Run comprehensive password audit"""
        print("Starting comprehensive password 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_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...")

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

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

        # Analyze patterns
        if cracked_passwords:
            pattern_analysis = self.analyze_password_patterns(cracked_passwords)
            audit_results.update(pattern_analysis)

        # Generate report
        report_file = os.path.join(output_dir, "password_audit_report.html")
        self.generate_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_analyzed']\\\\} passwords")

        return audit_results

def main():
    parser = argparse.ArgumentParser(description='John the Ripper 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('--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 installation
    if not auditor.verify_john_installation():
        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("Password audit completed successfully")
    else:
        print("Password audit failed")
        sys.exit(1)

if __name__ == "__main__":
    main()

Esempi di integrazione

SIEM Integrazione

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

# Configuration
HASH_DIR="/var/log/password_hashes"
WORDLIST="/usr/share/wordlists/rockyou.txt"
SPLUNK_HEC_URL="https://splunk.company.com:8088/services/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 "Authorization: Splunk $SPLUNK_TOKEN" \
        -H "Content-Type: application/json" \
        -d "$event_data"
\\\\}

# Function to audit passwords and send results
audit_and_report() \\\\{
    local hash_file="$1"
    local timestamp=$(date +%Y%m%d_%H%M%S)
    local session_name="audit_$timestamp"

    echo "Starting password audit: $hash_file"

    # Start John the Ripper
    john --session=$session_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_passwords=$(john --show $hash_file)

    # Parse results and send to SIEM
    echo "$cracked_passwords"|while IFS=':' read -r username password rest; do
        if [ -n "$username" ] && [ -n "$password" ]; then
            event_json=$(cat << EOF
\\\\{
    "time": "$(date -Iseconds)",
    "source": "john_the_ripper",
    "sourcetype": "password_audit",
    "event": \\\\{
        "timestamp": "$(date -Iseconds)",
        "username": "$username",
        "password_cracked": true,
        "password_length": $\\\\{#password\\\\},
        "hash_file": "$hash_file",
        "session": "$session_name",
        "event_type": "weak_password_detected"
    \\\\}
\\\\}
EOF
            )

            send_to_splunk "$event_json"
        fi
    done

    echo "Password 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_report "$path$file"
    fi
done

Risoluzione dei problemi

Questioni comuni

**Emissioni: ** Traduzione:

** Problemi di memoria: ** Traduzione:

** Problemi di conformità: ** Traduzione:

Ottimizzazione delle prestazioni

Ottimizzazione delle prestazioni di John the Ripper:

# CPU Optimization
export OMP_NUM_THREADS=$(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

Considerazioni di sicurezza

Sicurezza operativa

** Protezione dei dati. - Crittografia file hash e database password incrinati - Attuazione politiche di conservazione dei dati sicure per i risultati dell'audit password - Controllo dell'accesso agli strumenti di cracking password e risultati - Trasmissione sicura di file hash e report di audit - Pulizia regolare dei file temporanei e dei dati di sessione

** Considerazioni giuridiche ed etiche: - No. Solo le password di crack che possiedi o hai il permesso esplicito per testare - Comprendi i requisiti legali per i test di sicurezza delle password - Implementare procedure di gestione dei dati adeguate per informazioni sensibili - Rispetto della privacy e della riservatezza delle credenziali dell'utente - Attività di controllo della password del documento a fini di conformità

Password Security

Audit Best Practices: - Valutazioni regolari di forza della password - Attuazione delle politiche di password forti - Istruzione utente sulla sicurezza delle password - Distribuzione di autenticazione multifattore - Monitoraggio delle credenziali compromesse

Referenze

  1. John the Ripper Official Documentation
  2. [John the Ripper Jumbo]
  3. Tecniche di cracking password_
  4. Riferimento dei formati Hash_
  5. Le migliori pratiche di sicurezza password