Chapter 32: Malware, Ransomware, and APTs

"The only truly secure system is one that is powered off, cast in a block of concrete, and sealed in a lead-lined room with armed guards --- and even then I have my doubts." --- Gene Spafford

A Worm That Changed Everything

November 2, 1988. Robert Tappan Morris, a 23-year-old Cornell graduate student, releases a program onto the early internet. His stated goal was to measure the size of the internet. What happened instead was the first major internet worm --- and it brought roughly 10% of the internet's 60,000 connected machines to their knees.

The Morris Worm exploited the same fundamental weaknesses that malware exploits today --- weak passwords, unpatched software vulnerabilities, and excessive trust between systems. Morris used three attack vectors: a buffer overflow in fingerd, a debug backdoor in sendmail, and the rsh/rexec remote shell commands that trusted certain hosts. Thirty-seven years later, we are still fighting the same battle with better weapons on both sides. The malware landscape has evolved from that first worm into a multi-billion-dollar ransomware industry.


The Malware Family Tree

Malware is a catch-all term for malicious software. Understanding the taxonomy matters because different types require different detection strategies, different containment approaches, and different recovery procedures.

graph TD
    M["Malware"] --> SR["Self-Replicating"]
    M --> NR["Non-Replicating"]

    SR --> V["Virus<br/>Attaches to host files<br/>Requires user action<br/>Can be polymorphic"]
    SR --> W["Worm<br/>Self-propagating<br/>No user action needed<br/>Exploits network vulns"]

    NR --> T["Trojan<br/>Disguised as legitimate<br/>Relies on social engineering"]
    NR --> RAT["RAT<br/>Remote Access Trojan<br/>Full remote control<br/>Keylogging, screen capture"]
    NR --> RK["Rootkit<br/>Hides malware presence<br/>Kernel/user/boot level"]
    NR --> RW["Ransomware<br/>Encrypts victim data<br/>Demands payment"]
    NR --> SP["Spyware / Infostealer<br/>Steals credentials,<br/>cookies, crypto wallets"]
    NR --> BN["Botnet Agent<br/>Joins command network<br/>DDoS, spam, mining"]

    V --> VP["Polymorphic<br/>Changes signature<br/>each infection"]
    V --> VM["Metamorphic<br/>Rewrites entire code<br/>Same functionality"]

    RK --> RKU["User-mode<br/>Hooks API calls"]
    RK --> RKK["Kernel-mode<br/>Modifies kernel"]
    RK --> RKB["Bootkit<br/>Infects MBR/UEFI<br/>Survives OS reinstall"]

    style M fill:#e74c3c,color:#fff
    style SR fill:#e67e22,color:#fff
    style NR fill:#3498db,color:#fff
    style RW fill:#8e44ad,color:#fff

Viruses

A virus is code that attaches itself to a legitimate program and executes when that program runs. Like a biological virus, it cannot self-replicate without a host. Viruses spread through infected files --- executables, documents with macros, boot sectors.

Key characteristics:

  • Requires user action to spread (running an infected program, opening a document)
  • Attaches to legitimate files, modifying them
  • Can be polymorphic --- changing its code signature with each infection to evade signature-based antivirus by using variable encryption keys and decryption routines
  • Can be metamorphic --- rewriting its entire code while maintaining functionality, using code permutation, register reassignment, and instruction substitution

Worms

A worm is self-replicating malware that spreads without user action. It exploits network vulnerabilities to propagate from machine to machine autonomously. Worms are among the most destructive malware types because they can spread exponentially.

Notable worms and their propagation speeds:

WormYearExploitSpeedImpact
Morris1988fingerd, sendmail, rshHours~6,000 machines (~10% of internet)
Code Red2001IIS buffer overflow359K hosts in 14 hoursDefaced websites, DDoS on whitehouse.gov
SQL Slammer2003SQL Server UDP 1434Doubled every 8.5 seconds75K hosts in 10 minutes, 376-byte single packet
Conficker2008Windows SMB MS08-067Millions over weeksMassive botnet, still active years later
Stuxnet20104 Windows zero-daysUSB + networkFirst cyberweapon, destroyed Iranian centrifuges
WannaCry2017EternalBlue MS17-010200K+ in daysNHS shutdown, $4-8B damages

SQL Slammer doubling every 8.5 seconds remains one of the fastest-spreading pieces of malware in history. It was a single 376-byte UDP packet. It did not even write itself to disk --- it existed entirely in memory. The entire worm fit in a single UDP datagram. It scanned random IPs and sent itself faster than the network could handle, saturating internet backbone links within minutes. Elegant, in a terrifying sort of way.

Trojans and RATs

Trojans disguise themselves as legitimate software. Unlike viruses, they do not self-replicate. They rely on social engineering --- convincing users to install them through fake software updates, cracked applications, malicious browser extensions, or email attachments.

Remote Access Trojans (RATs) give attackers complete remote control over an infected system: keylogging, screen capture, webcam and microphone access, file system browsing, command shell access, and credential harvesting. Popular RATs in the wild include DarkComet, njRAT, Quasar, AsyncRAT, and Cobalt Strike.

