Skip to main content

2. Thinking Like an Attacker

To defend software, you must think like someone trying to break it. Attackers exploit assumptions, oversights, and shortcuts.

Example: Command Injection

# 2. Insecure
import os
filename = input("Enter file to compress: ")
os.system(f"tar -czf backup.tar.gz {filename}") # Dangerous if filename = '; rm -rf /'

# 2. Secure
import subprocess
filename = input("Enter file to compress: ")
if not filename.isalnum():
raise ValueError("Invalid filename.")
subprocess.run(["tar", "-czf", "backup.tar.gz", filename])

Lesson: Treat all input as untrusted, even from "safe" users.