Part 1: Introduction to Malware and Taxonomy
Part 2: Malware Architecture and Components
Part 3: Delivery and Initial Compromise
Part 4: Social Engineering Attacks
Part 5: Specialized Malware Components
Part 6: Defenses Against Malware
From Classification to Implementation
Understanding what malware does -- whether it's ransomware, a worm, or a trojan -- tells us about its objectives. But to defend against malware effectively, we need to understand how it works internally: how it gets onto a system, how it establishes itself, and how its various components coordinate to achieve the attacker's goals.
Modern malware is rarely a single monolithic program. Instead, it typically consists of multiple components working together, each serving a specific purpose in the attack chain. This modular approach gives attackers flexibility: they can update individual components, customize attacks for specific targets, and reduce the likelihood of detection by keeping each piece simple and focused.
The Classic Malware Lifecycle
Most malware attacks follow a predictable sequence of stages. Understanding this lifecycle helps us identify points where defenses can interrupt an attack. However, not all malware goes through all stages. Simple malware might execute its payload immediately upon infection, while sophisticated attacks involve multiple stages with careful orchestration.

Stage 1: Infection and Delivery
The first stage is getting the malware onto the target system. This is often the most challenging step for attackers because modern systems have numerous defenses at the perimeter.
Attackers employ various infection methods:
-
Exploiting vulnerabilities in software to execute code without user interaction
-
Social engineering to trick users into running malicious programs or clicking on malicious links
-
Physical access via infected USB drives or other removable media
-
Supply chain compromise where legitimate software is modified to include malware before it reaches users
-
Drive-by downloads where simply visiting a compromised website triggers malware installation
The initial payload that arrives on the system might be the complete malware package, but more often it's just the first stage: a small program designed to download and install the real malware. This approach makes the initial infection harder to detect and easier to update.

Stage 2: Dropper and Loader
Sophisticated attacks typically use a dropper or loader as the initial component. This small program has one job: deploy the actual malware payload.
A dropper (also called a downloader) downloads and installs the main malware from a remote server. Droppers are usually small and heavily obfuscated to evade detection. They might check the environment first. For instance, is this a virtual machine used for malware analysis? Is antivirus running? Is there an internet connection? What operating system version is running? Based on these checks, the dropper decides whether to proceed and which payload to download.
A loader is similar but includes the payload embedded within itself, typically encrypted or compressed. When executed, the loader unpacks and executes the hidden payload. This approach works when the attacker can't rely on internet connectivity or wants to avoid network traffic that might be monitored.
Why bother with this two-stage approach? Several reasons make it advantageous for attackers:
-
The initial payload is smaller and easier to deliver through email filters and other defenses
-
The main malware can be updated without reinfecting systems: just point the dropper to a new download location
-
Droppers can check for analysis environments and refuse to deploy if they detect sandboxes or virtual machines
-
Defenders who capture the dropper don't automatically get the main payload, making analysis more difficult
-
Different payloads can be delivered to different targets based on the dropper's environmental checks
Emotet, which operated from 2014 until its takedown in January 2021, shows how this approach worked. The initial infection might come from a phishing email with a malicious Word document. The macro in that document would download the Emotet loader. That loader would then establish persistence, contact command-and-control servers, and download additional modules -- perhaps a banking trojan, ransomware, or tools for lateral movement through the network.

Stage 3: Persistence Mechanisms
Once malware has successfully executed on a system, it needs to ensure it survives reboots and isn't easily removed. Persistence mechanisms achieve this by inserting the malware into locations where it will automatically execute when the system starts or when certain events occur.
On Windows systems, common persistence techniques include:
Registry Run keys are one of the most common persistence mechanisms. These registry locations specify programs that should run automatically:
-
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run -
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run
When a user logs in, Windows executes all programs listed in these keys. Malware simply adds an entry pointing to itself.
Scheduled Tasks provide flexible persistence by triggering at specific times or in response to events. Malware can create tasks that run at system startup, at user login, at specific times, or when certain conditions are met (such as network connection establishment). These tasks can run with elevated privileges if the malware has already obtained administrative access.
Windows Services run in the background, typically with SYSTEM privileges, and start automatically when Windows boots. Malware that installs itself as a service gains high privileges and persistence. Services run before users log in, giving malware early execution.
DLL hijacking exploits the way Windows searches for dynamic link libraries. When a program needs to load a DLL, Windows searches several directories in a specific order. Malware can place a malicious DLL in a location that's checked before the legitimate DLL's location. When the legitimate program tries to load the DLL, it gets the malicious version instead. This technique is particularly insidious because it doesn't require modifying legitimate files—just placing malicious files in the right location.
Boot sector modification (also called a bootkit) infects the Master Boot Record (MBR) or UEFI boot partition. This code executes before the operating system loads, giving the malware the earliest possible execution and the ability to compromise the OS from the ground up.
On Linux and macOS systems, persistence techniques include:
Cron jobs run commands on schedules. Malware can add entries to the user's crontab or system-wide cron directories to execute at regular intervals or specific times (like system startup with @reboot).
Init scripts or systemd services execute during system startup. On modern Linux systems using systemd, malware can create service unit files in /etc/systemd/system/ or user-specific directories. On older systems using init, malware modifies scripts in /etc/init.d/.
Modified shell configuration files like .bashrc, .bash_profile, .profile, or .zshrc execute whenever a user opens a terminal. Malware can add commands to these files that execute each time, relaunching itself if it's been terminated.
Compromised system binaries involve replacing legitimate programs with malicious versions. For instance, malware might replace /bin/ps with a version that includes malicious functionality while still performing the normal process listing operation, so users don't notice anything wrong.
Launch Agents and Launch Daemons on macOS are Apple's preferred mechanism for automatically executing programs. Malware creates property list (.plist) files in directories like ~/Library/LaunchAgents/ or /Library/LaunchDaemons/ that specify programs to run.
Cross-platform techniques that work on multiple operating systems include:
Browser extensions load whenever the browser starts. A malicious extension can monitor browsing, inject advertisements, steal credentials, or modify web pages. Since browsers run constantly for many users, this provides excellent persistence.
Items in startup folders execute automatically when the system or user session starts. On Windows, this is the Startup folder in the Start Menu. On Linux, this might be .config/autostart/ for GUI applications.
Abuse of legitimate software that has auto-start capabilities. For instance, malware might modify configuration files of legitimate programs that run at startup to include malicious commands.
A single piece of malware often establishes multiple persistence mechanisms. If a user or security software removes one, others remain to re-establish the infection. This redundancy makes complete removal difficult without specialized tools or, in severe cases, a complete system reinstallation.