Cobalt Strike deserves special mention. It is a legitimate commercial penetration testing tool created by Raphael Mudge, costing approximately $3,500 per user per year. It provides a "beacon" implant with sophisticated command-and-control capabilities: encrypted communications, malleable C2 profiles that mimic legitimate traffic (jQuery CDN requests, Amazon browsing, Google searches), in-memory execution that never touches disk, process injection, and credential harvesting via Mimikatz integration.

Unfortunately, cracked versions are widely used by real threat actors. According to Proofpoint's research, Cobalt Strike appeared in more APT campaigns than any purpose-built malware in 2021-2022. Its Malleable C2 feature allows the beacon traffic to be disguised as any HTTP traffic pattern, making network-level detection extremely challenging. The JA3/JA3S TLS fingerprinting technique (Chapter 34) was developed partly to detect Cobalt Strike beacons by their TLS handshake characteristics.

Rootkits

Rootkits hide the presence of malware on a system, operating at progressively deeper levels:

  • User-mode rootkits: Hook API calls to hide processes, files, and registry entries from task managers and file explorers
  • Kernel-mode rootkits: Modify the kernel's system call table to intercept and filter OS-level operations. Much harder to detect because the rootkit controls the very mechanism you would use to observe the system
  • Bootkits: Infect the Master Boot Record or UEFI firmware. Load before the operating system, before antivirus, before any security tool. Survive OS reinstallation
  • Hardware/firmware rootkits: Infect device firmware (network cards, hard drive controllers, BMC/IPMI). Survive even hard drive replacement

So how do you detect a rootkit that modifies the kernel, given that the kernel is what you use to observe the system? You cannot reliably detect a kernel rootkit from the infected system itself --- the rootkit controls what you can see. You have three options: boot from a clean external medium and examine the disk offline, use hardware-based attestation like Intel TXT or TPM-based measured boot to verify the integrity of the boot chain before the rootkit loads, or use a hypervisor-based approach where a thin hypervisor beneath the OS can observe kernel modifications from a higher privilege level.


Ransomware: The Business of Digital Extortion

The Ransomware Evolution Timeline

Ransomware has evolved from a curiosity to a multi-billion dollar criminal industry with its own ecosystem of specialists, supply chains, and customer support portals.

graph LR
    A["1989: AIDS Trojan<br/>First ransomware<br/>Floppy disk delivery<br/>Symmetric crypto (broken)<br/>$189 to PO Box"] --> B["2005-2012: GPCode era<br/>First RSA encryption<br/>Unbreakable without key<br/>Small-scale operations"]
    B --> C["2013: CryptoLocker<br/>RSA-2048 + Bitcoin<br/>Professional countdown UI<br/>$27M in 2 months<br/>Modern era begins"]
    C --> D["2016: RaaS Emerges<br/>Locky, Cerber, SamSam<br/>Affiliate model<br/>Developers take 30%"]
    D --> E["2017: WannaCry + NotPetya<br/>Worm + Ransomware hybrid<br/>200K+ victims, 150 countries<br/>$10B+ combined damage"]
    E --> F["2019: Double Extortion<br/>Maze introduces data leak<br/>Encrypt AND exfiltrate<br/>Pay or we publish"]
    F --> G["2021: Triple Extortion<br/>Colonial Pipeline $4.4M<br/>JBS $11M, Kaseya supply chain<br/>Encrypt + leak + DDoS"]
    G --> H["2023+: Mass Exploitation<br/>Cl0p MOVEit zero-day<br/>2500+ orgs, no encryption<br/>Pure data theft + extortion<br/>$1B+ annual payments"]

    style A fill:#95a5a6,color:#fff
    style C fill:#e67e22,color:#fff
    style E fill:#e74c3c,color:#fff
    style H fill:#8e44ad,color:#fff

How Ransomware Works Technically

Modern ransomware uses a hybrid encryption scheme --- symmetric encryption for speed, asymmetric for key protection:

sequenceDiagram
    participant R as Ransomware
    participant FS as File System
    participant C2 as C2 Server

    Note over R: Phase 1: Key Generation
    R->>R: Generate random AES-256 key (per victim)
    R->>R: Embed attacker's RSA-2048 public key

    Note over R: Phase 2: Preparation
    R->>R: Kill database processes (SQL, Oracle)
    R->>R: Stop backup services (Veeam, Acronis)
    R->>R: Delete Volume Shadow Copies (vssadmin)
    R->>R: Disable Windows Recovery

    Note over R: Phase 3: Encryption
    R->>FS: Enumerate target files (.docx, .xlsx, .pdf, .sql, .bak)
    loop For each file
        R->>FS: Read file
        R->>R: Encrypt with AES-256-CBC
        R->>FS: Write encrypted file (.locked extension)
        R->>FS: Delete original (secure wipe)
    end

    Note over R: Phase 4: Key Protection
    R->>R: Encrypt AES key with attacker's RSA public key
    R->>R: Delete AES key from memory
    R->>FS: Write ransom note with encrypted key blob

    Note over R: Phase 5: Communication
    R->>C2: Send victim ID + encrypted key
    R->>FS: Display ransom note with payment instructions
    Note over FS: Files recoverable ONLY by:<br/>1. Paying ransom for RSA private key<br/>2. Restoring from offline backups<br/>3. Finding implementation flaws (rare)

