Skip to content

Understanding Malware Types

💡
Before you start

Python 3 and a terminal. No malware is downloaded, written or run. macOS and Linux include Python; on Windows install it from python.org with “Add python.exe to PATH” ticked, then check with python3 --version.

The “malicious” files you create below are harmless by construction. They contain the first few bytes real programs begin with, followed by an English sentence; none of them can execute, and your antivirus will ignore them. The purpose is to let you read what a file claims to be and compare it with what it is — a skill that needs no dangerous sample to practise.

What Is Malware?

Malware -- short for malicious software -- is any program or code designed to harm, exploit, or otherwise compromise a computer system without the user's consent. Malware is an umbrella term that covers many distinct types of threats, each with different behaviors, delivery methods, and objectives.

Modern malware ranges from simple nuisance programs that display unwanted advertisements to sophisticated tools used by nation-state actors for espionage and sabotage. Understanding the different categories helps you recognize threats, respond appropriately, and choose effective defenses.

💡
Malware is not just a Windows problem.

While Windows has historically been the most targeted platform due to its market share, malware exists for macOS, Linux, Android, iOS, and even IoT devices. No operating system is immune. Your behavior and security practices matter more than your choice of platform.

Viruses, Worms, and Trojans

Viruses

A virus is malware that attaches itself to a legitimate program or file and spreads when that file is executed or shared. Like a biological virus, it requires a host to propagate. Viruses cannot spread on their own -- they depend on human action such as opening an infected email attachment, running a compromised program, or sharing an infected USB drive.

Viruses can corrupt or delete files, slow down your system, or serve as a delivery mechanism for other malware. Some viruses are polymorphic, meaning they change their code each time they replicate to evade antivirus detection.

Worms

Unlike viruses, worms are self-replicating malware that spread across networks without requiring human interaction. A worm exploits vulnerabilities in operating systems or network protocols to copy itself from one machine to another automatically. This makes worms particularly dangerous -- a single infection can spread to thousands of machines within hours.

The WannaCry attack of 2017 is a notable example. It exploited a vulnerability in Windows SMB protocol to spread across networks automatically, encrypting files on over 200,000 computers in 150 countries within a single day.

Trojans

A Trojan (named after the Trojan Horse of Greek mythology) disguises itself as legitimate software to trick users into installing it. Unlike viruses and worms, Trojans do not replicate themselves. Instead, they rely on social engineering -- the user downloads what they believe is a useful program, game, or utility, but it contains hidden malicious code.

Once installed, Trojans can create backdoors for remote access, steal credentials, download additional malware, or turn your computer into part of a botnet. Remote Access Trojans (RATs) are particularly dangerous because they give attackers full control over the infected system.

⚠️
Pirated software is a primary Trojan delivery vector.

Cracked games, pirated applications, and "free" versions of paid software frequently contain Trojans. The attacker bundles malware with functional software so the victim does not suspect anything is wrong. Always download software from official sources.

Spyware and Adware

Spyware

Spyware secretly monitors your activity and sends the collected information to a third party. It can track your browsing history, capture screenshots, record keystrokes, access your webcam and microphone, and harvest passwords and financial data. Commercial spyware (sometimes called "stalkerware") is also used for domestic surveillance, which is both unethical and illegal in most jurisdictions.

Advanced spyware like Pegasus, developed by the NSO Group, can infect smartphones with zero-click exploits -- meaning no user interaction is needed at all. While tools like Pegasus target high-profile individuals, consumer-grade spyware is widely available and commonly used in harassment and identity theft.

Adware

Adware displays unwanted advertisements on your device, often through browser pop-ups, injected ads on web pages, or system notification spam. While adware is generally less dangerous than other malware types, it degrades your computing experience, slows down your system, and may track your browsing habits to serve targeted ads. Some adware also serves as a gateway for more dangerous malware by redirecting you to malicious websites.

Rootkits and Keyloggers

Rootkits

A rootkit is malware designed to gain and maintain privileged access to a system while hiding its presence from the operating system and security software. Rootkits operate at a very low level -- sometimes embedding themselves in the operating system kernel, the boot sector, or even the firmware of hardware components.