Stage 4: Trigger Conditions
Not all malware executes immediately upon installation. Many pieces of malware wait for specific conditions before activating their payload. This delay serves several purposes: it can help evade detection by automated analysis systems, wait for an opportune moment when the malware is most likely to succeed, or synchronize actions across multiple infected systems.
Immediate execution is the simplest approach—the malware runs as soon as it's installed. This is common for malware with time-sensitive objectives or when stealth isn't a primary concern. Most ransomware operates this way since attackers want to monetize the infection quickly.
Time-based triggers activate the malware at specific moments:
A time bomb waits for a particular date and time. The Michelangelo virus activated on March 6 (the artist's birthday), though the predicted widespread damage never materialized: the virus was less prevalent than media reports suggested. More recently, the Shamoon wiper that attacked Saudi Aramco in 2012 was programmed to activate on a specific date, maximizing impact by giving the attackers time to spread it to many systems before the payload executed simultaneously.
A logic bomb waits for specific conditions to be met rather than a particular time. A disgruntled employee might plant malware that activates X days after their account is disabled, after a certain date passes, or when they fail to perform a regular action (a "dead man's switch"). Logic bombs can also check for the absence of a particular file—as long as that file exists, the bomb doesn't activate. The employee can delete the file to trigger the attack or leave it in place as insurance.
Event-based triggers respond to specific system events or user actions:
-
Activating when a user visits a banking website to intercept credentials at the most valuable moment.
-
Triggering when specific files are accessed. For instance, activating when the user opens a document containing "confidential" or "classified."
-
Waiting until the system is idle before running cryptojacking operations to avoid slowing down the user's work and thus attracting attention.
-
Counting system reboots before activating. Some analysis sandboxes don't reboot systems to save time, so malware that waits for the second or third reboot might evade automated analysis entirely.
-
Monitoring for the presence of analysis tools or debuggers and remaining dormant when detected.
Manual triggers give attackers direct control:
-
The malware waits for explicit commands from a command-and-control server.
-
Human operators decide when to activate the payload based on reconnaissance of what's on the compromised system.
-
This is common in Advanced Persistent Threat (APT) campaigns where attackers conduct extensive reconnaissance before deciding what to do with each compromised system.
Why delay activation? Malware analysis sandboxes typically run samples for a limited time, often just a few minutes or at most a few hours. Malware that waits for a time-based trigger or requires multiple reboots will appear completely benign during sandbox analysis. The sandbox will report "no malicious behavior detected" even though the malware would activate later in a real environment.
Delayed activation also allows attackers to wait for high-value targets. Not all infected systems are equally valuable. An APT group that has infected hundreds of systems might wait to deploy ransomware or wipe data until they've identified which systems contain the most valuable information or are most critical to operations.
Finally, synchronized triggers enable coordinated attacks. By programming malware to activate simultaneously across many systems, attackers can overwhelm incident response teams and maximize damage. The Shamoon attacks demonstrated this in action: thousands of systems began wiping their hard drives simultaneously, making a response nearly impossible.

Stage 5: Payload Execution
The payload is what the malware actually does: its core malicious functionality. This is where the attacker's objectives are realized. Everything before this stage is set up; the payload is the attack itself.
Data manipulation payloads include:
-
Encrypting files for ransomware attacks. The malware typically targets specific file types -- documents, images, databases, and backups -- while leaving system files intact so the computer still boots and the victim can see the ransom demand. Modern ransomware uses strong encryption (often AES-256 combined with RSA-2048 or similar public-key cryptography) that is effectively unbreakable without the decryption key.
-
Deleting or corrupting data for destructive attacks. Wipers might overwrite files with random data, delete files entirely, or corrupt them just enough to make them unusable. Some wipers target specific file types or directories, while others are indiscriminate.
-
Exfiltrating sensitive information like documents, credentials, or personal data. The malware might compress and encrypt the data before sending it to reduce bandwidth usage and avoid detection by data loss prevention systems. Exfiltration might happen slowly over time to avoid triggering bandwidth alerts.
System manipulation payloads include:
-
Installing backdoors for future access. These might be simple remote access tools or sophisticated frameworks that provide extensive control over the compromised system.
-
Modifying system settings to weaken security. This might include disabling Windows Defender, changing firewall rules, modifying audit settings to hide evidence, or altering user account controls.
-
Disabling antivirus or other security software. Some malware terminates antivirus processes, deletes their files, or corrupts their databases. More sophisticated malware might add exceptions to the antivirus configuration so the malware is ignored.
-
Creating new user accounts or virtual machines. New accounts provide alternative access methods. Some sophisticated malware creates entire virtual machines within the compromised system, giving attackers an isolated environment for their activities.
Resource abuse payloads include:
-
Mining cryptocurrency using the victim's CPU and GPU. Cryptojacking malware typically targets cryptocurrencies that are designed to be mineable on consumer hardware, like Monero. The malware often tries to be stealthy, limiting CPU usage to levels that won't be immediately obvious to users.
-
Sending spam emails from the victim's email account or using their computer as a relay. This allows spammers to leverage the reputation of legitimate email servers and IP addresses, improving delivery rates.
-
Launching distributed denial-of-service attacks against third parties. The malware participates in flooding a target with traffic, contributing a small amount of bandwidth that becomes significant when combined with thousands or millions of other compromised systems.
Surveillance payloads include:
-
Logging keystrokes to capture passwords, credit card numbers, messages, and anything else typed. Sophisticated keyloggers also capture the application or website where typing occurred, providing context for the stolen information.
-
Taking periodic screenshots of the user's screen. This captures visual passwords (like on-screen keyboards), graphics that can't be captured via keylogging, and generally provides a comprehensive view of user activity.
-
Recording audio or video from attached cameras and microphones. This might be continuous or triggered by specific events (like detecting a video call starting).
-
Monitoring network traffic to intercept unencrypted data or credentials sent over the network. This is particularly effective on shared networks where the malware can see traffic from other systems, not just the infected one.
The payload might execute once and terminate, or it might run continuously in the background. Some payloads are destructive and leave obvious evidence -- users definitely notice when ransomware encrypts all their files. Others operate silently for months or years without detection—spyware and backdoors fall into this category.

Stage 6: Propagation
Not all malware attempts to spread: trojans, most ransomware, and spyware typically remain on the initially infected system. But self-propagating malware can turn a single infection into an epidemic.
Viruses infect other files on the same system. When you run an infected program, the virus code executes first. It looks for other executable files or documents that support macros and copies itself into them. The original host program then executes normally, so the user doesn't notice anything wrong.
When those infected files are shared -- via email attachments, USB drives, network file shares, or cloud storage -- the infection spreads to other systems. However, this spreading requires user action at each step. Someone must share the infected file, and someone else must open it or run it. This limits the speed of viral propagation compared to worms.
Worms spread autonomously, requiring no user action beyond the initial infection. This is what makes them so dangerous and why they can achieve exponential growth rates.
A typical worm cycle looks like:
-
The worm infects System A
-
The worm scans the network for other systems (it might target random IP addresses or scan the local subnet)
-
The worm tests each discovered system for specific vulnerabilities
-
When vulnerable System B is found, the worm exploits the vulnerability
-
The worm copies itself to System B and executes
-
System B repeats steps 2-5
-
Both systems continue scanning and infecting additional systems
This creates exponential growth. One system infects two, those two infect four, those four infect eight, and so on. In the early stages, growth is slow because few systems are infected. But once a critical mass is reached, the number of infections can explode.
Common propagation methods include:
Email where malware sends copies of itself to contacts in the victim's address book. The ILOVEYOU worm (2000) used this method devastatingly: it sent itself to every contact in Microsoft Outlook, and because the message appeared to come from someone the recipient knew, many people opened it.
Network shares where malware copies itself to accessible file servers or shared folders. On Windows networks, malware often targets the C$ and ADMIN$ administrative shares that exist on systems with certain configurations.
Removable media where malware copies itself to any USB drive or external hard drive that's connected. It would often add an autorun.inf file (on Windows) that would cause the malware to execute automatically when the drive is inserted into another computer, though this feature has been largely disabled in modern Windows versions.
Network exploits where malware scans for vulnerable services and attempts to compromise them. This is what WannaCry did with the EternalBlue exploit targeting SMB. It's also what the Blaster worm (2003) did targeting the RPC DCOM (remote procedure call) vulnerability, and what Code Red (2001) did targeting IIS web servers.
Peer-to-peer networks where malware masquerades as popular files that users want to download. Someone searching for pirated movies or music might download a file that turns out to be malware.
Social media and messaging platforms where malware sends links to friends, followers, or connections. These often use URL shorteners to hide the actual destination. Because the message comes from someone known to the recipient, trust is higher and click rates improve.
Application programming interfaces (APIs) where malware uses legitimate API access (often stolen credentials) to send messages or post content that spreads the infection.
WannaCry demonstrated how effective autonomous propagation can be. It scanned for Windows systems with TCP port 445 (used by the SMB file sharing protocol) exposed to the network. When it found a system, it attempted the EternalBlue exploit, which exploited a buffer overflow in the way Windows handled specially crafted SMB packets. If successful, WannaCry could execute arbitrary code with SYSTEM privileges—the highest privilege level in Windows.
Within days, this approach had spread WannaCry to over 200,000 computers across 150 countries. Healthcare systems in the UK's National Health Service couldn't access patient records and had to cancel surgeries. Spain's Telefonica telecommunications company was affected. FedEx, Renault, Nissan, and many other large organizations experienced disruptions. The total economic impact was estimated at $4 billion.
Sidebar: The WannaCry Kill Switch
WannaCry's spread was eventually slowed by an accidental discovery. Security researcher Marcus Hutchins noticed that WannaCry checked for the existence of a specific, nonsensical domain name before proceeding with its attack. The domain was iuqerfsodp9ifjaposdfjhgosurijfaewrwergwea.com—clearly a randomly generated string.
If WannaCry could successfully resolve that domain (meaning the domain existed and responded to DNS queries), it assumed it was running in a malware analysis sandbox and terminated without running its payload. Malware analysts often redirect domains to their own servers to analyze what malware tries to communicate, so checking for unusual domain resolution is a common anti-analysis technique.
Hutchins registered the domain for about $10, essentially creating a global "kill switch" for WannaCry. Once the domain existed and responded to queries, most WannaCry infections stopped proceeding with their attacks. However, this only worked for the original variant. Modified versions without the kill switch appeared soon after, and the kill switch didn't help systems already encrypted before the domain was registered.
The kill switch's existence was itself unusual: it may have been included as a testing artifact that wasn't removed before deployment, or possibly as an intentional way for the attackers to stop the spread if it got out of control.
Putting It All Together: The WannaCry Example
Examining how WannaCry moved through these stages illustrates how the lifecycle works in practice:
Infection: The exact initial infection vector for WannaCry was never definitively determined, though phishing emails are suspected. However, once WannaCry infected its first systems, propagation became the primary infection method: the worm spread itself autonomously via the EternalBlue exploit.
Dropper: WannaCry didn't use a separate dropper in the traditional sense. The EternalBlue exploit directly deployed the complete ransomware component. The exploit shellcode downloaded a small executable called mssecsvc.exe which contained the full WannaCry functionality.
Persistence: WannaCry established multiple persistence mechanisms. It created registry keys at HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run to ensure execution at startup. It installed itself as a service named "mssecsvc2.0" which would run automatically. It also modified system files and configuration to maintain its presence.
Trigger: Activation was immediate. As soon as WannaCry infected a system, it began encrypting files and displaying the ransom demand. There was no waiting period or condition checking beyond the kill switch domain check.
Payload: The encryption component targeted over 170 file extensions, including documents (.doc, .docx, .pdf), images (.jpg, .png, .gif), databases (.sql, .mdb), archives (.zip, .rar), and many others. It used AES-128 encryption for file content and RSA-2048 for encrypting the AES keys. The ransom note demanded $300 initially, which doubled to $600 after three days. After seven days without payment, WannaCry threatened to delete the encryption keys permanently, making recovery impossible.
The ransom note appeared as a distinctive red-and-black window with text in 28 languages, showing a countdown timer and instructions for purchasing Bitcoin and sending payment. The window couldn't be closed without terminating critical WannaCry processes, which would make decryption impossible even if the ransom was paid.
Notably, the encryption key management was flawed. In many cases, even if victims paid the ransom, the decryption process was unreliable. The keys weren't properly tied to individual infections, making it difficult for attackers to decrypt files for specific victims. Some security researchers found ways to recover the encryption keys from memory in certain circumstances, allowing some victims to decrypt without paying.
Propagation: This was WannaCry's most devastating feature. It scanned for systems with TCP port 445 exposed to the network. Port 445 is used by Microsoft's Server Message Block (SMB) protocol for file and printer sharing. When WannaCry found a system with this port open, it sent specially crafted SMB packets designed to trigger the EternalBlue vulnerability.
EternalBlue was a zero-day exploit developed by the NSA and leaked by a group calling themselves "The Shadow Brokers" in April 2017—just weeks before WannaCry emerged. Microsoft had released a patch (MS17-010) in March 2017, but many systems remained unpatched. WannaCry specifically targeted Windows 7 and Windows Server 2008 systems, though it affected other versions as well.
The autonomous propagation allowed WannaCry to spread globally in a matter of days without any attacker intervention beyond the initial release. This represented a new evolution in ransomware—previous ransomware typically relied on phishing or exploit kits for spreading, infecting one victim at a time. WannaCry's worm functionality allowed it to spread like wildfire through vulnerable networks.
Organizations with flat networks (where all systems could communicate with each other) were particularly vulnerable. Once WannaCry infected one system inside the firewall, it could rapidly spread to all other vulnerable systems on the internal network. This is why the attack was so devastating to large organizations: a single infected system could compromise hundreds or thousands of others in minutes.
Command and Control Infrastructure
Most modern malware needs to communicate with its operators. This communication infrastructure is called Command and Control, abbreviated as C2 or C&C (sometimes written as CnC or C2). (I prefer the accuracy of C2 but C2 seems to be the most widely-used notation, so I'll stick with that.)
Command and control serves several critical functions:
-
Receiving commands from operators about what actions to take—whether to steal data, deploy additional malware, or activate certain features
-
Sending stolen data back to the attackers—credentials, documents, system information
-
Downloading updates or additional malware—new functionality, patches to evade new defenses, or different payloads
-
Coordinating activities across multiple infected systems—synchronizing DDoS attacks or timing ransomware deployment
-
Reporting status—infection confirmation, system information, campaign statistics
Without C2, malware is essentially fire-and-forget: once deployed, attackers have no further control. They can't update it to evade new defenses, command it to perform new actions based on what they discover about the target, or retrieve stolen data. C2 infrastructure transforms malware from a static threat into a dynamic tool that operators can wield for various purposes.
Different types of malware have different C2 needs:
-
Bots and botnets rely heavily on C2 to coordinate actions across thousands or millions of compromised systems
-
Backdoors use C2 to receive commands and maintain persistent access over time
-
Ransomware may use C2 to transmit encryption keys (stored on the attacker's server so victims can't recover them from the infected system)
-
Data exfiltration malware uses C2 to send stolen information to the attackers
-
Spyware and surveillance tools use C2 to receive instructions about what to monitor and to transmit collected data
Interestingly, some malware operates without traditional C2. WannaCry didn't need C2 for its primary function: the encryption was automatic and the Bitcoin payment addresses were hardcoded. However, this meant the attackers couldn't control the spread, update the code to fix the flawed decryption process, or respond to the kill switch discovery. The lack of C2 made WannaCry simultaneously more resilient (no C2 infrastructure to take down) and less flexible.
C2 Communication Methods
Attackers have developed numerous methods for maintaining command and control while trying to avoid detection.
Direct connection is the simplest approach. The malware connects directly to the attacker's server at a specific IP address or domain name. When the infected system starts or at regular intervals, it reaches out to this address and asks "any commands for me?" The server responds with instructions—perhaps "send me all .docx files" or "download and execute this file" or simply "standby."
This works but has significant drawbacks for attackers. Security teams can easily identify the C2 server's IP address or domain by analyzing captured malware or monitoring network traffic. Once identified, they can block connections to that address. Firewalls can prevent outbound connections to the known C2 IP. DNS filtering can prevent resolution of the C2 domain. Law enforcement can seize the C2 server. Once blocked or seized, the malware can no longer communicate with its operators—it becomes orphaned.
Domain-based C2 improves on direct connection by using domain names instead of hardcoded IP addresses. When defenders block one IP, attackers can simply change the DNS record to point the domain to a different IP address. All infected systems automatically start connecting to the new IP without any updates needed.
Domain Generation Algorithms (DGA) take this further—the malware generates pseudo-random domain names using an algorithm that both the malware and the operators know. For instance, the algorithm might generate 1000 domain names per day based on the current date as a seed. The malware tries to connect to these generated domains in sequence. Attackers only need to register a few of them and wait for infected systems to find them.
From the defender's perspective, this is extremely challenging. They must predict the algorithm (which requires reverse-engineering the malware) and then proactively register or block thousands of potential domains. Meanwhile, attackers only need to register a handful at any time—perhaps 10 domains out of the 1000 generated each day. If defenders manage to seize those, attackers simply register different ones from the daily set.
Modern DGA implementations have become quite sophisticated. They might incorporate multiple seeds (date, trending Twitter topics, stock prices) to make prediction harder. They might generate different domain sets for different malware variants. They might use legitimate-looking names rather than random strings to avoid detection by anomaly-based defenses.
Protocol tunneling hides C2 traffic within legitimate protocols, making it harder to distinguish from normal network activity:
HTTP/HTTPS traffic blends with normal web browsing. The malware's connection to the C2 server looks like any other website visit. Commands might be embedded in fake web page content, and responses might be formatted like form submissions. HTTPS encryption prevents network monitoring from seeing the actual content of the communication.
DNS tunneling encodes data within DNS queries and responses. DNS is essential for internet functionality—without it, hostnames can't be resolved to IP addresses. Because of this, DNS is rarely blocked completely. Malware can encode commands or data in the subdomain portion of DNS queries and receive responses in the DNS reply. For instance, a query for 74657374.malware.com might encode the word "test" in hexadecimal within the subdomain. The data transfer rate is slow, but it works even in highly restricted networks.
Social media platforms like Twitter, Facebook, Reddit, or Telegram can serve as C2 channels. The malware periodically checks specific accounts for new posts or messages. Attackers encode commands in tweets, posts, or images (using steganography). Since the infected system is just accessing normal social media sites, the traffic blends with legitimate use. The Hammertoss malware used by APT29 (a Russian state-sponsored group) used Twitter accounts for C2, with daily rotating accounts determined by an algorithm similar to DGA.
Cloud services like Dropbox, Google Drive, GitHub, or Pastebin can serve as C2 channels. Malware checks specific files or locations for new commands. Attackers post commands to these services using legitimate accounts. The traffic is encrypted (HTTPS) and goes to trusted cloud providers, making it difficult to block without blocking legitimate business use of these services.
Peer-to-peer (P2P) architecture eliminates central servers entirely. Instead of all infected systems connecting to one C2 server, they connect to each other, forming a mesh network. Commands are passed through this network from one infected system to another until they reach all members of the botnet.
This approach has significant advantages for attackers. There's no single point of failure—no central server to seize or block. Taking down the botnet requires finding and cleaning every single infected system. Even if defenders take down some nodes, the remaining nodes continue operating. The GameOver Zeus botnet used P2P architecture and proved extremely difficult to disrupt. It took a coordinated international law enforcement operation to significantly damage the botnet, and even then, it wasn't completely eradicated.
However, P2P also has disadvantages. It's more complex to implement. Commands propagate more slowly through the network. The lack of central control makes it harder for operators to know the exact state of their botnet.
Dead drop techniques avoid direct connections between operators and infected systems. The malware periodically checks a specific location -- perhaps a particular Twitter account, a pastebin post, a specific URL, a GitHub repository, or even comments on news articles -- for new commands. Attackers post commands to these locations using anonymous means (Tor, VPN, public WiFi). There's no direct connection between attacker and victim, making attribution and tracking extremely difficult.
The dead drop might be a legitimate website comment section where commands are posted as innocuous-looking comments. It might be steganographic messages hidden in images posted to Instagram. It might be blockchain transactions where commands are encoded in the transaction data. Defenders can monitor these locations, but identifying the operators who post commands is much harder than tracking direct connections.
C2 Operational Security
Attackers employ various techniques to protect their C2 infrastructure from discovery, analysis, and disruption.
Encryption protects all C2 traffic so that network monitoring can't reveal the commands being sent or data being stolen. Even if defenders capture the network traffic, without the encryption keys it appears as random noise. Modern malware typically uses strong encryption (AES-256 or similar) with key exchange mechanisms that prevent decryption even if some sessions are compromised.
Some malware uses custom encryption rather than standard algorithms. While custom cryptography is generally considered poor security practice (it's usually weaker than well-studied algorithms), it does force defenders to reverse-engineer the malware to understand the encryption scheme before they can decrypt captured traffic.
Beaconing involves periodic check-ins rather than constant connection. Instead of maintaining an open connection to the C2 server, malware "phones home" at intervals—perhaps every hour, every 12 hours, or even daily. During the beacon, it sends status information and receives any waiting commands.
This pattern mimics legitimate software update checks. Many applications check for updates periodically—Windows Update, antivirus updates, application updates. A beacon every few hours doesn't stand out in network logs. It also reduces the total amount of network traffic, making statistical anomaly detection less effective.
Some sophisticated malware uses randomized beacon intervals (anywhere from 2-6 hours rather than exactly every 4 hours) to avoid creating predictable patterns. Others beacon more frequently when the system is idle and less frequently when the user is active, further blending with normal behavior.
Domain fronting makes traffic appear to go to a legitimate, trusted domain like google.com or cloudflare.com while actually communicating with the attacker's C2 server. This technique exploits how content delivery networks (CDNs) route traffic.
Here's how it works: The malware establishes an HTTPS connection that appears to go to a legitimate domain hosted on a CDN. The TLS/SSL handshake and SNI (Server Name Indication) field specify the legitimate domain. However, inside the encrypted HTTP request (which network observers can't see), the Host header specifies a different domain: the actual C2 server is also hosted on the same CDN.
The CDN routes the request based on the Host header inside the encrypted content, not the SNI field visible to network observers. From the network's perspective, the connection goes to google.com or amazon.com. In reality, it's routed to the attacker's domain.
Defending against domain fronting is extremely difficult. Blocking all traffic to major CDNs would cripple internet functionality. Detecting domain fronting requires decrypting TLS traffic (which requires man-in-the-middle certificates that break TLS's security model) or cooperation from the CDN provider. Major CDN providers like Google and Amazon have taken steps to prevent domain fronting, but it remains an effective technique on smaller CDNs or through more sophisticated implementations.
Fast flux rapidly changes DNS records, with C2 domains pointing to different IP addresses every few minutes or even seconds. The malware queries the domain and gets one IP address. Ten minutes later, the same domain resolves to a completely different IP. The IPs might belong to compromised systems, VPN endpoints, proxy servers, or legitimate hosting providers.
This technique makes identifying and blocking C2 infrastructure a game of whack-a-mole. By the time security teams identify and block an IP address, it's no longer being used. The C2 domain might cycle through hundreds or thousands of different IPs.
Double flux takes this further by also rapidly changing the DNS servers (NS records) for the domain, making it harder to take down the domain itself through DNS registrar intervention.
Tor and VPN routing anonymizes the C2 server's location. Traffic is routed through multiple intermediary nodes (in Tor's case) or through VPN servers, making it extremely difficult to determine where the C2 server actually resides.
The Tor network provides strong anonymization—tracing traffic back to its origin requires compromising multiple Tor nodes, which is possible for well-funded adversaries (nation-states) but difficult for most defenders. However, Tor also introduces latency and can be blocked by network-level filtering (though such blocking also prevents legitimate Tor use).
Some malware uses "onion routing" style techniques without using the Tor network itself, creating their own networks of proxy nodes from other infected systems or compromised servers.
IP and Traffic Obfuscation:
Proxy chains route C2 traffic through multiple compromised systems before reaching the actual C2 server. Even if defenders trace the connection, they find another compromised system rather than the attacker's infrastructure.
Traffic mimicry makes C2 traffic look like legitimate applications. The malware might format its C2 communication to look like FTP traffic, HTTP traffic, or even protocols like SMTP. Some sophisticated malware replicates the communication patterns of specific applications—for instance, mimicking Skype or WhatsApp protocol structures.
Timing-based channels use the timing of packets or connections to encode information, rather than their content. This is extremely difficult to detect because the packets themselves might be entirely innocuous—it's the pattern of when they arrive that carries meaning.
Multi-Stage Malware Architecture
Modern malware rarely operates as a single program. Instead, attacks typically unfold across multiple stages, each simple enough to evade detection while collectively achieving sophisticated objectives.
A typical multi-stage attack might look like:
Stage 0: Initial Compromise The victim receives a phishing email with a malicious link or attachment. Alternatively, they visit a compromised website, plug in an infected USB drive, or experience another initial infection vector. This stage gets a foothold on the system but typically involves minimal malicious code.
Stage 1: Dropper/Loader Execution A small script or executable runs. This is often legitimate functionality being abused—a PowerShell script, a macro in an Office document, or JavaScript in a PDF. This first-stage code is highly obfuscated and performs environment checks:
-
Is this running in a virtual machine? (Check for VMware or VirtualBox artifacts)
-
Is a debugger or analysis tool attached? (Check for common debugging tools)
-
Is antivirus running? (Enumerate running processes)
-
Is there internet connectivity? (Attempt to resolve DNS or connect to a test server)
-
What operating system and version is running? (Check system properties)
-
What language is the system using? (Some malware avoids infecting systems in certain countries)
Based on these checks, the dropper decides whether to proceed. If it detects an analysis environment, it might terminate cleanly to avoid revealing its behavior to researchers. If conditions are favorable, it proceeds to the next stage.
Stage 2: Download Additional Components The dropper contacts a C2 server or download location and retrieves additional components. These might include:
-
The main malware payload customized for the detected operating system
-
Specific modules appropriate for the detected system architecture (32-bit vs 64-bit)
-
Tools for establishing persistence
-
Exploitation tools for elevating privileges if the initial infection is running with limited permissions
This stage often uses legitimate system tools to avoid detection. On Windows, PowerShell, certutil, or bitsadmin might be used to download files. On Linux, wget or curl serve this purpose. Using built-in tools means there's no suspicious network activity from unknown programs.
Stage 3: Establish Persistence Multiple persistence mechanisms are established as described in Stage 3 earlier. This often involves:
-
Creating scheduled tasks or cron jobs
-
Adding registry keys (on Windows)
-
Installing services or launch daemons
-
Modifying legitimate files or configuration
Redundant persistence ensures that if one mechanism is detected and removed, others remain to re-infect the system.
Stage 4: Deploy Final Payload The main malware functionality is deployed. This might be:
-
A sophisticated backdoor or RAT
-
Keylogging and credential-stealing tools
-
Ransomware encryption routines
-
Cryptocurrency mining software
-
Data exfiltration tools
This payload often runs entirely in memory (fileless malware) rather than writing to disk. It's injected into legitimate processes or runs within PowerShell or WMI, making it extremely difficult to detect with traditional file-based antivirus.
Stage 5: Operational Phase Additional modules are downloaded over time as needed:
-
A keylogger module when the user visits banking sites
-
A screenshot tool when sensitive applications are detected
-
Network scanning tools when exploring the internal network
-
Lateral movement tools when attempting to compromise other systems
-
Ransomware when the attackers decide it's time to monetize access
This stage might last days, weeks, months, or even years in sophisticated APT campaigns. The attackers conduct reconnaissance, determine what's valuable, move laterally through the network, and eventually achieve their objectives.
This multi-stage approach has several advantages for attackers:
Evasion: Each component is simple and focused, making it less likely to trigger behavioral detection. The initial dropper might do nothing obviously malicious—it just downloads a file. The downloaded file might be encrypted and only decrypted in memory. The final payload never exists as a file on disk.
Resilience: If one stage is caught and blocked, earlier stages might still succeed. If the main payload is detected and removed, the persistence mechanisms can reinfect. If the initial C2 server is taken down, later stages might use a different C2 infrastructure.
Flexibility: The main payload never touches disk until after the initial defenses have been bypassed. Attackers can update individual stages without reinfecting systems. Different payloads can be delivered to different targets based on reconnaissance.
Analysis Resistance: Analyzing the complete attack requires capturing all stages. A researcher who only gets the first-stage dropper can't fully understand what the attack does. Automated sandboxes might only see the first stage, which appears benign.
Sidebar: The Emotet Infection Chain
Emotet demonstrated a multi-stage architecture taken to an extreme. A typical Emotet infection proceeded as follows:
Stage 1: A phishing email arrives with an attached Word document or Excel spreadsheet. The filename is often related to invoices, shipping notifications, or other business documents to encourage opening. The document contains malicious macros.
Stage 2: When opened, the document displays a message like "This document was created in a newer version of Microsoft Office. To view the content, please enable macros." This is social engineering—the document wasn't created in a newer version, but users often believe this and enable macros without understanding the risk.
Stage 3: The macro executes PowerShell commands that download the Emotet loader from compromised WordPress sites or other web servers. The loader is often named to look like a legitimate file.
Stage 4: The Emotet loader establishes persistence through multiple mechanisms—registry keys, scheduled tasks, and services. It also implements process injection to hide within legitimate Windows processes like explorer.exe or svchost.exe.
Stage 5: Emotet contacts its C2 infrastructure (multiple servers for redundancy) and reports the infection. It sends system information—computer name, domain, installed software, and other reconnaissance data.
Stage 6: Based on commands from C2, Emotet downloads additional modules:
-
An email harvesting module that steals email addresses and content from Outlook and other email clients - A network spreading module that uses techniques like SMB exploitation and brute-force credential attacks to move laterally
-
Browser credential stealing modules
-
A spam module that uses the infected system to send more phishing emails
Stage 7: Emotet serves as a delivery platform for other malware families. It downloads and installs:
-
TrickBot, a banking trojan that steals credentials and provides additional backdoor access
-
Qbot, another banking trojan
-
Eventually, Ryuk ransomware when the attackers decide to monetize the access
This entire infrastructure operated as a malware-as-a-service platform. The Emotet operators sold access to infected systems to other criminal groups, who then deployed their own malware. A single Emotet infection could result in banking credential theft, cryptocurrency wallet theft, and ultimately ransomware—all from different criminal groups working through the Emotet platform.
The Emotet takedown in January 2021 required coordinated action by law enforcement agencies in eight countries, seizing hundreds of servers and disrupting the infrastructure that supported this multi-stage operation.
Modular Malware Design
Modern malware platforms often feature modular architecture similar to legitimate software frameworks. Rather than one monolithic program that does everything, there's a core module that handles basics and a plugin system for additional capabilities.
The core module typically handles:
-
Basic system interaction and Windows/Linux API calls
-
Persistence mechanisms (establishing and maintaining presence)
-
C2 communication (beaconing, command processing, response handling)
-
Module management (loading, updating, and unloading plugins)
-
Self-defense (detecting and evading security software)
-
Process injection (hiding within legitimate processes)
Plugin modules are downloaded as needed and provide specific capabilities:
Keylogger module: Captures typed passwords, messages, and other keyboard input. This module only runs when needed, reducing detection risk.
Screenshot module: Periodically captures screen images for visual surveillance. Useful for capturing virtual keyboards, graphical content, and general user activity.
File stealer module: Searches for and exfiltrates specific files—documents, configuration files, source code, databases. Might target file extensions (.doc, .xls, .pdf) or content patterns (search for "password" or "confidential" within files).
Browser credential stealer: Extracts saved passwords, cookies, and browsing history from Chrome, Firefox, Edge, and other browsers. Modern browsers encrypt saved passwords, but these modules use techniques to decrypt them.
Network scanner module: Discovers other systems on the network, identifies open ports and services, and maps the network topology.
Exploitation tools: Various exploits for compromising other systems on the network or elevating privileges on the current system. These are often kept separate so they can be updated as new exploits are discovered.
Anti-forensics tools: Modules that clear logs, delete evidence, and cover the attacker's tracks.
This modular approach provides significant flexibility:
Customization: Attackers deploy only the modules needed for each specific target. A infection in a home user's system might get keylogger and browser credential stealer modules. An infection in a corporate environment might get network scanner and lateral movement modules. This reduces the footprint and detection risk.
Updates: Individual modules can be updated without touching the core. If a new privilege escalation exploit is discovered, just that module is replaced. If antivirus starts detecting the keylogger module, a new version can be deployed while everything else remains unchanged.
Reduced Initial Footprint: The initial infection only needs to deploy the core module. This is smaller, simpler, and less likely to be detected than a monolithic program containing all functionality. Additional capabilities are added only when needed.
Capability Hiding: Attackers only reveal capabilities when using them. Security researchers who capture the core module don't automatically know all the attacker's capabilities. Each plugin must be captured and analyzed separately.
Both Metasploit (a legitimate penetration-testing framework frequently abused by attackers) and Cobalt Strike (another legitimate red-team tool commonly repurposed for malicious use) exemplify this modular architecture. These frameworks provide a core agent (Meterpreter for Metasploit, Beacon for Cobalt Strike) with dozens of optional modules for different tasks.
Advanced Persistent Threat (APT) groups (typically state-sponsored attackers conducting long-term campaigns) often develop custom modular frameworks specifically tailored to their needs. For instance:
-
The Equation Group (attributed to NSA) used multiple frameworks, including one called "DoubleFantasy" with modular architecture
-
APT29 (Russian state-sponsored) has used multiple frameworks, including "WellMess" and "WellMail" with plugin systems
-
APT28 (also Russian attribution) used the "X-Agent" framework with modular capabilities
These custom frameworks are often discovered years after their initial deployment, suggesting they remained undetected for extended periods precisely because of their modular, flexible design that could be customized for each target.
In the next part, we'll examine how malware actually gets delivered to victims, covering zero-day exploits, trojan horses, supply chain attacks, and the physical attack vectors that bypass network defenses entirely.