Why not encrypt everything with RSA directly? Performance. RSA encryption is roughly 1,000 times slower than AES. If you are encrypting terabytes of data --- and modern ransomware specifically targets large file shares and databases --- you need symmetric encryption for speed. RSA only encrypts the relatively small AES key. It is the same hybrid approach that TLS uses (Chapter 6), just weaponized. Some ransomware even uses multiple threads and prioritizes high-value file types to maximize damage before detection.

WannaCry: The Ransomworm That Shut Down Hospitals

On May 12, 2017, WannaCry tore across the globe. It combined ransomware with a worm --- self-propagating through the EternalBlue exploit (CVE-2017-0144), a vulnerability in Windows SMBv1 that had been discovered by the NSA's Equation Group and leaked by the Shadow Brokers hacking group two months earlier.

Technical details of EternalBlue:

  • Exploited a buffer overflow in the SMBv1 SrvOs2FeaListSizeToNt() function
  • Allowed remote code execution on any unpatched Windows machine with port 445 exposed
  • No authentication required --- the exploit runs at the protocol level before any credential check
  • Microsoft had released patch MS17-010 on March 14, 2017 --- two months before WannaCry

Impact:

  • Infected 200,000+ computers in 150 countries within days
  • Hit the UK National Health Service, causing hospital closures and canceled surgeries. 80 NHS trusts affected, 19,000 appointments canceled, ambulances diverted
  • Affected FedEx ($400M), Telefonica, Renault-Nissan, Deutsche Bahn, and many others
  • Demanded $300-600 in Bitcoin per machine
  • Killed by accident when researcher Marcus Hutchins ("MalwareTech") registered a domain that served as a kill switch --- the malware checked if a specific domain was registered before executing, intended as a sandbox detection mechanism
  • Total estimated damages: $4-8 billion
  • Attributed to the Lazarus Group (North Korea) by the US, UK, and other governments
# Check if a system is vulnerable to EternalBlue using nmap
$ nmap -p445 --script smb-vuln-ms17-010 192.168.1.0/24
Host: 192.168.1.105
| smb-vuln-ms17-010:
|   VULNERABLE:
|   Remote Code Execution vulnerability in Microsoft SMBv1
|     State: VULNERABLE
|     Risk factor: HIGH
|     References: https://technet.microsoft.com/en-us/library/security/ms17-010.aspx
When WannaCry hit, response teams spent 72 straight hours patching every Windows machine and blocking port 445 at every network boundary. The patch (MS17-010) had been available for two months. Two months. Every infected organization had two months to apply a critical patch and did not.

But here is the part that haunts responders: in one organization, 47 machines running Windows XP embedded in medical devices could not be patched because the device manufacturer had not certified the update. They could not be taken offline because patients depended on them. Those machines ended up on isolated VLANs with strict firewall rules blocking SMB entirely. That is the reality of patch management in organizations with legacy systems. "Just patch everything" is the right answer that is impossible to execute perfectly.

NotPetya: The Most Destructive Cyberattack in History

One month after WannaCry, NotPetya hit Ukraine on June 27, 2017. It was disguised as ransomware but was actually a wiper --- designed to destroy data, not hold it for ransom. The ransom payment mechanism was deliberately broken: the "installation ID" displayed to victims was randomly generated and could not be used to decrypt files.

NotPetya was distributed through a supply chain attack on M.E.Doc, Ukrainian tax accounting software used by nearly every company operating in Ukraine. It used EternalBlue plus credential harvesting (via a modified version of Mimikatz) to spread laterally through networks with devastating speed.

Damages exceeded $10 billion:

CompanySectorLoss
MaerskShipping$300M. Reinstalled 45,000 PCs, 4,000 servers, 2,500 applications
MerckPharmaceutical$870M. Lost production of Gardasil vaccine
FedEx/TNT ExpressLogistics$400M
MondelezFood/Consumer$188M
Saint-GobainConstruction$384M
Total estimated$10B+

NotPetya was attributed to Russia's GRU military intelligence (Unit 74455, "Sandworm"), targeting Ukraine but collaterally damaging companies worldwide. It remains the most expensive cyberattack in history.

Ransomware-as-a-Service (RaaS)

Modern ransomware operates as a professionalized criminal enterprise with specialized roles:

