Chapter 50 Β· Concepts

Malicious Code Concepts

Malware taxonomy, propagation comparison, real-world attack breakdowns, and the full defense stack in structured reference format.

Malware Types β€” Quick Reference

TypeSelf-Replicates?User Action Required?Primary PurposeKey Characteristic
VirusYes (via host file)Yes β€” must execute infected hostSpread; damage; payload deliveryAttaches to legitimate files; requires host execution
WormYes (autonomous)No β€” exploits vulnerability directlyRapid network propagationSpreads without user interaction; no host file needed
Trojan HorseNoYes β€” user installs itDeliver hidden payloadDisguised as legitimate software; no self-replication
RansomwareDepends on deliveryDepends on deliveryExtortion via encryptionEncrypts files; demands payment; delivery varies
SpywareNoUsually (Trojan delivery)Covert data collectionSilent operation; exfiltrates data to attacker
RootkitNoUsually (elevated privileges needed)Hide attacker presenceModifies OS to conceal malware from detection tools
KeyloggerNoUsuallyCredential/keystroke captureRecords all keystrokes; can be software or hardware
Logic BombNoNo β€” triggers automaticallyDelayed payload executionDormant until trigger condition; often insider-planted
RAT / BackdoorNoUsually (Trojan delivery)Persistent remote controlHidden access channel; full remote administration
Fileless MalwareNoUsually (exploit or phishing)Evade filesystem detectionRuns in memory; no malicious files on disk

Virus vs. Worm β€” Propagation Comparison

PropertyVirusWorm
Host file neededYes β€” attaches to an executable, document, or scriptNo β€” standalone; installs itself directly
User action needed to spreadYes β€” user must execute the infected fileNo β€” exploits vulnerability; spreads automatically
Propagation speedLimited by how often users share/execute infected filesExtremely fast β€” exponential; one host infects many simultaneously
Network spreadIndirect β€” through shared files, email, USBDirect β€” scans and exploits network services autonomously
ExampleMelissa virus (1999) β€” spread via infected Word document email attachmentsWannaCry (2017) β€” spread via SMBv1 exploit with no user interaction
Primary defenseAnti-malware scanning of files; user trainingPatching vulnerable services; firewall rules blocking exploit traffic

WannaCry Attack β€” Step by Step

1. Vulnerability exists β€” Windows SMBv1 contains a critical remote code execution flaw (MS17-010 / EternalBlue); all unpatched Windows systems with SMB port 445 accessible are vulnerable
2. Exploit delivery β€” attacker (or infected machine acting as propagation node) sends a specially crafted SMBv1 packet to a target machine's port 445; no user interaction required; the packet exploits the vulnerability
3. Arbitrary code execution achieved β€” the malformed packet causes SMBv1 to execute attacker-controlled code on the target system with system-level privileges
4. Ransomware payload installed β€” WannaCry's ransomware component is installed and begins encrypting user files (documents, photos, databases) using AES encryption; a ransom note appears demanding Bitcoin payment
5. Worm propagation begins β€” the infected machine immediately begins scanning IP ranges for other systems with port 445 open; for each vulnerable system found, steps 2–5 repeat; one infected machine becomes many
6. Decryption key held ransom β€” without the decryption key (controlled by the attacker), encrypted files are inaccessible; systems without offline backups face full data loss if the ransom is not paid

Real-World Attack Comparison

AttackMalicious Code TypeTargetMechanismScale
WannaCry (2017)Worm + Ransomware executableUnpatched Windows systems (SMBv1)Arbitrary code execution via MS17-010 exploit; encrypted files; demanded Bitcoin ransom230,000+ machines, 150 countries
British Airways XSS (2018)Malicious JavaScript (22 lines)British Airways checkout web pagesInjected script silently exfiltrated payment card data as customers typed it~380,000 victims' payment data
Estonian Health DB (year undisclosed)SQL injectionNational healthcare database applicationUnsanitized query input allowed arbitrary SQL execution; full database read accessEntire country's health records

Cross-Site Scripting (XSS) β€” How It Works

