John the ripper
John la hoja de la carne de arroz
Overview¶
John the Ripper es una de las herramientas de grieta de contraseña más potentes y versátiles disponibles, diseñadas para detectar contraseñas débiles y realizar auditorías integrales de seguridad de contraseñas en múltiples plataformas y formatos hash. Originalmente desarrollado por Solar Designer, John the Ripper se ha convertido en una sofisticada plataforma de recuperación de contraseñas y pruebas de seguridad que soporta cientos de tipos de hash y cipher, lo que lo convierte en una herramienta esencial para los profesionales de seguridad, testadores de penetración y administradores de sistemas que realizan evaluaciones de políticas de contraseña. La arquitectura modular de la herramienta y las amplias capacidades de personalización permiten realizar auditorías automáticas de contraseñas y realizar operaciones de recuperación manual de contraseñas avanzadas.
La fuerza central de John the Ripper reside en su enfoque integral de la grieta de contraseñas, combinando múltiples modos de ataque incluyendo ataques de diccionarios, ataques de fuerza bruta, ataques híbridos y transformaciones avanzadas basadas en reglas. El sistema inteligente de generación de candidatos de contraseña de la herramienta puede explorar eficientemente espacios de contraseña usando listas de palabras, conjuntos de caracteres y reglas de mutación sofisticadas que simulan patrones comunes de creación de contraseñas. El soporte multiformato de John abarca los formatos tradicionales de cripta Unix, los hashes modernos de cripta y cripta, los hashes de Windows NTLM, los formatos de aplicaciones específicas y los formatos de archivo cifrados, lo que lo hace adecuado para diversos escenarios de recuperación de contraseñas en diferentes sistemas y aplicaciones.
Las características avanzadas de John the Ripper incluyen soporte de computación distribuido para operaciones de recuperación de contraseñas a gran escala, aceleración de GPU para la grieta de alto rendimiento, desarrollo de reglas personalizadas para ataques dirigidos, y gestión integral de sesión para operaciones de larga duración. La arquitectura extensible plugin de la herramienta permite el soporte de formato hash personalizado y las implementaciones de ataques especializados, mientras que sus informes detallados de progreso y estadísticas proporcionan información sobre los patrones de fuerza de contraseña y la eficacia de la política de seguridad. Con su comunidad de desarrollo activo, actualizaciones regulares y historial comprobado en evaluaciones de seguridad, John the Ripper sigue siendo el estándar de oro para las pruebas de seguridad de contraseñas y un componente indispensable de cualquier herramienta de seguridad integral.
Instalación¶
Ubuntu/Debian Instalación¶
Instalación de John the Ripper en los sistemas 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 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 installation
john --version
Instalación de 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
Docker Instalación¶
Corriendo a John el Destripador en 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 básico¶
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
# 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¶
Realización de la contraseña básica cracking:
# 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
Ataques de Wordlist¶
Ataques avanzados basados en listas de palabras:
# 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
Características avanzadas¶
Ataques basados en reglas¶
Crear y usar reglas personalizadas:
# 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
Session Management¶
Gestión de sesiones de larga duración:
# 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
Performance Optimization¶
Optimizando el rendimiento de John 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
Distributed Cracking¶
Configuración de la contraseña distribuida:
# Split wordlist for distribution
split -l 1000000 rockyou.txt wordlist_part_
# Distribute across multiple machines
# Machine 1:
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 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()
Integración Ejemplos¶
SIEM Integration¶
#!/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
Troubleshooting¶
Common Issues¶
** Cuestiones relativas a las misiones**
# 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
** Cuestiones de memoria:**
# Reduce memory usage
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_
** Cuestiones de desempeño**
# 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¶
Optimizando el rendimiento de John 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
Security Considerations¶
Operational Security¶
Protección de datos** - Encrypt hash files and cracked password databases - Implementar políticas de retención de datos seguras para los resultados de la auditoría de contraseñas - Control de acceso a herramientas y resultados de cracking contraseña - Transmisión segura de archivos de hash e informes de auditoría - Limpieza regular de archivos temporales y datos de sesión
** Consideraciones jurídicas y éticas:** - Sólo contraseñas de crack que posees o tienes permiso explícito para probar - Comprender los requisitos legales para las pruebas de seguridad de contraseñas - Aplicar procedimientos adecuados de tratamiento de datos para información confidencial - Respetar la privacidad y la confidencialidad de las credenciales de usuario - Actividades de auditoría de contraseñas para fines de cumplimiento
Password Security¶
Audit Best Practices: - Evaluaciones de la fuerza de la contraseña regular - Aplicación de políticas firmes de contraseña - Educación del usuario en seguridad de contraseñas - Implementación de autenticación multifactorial - Vigilancia de las credenciales comprometidas
Referencias¶
- John the Ripper Official Documentation_
- [Juan el Destripador Jumbo](URL_25__
- [Password Cracking Techniques]
- [Dish Formats Reference](URL_27__
- Password Security Best Practices_