graph TD
    subgraph "RaaS Ecosystem"
        DEV["Developers<br/>Build ransomware binary<br/>Maintain C2 infrastructure<br/>Handle payment processing<br/>Provide 'customer support'<br/>Take 70-80% of ransom"]
        AFF["Affiliates<br/>Gain initial access<br/>Deploy ransomware<br/>Negotiate with victims<br/>Receive 20-30% of ransom"]
        IAB["Initial Access Brokers<br/>Sell compromised credentials<br/>Sell VPN/RDP access<br/>$500-$5000 per access"]
        BPH["Bulletproof Hosting<br/>Infrastructure immune<br/>to takedown requests"]
        ML["Money Launderers<br/>Convert crypto to fiat<br/>Mixing services, DEXs"]
        NEG["Negotiators<br/>Professional ransom<br/>negotiation services<br/>For both sides"]
    end

    IAB -->|"Sell access"| AFF
    DEV -->|"Provide toolkit"| AFF
    AFF -->|"Deploy, negotiate"| VICTIM["Victim Organization"]
    VICTIM -->|"Pay ransom"| DEV
    DEV -->|"Host infrastructure"| BPH
    DEV -->|"Launder proceeds"| ML
    VICTIM -.->|"Hire negotiator"| NEG

    style DEV fill:#e74c3c,color:#fff
    style AFF fill:#e67e22,color:#fff
    style IAB fill:#3498db,color:#fff
    style VICTIM fill:#2c3e50,color:#fff

Ransomware has its own complete supply chain with specialists for each part. LockBit had a bug bounty program offering $1 million for anyone who could deanonymize its developer. RaaS groups interview potential affiliates, check references, and reject applicants who target hospitals or critical infrastructure --- not out of ethics, but because it draws unwanted law enforcement attention. It is a fully professionalized criminal industry with estimated annual revenues exceeding $1 billion, complete with customer support portals, affiliate programs, and service-level guarantees.


Advanced Persistent Threats (APTs)

APTs are threat actors --- typically nation-state sponsored or affiliated --- that conduct long-term, targeted intrusion campaigns against specific organizations. The word "persistent" is key: these attackers do not smash and grab. They establish footholds and maintain access for months or years, moving slowly and deliberately to avoid detection.

APT Lifecycle Mapped to the Cyber Kill Chain

graph TD
    R["1. RECONNAISSANCE<br/>OSINT, scanning, LinkedIn<br/>Identify targets and vulns<br/>Weeks to months"] --> W["2. WEAPONIZATION<br/>Create exploit + payload<br/>Custom malware for target<br/>Zero-day or known CVE"]
    W --> D["3. DELIVERY<br/>Spear phishing email<br/>Watering hole website<br/>Supply chain compromise"]
    D --> E["4. EXPLOITATION<br/>Execute exploit<br/>Gain initial code execution<br/>Establish foothold"]
    E --> I["5. INSTALLATION<br/>Install persistent backdoor<br/>RAT, web shell, scheduled task<br/>Survive reboot"]
    I --> C2["6. COMMAND & CONTROL<br/>Encrypted C2 channel<br/>DNS over HTTPS, CDN fronting<br/>Blend with normal traffic"]
    C2 --> A["7. ACTIONS ON OBJECTIVES<br/>Lateral movement<br/>Privilege escalation<br/>Data exfiltration / destruction"]

    D1["DEFENDER: Block delivery<br/>Email gateway, web filter"] -.-> D
    D2["DEFENDER: Detect exploitation<br/>EDR, application whitelisting"] -.-> E
    D3["DEFENDER: Detect persistence<br/>Sysmon, autoruns monitoring"] -.-> I
    D4["DEFENDER: Detect C2<br/>DNS monitoring, JA3, proxy logs"] -.-> C2
    D5["DEFENDER: Detect lateral movement<br/>Network segmentation, deception"] -.-> A

    style R fill:#3498db,color:#fff
    style D fill:#e67e22,color:#fff
    style E fill:#e74c3c,color:#fff
    style C2 fill:#8e44ad,color:#fff
    style A fill:#2c3e50,color:#fff
    style D1 fill:#27ae60,color:#fff
    style D2 fill:#27ae60,color:#fff
    style D3 fill:#27ae60,color:#fff
    style D4 fill:#27ae60,color:#fff
    style D5 fill:#27ae60,color:#fff

The key insight of the kill chain model is that defenders can break the chain at any stage. You do not need to prevent initial access (though you should try) --- detecting persistent backdoors, C2 communication, or lateral movement all provide opportunities to stop the attack before objectives are achieved.

Notable APT Groups

GroupAttributionNotable OperationsPrimary Targets
APT28 (Fancy Bear)Russia GRU Unit 26165DNC hack (2016), WADA breach, Bundestag hackGovernment, military, media
APT29 (Cozy Bear)Russia SVRSolarWinds (2020), COVID vaccine researchGovernment, think tanks, tech
Lazarus GroupNorth Korea RGBSony Pictures (2014), WannaCry (2017), $1.7B+ crypto theftFinance, crypto, defense
APT41 (Double Dragon)China MSSSupply chain attacks, telecom espionageTelecom, healthcare, gaming
Equation GroupUSA NSA (alleged)Stuxnet, Flame, EternalBlue toolsNuclear programs, telecom
SandwormRussia GRU Unit 74455NotPetya, Ukraine power grid (2015, 2016, 2022)Critical infrastructure
APT10 (Stone Panda)China MSSCloud Hopper (targeting MSPs)Technology, MSPs, government