Because rootkits conceal themselves from the OS itself, they are extremely difficult to detect with conventional antivirus tools. Detecting a rootkit often requires booting from external media and scanning the drive offline, or using specialized rootkit detection tools that compare expected system behavior with actual system behavior.

Keyloggers

A keylogger records every keystroke you make and transmits the log to an attacker. This captures passwords, credit card numbers, private messages, and anything else you type. Keyloggers can be software-based (installed as malware) or hardware-based (a small device plugged between your keyboard and computer).

What a keylogger captures:

[2026-03-03 10:15:22] bankofamerica.com
[2026-03-03 10:15:25] TAB john.doe@email.com
[2026-03-03 10:15:28] TAB MyS3cretP@ssw0rd!      <-- Your password, in plaintext
[2026-03-03 10:15:30] ENTER
💡
Hardware keyloggers bypass all software security.

A hardware keylogger is a small device that plugs inline between your keyboard cable and your computer. Because it operates at the hardware level, no antivirus or anti-malware software can detect it. If you use a public or shared computer, visually inspect the keyboard connection before typing anything sensitive.

How Malware Spreads

Understanding malware delivery methods helps you avoid the most common infection vectors. Attackers use a variety of techniques to get malware onto your system.

  • Email attachments -- Infected documents, spreadsheets, or executable files sent as email attachments remain the most common delivery method
  • Malicious downloads -- Software from untrusted sources, pirated content, and fake "free" tools frequently bundle malware
  • Drive-by downloads -- Visiting a compromised or malicious website can trigger automatic malware downloads without your knowledge, exploiting browser vulnerabilities
  • USB drives and removable media -- Infected USB drives can execute malware automatically when plugged in, especially on systems with autorun enabled
  • Network propagation -- Worms and some other malware types spread automatically across networks by exploiting unpatched vulnerabilities
  • Software supply chain attacks -- Attackers compromise legitimate software update mechanisms to distribute malware to all users of that software
  • Malicious ads (malvertising) -- Legitimate advertising networks can unknowingly serve ads containing malicious code

Signs of Infection and Prevention

Signs Your Device May Be Infected

  • Significant slowdown -- Your system is noticeably slower than normal, especially during startup
  • Unexpected pop-ups -- Advertisements or warning messages appearing outside of your browser
  • Unknown programs -- Applications you do not remember installing appear in your program list or taskbar
  • High network activity -- Your internet connection is unusually slow or your data usage spikes for no apparent reason
  • Disabled security tools -- Your antivirus or firewall has been turned off and you cannot re-enable it
  • Unusual account activity -- Emails sent from your account that you did not write, or login attempts you did not make
  • Files changed or missing -- Documents are encrypted, renamed, or deleted without your action

Prevention Best Practices

  • Keep everything updated -- Install operating system, browser, and application updates promptly. Most malware exploits known vulnerabilities that patches have already fixed
  • Use reputable antivirus software -- Keep it running and up to date. Enable real-time scanning
  • Download from official sources only -- Use official app stores, developer websites, and verified package repositories
  • Be cautious with email attachments -- Do not open attachments from unknown senders, and verify unexpected attachments even from known contacts
  • Disable autorun for removable media -- Prevent USB drives from executing code automatically when plugged in
  • Use a standard user account -- Run as a standard user rather than administrator for daily tasks. This limits what malware can do if it executes
  • Enable your firewall -- A properly configured firewall blocks unauthorized network connections
  • Back up your data regularly -- Backups do not prevent infection, but they ensure you can recover without paying ransoms or losing files permanently
⚠️
No single tool provides complete protection.

Antivirus software catches many threats but cannot detect everything, especially zero-day exploits and sophisticated targeted attacks. Defense in depth -- combining multiple layers of protection with good security habits -- is the only reliable strategy.

What to Do If Infected

