These are the notes for Cybersecurity Fundamentals (defensive), episode 5. Last time, in the kill chain, the attacker planted a program at step 5 that stayed and called home. Today: what are those programs, and how do defenders stop each kind? Malware is short for malicious software: any program written to harm you, spy on you, or take control of your computer. You'll invent each family by breaking a small Python program and fixing it: virus vs worm and patching, trojans, droppers and loaders, ransomware, wipers and offline backups, spyware, adware, keyloggers and RATs, rootkits, bootkits, fileless malware and living off the land (LOLBins), botnets, command and control (C2) and cryptojackers, logic bombs, and finally how antivirus signatures work and why polymorphism beats them. Every term is explained the first time it appears, and the Glossary at the end defines them all again.
Safety note: every "malware" here is a harmless toy simulation: Python dictionaries and strings on made-up data. Nothing runs, spreads or touches a real system. Every code sample runs as-is; outputs are real (Python 3).
The problems you'll solve
| Problem | Idea it teaches |
|---|---|
| Something spread across the office overnight, with no clicks | Virus vs worm, patching |
| A free game that does something else too | Trojan, payload, dropper, loader |
| "We have a backup", but the backup is locked too | Ransomware, wiper, 3-2-1 offline backups |
| Someone is watching | Spyware, keylogger, RAT, adware |
| The antivirus sees nothing | Rootkit, bootkit, fileless malware, LOLBins |
| 10,000 cameras obey one stranger | Bot, botnet, C2, beaconing, cryptojacker |
| Code that waits for a date | Logic bomb (time bomb) |
| A mutated copy scans clean | Signatures, polymorphism, behaviour detection, EDR |
Problem 1: virus vs worm
Think of a cold spreading in a hostel:
| In a hostel | In computers | Meaning |
|---|---|---|
| Germs on a shared cup: you catch them only if you use the cup | Virus | Attaches itself to a normal file or program (its host) and spreads only when a person runs that file, e.g. an infected file on a pen drive |
| Germs floating in the air: you catch them just by being there | Worm | A standalone program that copies itself from computer to computer over the network, with nobody clicking anything |
| A vaccine | Patch | An update that fixes the hole (vulnerability) the worm uses to get in |
Demo 1: a worm on a toy network
# six office PCs, and which ones each can reach
links = {"A": ["B", "C"], "B": ["D"], "C": ["E"],
"D": ["F"], "E": [], "F": []}
def worm(start, patched): # copies itself, no clicks
infected, todo = set(), [start]
while todo:
pc = todo.pop()
if pc in infected or pc in patched:
continue
infected.add(pc)
todo += links[pc] # try every neighbour
return sorted(infected)
print("no patches: ", worm("A", set()))
print("B, C patched:", worm("A", {"B", "C"}))
Output:
no patches: ['A', 'B', 'C', 'D', 'E', 'F']
B, C patched: ['A']
todo is a to-do list of PCs to try; todo.pop() takes one off; todo += links[pc] adds all its neighbours. No person ever clicks. Two patches stopped five infections: worms need unpatched neighbours.
Worms in real life
- Morris worm, 2 November 1988. Released from the MIT network by Robert Tappan Morris, then a Cornell graduate student. It is commonly reported to have hit around 6,000 UNIX machines, and it led DARPA to fund CERT/CC at Carnegie Mellon, the first computer emergency response team (a team that coordinates responses to security incidents).
- WannaCry, 12 May 2017. A ransomware worm: it locked files and spread by itself, using the EternalBlue exploit against Microsoft's SMB file-sharing protocol. Estimates range from about 200,000 (Europol) to more than 300,000 computers in 150 countries. Up to 70,000 devices in the UK's NHS may have been affected. It was slowed when researcher Marcus Hutchins registered a kill-switch domain hardcoded in it.
- The painful part: Microsoft's patch for that hole, MS17-010, was released on 14 March 2017, about two months earlier. Victims simply hadn't installed it. Most worms use known holes: patch fast, especially network-facing services.
An exploit (episode 1) is a technique or piece of code that takes advantage of a vulnerability. A protocol is an agreed set of rules for how computers talk; SMB is Windows' file-sharing protocol.
Problem 2: trojans, droppers and loaders
The old Greek story: an army can't break into Troy, so it leaves a beautiful wooden horse as a "gift", and the city pulls it inside.
| The story | In computers | Meaning |
|---|---|---|
| A wooden horse, a gift | Trojan | A program that looks useful (a free game, a cracked app) but also does something harmful. It doesn't spread by itself: you install it |
| Soldiers hidden inside | Payload / Dropper | The payload is the harmful part of any malware. A dropper carries the payload inside itself and drops it onto your computer |
| A signal to the army outside | Loader | A small first program that downloads the real payload later from the internet; small, so it looks innocent |
Defence: install software only from official stores and vendors, never "cracked" versions; application allowlisting (only approved programs may run).
Problem 3: ransomware, wipers and backups
A shop backs up to a sync folder: every change is copied instantly to the cloud. Then ransomware arrives: it locks every file, usually by encrypting it (scrambling it so only a secret key can unscramble it), and a note demands payment. Ransom means money paid to free something. The backup? Locked too.
Demo 2: why the sync folder failed
files = {"bill.xlsx": "data", "pics.zip": "data"}
synced = files # "backup" = a live sync folder
offline = dict(files) # a copy on an unplugged drive
def toy_ransomware(d): # just overwrites text
for name in d:
d[name] = "LOCKED"
toy_ransomware(files)
print("files: ", files)
print("synced: ", synced)
print("offline:", offline)
Output:
files: {'bill.xlsx': 'LOCKED', 'pics.zip': 'LOCKED'}
synced: {'bill.xlsx': 'LOCKED', 'pics.zip': 'LOCKED'}
offline: {'bill.xlsx': 'data', 'pics.zip': 'data'}
In Python, synced = files doesn't copy: both names point to the same dictionary, exactly like a sync folder mirrors every change. dict(files) makes a real, separate copy. Only the copy the attacker couldn't reach survived.
Ransomware, wipers and the 3-2-1 rule
- Ransomware locks files and demands payment. WannaCry asked for about US$300 in Bitcoin, rising to US$600 after a few days.
- A wiper looks similar but simply destroys data; no key exists even if you pay. Its goal is disruption.
- A sync is not a backup: it copies the damage instantly.
- 3-2-1 rule: 3 copies of your data, on 2 different kinds of storage, with 1 copy offsite (in another place).
- Keep at least one copy offline (unplugged) or immutable (locked so it can't be changed or deleted for a period), and test restoring it. A backup you've never restored is only a hope.
Problem 4: malware that watches
| In your house | On your computer | Meaning |
|---|---|---|
| A hidden camera | Spyware | Secretly collects your data: messages, location, browsing |
| Someone noting every key you press | Keylogger | Records keystrokes, so it catches every password you type |
| A stranger holding your TV remote | RAT (remote access trojan) | Gives the attacker full remote control: files, screen, even the webcam |
| Flyers stuffed in your door daily | Adware | Floods you with ads; annoying, and the ads often lead to scams |
Defence: install apps only from trusted stores, check the permissions an app asks for, keep the system updated, and use phishing-resistant sign-in (episode 29) so a stolen password alone isn't enough.
Problem 5: malware that hides
| A bank robbery | In computers | Meaning |
|---|---|---|
| The thief replaces the CCTV feed with an old video | Rootkit | Changes the operating system itself so that when the system or antivirus looks, the malware isn't listed |
| The thief hides inside before the guard's shift starts | Bootkit | Starts during boot (when the computer starts up), before the operating system loads, so it runs before any protection |
| The thief brings no tools and uses the bank's own | Living off the land | Using programs already built into the system, such as PowerShell; those programs are called LOLBins (living-off-the-land binaries; a binary is a program file) |
The operating system (OS) is the main software that runs the computer (Windows, Linux, macOS, Android).
Fileless malware combines these ideas: it runs only in memory (RAM, the computer's short-term working space) and leaves no file on disk, often using LOLBins like PowerShell. No file means nothing for a traditional file scanner to scan.
Defence: watch behaviour (episode 4's indicators of attack), and use secure boot, a feature that checks that only trusted, signed code runs during start-up, which catches bootkits.
Problem 6: botnets, C2 and cryptojackers
Thousands of home security cameras still use default passwords and are never updated. Malware takes them over quietly. Each infected device is a bot; it checks in with the attacker's command and control (C2) server every minute: "any orders for me?". One day the order comes: everyone, flood this website with traffic. Ten thousand devices at once, and the site goes down (a DDoS, distributed denial of service: overwhelming a service with traffic from many machines; episode 23). A network of bots under one controller is a botnet.
Demo 3: spotting a bot by its heartbeat
# time (seconds) of each connection this PC made
log = {"updates.example.com": [0, 3600, 9100],
"x9k2.example.net": [0, 60, 120, 180, 240, 300]}
for host, times in log.items():
gaps = {b - a for a, b in zip(times, times[1:])}
beacon = len(gaps) == 1 and len(times) > 4
print(f"{host:20} gaps={sorted(gaps)}",
"<- BEACON?" if beacon else "")
Output:
updates.example.com gaps=[3600, 5500]
x9k2.example.net gaps=[60] <- BEACON?
zip(times, times[1:]) pairs each time with the next one, so b - a is the gap. Putting the gaps in a set {...} removes duplicates: one unique gap means perfectly regular. A regular heartbeat to the same host is called beaconing, a classic sign of a bot calling its C2 server.
Bots, botnets, C2 and cryptojacking
- Bot: an infected device that takes orders.
- Botnet: many bots with one controller.
- C2 (command and control): the server that sends the orders.
- Cryptojacker: malware that secretly uses your processor to mine cryptocurrency (do heavy calculations that earn digital money) for the attacker, while you pay the electricity bill. Signs: the device is hot and slow, the fan is loud, odd network traffic.
- Defence: change default passwords, update devices, and watch outbound traffic for beacons.
Problem 7: a logic bomb
Found in a code review (not run, it's a picture of the idea):
def nightly_job(today, staff):
run_payroll(staff)
# looks like normal cleanup...
if today >= date(2026, 12, 31) and "ravi" not in staff:
delete_all_records() # the bomb
A logic bomb is code that does damage only when a condition becomes true; a date-based one is also called a time bomb. It works perfectly for months, then fires. Defence: code review (a second person reads every change: separation of duties again), and removing access when people leave.
Problem 8: how antivirus works
| At the airport | In antivirus | Meaning |
|---|---|---|
| A wanted poster with a face | Signature | A short pattern of bytes (the raw contents of a file) taken from known malware |
| A criminal in a new disguise | Polymorphism | Malware that changes its own bytes with every copy (poly = many, morph = shape) |
| Officers watching behaviour | Behaviour detection | Judging what a program does, not what it looks like |
Demo 4: a signature scanner
SIGNATURES = {b"EVIL_LOOP_v1": "Toy.Trojan.A"}
def scan(name, data):
for sig, label in SIGNATURES.items():
if sig in data:
return f"{name}: DETECTED {label}"
return f"{name}: clean"
print(scan("game.exe", b"..EVIL_LOOP_v1.."))
print(scan("game2.exe", b"..EVIL_LOOP_v2..")) # mutated
Output:
game.exe: DETECTED Toy.Trojan.A
game2.exe: clean
One changed byte, and the signature misses it. Signatures are fast and precise, but only for what they have already seen. (Real antivirus also uses hashes, smarter patterns, unpacking and emulation, but the weakness is the same.)
Demo 4b: behaviour detection
# behaviour: what each program did in one minute
seen = {"game2.exe": (950, ".locked"), # files changed,
"editor.exe": (3, None)} # new extension
for name, (changed, ext) in seen.items():
bad = changed > 100 and ext is not None
print(f"{name:10}", "STOPPED" if bad else "ok")
Output:
game2.exe STOPPED
editor.exe ok
Changing hundreds of files and renaming them to .locked looks like ransomware, whatever its bytes are. Modern antivirus and EDR (endpoint detection and response) tools combine signatures (for the known) with behaviour (for the new). An endpoint is any device people use: a laptop, desktop, phone or server.
Common mistakes (and what they print)
| Mistake | Real output | Why | Fix |
|---|---|---|---|
patched = set() ("update later") |
no patches: ['A', 'B', 'C', 'D', 'E', 'F'] |
Worms use known, unpatched holes | Patch fast, especially network services |
synced = files ("that's our backup") |
synced: {'bill.xlsx': 'LOCKED', ...} |
A sync copies the damage instantly | 3-2-1 with one offline copy, tested |
| Signatures only | game2.exe: clean |
Mutated malware has new bytes | Add behaviour detection (EDR) |
Camera password left as admin |
x9k2.example.net gaps=[60] <- BEACON? |
Default passwords recruit bots | Change defaults, update devices |
| Installing a "cracked" app | (a trojan, installed by you) | Trojans need you to run them | Official stores and vendors only |
Mini project: a 3-2-1 backup checker
copies = [("laptop", "ssd", "home", "online"),
("cloud sync folder", "cloud", "remote", "online"),
("USB drive, drawer", "usb", "home", "offline")]
checks = {
"3 copies": len(copies) >= 3,
"2 kinds of media": len({c[1] for c in copies}) >= 2,
"1 offsite": any(c[2] == "remote" for c in copies),
"1 offline": any(c[3] == "offline" for c in copies),
}
for rule, ok in checks.items():
print(f"{rule:17} {'OK' if ok else 'MISSING'}")
Output:
3 copies OK
2 kinds of media OK
1 offsite OK
1 offline OK
Try removing the USB drive: two rules turn to MISSING. Remember the last rule the code can't check: test a restore.
Practice
- In Demo 1, patch only
D. Predict who gets infected, then run it. What if onlyAis patched? - Add a host with connection times
[0, 59, 120, 180, 241, 300]to Demo 3. Is it still flagged? If not, change the rule so small random variations (called jitter) don't hide a beacon. - Add a second signature
b"LOCK_ALL_FILES": "Toy.Ransom.B"and a third file to Demo 4. - Name the family: (a) a "free PDF converter" that also installs a remote-control tool; (b) your laptop fan runs at full speed all day and a strange process uses 95% CPU; (c) the task manager shows nothing, but the network shows traffic from a hidden program; (d) every file renamed to
.lockedwith a payment note. - A company's only backup is a cloud sync folder. Write three changes that would make it ransomware-proof.
Solutions
1.
links = {"A": ["B", "C"], "B": ["D"], "C": ["E"],
"D": ["F"], "E": [], "F": []}
def worm(start, patched):
infected, todo = set(), [start]
while todo:
pc = todo.pop()
if pc in infected or pc in patched:
continue
infected.add(pc)
todo += links[pc]
return sorted(infected)
print("only D patched:", worm("A", {"D"}))
print("only A patched:", worm("A", {"A"}))
Output:
only D patched: ['A', 'B', 'C', 'E']
only A patched: []
Patching D also protects F, because F is only reachable through D. Patching the starting machine stops everything.
- With the original rule, the gaps are
{59, 60, 61}: three unique values, so it isn't flagged. A tolerance fixes that:
log = {"updates.example.com": [0, 3600, 9100],
"x9k2.example.net": [0, 60, 120, 180, 240, 300],
"jitter.example.org": [0, 59, 120, 180, 241, 300]}
for host, times in log.items():
gaps = [b - a for a, b in zip(times, times[1:])]
beacon = len(gaps) >= 4 and max(gaps) - min(gaps) <= 5
print(f"{host:20} gaps={gaps}", "<- BEACON?" if beacon else "")
Output:
updates.example.com gaps=[3600, 5500]
x9k2.example.net gaps=[60, 60, 60, 60, 60] <- BEACON?
jitter.example.org gaps=[59, 61, 60, 61, 59] <- BEACON?
3.
SIGNATURES = {b"EVIL_LOOP_v1": "Toy.Trojan.A",
b"LOCK_ALL_FILES": "Toy.Ransom.B"}
def scan(name, data):
for sig, label in SIGNATURES.items():
if sig in data:
return f"{name}: DETECTED {label}"
return f"{name}: clean"
print(scan("game.exe", b"..EVIL_LOOP_v1.."))
print(scan("invoice.exe", b"..LOCK_ALL_FILES.."))
print(scan("notes.txt", b"buy milk"))
Output:
game.exe: DETECTED Toy.Trojan.A
invoice.exe: DETECTED Toy.Ransom.B
notes.txt: clean
- (a) trojan carrying a RAT; (b) cryptojacker; (c) rootkit (hiding itself from the system's own tools); (d) ransomware.
- Add a true backup with versioning (older versions kept), keep one copy offline or immutable, follow 3-2-1, and test restores regularly. Also limit who can delete backups (least privilege).
Quick quiz
A program spread to 300 PCs in one night. Nobody opened a file or clicked a link. It used an unpatched hole in a network service. It is most likely a...
A. trojan · B. worm · C. keylogger · D. logic bomb
Answer
B, a worm. It spreads by itself over the network with no user action. A trojan needs you to install it. The defence is the patch.
Interview questions
- Virus vs worm vs trojan? A virus attaches to a host file and spreads when a person runs it; a worm is standalone and spreads itself over the network; a trojan pretends to be useful software and is installed by the victim.
- How would you protect an organisation against ransomware? Patch quickly, least privilege, email and web filtering, EDR with behaviour detection, network segmentation, MFA, and offline/immutable 3-2-1 backups with tested restores and an incident response plan.
- Ransomware vs wiper? Ransomware encrypts and demands payment (a key exists); a wiper destroys data with no recovery, aimed at disruption.
- What is a rootkit and how is it detected? Malware that modifies the OS to hide itself. Detect with secure boot, integrity checking, scanning from outside the running OS, and behaviour/network anomalies; the usual fix is a rebuild.
- What is fileless malware / living off the land? Malware that runs in memory and abuses built-in tools (LOLBins like PowerShell) instead of dropping files; detected by behaviour, script logging and EDR.
- What is a botnet and what is C2? A network of infected devices controlled by one operator through a command-and-control server; detected by beaconing, unusual outbound connections and known-bad destinations.
- How do antivirus signatures work, and what are their limits? They match known byte patterns or hashes; fast and precise for known malware but miss new or polymorphic variants, so they are combined with heuristics and behaviour detection (EDR).
- Dropper vs loader? A dropper carries the payload inside itself; a loader downloads it later.
Glossary
| Term | Meaning in plain words | Example |
|---|---|---|
| Malware | Malicious software: any program written to harm, spy or take control | Viruses, worms, ransomware |
| Virus | Malware that attaches to a host file and spreads when a person runs it | An infected file on a pen drive |
| Host (file) | The normal file a virus attaches itself to | A program or document |
| Worm | Malware that copies itself over the network with no clicks | Morris worm, WannaCry |
| Patch | An update that fixes a vulnerability | MS17-010 |
| Exploit | Code or a technique that takes advantage of a vulnerability | EternalBlue |
| Protocol | Agreed rules for how computers talk | SMB, HTTP |
| SMB | Server Message Block, Windows' file-sharing protocol | Used by WannaCry to spread |
| CERT / CERT/CC | A computer emergency response team that coordinates incident response | Founded after the Morris worm |
| Kill switch | A hidden condition that stops malware when triggered | WannaCry's domain check |
| Trojan | Malware disguised as useful software that you install | A "free" game with a hidden extra |
| Payload | The harmful part of a piece of malware | The code that steals or locks |
| Dropper | Malware that carries its payload inside and drops it | The horse with soldiers inside |
| Loader | A small program that downloads the real payload later | A signal to the army outside |
| Ransomware | Malware that locks (encrypts) files and demands payment | WannaCry |
| Encrypt | Scramble data so only a secret key can unscramble it | Episode 10 |
| Ransom | Money demanded to free something | US$300 in Bitcoin |
| Wiper | Malware that destroys data with no recovery | Disruption, not money |
| Sync folder | A folder that mirrors every change to another place instantly | Copies the damage too |
| 3-2-1 rule | 3 copies, 2 kinds of storage, 1 offsite | Laptop, cloud, USB drive |
| Offline / immutable backup | A copy that can't be reached or changed | An unplugged drive |
| Spyware | Malware that secretly collects your data | Reads messages, tracks location |
| Keylogger | Malware that records keystrokes | Captures passwords |
| RAT | Remote access trojan: gives full remote control | Webcam, files, screen |
| Adware | Software that floods you with ads | Pop-ups leading to scams |
| Operating system (OS) | The main software that runs a computer | Windows, Linux, Android |
| Rootkit | Malware that changes the OS to hide itself | Not listed in task manager |
| Boot | The start-up process of a computer | Power on to login screen |
| Bootkit | Malware that starts before the operating system | Runs before protections |
| Secure boot | Checks that only trusted code runs during start-up | Catches bootkits |
| Binary | A program file | powershell.exe |
| Living off the land | Using tools already built into the system | Abusing PowerShell |
| LOLBins | Living-off-the-land binaries: built-in programs attackers abuse | PowerShell, certutil |
| Memory (RAM) | The computer's short-term working space | Cleared on restart |
| Fileless malware | Malware that runs only in memory, no file on disk | Uses LOLBins |
| Bot | An infected device that takes orders | A hijacked camera |
| Botnet | Many bots with one controller | 10,000 cameras |
| Command and control (C2) | The server that sends orders to bots or implants | x9k2.example.net |
| Beaconing | Regular check-ins to the same host | Every 60 seconds |
| Jitter | Small random variation in timing, used to hide beacons | 59, 61, 60 seconds |
| DDoS | Distributed denial of service: flooding a service from many machines | Episode 23 |
| Cryptojacker | Malware that mines cryptocurrency with your computer | Hot, slow, loud fan |
| Mining (crypto) | Heavy calculations that earn cryptocurrency | Uses lots of CPU |
| Logic bomb | Code that does damage when a condition becomes true | Fires if Ravi leaves |
| Time bomb | A logic bomb triggered by a date | After 31 Dec 2026 |
| Code review | A second person reads every change before it ships | Catches logic bombs |
| Antivirus | Software that detects and removes malware | Signature + behaviour |
| Signature | A byte pattern or hash from known malware | EVIL_LOOP_v1 |
| Bytes | The raw contents of a file | b"..EVIL_LOOP_v1.." |
| Polymorphism | Malware changing its own bytes with each copy | v1 → v2 |
| Behaviour detection | Judging what a program does | 950 files changed in a minute |
| Heuristics | Rules of thumb that score suspicious traits | "renames many files" |
| EDR | Endpoint detection and response: watches devices' behaviour and responds | Stops game2.exe |
| Endpoint | Any device people use | Laptop, phone, server |
Summary
- Malware = malicious software. A virus needs a person; a worm spreads itself; patches stop worms (WannaCry's patch was out two months earlier).
- Trojans hide in gifts; droppers carry the payload, loaders fetch it later.
- Ransomware locks, wipers destroy. A sync is not a backup: use 3-2-1 with one offline copy, and test restores.
- Spyware, keyloggers, RATs and adware watch and annoy; install only trusted software.
- Rootkits, bootkits and fileless malware hide; LOLBins let attackers live off the land. Watch behaviour; use secure boot.
- Botnets obey a C2 server; regular beaconing gives them away. Cryptojackers steal your CPU. Change default passwords.
- Logic bombs wait for a condition; code review catches them.
- Antivirus signatures catch the known; polymorphic malware slips past; behaviour detection and EDR catch the new.
Next episode: social engineering and phishing: how attackers trick people, fake links, lookalike domains, deepfakes, and a red-flags checklist.
Sources: Wikipedia, "Morris worm"; Wikipedia, "WannaCry ransomware attack". Fetched 28 Oct 2026.