SolarWinds: The Anatomy of a Supply Chain APT

In December 2020, FireEye (now Mandiant) discovered that attackers had compromised SolarWinds' Orion software build system and inserted a backdoor --- dubbed SUNBURST --- into legitimate software updates. This is the definitive example of a supply chain attack.

sequenceDiagram
    participant A as APT29 (Cozy Bear)
    participant SW as SolarWinds Build System
    participant O as Orion Software Update
    participant C as 18,000 Customers
    participant T as ~100 High-Value Targets
    participant DNS as C2 via DNS

    Note over A,SW: Oct 2019: Initial access to build environment
    A->>SW: Compromise build pipeline
    A->>SW: Insert SUNBURST backdoor into source

    Note over SW,O: Feb 2020: Malicious build created
    SW->>O: Build Orion update with SUNBURST
    O->>O: Legitimately signed by SolarWinds

    Note over O,C: Mar-Jun 2020: Update distributed
    O->>C: Push update to 18,000 customers
    C->>C: Install "legitimate" signed update

    Note over C,DNS: SUNBURST activation
    C->>C: Dormant for 2 weeks after install
    C->>DNS: Encode victim info in DNS subdomain
    DNS->>A: Receive victim identification

    Note over A,T: Selective targeting
    A->>A: Evaluate 18,000 victims
    A->>T: Activate only ~100 high-value targets
    A->>T: Deploy TEARDROP second-stage malware
    T->>A: Exfiltrate sensitive data

    Note over T: Dec 8, 2020: FireEye detects own breach
    Note over T: Dec 13, 2020: Public disclosure

SUNBURST's sophistication:

  • Lay dormant for two weeks after installation before activating
  • Encoded victim identification data in DNS subdomain queries --- appearing as normal DNS traffic
  • Checked for security tools (Carbon Black, CrowdStrike, ESET, F-Secure, FireEye) and would deactivate itself if detected
  • Checked if the system was joined to domains matching a hardcoded list of security companies
  • Used legitimate SolarWinds digital signatures, making it indistinguishable from authentic updates
  • Communicated via DNS to avoid network-level detection

Consider what happened next: 18,000 organizations installed the backdoor, but only about 100 were actually targeted. The attackers were disciplined. They had access to 18,000 networks and chose to activate only in the ones that mattered to their intelligence objectives --- Treasury, Commerce, Homeland Security, Microsoft, Intel, Cisco. That restraint is what makes APTs different from criminal hackers. A ransomware gang would have hit all 18,000. An APT exercises operational security and patience that most defenders never encounter.


Defenses Against Malware, Ransomware, and APTs

Endpoint Detection and Response (EDR) vs. Traditional Antivirus

Traditional antivirus uses signature matching --- comparing files against a database of known malware hashes. This approach is fundamentally reactive and fails against novel malware, polymorphic variants, and fileless attacks that never write to disk.

EDR solutions monitor endpoint behavior in real-time:

flowchart LR
    subgraph "Traditional Antivirus"
        FA["File arrives"] --> FH["Hash/signature<br/>check"]
        FH -->|Known bad| FB["Block"]
        FH -->|Unknown| FP["Pass through"]
    end

    subgraph "EDR Behavioral Detection"
        PA["Process executes"] --> PM["Monitor behavior:<br/>Child processes<br/>Network connections<br/>File operations<br/>Registry changes<br/>Memory injection"]
        PM --> PS{"Suspicious<br/>pattern?"}
        PS -->|Yes| PB["Alert + Block +<br/>Record full telemetry<br/>for investigation"]
        PS -->|No| PC["Continue monitoring"]
    end

    style FB fill:#e74c3c,color:#fff
    style FP fill:#e67e22,color:#fff
    style PB fill:#e74c3c,color:#fff
    style PC fill:#27ae60,color:#fff

Example behavioral detection: Word.exe spawns PowerShell.exe which downloads and executes a payload. Legitimate Word documents do not spawn PowerShell. EDR detects this process parent-child relationship anomaly regardless of whether the payload's hash is in any signature database.

Living-off-the-land (LOTL) techniques are the biggest challenge for EDR. Attackers use legitimate system tools --- PowerShell, WMI, PsExec, certutil, mshta, rundll32 --- that are already present in the environment and whitelisted. Detecting malicious use of legitimate tools requires understanding normal usage patterns and flagging deviations.

Network Segmentation

Network segmentation limits lateral movement. If an attacker compromises one system, segmentation prevents them from reaching critical assets directly.

graph TD
    subgraph "Flat Network - BAD"
        FW1["Workstations"] <--> FS1["Servers"]
        FS1 <--> FD1["Databases"]
        FW1 <--> FD1
        FN1["Everything can reach everything"]
    end

    subgraph "Segmented Network - GOOD"
        W["Workstations<br/>VLAN 10"] -->|"FW: HTTP/S only"| A["App Servers<br/>VLAN 20"]
        A -->|"FW: TCP 5432 only"| D["Databases<br/>VLAN 30"]
        W -.->|"BLOCKED"| D
    end

    style FN1 fill:#e74c3c,color:#fff
    style W fill:#3498db,color:#fff
    style A fill:#f39c12,color:#fff
    style D fill:#27ae60,color:#fff