If you suspect your device is infected with malware, take immediate action to contain the damage and begin the cleanup process.

  • Disconnect from the network -- Unplug your Ethernet cable or disable Wi-Fi to prevent the malware from spreading to other devices or communicating with its command server
  • Do not log in to sensitive accounts -- If a keylogger is active, any credentials you type will be captured
  • Boot into safe mode -- Safe mode loads only essential system services, which may prevent the malware from running
  • Run a full antivirus scan -- Use an updated antivirus tool. Consider using a bootable antivirus rescue disk for thorough scanning
  • Remove detected threats -- Follow your antivirus tool's recommendations for quarantine or removal
  • Change all passwords -- After cleaning the infection, change passwords for all accounts accessed from the infected device, using a different clean device
  • Monitor your accounts -- Watch for unauthorized activity on financial accounts, email, and social media for several weeks after the incident
  • Consider a clean reinstall -- For serious infections, especially rootkits, a complete OS reinstall from clean media is the most reliable way to ensure the malware is fully removed

Find Out What a File Really Is, in Five Steps

Knowing the names of malware families is worth very little on the day something lands in your downloads folder. What decides that day is a different question: is this file what its name says it is, and what is it allowed to do if I open it? In the next twenty minutes you will create files whose names lie, identify them by reading their contents, meet the invisible character that makes an .exe display as a Word document, watch a one-byte change defeat a signature check, and finish with a script you can point at your own Downloads folder. Every line of output below came from running these files.

1
Create four files and read what they actually contain

Go: open a terminal in a folder you can write to — cd ~/Desktop on macOS or Linux, cd %USERPROFILE%\Desktop on Windows.

Do: save this as magic.py and run python3 magic.py. Every file type begins with a short fixed sequence called a magic number; it is written by whatever program created the file, and renaming the file does not touch it.

"""What a file IS, versus what its name claims."""
import os

os.makedirs("samples", exist_ok=True)

SAMPLES = {
    "invoice.pdf":       b"%PDF-1.7\n1 0 obj\n<< /Type /Catalog >>",
    "holiday-photo.jpg": b"MZ\x90\x00\x03\x00\x00\x00This is a Windows program.",
    "accounts.xlsx":     b"PK\x03\x04\x14\x00\x06\x00 (a zip container)",
    "readme.txt":        b"Just text, nothing clever.",
}

MAGIC = [
    (b"%PDF-",      "PDF document"),
    (b"MZ",         "Windows executable (.exe/.dll)"),
    (b"PK\x03\x04", "ZIP container (.zip/.docx/.xlsx)"),
    (b"\x7fELF",    "Linux executable"),
]

for name, data in SAMPLES.items():
    open(os.path.join("samples", name), "wb").write(data)

print("%-22s %-10s %s" % ("NAME ON DISK", "CLAIMS", "ACTUALLY IS"))
print("-" * 66)
for name in SAMPLES:
    head = open(os.path.join("samples", name), "rb").read(8)
    kind = next((k for sig, k in MAGIC if head.startswith(sig)), "plain data")
    ext = os.path.splitext(name)[1]
    warn = "  <-- LIES" if (ext == ".jpg" and "executable" in kind) else ""
    print("%-22s %-10s %s%s" % (name, ext, kind, warn))
print()
print("Four files written to samples/. Only the last column was read from")
print("the file itself; the other two were read from its name.")

You should see: one of the four disagreeing with its own name:

NAME ON DISK           CLAIMS     ACTUALLY IS
------------------------------------------------------------------
invoice.pdf            .pdf       PDF document
holiday-photo.jpg      .jpg       Windows executable (.exe/.dll)  <-- LIES
accounts.xlsx          .xlsx      ZIP container (.zip/.docx/.xlsx)
readme.txt             .txt       plain data

Four files written to samples/. Only the last column was read from
the file itself; the other two were read from its name.

The samples are harmless — holiday-photo.jpg contains the two letters MZ and a sentence, not a real program. But those two letters are what Windows reads to decide something is executable, and they are what your eye never sees. The extension is a hint written by whoever named the file, and whoever named the file may be the attacker.

If not: PermissionError means the folder is not writable — cd somewhere you own first. If the <-- LIES marker does not appear, the byte string for holiday-photo.jpg lost its MZ prefix when copying; it must be the first two characters inside the quotes.