1. Attacker gains write access to target website β€” through a separate vulnerability (broken authentication, file upload flaw, admin credential theft); attacker modifies pages served to users
2. Malicious script injected β€” attacker adds JavaScript to a page; in BA's case, 22 lines added to checkout pages that read form field values as users typed them
3. Victim visits the page β€” real user navigates to the checkout page; browser downloads the page including the injected script; the browser cannot distinguish legitimate code from injected code
4. Script executes in victim's browser β€” the malicious JavaScript runs with the same permissions as the legitimate site's scripts; it reads card number, expiration, CVV, name, billing address from the form fields in real time
5. Data exfiltrated β€” as the user types payment data and submits the form, the injected script also sends the captured data to the attacker's server; the legitimate transaction completes normally; the victim has no indication anything occurred

SQL Injection β€” How It Works

A SQL injection vulnerability exists when user input is incorporated into a database query without sanitization. Consider a login form where the application builds a query:

SELECT * FROM users WHERE username = '[input]' AND password = '[input]'

If the user types: ' OR '1'='1' -- as the username, the query becomes:

SELECT * FROM users WHERE username = '' OR '1'='1' --' AND password = '...'

The condition '1'='1' is always true; the password check is commented out (--). The query returns all users β€” authentication bypassed. More advanced injections can read any table, modify data, or in some configurations execute OS commands.

Defense: Parameterized queries (prepared statements) β€” the query structure is defined separately from user data, so the database never interprets user input as SQL commands. Input validation as a secondary layer.

Defense Stack β€” Matched to Attack Types

DefenseAttacks AddressedHow
Anti-malware (endpoint)Viruses, Trojans, ransomware, spyware, keyloggers, RATsSignature-based detection of known malware; heuristic/behavioral detection of suspicious activity; sandboxing of unknown executables
FirewallWorm propagation, RAT C2 traffic, exploit deliveryBlocks traffic to vulnerable ports (e.g., SMB port 445 from external sources); blocks known malicious IPs/domains; alerts on anomalous outbound connections
Patching and updatesWorms, exploit-delivered ransomware, drive-by downloadsCloses the specific vulnerabilities exploits use; MS17-010 patch prevented all WannaCry infections on patched systems; patches must be applied promptly
Input validation / parameterized queriesSQL injection, XSSPrevents user input from being interpreted as code; separates data from executable instructions at the application layer
Content Security Policy (CSP)Cross-site scriptingHTTP header that restricts which scripts can execute on a page; limits damage from injected scripts even if XSS injection succeeds
Secure computing habitsTrojans, macro viruses, phishing-delivered ransomwareUsers who don't install untrusted software, don't enable macros in unsolicited documents, and don't click suspicious links remove the human-action delivery vector
Offline backupsRansomwareIf files can be restored from backup, ransomware loses its leverage; backups must be offline or air-gapped so ransomware can't encrypt them too
Behavioral monitoring / EDRFileless malware, rootkits, RATsWatches process behavior rather than file signatures; detects unusual use of PowerShell, WMI, or system tools regardless of whether malicious files are present
Least privilegeAll malware that requires elevated accessMalware running under a low-privilege user account has limited impact; rootkits require OS-level privileges; limiting user rights limits malware capabilities

Malware Detection Methods

MethodHow It WorksStrengthLimitation
Signature-basedCompares file byte patterns against database of known malware signaturesFast; low false-positive rate for known malwareMisses new (zero-day) and obfuscated malware; requires constant signature updates
Heuristic analysisAnalyzes code structure and behavior patterns for malware-like characteristicsCan detect variants of known malware not in signature databaseHigher false-positive rate; sophisticated malware can evade heuristics
Behavioral monitoringWatches running processes for suspicious actions (mass file encryption, network scanning, registry modification)Detects malware by what it does, not what it looks like; catches fileless malwareMay catch malware only after it begins executing; some legitimate tools behave similarly
SandboxingExecutes suspicious files in isolated environment; observes behavior without risk to production systemsCan safely detonate unknown malware to observe payloadAdvanced malware detects sandbox environments and behaves benignly until it detects a real system