If ransomware lands on a workstation in a segmented network, it cannot reach the database servers directly. It would need to first compromise an app server, then pivot from there. Each hop requires a new exploit or credential. Segmentation does not prevent lateral movement entirely, but it slows attackers down and gives defenders time to detect and respond. The key insight is that dwell time --- the time between initial compromise and detection --- is what determines how much damage an attacker can do. Segmentation buys you dwell time.

Backup Strategy: The 3-2-1-1-0 Rule

Backups are the ultimate defense against ransomware --- if done correctly. The 3-2-1 rule has been extended to 3-2-1-1-0:

  • 3 --- Keep at least 3 copies of your data
  • 2 --- Store on at least 2 different types of media (disk + tape, disk + cloud)
  • 1 --- Keep at least 1 copy offsite (different physical location or cloud region)
  • 1 --- Keep at least 1 copy offline or immutable (air-gapped tape, immutable cloud storage with object lock)
  • 0 --- Zero errors: verify backups regularly with actual restore tests
Ransomware operators know about backups. Modern ransomware specifically targets backup systems:
- Deletes Volume Shadow Copies: `vssadmin delete shadows /all /quiet`
- Searches for and encrypts network-attached backup shares
- Targets backup software (Veeam, Acronis, Veritas) with specific exploits
- Destroys backup catalogs even if backup data is unreachable
- Some variants hunt for AWS access keys to delete S3 buckets
- Conti's playbook specifically included instructions for locating and destroying Veeam backup servers

Your backups MUST include an offline or immutable copy that ransomware cannot reach. If your backups are on a network share that the infected system can access, they will be encrypted too. AWS S3 Object Lock and Azure Immutable Blob Storage provide cloud-native immutability.
Test your backup strategy against ransomware with this checklist:

1. Can a compromised workstation reach your backup server? If yes, segment it immediately
2. Are your backups immutable (write-once-read-many)? Enable S3 Object Lock or Azure Immutable Blob Storage
3. When was the last time you tested a full restore? Untested backups are not backups
4. How long would a full restore take? Is that acceptable for your business? (RTO = Recovery Time Objective)
5. How much data could you lose between your last backup and the incident? Is that acceptable? (RPO = Recovery Point Objective)
6. Are backup credentials separate from domain credentials? Ransomware harvests domain admin credentials with Mimikatz --- if the backup server uses the same credentials, it is compromised too

Simulate: Assume all your online backups are encrypted. Can you still restore from the offline/immutable tier? If not, add one today.

Patch Management

Patch management is not glamorous. Nobody gives a conference talk about applying Windows updates. But patching MS17-010 two months before WannaCry would have prevented the worst cyberattack in history at that point. Every organization that was hit had two months of warning.

Effective patch management requires:

  1. Asset inventory --- you cannot patch what you do not know exists. Shadow IT and forgotten servers are the most dangerous
  2. Vulnerability prioritization --- not all CVEs are equal. Use CVSS scores, EPSS (Exploit Prediction Scoring System), and CISA KEV (Known Exploited Vulnerabilities) catalog to prioritize
  3. Patching SLAs --- Critical/actively exploited: 24-72 hours. High: 7 days. Medium: 30 days. Low: next maintenance window
  4. Testing pipeline --- test patches in staging before production, but do not let testing become an excuse for delay
  5. Exception management --- when a system cannot be patched (legacy, vendor certification), document the risk and implement compensating controls (network isolation, enhanced monitoring)

Malware Analysis Fundamentals

When you find a suspicious file, how do you actually analyze it safely? There are two approaches: static analysis (examining the file without running it) and dynamic analysis (running it in a controlled environment and observing behavior). Both have value, and professional analysts use both.

Static Analysis:

# Step 1: Determine file type (don't trust the extension)
$ file suspicious.exe
suspicious.exe: PE32 executable (GUI) Intel 80386, for MS Windows

# Step 2: Compute hashes for threat intel lookup
$ sha256sum suspicious.exe
a1b2c3d4e5f6... suspicious.exe
$ md5sum suspicious.exe
d4e5f6a7b8c9... suspicious.exe

# Step 3: Check hash against VirusTotal
$ curl -s "https://www.virustotal.com/api/v3/files/a1b2c3d4e5f6..." \
    -H "x-apikey: YOUR_KEY" | jq '.data.attributes.last_analysis_stats'
# {"malicious": 42, "undetected": 25, "suspicious": 3}

# Step 4: Extract strings (reveals C2 URLs, commands, credentials)
$ strings suspicious.exe | grep -E "http|\.com|\.exe|cmd|powershell"
http://evil-c2-server.com/beacon
cmd.exe /c whoami
C:\Users\Public\payload.dll

# Step 5: For Office documents, analyze macros
$ python3 -m oletools.olevba document.docm
VBA MACRO AutoOpen found
SUSPICIOUS: Shell, PowerShell, WScript.Shell, CreateObject
IOC: URL http://malware-domain.com/stage2.ps1