2
Meet the character that moves the extension

Go: the same folder.

Do: save this as rlo.py and run python3 rlo.py. There is a Unicode character whose only job is to reverse the direction of the text after it — it exists for legitimate Arabic and Hebrew typesetting.

"""One invisible character, and the extension appears to move."""

RLO = "\u202e"                    # RIGHT-TO-LEFT OVERRIDE, an invisible character

real = "salary" + RLO + "cod.exe"    # what is actually stored on disk

def as_displayed(name):
    """What a file manager draws: everything after the override, reversed."""
    if RLO not in name:
        return name
    before, after = name.split(RLO, 1)
    return before + after[::-1]

print("stored on disk :", repr(real))
print("characters     :", len(real))
print("really ends in :", real[real.rindex("."):])
print()
print("drawn on screen:", as_displayed(real))
print("looks like it  :", "is a Word document")
print()
print("codepoints after 'salary':")
for ch in real[6:]:
    label = "RIGHT-TO-LEFT OVERRIDE  <-- invisible" if ch == RLO else ""
    print("    U+%04X  %s %s" % (ord(ch), repr(ch), label))

You should see: a file that ends .exe being drawn as a document:

stored on disk : 'salary\u202ecod.exe'
characters     : 14
really ends in : .exe

drawn on screen: salaryexe.doc
looks like it  : is a Word document

codepoints after 'salary':
    U+202E  '\u202e' RIGHT-TO-LEFT OVERRIDE  <-- invisible
    U+0063  'c' 
    U+006F  'o' 
    U+0064  'd' 
    U+002E  '.' 
    U+0065  'e' 
    U+0078  'x' 
    U+0065  'e' 

The character is written here as \u202e so that it stays visible on this page. In a filename it occupies no width at all: there is nothing to notice, no odd spacing, no strange glyph. Your file manager is not malfunctioning when it shows salaryexe.doc — it is correctly rendering text that was deliberately constructed to be read backwards.

This is worth knowing about because it defeats the one habit most people do have: glancing at the end of the filename.

If not: if drawn on screen prints the same thing as stored on disk, the RLO constant lost its backslash and became the literal text u202e; it must read "\u202e". The repr() output showing \u202e is correct — that is Python telling you the character is non-printing.

3
Defeat a signature check with a single byte

Go: the same folder.

Do: save this as signature.py and run python3 signature.py.

"""Why a list of known-bad hashes is necessary but never sufficient."""
import hashlib

original = b"MZ\x90\x00 evil payload: steal passwords and phone home"
BLOCKLIST = {hashlib.sha256(original).hexdigest()}

def scan(sample):
    h = hashlib.sha256(sample).hexdigest()
    return h, ("BLOCKED - known malware" if h in BLOCKLIST else "allowed - not on the list")

print("the sample the vendor analysed:")
h, verdict = scan(original)
print("   sha256", h[:24], "...", verdict)

print()
print("the same program with one harmless byte appended:")
variant = original + b"\x00"
h, verdict = scan(variant)
print("   sha256", h[:24], "...", verdict)

print()
print("behaviour identical. Detection: gone.")
print("changed bytes:", len(variant) - len(original), "of", len(original))

You should see: the identical program blocked and then allowed:

the sample the vendor analysed:
   sha256 600c4e3523028ca2d70d1e96 ... BLOCKED - known malware

the same program with one harmless byte appended:
   sha256 be0c565c1d99d3e6b1c58bfc ... allowed - not on the list

behaviour identical. Detection: gone.
changed bytes: 1 of 49

A hash changes completely when any byte changes — that is what makes hashes useful for detecting tampering, and useless as the only way to detect malware. Appending a zero byte took no skill and produced a file that behaves identically and matches nothing on any list.

The conclusion is not that antivirus is pointless. Signature matching stops the enormous volume of unmodified, recycled malware cheaply and instantly, which is real value. It is that a clean scan means “not recognised”, never “safe” — which is why modern products also watch what a program does after it starts.

