Python 3 and a terminal. Nothing outside the folder you choose is touched, and no real
ransomware is downloaded 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.
Read this before running step 2. That step scrambles files, so it is written
to touch only two folders it created itself, named on a single visible line, inside whatever
directory you are standing in. It cannot search your disk and has no way to reach anything else.
Even so, follow the habit that makes such things safe: make a new empty folder and work there
— mkdir ransomware-lab then cd ransomware-lab — so that
nothing of yours shares a name with anything below.
What Is Ransomware?
Ransomware is a type of malware that encrypts your files or locks you out of your system, then demands a payment (ransom) in exchange for restoring access. It is one of the most destructive and financially damaging forms of cyberattack, affecting individuals, businesses, hospitals, schools, and government agencies worldwide.
Unlike other malware that operates silently, ransomware announces itself. After encrypting your files, it displays a ransom note demanding payment -- typically in cryptocurrency -- with a deadline. If you do not pay within the timeframe, the attackers may increase the ransom, permanently delete your decryption key, or publish your stolen data.
Modern ransomware operations function like professional enterprises with customer support, affiliate programs, and even service-level agreements. Ransomware-as-a-Service (RaaS) platforms let criminals without technical skills launch attacks for a percentage of the proceeds. This has dramatically increased the volume of attacks.
How Ransomware Works
A ransomware attack follows a predictable sequence, though modern variants have become increasingly sophisticated in each phase.
Phase 1: Initial Access
The attacker gains access to the target system. The most common entry points are phishing emails with malicious attachments, exploiting unpatched vulnerabilities in internet-facing services (such as VPN appliances or Remote Desktop Protocol), and compromised credentials purchased from darknet marketplaces.
Phase 2: Lateral Movement and Escalation
Once inside, sophisticated attackers do not encrypt immediately. They spend days or weeks moving laterally through the network, escalating privileges, identifying critical systems, and locating backup infrastructure. Their goal is to maximize damage and ensure backups cannot be used for recovery.
Phase 3: Data Exfiltration
Modern ransomware operations practice "double extortion" -- they steal sensitive data before encrypting it. This gives them a second lever: even if you restore from backups, they threaten to publish your confidential data unless you pay. Some groups have escalated to "triple extortion," adding DDoS attacks or contacting your customers directly.
Phase 4: Encryption and Ransom Demand
The ransomware encrypts files using strong encryption algorithms (typically AES-256 for
file encryption with RSA or ECC for key wrapping). Encrypted files receive a new extension
(such as .locked, .encrypted, or a random string), and a ransom
note appears on every affected system.
YOUR FILES HAVE BEEN ENCRYPTED
All your documents, photos, databases, and other important files
have been encrypted with military-grade encryption.
You cannot decrypt your files without our private key.
To recover your files, you must pay 2.5 BTC to:
bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh
You have 72 hours. After that, the price doubles.
After 7 days, your files will be permanently lost.
Contact: recovery_support@protonmail.com
Notable Ransomware Attacks
These high-profile incidents demonstrate the scale and impact of ransomware on critical infrastructure and everyday life.
- WannaCry (2017) -- Exploited the EternalBlue SMB vulnerability to spread automatically across networks. Infected over 200,000 systems in 150 countries in a single day, including the UK's National Health Service, causing hospitals to cancel surgeries and divert ambulances
- NotPetya (2017) -- Disguised as ransomware but was actually a destructive wiper. Spread through a compromised Ukrainian tax software update, causing an estimated $10 billion in global damage. Shipping giant Maersk had to reinstall 45,000 PCs and 4,000 servers
- Colonial Pipeline (2021) -- Forced the shutdown of the largest fuel pipeline in the US, causing gas shortages across the East Coast. The company paid a $4.4 million ransom. Entry point was a single compromised VPN password
- Kaseya VSA (2021) -- REvil ransomware exploited a vulnerability in Kaseya's remote management software to attack managed service providers and their downstream clients simultaneously, affecting up to 1,500 businesses
While headline-grabbing attacks target large organizations, small businesses and individuals are frequently hit because they lack dedicated security teams and often have weaker defenses. Automated ransomware campaigns do not discriminate by size.
Prevention Strategies
Preventing ransomware requires a combination of technical controls, user training, and operational discipline. No single measure is sufficient on its own.
- Patch management -- Apply security updates promptly. Many ransomware attacks exploit vulnerabilities for which patches have been available for months or years
- Email security -- Deploy email filtering that scans attachments for malware, blocks executable file types, and flags suspicious links. Train users to recognize phishing
- Network segmentation -- Divide your network into segments so that a single compromised system cannot reach all others. Isolate critical systems and backup infrastructure
- Principle of least privilege -- Users and services should have only the minimum permissions needed. Admin accounts should never be used for daily tasks
- Disable unnecessary services -- Turn off Remote Desktop Protocol (RDP) if not needed. If required, protect it with a VPN and multi-factor authentication
- Endpoint detection and response (EDR) -- Modern EDR tools can detect ransomware behavior patterns (mass file encryption, shadow copy deletion) and stop the attack in progress
- Multi-factor authentication -- Require MFA for all remote access, admin accounts, and email. This prevents attackers from using stolen passwords
Backup Strategies Against Ransomware
Backups are your most powerful defense against ransomware -- but only if they are designed to survive an attack. Ransomware operators specifically target backups to eliminate your ability to recover without paying.
The 3-2-1 Rule
Maintain at least 3 copies of your data, on at least 2 different types of media, with at least 1 copy stored offsite or offline. For ransomware resilience, the offsite/offline copy is critical.
Air-Gapped and Immutable Backups
- Air-gapped backups -- Backups stored on media that is physically disconnected from the network. An external hard drive that is only connected during backup operations and stored securely afterward
- Immutable backups -- Backups stored in a way that prevents modification or deletion for a defined retention period. Many cloud providers offer immutable storage options (e.g., object lock)
- Versioned backups -- Maintain multiple historical versions so you can restore from a point before the ransomware was deployed, even if you do not discover the attack immediately
A backup that has never been tested is not a backup -- it is a hope. Perform regular restore tests to verify that your backup data is complete, uncorrupted, and that you can actually restore from it within an acceptable timeframe. Many organizations discover their backups are broken only when they desperately need them.
Incident Response Steps
If ransomware strikes, a structured response minimizes damage and improves your chances of recovery. Every minute counts in the early stages.
- Isolate immediately -- Disconnect infected systems from the network. Do not shut them down (forensic evidence in memory may be lost), but unplug network cables and disable Wi-Fi
- Identify the scope -- Determine which systems and data are affected. Check network shares, cloud storage, and connected backup systems
- Preserve evidence -- Take screenshots of ransom notes, document affected file extensions, and preserve system logs. This information helps identify the ransomware variant and may aid law enforcement
- Identify the variant -- Upload a ransom note or encrypted file sample to services like ID Ransomware (id-ransomware.malwarehunterteam.com) to identify the specific ransomware family. Some variants have known decryptors available for free
- Report to authorities -- Contact law enforcement (FBI's IC3 in the US, Action Fraud in the UK, or your national equivalent). They may have intelligence on the specific threat actor
- Assess backup integrity -- Before restoring, verify that your backups are clean and were not compromised. Ransomware operators often lurk in networks for weeks before encrypting
- Restore and rebuild -- Restore systems from clean backups. Rebuild any systems that cannot be verified as clean. Change all credentials before bringing systems back online
Should You Pay the Ransom?
The question of whether to pay is one of the most difficult decisions a ransomware victim faces. There are strong arguments on both sides, and no universally correct answer.
Arguments Against Paying
- No guarantee of recovery -- Paying does not guarantee you will receive a working decryption key. Some victims pay and receive nothing, or receive a buggy decryptor that corrupts files
- Funds criminal enterprise -- Every ransom payment finances the development of more sophisticated attacks and encourages more criminals to enter the ransomware business
- Marks you as a target -- Paying once signals that you are willing to pay, making you a target for repeat attacks by the same group or others
- Potential legal issues -- In some jurisdictions, paying ransoms to sanctioned entities is illegal and can result in fines
Arguments for Paying
- Business survival -- When backups are destroyed and the alternative is permanent data loss or business closure, paying may be the only practical option
- Cost comparison -- The cost of extended downtime, lost revenue, and rebuilding from scratch may far exceed the ransom amount
- Life safety -- When hospitals or critical infrastructure are affected and lives are at stake, the moral calculus changes
Develop an incident response plan that includes your organization's position on ransom payments, who has authority to make the decision, and what thresholds or criteria apply. Making this decision during a crisis, under time pressure, leads to worse outcomes.
Lose Your Files and Get Them Back, in Five Steps
Everyone knows the advice: keep backups. Almost nobody has tested one, and a surprising number of people discover on the worst possible day that the backup was encrypted alongside everything else. In the next twenty minutes you will build a small folder of documents, run something that behaves exactly as ransomware behaves, discover that one of your two backups is gone too, fail to brute-force the key, and then recover everything in seconds from the copy that was out of reach. Every line of output below came from running these files.
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 setup_files.py and run python3 setup_files.py. It
creates three folders in the directory you are standing in and touches nothing else.
"""Build a small pretend home folder, plus two kinds of backup."""
import os, shutil
for d in ("Documents", "BackupDrive", "OfflineDrive"):
shutil.rmtree(d, ignore_errors=True)
os.makedirs(d)
DOCS = {
"tax-return-2025.txt": "Total income: 41,200. Tax paid: 7,844.",
"wedding-speech.txt": "When I first met her, I was holding a cheese sandwich.",
"passwords-hint.txt": "bank = the street we lived on + year",
}
for name, text in DOCS.items():
open(os.path.join("Documents", name), "w").write(text)
# One backup drive is plugged in all the time. One lives in a drawer.
for name in DOCS:
shutil.copy(os.path.join("Documents", name), os.path.join("BackupDrive", name))
shutil.copy(os.path.join("Documents", name), os.path.join("OfflineDrive", name))
for d in ("Documents", "BackupDrive", "OfflineDrive"):
print("%-14s %d file(s)" % (d, len(os.listdir(d))))
print()
print("BackupDrive = an external disk left connected, or a synced cloud folder")
print("OfflineDrive = a disk in a drawer, unplugged since last Sunday")
You should see: three folders, each holding the same three documents:
Documents 3 file(s)
BackupDrive 3 file(s)
OfflineDrive 3 file(s)
BackupDrive = an external disk left connected, or a synced cloud folder
OfflineDrive = a disk in a drawer, unplugged since last Sunday
The distinction between the two backups is the whole point of this section, and it
is not about brand, price or cloud-versus-disk. BackupDrive stands for anything your
computer can write to right now without you doing anything — an external disk left plugged
in, a mapped network drive, a synced folder. OfflineDrive stands for a disk that is
physically disconnected.
If not: PermissionError means the folder is not writable; cd
somewhere you own. If a folder already existed with other files in it, the script deleted and
recreated it — that is why it uses three distinctive names, but check you are not standing
in a folder of your own called Documents before running it.
Go: the same folder.
Do: save this as encrypt_all.py and run python3 encrypt_all.py.
Read the TARGETS line before you run it: this script only ever touches the two
folder names written there, in the directory you are standing in.
"""What ransomware does. It touches only the folders named on line 12."""
import os, secrets
# The key exists for a few milliseconds, then is thrown away -- exactly as the
# real thing sends it to the attacker and keeps no copy on your machine.
key = secrets.token_bytes(32)
def xor(data, k):
return bytes(b ^ k[i % len(k)] for i, b in enumerate(data))
TARGETS = ["Documents", "BackupDrive"] # note which one is NOT here
count = 0
for folder in TARGETS:
for name in sorted(os.listdir(folder)):
path = os.path.join(folder, name)
raw = open(path, "rb").read()
open(path + ".locked", "wb").write(xor(raw, key))
os.remove(path)
count += 1
open("READ-ME-TO-RECOVER.txt", "w").write(
"Your files are encrypted. Pay to receive the key.\n")
del key # gone. Not recoverable from here.
print("files encrypted:", count)
for folder in ("Documents", "BackupDrive", "OfflineDrive"):
print("%-14s %s" % (folder, sorted(os.listdir(folder))))
print()
print("The connected backup was encrypted alongside the originals.")
print("It was reachable, so it was a target -- not a backup.")
You should see: six files locked — three of which you thought were safe:
files encrypted: 6
Documents ['passwords-hint.txt.locked', 'tax-return-2025.txt.locked', 'wedding-speech.txt.locked']
BackupDrive ['passwords-hint.txt.locked', 'tax-return-2025.txt.locked', 'wedding-speech.txt.locked']
OfflineDrive ['passwords-hint.txt', 'tax-return-2025.txt', 'wedding-speech.txt']
The connected backup was encrypted alongside the originals.
It was reachable, so it was a target -- not a backup.
This is the single most important line in the section:
BackupDrive was encrypted because it was reachable. Ransomware does not
“skip backups”; it encrypts every path it can write to, and a permanently connected
backup drive is simply another path. So is a synced cloud folder, which will helpfully replicate
the encrypted versions upward within minutes.
Note also what the script did with the key: it created it, used it, and deleted it. A real attack sends it away first. Either way, in the next step you are in the position of someone who has just read the ransom note.
If not: FileNotFoundError means step 1 was not run in this folder. If
OfflineDrive also shows .locked files, a third folder name was added to
TARGETS — it must contain exactly the two names shown.
Go: the same folder.
Do: save this as try_recover.py and run python3 try_recover.py.
It guesses keys for three seconds and reports how far it got.
"""Try to get the files back without the key."""
import os, secrets, time
path = os.path.join("Documents", "tax-return-2025.txt.locked")
data = open(path, "rb").read()
print("locked file:", path, "-", len(data), "bytes")
print("first bytes:", data[:16].hex())
print()
# Guess keys at random and see whether the result looks like the text we know.
start = time.time()
tries = 0
while time.time() - start < 3:
guess = secrets.token_bytes(32)
out = bytes(b ^ guess[i % 32] for i, b in enumerate(data[:8]))
tries += 1
if out.startswith(b"Total in"):
print("recovered after", tries, "guesses")
break
else:
print("guesses made in 3 seconds :", format(tries, ","))
total = 2 ** 256
print("possible 32-byte keys : 2^256")
print("fraction of the space tried:", "%.2e" % (tries / total))
print()
print("At this rate, covering the space takes longer than the age of the")
print("universe by a factor with more than sixty digits. There is no")
print("technique hiding here -- this is why paying is even considered.")
You should see: roughly a million guesses, and a number that makes the point:
locked file: Documents/tax-return-2025.txt.locked - 38 bytes
first bytes: 153ca46a10e37a29ae4f36c9a9a406bf
guesses made in 3 seconds : 1,082,131
possible 32-byte keys : 2^256
fraction of the space tried: 9.35e-72
At this rate, covering the space takes longer than the age of the
universe by a factor with more than sixty digits. There is no
technique hiding here -- this is why paying is even considered.
Two figures here will differ on your machine, and should. The hex
bytes are different every run because the key in step 2 is random, and the number of guesses
depends on how fast your processor is — anything from a few hundred thousand to a few
million is normal. What will not differ is the exponent: the fraction of the key space you
covered is around 1e-71 either way.
People sometimes assume there must be a clever trick, a decryption tool, a flaw. Sometimes there genuinely is — researchers have broken particular families and published free decryptors, and it is always worth searching for one before doing anything else. But that is luck, dependent on somebody else's mistake. The defence you control is entirely in the next two steps.
If not: if it prints recovered after N guesses, you have witnessed something
with a probability below one in 1e60 and should buy a lottery ticket; far more
likely the key length was reduced when copying. If it finishes instantly with
0 guesses, the loop condition was altered — it runs for three seconds by
wall clock.
Go: the same folder.
Do: save this as restore.py and run python3 restore.py.
"""Recovery, from the only copy the attack could not reach."""
import os, shutil, hashlib
def digest(path):
return hashlib.sha256(open(path, "rb").read()).hexdigest()[:16]
for name in sorted(os.listdir("Documents")):
os.remove(os.path.join("Documents", name))
restored = 0
for name in sorted(os.listdir("OfflineDrive")):
src = os.path.join("OfflineDrive", name)
dst = os.path.join("Documents", name)
shutil.copy(src, dst)
same = digest(src) == digest(dst)
print("%-24s restored checksum %s" % (name, "matches" if same else "DIFFERS"))
restored += same
print()
print("files restored and verified:", restored, "of", len(os.listdir("OfflineDrive")))
print()
print(open(os.path.join("Documents", "wedding-speech.txt")).read().strip())
print()
print("Total time to recover: seconds. Amount paid: nothing.")
You should see: everything back, checksummed, and the speech readable again:
passwords-hint.txt restored checksum matches
tax-return-2025.txt restored checksum matches
wedding-speech.txt restored checksum matches
files restored and verified: 3 of 3
When I first met her, I was holding a cheese sandwich.
Total time to recover: seconds. Amount paid: nothing.
The checksum comparison is not decoration. Copying a file can truncate it, and a restore that produces the right filenames with the wrong contents is a failure that looks exactly like a success — which is why the script compares the bytes rather than the names, and prints the sentence from inside one of the files so a human can see it.
The rule people remember as 3-2-1 — three copies, two kinds of media, one offsite — is really about the word that does the work here: unreachable. One copy must not be writable by the computer being attacked. Unplugged is unreachable. A cloud service with genuine version history is unreachable in a weaker but usually adequate sense, because the old versions cannot be overwritten by the sync client.
If not: if a line prints DIFFERS, the copy did not complete — check free
disk space. If Documents is empty afterwards, OfflineDrive was empty
before you started, which means step 1 did not finish.
Go: the same folder. This is the step that separates people who recover from people who thought they would.
Do: save this as test_backup.py and run python3 test_backup.py.
"""A backup you have never restored is a hypothesis, not a backup."""
import os, hashlib
os.makedirs("BadBackup", exist_ok=True)
# A backup job that "succeeded" -- it ran, it exited 0, it wrote a file.
open(os.path.join("BadBackup", "tax-return-2025.txt"), "w").write("")
def check(folder, expected_names):
problems = []
for name in expected_names:
path = os.path.join(folder, name)
if not os.path.exists(path):
problems.append("%s MISSING" % name)
elif os.path.getsize(path) == 0:
problems.append("%s is 0 bytes" % name)
return problems
expected = sorted(os.listdir("Documents"))
for folder in ("OfflineDrive", "BadBackup"):
problems = check(folder, expected)
print("%-14s %s" % (folder, "; ".join(problems) if problems else "all files present and non-empty"))
print()
print("exit code of the backup job that produced BadBackup: 0")
print("what it backed up : nothing")
print()
print("Check the RESTORE, never the exit code. The only proof a backup")
print("works is a file you have read after taking it out again.")
You should see: one healthy backup and one that reported success while saving nothing:
OfflineDrive all files present and non-empty
BadBackup passwords-hint.txt MISSING; tax-return-2025.txt is 0 bytes; wedding-speech.txt MISSING
exit code of the backup job that produced BadBackup: 0
what it backed up : nothing
Check the RESTORE, never the exit code. The only proof a backup
works is a file you have read after taking it out again.
The BadBackup folder is not a contrived example. A backup job whose
source path is wrong, whose credentials expired, or which ran while the drive was unmounted will
frequently create the destination, write nothing, and exit reporting success. Nothing alerts you,
because from the job's point of view nothing went wrong.
So put a date in your calendar — twice a year is enough — and on that day restore one real file from the backup and open it. Not check that the backup ran; not look at a green tick; open a document and read it. That five-minute habit is the entire difference between owning a backup and owning a folder you have never looked inside.
If not: if BadBackup reports everything present, the empty-file write on the
second line did not happen — open(..., "w").write("")
creates a zero-byte file, and the check reports it because zero bytes is exactly the symptom.
Without scrolling up: a friend says they are safe from ransomware because everything is in a cloud drive that syncs automatically, so there is always a second copy. What is wrong with that, and what one setting would you ask them to check? Answer: a sync client is not a backup — it is a mechanism for making two folders identical as fast as possible. When the local files are encrypted, the client faithfully replicates the encrypted versions upward, usually within minutes, and the second copy becomes a second copy of the damage. Step 2 demonstrated exactly this: the permanently reachable copy was encrypted alongside the originals. The setting to check is version history — whether the service retains previous versions of a file, for how long, and whether the account can roll a whole folder back to a point in time. With that, the cloud copy is genuinely useful; without it, the friend has one copy stored in two places.
Now do it without the page: take the backup you actually rely on right now — a drive, a cloud folder, a phone — and restore one real file from it to a new location, then open the file and read it. Time how long the whole thing takes. If the answer is “I could not work out how” or “longer than I expected”, you have learned something more useful than any of the five steps above, because you learned it before it mattered.
Summary
Ransomware is one of the most impactful cyber threats today, but it is also one of the most preventable with proper preparation.
- Ransomware encrypts your files and demands payment for the decryption key, with modern variants also stealing data for double extortion
- Attacks follow a predictable lifecycle -- initial access, lateral movement, data exfiltration, then encryption
- Major incidents like WannaCry and Colonial Pipeline demonstrate that ransomware can impact critical infrastructure and daily life
- Prevention requires layers -- patching, email security, network segmentation, least privilege, MFA, and EDR
- Backups are your strongest defense -- but they must be air-gapped or immutable, versioned, and regularly tested
- Incident response should be planned in advance: isolate, identify, preserve evidence, check for free decryptors, and restore from clean backups
- The ransom payment decision should be made before an attack occurs, as part of your incident response plan
The organizations that recover from ransomware quickly and without paying are the ones that invested in prevention, maintained tested backups, and had an incident response plan ready before the attack happened. Start building your defenses today.