# Step 6: PE header analysis (imports reveal capabilities)
$ python3 -c "
import pefile
pe = pefile.PE('suspicious.exe')
for entry in pe.DIRECTORY_ENTRY_IMPORT:
    print(entry.dll.decode())
    for func in entry.imports:
        if func.name:
            print(f'  {func.name.decode()}')
"
# KERNEL32.dll
#   CreateRemoteThread    <-- Process injection
#   VirtualAllocEx        <-- Remote memory allocation
# ADVAPI32.dll
#   RegSetValueExA        <-- Registry modification (persistence)
# WININET.dll
#   InternetOpenUrlA      <-- HTTP communication (C2)

Dynamic Analysis requires a sandboxed environment (a VM that you can snapshot and restore):

# Use an isolated VM with network monitoring
# Popular sandboxes: ANY.RUN, Joe Sandbox, Cuckoo Sandbox

# Monitor network connections during execution
$ sudo tcpdump -i eth0 -w /tmp/malware_traffic.pcap &
# Run the sample in the VM
# Stop capture, analyze connections

# Monitor file system changes
$ inotifywait -r -m /tmp/malware_workspace/ &
# Run the sample, observe created/modified files

# Monitor process creation (Linux)
$ sudo auditctl -a always,exit -F arch=b64 -S execve
# Run sample, review audit log for spawned processes
Never analyze malware on a production system or on a machine connected to your corporate network. Always use an isolated VM with no network access (or network access routed through a monitoring proxy). Snapshot the VM before analysis so you can restore to a clean state. Some malware detects VMs and behaves differently, so advanced analysis may require bare-metal environments.

Threat Intelligence and IOC Sharing

Threat intelligence transforms raw IOCs into actionable context. Knowing that an IP address is "bad" is less useful than knowing it is associated with APT29, has been active since January, targets government agencies, and is part of a SolarWinds follow-on campaign.

Threat Intel Frameworks:

  • STIX (Structured Threat Information Expression): Standard format for threat intelligence data
  • TAXII (Trusted Automated Exchange of Indicator Information): Protocol for exchanging STIX data
  • MISP (Malware Information Sharing Platform): Open-source threat intelligence platform for sharing IOCs across organizations
  • ISACs (Information Sharing and Analysis Centers): Industry-specific sharing communities (FS-ISAC for financial services, H-ISAC for healthcare)

IOC Lifecycle: IOCs have a shelf life. IP addresses get recycled, domains get taken down and re-registered, file hashes change with each recompilation. A threat intelligence program must continuously ingest, validate, and expire IOCs. Stale IOCs generate false positives and waste analyst time.

YARA Rules: Writing Custom Malware Signatures

YARA is the industry standard for writing custom malware signatures. If you find a new malware sample and want to write a detection rule that finds other samples from the same family, YARA lets you define patterns --- strings, hex sequences, conditions --- that identify malware families even when individual file hashes change with each recompilation.

rule Emotet_Dropper {
    meta:
        author = "Security Team"
        description = "Detects Emotet document dropper"
        date = "2026-01-15"
        reference = "https://attack.mitre.org/software/S0367/"

    strings:
        $macro1 = "AutoOpen" nocase
        $macro2 = "WScript.Shell" nocase
        $ps = "powershell" nocase wide
        $b64 = /[A-Za-z0-9+\/]{40,}={0,2}/ // base64 encoded payload
        $url = /https?:\/\/[a-z0-9\-\.]{5,}\.(com|net|org|xyz)/ nocase
        $hex_pattern = { 4D 5A 90 00 03 00 00 00 } // MZ header in embedded PE

    condition:
        filesize < 5MB and
        (
            ($macro1 and $macro2 and $ps) or
            ($macro1 and $b64 and $url) or
            ($hex_pattern at 0)
        )
}
# Scan a directory with your YARA rules
$ yara -r emotet_rules.yar /quarantine/samples/
Emotet_Dropper /quarantine/samples/invoice_march.docm
Emotet_Dropper /quarantine/samples/payment_details.xlsm

# Scan running processes
$ yara -p 4 malware_rules.yar /proc/
David Bianco's Pyramid of Pain ranks IOC types by how much pain they cause an attacker when you detect and block them:

1. **Hash values (trivial):** Attacker recompiles and gets a new hash. Seconds of effort.
2. **IP addresses (easy):** Attacker switches to a new VPS or proxy. Minutes of effort.
3. **Domain names (simple):** Attacker registers a new domain. Hours of effort.
4. **Network/host artifacts (annoying):** Attacker must change their tools' behavioral patterns. Days of effort.
5. **Tools (challenging):** Attacker must find or develop new tools. Weeks of effort.
6. **TTPs (tough):** Attacker must change their entire methodology. Months to years of effort.

This is why behavioral detection (EDR, SIEM correlation rules) is more valuable than signature-based detection. Detecting the TTP "process injection via CreateRemoteThread from a Word macro" catches an entire class of attacks, not just one sample. The attacker can change their hash, IP, and domain in minutes --- but changing their fundamental attack technique requires significant effort and skill.

