Malware and Ransomware
A finance clerk opens an invoice attachment on Monday morning. By lunchtime the shared drive is full of files called Q3-report.xlsx.locked, every folder holds a text file with payment instructions, and the backups that were mounted on the same server have the same extension. Nobody saw anything "break into" the network: a program ran with the clerk's own permissions and did what programs can do, open files and write them back.
That is the uncomfortable centre of malware: it is ordinary code with hostile intent. The operating system cannot tell a backup tool that rewrites ten thousand files from ransomware that rewrites ten thousand files. Defence therefore rests on three things: stopping unknown code from running, noticing the behaviour that gives it away, and being able to restore everything when both fail.
The survey course has a first look at malware types and backups against ransomware. This lesson adds the analyst's view: how malware is identified, how ransomware is detected while it runs, and the backup rule that makes it survivable. Real analysis (sandboxes, unpacking, memory forensics) is the subject of Malware Analysis, Forensics & Incident Response.
Safety note: this lesson contains no malicious code. The only "malware" is the EICAR test file, a 68-byte string that every anti-virus product agrees to detect so that people can test their tools safely, and the ransomware activity is a synthetic log.
Definitions
| Term | Meaning |
|---|---|
| Malware | Software written to act against the interests of the system's owner or user |
| Virus / worm | A virus infects other files and spreads when they are run; a worm spreads by itself over the network |
| Trojan | Malware disguised as something wanted (a cracked game, a "PDF viewer") |
| Ransomware | Encrypts (and nowadays usually also steals) data, then demands payment for the key and for silence |
| Loader / dropper | A small first stage whose only job is to fetch and start the real payload |
| Infostealer | Collects saved passwords, browser cookies and tokens and sends them out |
| Persistence | Whatever makes the malware start again after a reboot: a service, a scheduled task, a Run key |
| C2 (command and control) | The channel through which an operator sends commands to infected machines |
| IOC (indicator of compromise) | An observable such as a file hash, domain or registry path that points to a known infection |
Most modern intrusions chain several of these: a phishing attachment delivers a loader, the loader fetches an infostealer or remote-access tool, an operator uses the stolen credentials to move through the network, and ransomware is the last step, often days later. That delay is the defender's chance.
Identifying a known sample: hashes and YARA
The cheapest detection is recognising a file you have seen before. A cryptographic hash (SHA-256) identifies one exact file; change one byte and the hash changes completely. A YARA rule describes a family: byte strings, their positions and conditions such as file size, so it still matches when the attacker recompiles. The session below runs in your sandbox on the course's sample files only (no network):
cd $SAMPLES/files
sha256sum eicar.com hello.txt
file eicar.com hello.txt.gz random.bin
cat $SAMPLES/rules/eicar.yar
yara -s $SAMPLES/rules/eicar.yar .275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f eicar.com
f751a306e3c158aeaebf626a72e93986c9835f1ddd904b4b4dda7fc74f2607e5 hello.txt
eicar.com: EICAR virus test files
hello.txt.gz: gzip compressed data, max compression, original size modulo 2^32 51
random.bin: data
rule eicar_test_file
{
meta:
description = "EICAR anti-virus test file (harmless)"
reference = "https://www.eicar.org/download-anti-malware-testfile/"
strings:
$s = "EICAR-STANDARD-ANTIVIRUS-TEST-FILE!"
condition:
$s at 28 and filesize < 128
}
eicar_test_file ./eicar.com
0x1c:$s: EICAR-STANDARD-ANTIVIRUS-TEST-FILE!
yara -s reports the rule name, the file and where the string matched (offset 0x1c = 28, which the rule's $s at 28 demands). The hash is what you would search for in threat-intelligence feeds; the rule is what you would deploy to scan mail attachments and file shares. Both only find known malware, which is why behaviour matters.
Entropy: what encrypted data looks like
Shannon entropy measures how unpredictable the bytes of a file are, from 0 bits per byte (one byte value repeated) to 8 (every value equally likely). Text sits around 4 to 5, compressed and encrypted data close to 8. Ransomware turns documents into high-entropy blobs, and packed malware hides its code the same way, so entropy is a quick triage signal:
cat > entropy.py <<'PY'
import collections, math, sys
for path in sys.argv[1:]:
data = open(path, "rb").read()
counts = collections.Counter(data)
h = -sum(c / len(data) * math.log2(c / len(data)) for c in counts.values())
print(f"{h:4.2f} bits/byte {len(data):5d} bytes {path.rsplit('/', 1)[-1]}")
PY
python3 entropy.py $SAMPLES/files/hello.txt $SAMPLES/files/hello.txt.gz $SAMPLES/files/random.bin4.25 bits/byte 51 bytes hello.txt
5.08 bits/byte 69 bytes hello.txt.gz
7.95 bits/byte 4096 bytes random.bin
Small files can't reach 8 (51 bytes have at most 51 distinct values, so at most log2(51) ≈ 5.7 bits per byte), which is why detectors look at entropy together with size and file type: a 2 MB .docx is a ZIP and already compressed, so entropy alone is not proof.
Detecting ransomware while it runs
Ransomware has a loud behavioural fingerprint: one process rewrites many files in a short time, the new content has high entropy, and the names change. Endpoint detection products watch file-system events for exactly this. The program below applies such a rule to a synthetic event log of a file server: for each process it counts writes in a 60-second window whose content entropy is above 7.5 bits per byte, or that rename a file to a new extension, and raises an alert at 20.
from collections import defaultdict, deque
# Synthetic file-server events: (second, process, action, path, entropy of the new content)
events = []
for i in range(40): # a backup job: many writes, compressed archives
events.append((i * 3, "backup.exe", "write", f"/srv/archive/day{i % 7}.zip", 7.9))
for i in range(12): # an office user saving documents
events.append((5 + i * 25, "winword.exe", "write", f"/srv/finance/report{i}.docx", 7.6))
for i in range(30): # the suspicious process, starting at t = 200 s
events.append((200 + i, "invoice_viewer.exe", "rename", f"/srv/finance/file{i}.xlsx.locked", 7.99))
events.sort()
WINDOW, LIMIT = 60, 20
recent = defaultdict(deque)
alerted = set()
for t, proc, action, path, entropy in events:
suspicious = action == "rename" or (entropy > 7.5 and not path.endswith((".zip", ".docx")))
if not suspicious:
continue
q = recent[proc]
q.append(t)
while q and q[0] <= t - WINDOW:
q.popleft()
if len(q) >= LIMIT and proc not in alerted:
alerted.add(proc)
print(f"ALERT t={t}s {proc}: {len(q)} suspicious writes/renames in {WINDOW}s, last {path}")
print("processes alerted:", sorted(alerted))
print("backup.exe writes:", sum(1 for e in events if e[1] == "backup.exe"), "(not flagged: expected type)")ALERT t=219s invoice_viewer.exe: 20 suspicious writes/renames in 60s, last /srv/finance/file19.xlsx.locked
processes alerted: ['invoice_viewer.exe']
backup.exe writes: 40 (not flagged: expected type)
Notice what the rule needed to avoid a false alarm: the backup job writes more files than the ransomware does, and with higher entropy, but it writes the type it is expected to write. Real products add more context (is the process signed? did it start from a mail attachment? does it delete shadow copies?), and many contain the process automatically at the alert, because a human answering an alert in ten minutes is too slow when 30 files a second are lost.
Prevention and recovery
| Layer | Control |
|---|---|
| Stop delivery | Mail filtering, blocking macros from the Internet, no admin rights for daily work |
| Stop execution | Application allow-listing, signed code only, EDR in blocking mode |
| Limit spread | Patching, MFA everywhere, network segmentation, no shared local admin passwords |
| Detect | Behaviour rules as above, alerts on new services and tasks, deletion of shadow copies |
| Survive | 3-2-1-1-0 backups: 3 copies, on 2 kinds of media, 1 off-site, 1 offline or immutable, 0 errors in restore tests |
The last row is the one that decides whether ransomware is an incident or a catastrophe. A backup the infected server can write to is not a backup, as the clerk's company found out. Immutable storage (object lock, write-once media) or a copy that is physically disconnected survives an attacker with admin rights, and only a restore test proves that a backup works. Paying the ransom is no plan: decryptors are often slow or faulty, nothing guarantees that the stolen copy is deleted, and paying can itself be illegal where the group is under sanctions (the US Treasury's OFAC, for example, warns that such payments can breach sanctions law).
Pitfalls
- Trusting the hash list. Attackers recompile or repack for each victim, so a sample's hash may be seen exactly once. Hashes are for confirming known files and sharing IOCs, not for catching new ones.
- High entropy means malware. Archives, media files and encrypted databases are all near 8 bits per byte. Entropy is a signal to combine, not a verdict.
- Backups on the same domain. If the backup server uses the same admin accounts as everything else, the attacker deletes the backups first. Separate credentials and immutability.
- Running samples on your own machine. Real samples are only handled in an isolated analysis VM with no shared folders, as described in your isolated lab. In this course, EICAR is all you need.
Practice
- Change
LIMITto 40 in the detector. What happens, and what does that tell you about choosing thresholds? - An attacker's ransomware keeps the file names and writes 5 files per minute. Which part of the rule still catches it, and which part fails?
Answers
- No alert: the suspicious process makes only 30 changes in total, so a window can never hold 40. A threshold above the attacker's rate misses the attack; one below the busiest legitimate process floods analysts with false alarms. Thresholds come from measuring normal activity first.
- Renames are gone and 5 per minute stays far below 20 per 60 s, so this rule misses it. High-entropy writes to
.xlsxfiles are still marked suspicious, so a longer window (for example 20 in an hour) or a rule on "a document type suddenly written with entropy near 8" would catch it. Slow ransomware is a real evasion tactic; that is why detection combines several signals.
Test yourself
Why does a SHA-256 hash of a malware sample often fail to detect the next infection by the same group?
- SHA-256 is broken
- The attackers rebuild or repack the file, so its bytes and therefore its hash change
- Hashes only work on text files
- Anti-virus products don't use hashes
In the sandbox session, which file had the highest entropy?
- hello.txt
- hello.txt.gz
- random.bin
- eicar.com
What does the last '0' in the 3-2-1-1-0 backup rule stand for?
- Zero copies on the production server
- Zero errors when restores are tested
- Zero days of retention
- Zero cloud copies
Why did the backup job not trigger the ransomware rule even though it wrote more high-entropy files?
- Its entropy was below the threshold
- The rule ignores processes with 'backup' in the name
- It wrote the file type it is expected to write (.zip) and renamed nothing
- Backups run at night