John the Ripper aide-mémoire
Overview
John the Ripper is one of the most powerful and versatile cassage de mots de passe tools available, designed to detect weak mot de passes and perform comprehensive mot de passe security auditing across multiple platforms and hash formats. Originally developed by Solar Designer, John the Ripper has evolved into a sophisticated mot de passe recovery and security testing platform that supports hundreds of hash and cipher types, making it an essential tool for security professionals, penetration testers, and system administrators conducting mot de passe policy assessments. The tool's modular architecture and extensive customization capabilities enable both automated mot de passe auditing and advanced manual mot de passe recovery operations.
The core strength of John the Ripper lies in its comprehensive approach to cassage de mots de passe, combining multiple attack modes including attaque par dictionnaires, force brute attacks, hybrid attacks, and advanced rule-based transformations. The tool's intelligent mot de passe candidate generation system can efficiently explore mot de passe spaces using wordlists, character sets, and sophisticated mutation rules that simulate common mot de passe creation patterns. John's multi-format support 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 mot de passe recovery scenarios across different systems and applications.
John the Ripper's advanced features include distributed computing support for large-scale mot de passe recovery operations, GPU acceleration for high-performance cracking, custom rule development for cibleed attacks, and comprehensive session management for long-running operations. The tool's extensible plugin architecture allows for custom hash format support and specialized attack implementations, while its detailed progress reporting and statistics provide insights into mot de passe 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 mot de passe security testing and an indispensable component of any comprehensive security toolkit.
Installation
Ubuntu/Debian Installation
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 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 Installation
# 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 Installation
# 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
Windows Installation
# Download pre-compiled binaries
# https://www.openwall.com/john/
# Extract to desired location
# exemple: 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 Installation
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 support (NVIDIA)
docker run --gpus all -it --rm \
-v $(pwd):/work \
john-the-ripper john --list=opencl-devices
Basic utilisation
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
# exemple output format: nom d'utilisateur: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 clés
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 cassage de mots de passe:
# Simple attaque par dictionnaire
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 mot de passes
john --show hashes.txt
# Show cracked mot de passes 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 (force brute)
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 algorithmes)
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
session Management
Managing long-running sessions:
# 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 mot de passe found
Beep = Y
# Log file
LogFile = john.log
EOF
# Use custom configuration
john --config=john.conf --wordlist=wordlist.txt hashes.txt
Performance Optimization
Optimizing John the Ripper performance:
# Multi-core processusing
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
Setting up distributed cassage de mots de passe:
# 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
hôteS=("server1" "server2" "server3" "server4")
WORDLIST="rockyou.txt"
hashES="hashes.txt"
TOTAL_NODES=$\\\{#hôteS[@]\\\}
for i in "$\\\{!hôteS[@]\\\}"; do
NODE=$((i + 1))
hôte="$\\\{hôteS[$i]\\\}"
echo "Starting node $NODE on $hôte"
ssh $hôte "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 mot de passe Audit Script
#!/usr/bin/env python3
# Comprehensive mot de passe audit using John the Ripper
import subprocessus
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 = subprocessus.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 = subprocessus.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 = subprocessus.run([extractor, source_path],
stdout=f, stderr=subprocessus.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_mot de passes(self, hash_file, attack_config):
"""Crack mot de passes 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 cassage de mots de passe: \\\{' '.join(cmd)\\\}")
try:
# Start cracking processus
processus = subprocessus.Popen(cmd, stdout=subprocessus.PIPE,
stderr=subprocessus.PIPE, text=True)
self.sessions[session_name] = \\\{
'processus': processus,
'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]
processus = session['processus']
start_time = session['start_time']
try:
if timeout:
stdout, stderr = processus.communicate(timeout=timeout)
else:
stdout, stderr = processus.communicate()
end_time = time.time()
duration = end_time - start_time
result = \\\{
'session': session_name,
'duration': duration,
'returncode': processus.returncode,
'stdout': stdout,
'stderr': stderr
\\\}
return result
except subprocessus.TimeoutExpired:
print(f"session \\\{session_name\\\} timed out")
processus.kill()
return None
except Exception as e:
print(f"Error monitoring session: \\\{e\\\}")
return None
def get_cracked_mot de passes(self, hash_file, format_type=None):
"""Retrieve cracked mot de passes"""
cmd = [self.john_path, "--show"]
if format_type:
cmd.extend(["--format=" + format_type])
cmd.append(hash_file)
try:
result = subprocessus.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 mot de passe'):
parts = line.split(':')
if len(parts) >``= 2:
cracked.append(\\\\{
'nom d'utilisateur': parts[0],
'mot de passe': parts[1],
'full_line': line
\\\\})
return cracked
else:
print(f"Error getting cracked mot de passes: \\\\{result.stderr\\\\}")
return []
except Exception as e:
print(f"Error retrieving mot de passes: \\\\{e\\\\}")
return []
def analyze_mot de passe_patterns(self, cracked_mot de passes):
"""Analyze mot de passe patterns and weaknesses"""
analysis = \\\\{
'total_cracked': len(cracked_mot de passes),
'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,
'cléboard_patterns': 0,
'date_patterns': 0,
'name_patterns': 0
\\\\},
'weak_mot de passes': []
\\\\}
import re
for entry in cracked_mot de passes:
mot de passe = entry['mot de passe']
length = len(mot de passe)
# 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]', mot de passe))
has_upper = bool(re.search(r'[A-Z]', mot de passe))
has_digit = bool(re.search(r'[0-9]', mot de passe))
has_symbol = bool(re.search(r'[^a-zA-Z0-9]', mot de passe))
if mot de passe.islower():
analysis['character_sets']['lowercase_only'] += 1
elif mot de passe.isupper():
analysis['character_sets']['uppercase_only'] += 1
elif mot de passe.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'(mot de passe | admin | user | test | guest)', mot de passe.lower()): |
analysis['common_patterns']['dictionary_words'] += 1
| if re.search(r'(qwerty | asdf | zxcv | 1234)', mot de passe.lower()): |
analysis['common_patterns']['cléboard_patterns'] += 1
if re.search(r'(19|20)\d\\\\{2\\\\}', mot de passe):
analysis['common_patterns']['date_patterns'] += 1
# Weak mot de passe identification
if (length < 8 or
mot de passe.lower() in ['mot de passe', '123456', 'admin', 'user'] or
mot de passe.isdigit() or
mot de passe.islower()):
analysis['weak_mot de passes'].append(entry)
return analysis
def generate_report(self, audit_results, output_file="mot de passe_audit_report.html"):
"""Generate comprehensive audit report"""
html_content = f"""
<!DOCTYPE html>
<html>
<head>
<title>mot de passe 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>mot de passe Security Audit Report</h1>
<p>Generated: \\\\{datetime.now().isoformat()\\\\}</p>
<div class="section">
<h2>Executive Summary</h2>
<ul>
<li>Total mot de passes Analyzed: \\\\{audit_results.get('total_analyzed', 0)\\\\}</li>
<li>mot de passes 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 mot de passes: \\\\{len(audit_results.get('weak_mot de passes', []))\\\\}</li>
</ul>
</div>
<div class="section">
<h2 class="critical">Critical Findings</h2>
<h3>Weak mot de passes</h3>
<table>
<tr><th>nom d'utilisateur</th><th>mot de passe</th><th>Weakness</th></tr>
"""
for weak in audit_results.get('weak_mot de passes', [])[:20]:
weakness = "Short/Common/Simple"
html_content += f"""
<tr>
<td>\\\\{weak['nom d'utilisateur']\\\\}</td>
<td>\\\\{weak['mot de passe']\\\\}</td>
<td>\\\\{weakness\\\\}</td>
</tr>"""
html_content += """
</table>
</div>
<div class="section">
<h2>mot de passe 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 mot de passe 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 authentification</li>
<li>Regular mot de passe 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 mot de passe audit"""
print("Starting comprehensive mot de passe 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_mot de passes(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_mot de passes = self.get_cracked_mot de passes(hash_file)
audit_results['total_cracked'] = len(cracked_mot de passes)
# Analyze patterns
if cracked_mot de passes:
pattern_analysis = self.analyze_mot de passe_patterns(cracked_mot de passes)
audit_results.update(pattern_analysis)
# Generate report
report_file = os.path.join(output_dir, "mot de passe_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']\\\\} mot de passes")
return audit_results
def main():
parser = argparse.ArgumentParser(Description='John the Ripper mot de passe 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("mot de passe audit completed successfully")
else:
print("mot de passe audit failed")
sys.exit(1)
if __name__ == "__main__":
main()
Integration exemples
SIEM Integration
#!/bin/bash
# John the Ripper SIEM integration script
# configuration
hash_DIR="/var/log/mot de passe_hashes"
WORDLIST="/usr/share/wordlists/rockyou.txt"
SPLUNK_HEC_URL="https://splunk.company.com:8088/services/collector/event"
SPLUNK_jeton="your-hec-jeton"
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 "autorisation: Splunk $SPLUNK_jeton" \
-H "Content-Type: application/json" \
-d "$event_data"
\\\\}
# Function to audit mot de passes 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 mot de passe 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_mot de passes=$(john --show $hash_file)
# Parse results and send to SIEM
echo "$cracked_mot de passes"|while IFS=':' read -r nom d'utilisateur mot de passe rest; do
if [ -n "$nom d'utilisateur" ] && [ -n "$mot de passe" ]; then
event_json=$(cat << EOF
\\\\{
"time": "$(date -Iseconds)",
"source": "john_the_ripper",
"sourcetype": "mot de passe_audit",
"event": \\\\{
"timestamp": "$(date -Iseconds)",
"nom d'utilisateur": "$nom d'utilisateur",
"mot de passe_cracked": true,
"mot de passe_length": $\\\\{#mot de passe\\\\},
"hash_file": "$hash_file",
"session": "$session_name",
"event_type": "weak_mot de passe_detected"
\\\\}
\\\\}
EOF
)
send_to_splunk "$event_json"
fi
done
echo "mot de passe 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
dépannage
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 utilisation
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
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
Data Protection: - Encrypt hash files and cracked mot de passe databases - Implement secure data retention policies for mot de passe audit results - Control access to cassage de mots de passe tools and results - Secure transmission of hash files and audit reports - Regular cleanup of temporary files and session data
Legal and Ethical Considerations: - Only crack mot de passes you own or have explicit permission to test - Understand legal requirements for mot de passe security testing - Implement proper data handling procedures for sensitive information - Respect privacy and confidentiality of user identifiants - Document mot de passe auditing activities for compliance purposes
mot de passe Security
Audit Best Practices: - Regular mot de passe strength assessments - Implementation of strong mot de passe policies - User education on mot de passe security - Multi-factor authentification deployment - Monitoring for compromised identifiants