If not: if both lines print the same hash, variant was assigned original without the appended byte — the + b"\x00" is the whole experiment. Your hex digits will match those above exactly, because nothing here is random.

4
Sort files by what they can do, not by what they are called

Go: the same folder. This is the classification that actually helps.

Do: save this as capability.py and run it.

"""Ask what a file is ALLOWED to do, not what it is called."""

FILES = [
    ("report.pdf",       "PDF document",        False, "renders; may embed a link you must click"),
    ("report.docm",      "Word, macro-enabled", True,  "runs code the moment macros are enabled"),
    ("setup.exe",        "Windows executable",  True,  "runs code with your full user rights"),
    ("invoice.iso",      "disc image",          True,  "mounts as a drive; hides what is inside"),
    ("photo.jpg",        "JPEG image",          False, "decoded by an image library"),
    ("script.lnk",       "Windows shortcut",    True,  "can point at PowerShell with arguments"),
    ("archive.zip",      "ZIP container",       False, "harmless until you open what is inside"),
]

print("%-14s %-22s %-9s %s" % ("FILE", "TYPE", "CAN RUN?", "WHAT HAPPENS WHEN YOU OPEN IT"))
print("-" * 96)
for name, kind, runs, effect in FILES:
    print("%-14s %-22s %-9s %s" % (name, kind, "YES" if runs else "no", effect))

runners = [f[0] for f in FILES if f[2]]
print()
print("files that can execute code:", ", ".join(runners))
print()
print("Notice .lnk and .iso -- neither looks like a program, and both are")
print("common precisely because they are not what people are told to fear.")

You should see: four of the seven able to execute code:

FILE           TYPE                   CAN RUN?  WHAT HAPPENS WHEN YOU OPEN IT
------------------------------------------------------------------------------------------------
report.pdf     PDF document           no        renders; may embed a link you must click
report.docm    Word, macro-enabled    YES       runs code the moment macros are enabled
setup.exe      Windows executable     YES       runs code with your full user rights
invoice.iso    disc image             YES       mounts as a drive; hides what is inside
photo.jpg      JPEG image             no        decoded by an image library
script.lnk     Windows shortcut       YES       can point at PowerShell with arguments
archive.zip    ZIP container          no        harmless until you open what is inside

files that can execute code: report.docm, setup.exe, invoice.iso, script.lnk

Notice .lnk and .iso -- neither looks like a program, and both are
common precisely because they are not what people are told to fear.

Most advice reduces to “do not open .exe files”, and almost nobody is caught by an .exe any more. The two rows worth memorising are .lnk and .iso: a shortcut is a tiny file that can launch PowerShell with whatever arguments the attacker chose, and a disc image mounts as a drive, which historically stripped the warning a downloaded file would otherwise carry.

The useful question is therefore not “is this file type dangerous” but “does opening this hand control to somebody else”. A macro-enabled document does. A PDF mostly does not — it asks you to click a link instead, which is why so much phishing arrives as a perfectly genuine PDF.

If not: if the table wraps awkwardly, widen the terminal — the rows are 96 characters. The summary line beneath it contains the same information.

5
Point the check at a real folder

Go: the same folder. Step 1 left four files in samples/.

Do: save this as checkdir.py and run python3 checkdir.py samples. It reports only the disagreements, so silence is a good result.

"""Point this at a real folder and let it disagree with the names."""
import os, sys

MAGIC = [
    (b"%PDF-",      "PDF document"),
    (b"MZ",         "Windows executable"),
    (b"PK\x03\x04", "ZIP container (.zip/.docx/.xlsx)"),
    (b"\x7fELF",    "Linux executable"),
    (b"\xff\xd8\xff", "JPEG image"),
    (b"\x89PNG",    "PNG image"),
]
EXPECTED = {".pdf": "PDF document", ".jpg": "JPEG image", ".jpeg": "JPEG image",
            ".png": "PNG image", ".zip": "ZIP container (.zip/.docx/.xlsx)",
            ".docx": "ZIP container (.zip/.docx/.xlsx)",
            ".xlsx": "ZIP container (.zip/.docx/.xlsx)"}