Indicators of Compromise (IOCs)

IOCs are forensic artifacts that indicate a system has been compromised. They are the digital fingerprints of an attack:

IOC TypeExampleDetection Method
File hash (MD5/SHA256)e7d705a3286e19ea42f587b344ee6865File scanning, EDR
IP address185.234.72.19Firewall logs, proxy logs
Domain nameevil-c2-server.comDNS logs, proxy logs
URL path/wp-content/plugins/backdoor.phpWeb server logs
Email addressattacker@phishing-domain.comEmail gateway logs
Registry keyHKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\backdoorRegistry monitoring
Mutex nameGlobal\SUNBURST_MutexProcess monitoring
JA3 hasha0e9f5d64349fb13191bc781f81f42e1TLS inspection
YARA rulePattern matching malware family characteristicsFile scanning

Practical Detection with Command-Line Tools

# Check for unusual network connections
$ netstat -tulnp | grep ESTABLISHED
# Look for connections to unexpected IPs, especially on unusual ports

# Check for suspicious processes (Linux)
$ ps auxf | head -50
# Look for: processes running from /tmp, random character names,
# processes running as root that shouldn't be

# Check for unauthorized scheduled tasks
$ crontab -l
$ ls -la /etc/cron.d/
$ cat /etc/crontab
# Look for: base64-encoded commands, downloads from external URLs

# Check for recently modified files in system directories
$ find /usr/bin /usr/sbin -mtime -7 -type f -ls
# System binaries should not change outside of patching

# Check for unusual SUID binaries (potential privilege escalation)
$ find / -perm -4000 -type f 2>/dev/null
# Compare against a known-good baseline

# Check for processes with deleted executables (common for in-memory malware)
$ ls -la /proc/*/exe 2>/dev/null | grep deleted

# Scan for known malware signatures with ClamAV
$ clamscan -r /home/ --infected --log=/var/log/clamscan.log
Build a baseline of your system's normal state:

$ ps aux > /secure/baseline/processes_$(date +%Y%m%d).txt
$ netstat -tulnp > /secure/baseline/network_$(date +%Y%m%d).txt
$ find /usr -type f -exec sha256sum {} \; > /secure/baseline/checksums_$(date +%Y%m%d).txt

Compare regularly against this baseline. Any differences warrant investigation. This is a basic host-based intrusion detection approach. Tools like OSSEC, Wazuh, and AIDE automate this process and alert on changes.

What You've Learned

In this chapter, you explored the full landscape of malicious software and advanced threats:

  • Malware taxonomy: Viruses need hosts and user action. Worms self-propagate autonomously. Trojans deceive users into installing them. RATs provide full remote control. Rootkits hide at progressively deeper levels from user-mode to firmware. Each type demands different detection strategies.

  • Ransomware evolution: From the 1989 AIDS Trojan to modern Ransomware-as-a-Service operations with double and triple extortion. Ransomware is now a professionalized criminal industry with estimated annual revenues exceeding $1 billion, complete with customer support, affiliate programs, and bug bounties.

  • WannaCry and NotPetya: Two attacks in 2017 that demonstrated the catastrophic potential of worm-capable malware exploiting unpatched vulnerabilities. WannaCry shut down hospitals; NotPetya destroyed $10 billion in corporate infrastructure. Both were preventable with timely patching.

  • APT lifecycle: Nation-state actors follow the kill chain from reconnaissance through C2 to actions on objectives. Their patience, discipline, and willingness to wait months before activating distinguish them from criminal actors who maximize speed.

  • SolarWinds: The definitive supply chain attack. Compromising a trusted software vendor's build system gave APT29 access to 18,000 networks while selectively targeting approximately 100 high-value government and corporate organizations.

  • Defense in depth: EDR over signature-based antivirus for behavioral detection. Network segmentation to slow lateral movement and increase dwell time. The 3-2-1-1-0 backup rule with offline or immutable copies. Patch management with clear SLAs. IOC-based detection and baseline comparison.

  • Malware analysis: Static analysis (file type identification, hash computation, string extraction, PE header analysis, macro extraction) and dynamic analysis (sandboxed execution with network and filesystem monitoring) are complementary approaches. YARA rules enable custom signature writing that detects malware families across variant recompilations. Tools like VirusTotal, oletools, and pefile are essential in the analyst's toolkit.

  • Threat intelligence and the Pyramid of Pain: IOCs range from trivial to block (file hashes, which attackers change in seconds) to extremely painful (TTPs, which require months to change). Behavioral detection targeting TTPs provides more durable defense than signature-based detection. STIX, TAXII, and MISP provide standardized formats and platforms for sharing threat intelligence across organizations.

The threat landscape will keep evolving, but the fundamentals do not change: patch promptly, segment aggressively, back up immutably, detect quickly, and assume breach. The question is never "will you be attacked?" but "how quickly will you detect and contain it?" If you cannot remember when your last backup restore test was, the answer is "too long ago." Go fix that.