folder = sys.argv[1] if len(sys.argv) > 1 else "."
suspicious = 0
for name in sorted(os.listdir(folder)):
    path = os.path.join(folder, name)
    if not os.path.isfile(path):
        continue
    head = open(path, "rb").read(8)
    kind = next((k for sig, k in MAGIC if head.startswith(sig)), "plain data / unknown")
    ext = os.path.splitext(name)[1].lower()
    if "\u202e" in name:
        print("%-24s NAME CONTAINS A RIGHT-TO-LEFT OVERRIDE" % name)
        suspicious += 1
    elif ext in EXPECTED and EXPECTED[ext] != kind:
        print("%-24s says %-6s but is %s" % (name, ext, kind))
        suspicious += 1

print()
print("files checked in %s: %d" % (folder, sum(1 for n in os.listdir(folder)
                                               if os.path.isfile(os.path.join(folder, n)))))
print("names that disagree with their contents:", suspicious)

You should see: the one planted mismatch, and nothing else:

holiday-photo.jpg        says .jpg   but is Windows executable

files checked in samples: 4
names that disagree with their contents: 1

Now run it against a folder that matters: python3 checkdir.py ~/Downloads on macOS or Linux, or python3 checkdir.py %USERPROFILE%\Downloads on Windows. Most people find nothing, which is the correct and boring outcome — and worth doing once, because a tool you have never run on real data is a tool you do not know works.

Then do the thing that helps every day rather than once: turn on file extensions permanently. On Windows, in File Explorer, open the View menu and tick File name extensions. On macOS, in Finder, open Settings → Advanced and tick Show all filename extensions. Both are off by default, which is why invoice.pdf.exe is displayed to most people as invoice.pdf.

If not: FileNotFoundError means samples/ is not in the folder you are standing in — run python3 magic.py first, since that is what creates it. If your Downloads scan reports a .docx as a ZIP container, that is correct and not a finding: modern Office documents genuinely are ZIP archives, which is why the script treats that as the expected type.

🎉
Check yourself before moving on

Without scrolling up: a colleague forwards an attachment, your antivirus scans it and reports it clean, and the file is called Q3-figures.xlsx. Name two things that result still leaves open, and say what you would check. Answer: first, a clean scan means the file matched nothing known — step 3 showed that one appended byte removes a file from every signature list while changing nothing about what it does, so “clean” is “unrecognised”. Second, the name proves nothing about the contents: the extension is text chosen by whoever created the file, and step 2 showed the visible ending can be reversed by an invisible character. What to check is what it actually is — run the folder scanner over it — and then what it is allowed to do: a genuine .xlsx is a ZIP container that cannot execute anything, whereas the macro-enabled .xlsm and .docm forms can. And the check no software performs: whether your colleague actually sent it, asked on a channel other than the one it arrived on.

Now do it without the page: add two more magic numbers to checkdir.py — GIF, which begins GIF8, and RAR, which begins Rar! — then create a file that lies about being a GIF and confirm your scanner catches it. Then answer the question the code cannot: on the computer you are using now, are file extensions visible? If you do not know, you have just found the most valuable five-second change on this page.

Summary

Malware is a broad category of threats that includes many distinct types, each with different behaviors and risks. Understanding what you are facing helps you respond effectively.

  • Viruses attach to files and require human action to spread
  • Worms self-replicate across networks without user interaction
  • Trojans disguise themselves as legitimate software to trick you into installing them
  • Spyware secretly monitors your activity and steals personal data
  • Rootkits hide deep in your system to maintain persistent, undetectable access
  • Keyloggers capture everything you type, including passwords and financial information
  • Prevention requires keeping software updated, using antivirus, downloading from official sources, and practicing caution with email and removable media
  • If infected, disconnect from the network, scan thoroughly, change passwords from a clean device, and consider a full reinstall for severe infections
🎉
Knowledge is your best antivirus.

Technical defenses are essential, but understanding how malware works and how it reaches you is what prevents infection in the first place. Most malware relies on user mistakes -- and informed users make far fewer of them.