These are the notes for Cybersecurity Fundamentals (defensive), episode 51. For many episodes we met attacks one at a time: SQL injection (38), command injection (39), XSS (40), CSRF (42), SSRF (43), path traversal (47), broken access control (37) and the API Top 10 (49-50). Today we step back and find the few coding habits that prevent most of them, in any language: know where your trust boundaries are, follow untrusted data from sources to sinks, validate with allowlists after canonicalising, encode or parameterise at every sink, handle errors safely, fail closed with secure defaults, give code the least privilege it needs, and program defensively. Then we meet the standards the industry uses to check all this: OWASP ASVS, the OWASP Cheat Sheet Series, the SEI CERT coding standards and the CWE Top 25. Every term is explained the first time it appears; the Glossary at the end defines them all again.
Neha, Ravi, the shop, the database address and password and every value are made up. Nothing outside the machine is contacted; the "shell sink" only runs echo with our own text. Samples were run on 12 Nov 2026 with Python 3.13 and OpenJDK 21; every output below is copied from a real run (the error reference id and the temporary folder name are random and differ each run).
The problems you'll solve
| Problem | Idea it teaches |
|---|---|
| A customer edits the quantity to -4 and the bill becomes -1,000 | trust boundary, validating on the server |
| Which data is dangerous, and where? | taint, sources, sinks, static analysis |
A filter blocks <script> but not <SCRIPT> |
input validation: denylist vs allowlist, syntactic vs semantic |
| "Admin" and full-width "admin" slip past a reserved-name check | canonicalisation before validation |
| A valid name, O'Neil, breaks HTML, SQL and a shell command | output encoding, parameterisation |
| An error page shows a stack trace and a database password | safe error handling |
| An outage makes a permission check say "yes" | fail open vs fail closed, secure defaults |
| A read-only report could delete every order | least privilege in code |
| A big order wraps to a negative total in Java | defensive programming, integer overflow |
| Where are these rules written down? | OWASP ASVS levels, OWASP Cheat Sheet Series, SEI CERT, CWE Top 25 |
Problem 1: trust boundaries
Real-life example: a housing society. At the main gate a guard checks every visitor, courier and delivery. Inside are residents you trust; outside are strangers.
- Untrusted data is any data that comes from outside your control: a web request, a form field, a cookie, an uploaded file, an environment variable, a message queue, or the reply from another API. "Outside" includes the customer's own browser, because the customer can edit anything it sends.
- A trust boundary is the line in your system where data crosses from a less trusted place to a more trusted one, like the society gate. Example: the moment a web request reaches your server code.
- The rule: check data at the trust boundary, on the server, every time. A check in the browser (JavaScript) is only a convenience for honest users; an attacker simply skips it.
Demo 1: a cart that trusts the request
# Neha's shop: the cart total, computed from the request.
PRICE = {"chai-mug": 250, "tea-box": 400}
def total_v1(request): # trusts every field it is given
qty = int(request["qty"])
return PRICE[request["item"]] * qty
print("normal :", total_v1({"item": "chai-mug", "qty": "2"}))
print("edited :", total_v1({"item": "chai-mug", "qty": "-4"}))
def total_v2(request): # the trust boundary is HERE
item, qty = request.get("item"), request.get("qty", "")
if item not in PRICE:
raise ValueError("unknown item")
if not qty.isdigit() or not 1 <= int(qty) <= 10:
raise ValueError("qty must be a whole number 1-10")
return PRICE[item] * int(qty)
for req in ({"item": "chai-mug", "qty": "2"},
{"item": "chai-mug", "qty": "-4"},
{"item": "laptop", "qty": "1"}):
try:
print("v2", req["qty"], req["item"], "->", total_v2(req))
except ValueError as e:
print("v2", req["qty"], req["item"], "-> rejected:", e)
Real output:
normal : 500
edited : -1000
v2 2 chai-mug -> 500
v2 -4 chai-mug -> rejected: qty must be a whole number 1-10
v2 1 laptop -> rejected: unknown item
total_v1 turned an edited quantity of -4 into a bill of -1000: the shop would owe the customer money. total_v2 is the guard at the gate: the item must be one we sell and the quantity a whole number from 1 to 10. Everything else is rejected.
Problem 1b: taint, sources and sinks
Security tools follow untrusted data through a program:
- A source is a place where untrusted data enters the program:
request.args,input(), a file read,os.environ, a response from another service. - A sink is a place where data turns into an action, and where bad data does damage: a SQL query, a shell command, an HTML page, a file path,
eval, a redirect URL, a log line. - Taint is a mark meaning "this came from a source and hasn't been checked yet". The mark spreads: join tainted text with anything and the result is tainted.
- A taint bug is tainted data reaching a sink without a check in between. Most of the injection bugs in this course (SQL, command, XSS, path traversal, SSRF) are exactly this.
- Static analysis tools read your code without running it; many of them do taint analysis, tracing each source to each sink and flagging paths with no check.
source (request, file, env) ──► our code (copied, joined) ──► sink (SQL, shell, HTML, path)
▲
validation / encoding / parameters must sit here
Demo 2: a tiny taint tracker
# A tiny taint tracker: outside data carries a mark until checked.
class Tainted(str): # a str with a "dirty" label
def __add__(self, other): return Tainted(str(self) + str(other))
def __radd__(self, other): return Tainted(str(other) + str(self))
def source(value): # where outside data comes IN
return Tainted(value) # request, file, env, other API
def sink(kind, text): # where data becomes an action
if isinstance(text, Tainted):
raise RuntimeError(f"tainted data reached the {kind} sink")
print(f"{kind:5} OK: {text}")
def clean_pincode(value): # validation removes the mark
if not (len(value) == 6 and value.isdigit()):
raise ValueError("bad pincode")
return str(value) # plain str: trusted now
pin = source("560001; reboot") # an edited form field
for step in ("raw", "checked"):
try:
value = pin if step == "raw" else clean_pincode(pin)
sink("shell", "deliver to " + value)
except (RuntimeError, ValueError) as e:
print(f"{step:7} -> {type(e).__name__}: {e}")
sink("shell", "deliver to " + clean_pincode(source("560001")))
Real output:
raw -> RuntimeError: tainted data reached the shell sink
checked -> ValueError: bad pincode
shell OK: deliver to 560001
The raw pincode, with ; reboot glued on, was stopped at the shell sink. After clean_pincode (exactly six digits) the bad value is rejected and the real pincode becomes a plain, trusted str.
Problem 2: input validation
Real-life example: a wedding hall. A list of troublemakers not to let in (a denylist) misses any gatecrasher not on the list, or one in a new shirt. The guest list (an allowlist) lets in only invited people.
- Input validation means checking that input has the shape and meaning you expect before you use it.
- A denylist (blocklist) rejects known-bad input. It is always incomplete: there are endless ways to write bad input.
- An allowlist accepts only known-good input and rejects everything else. Prefer it.
- Syntactic validation checks the form: type, length, range, format (e.g. a pincode is exactly six digits).
- Semantic validation checks that the value makes sense in context (e.g. a delivery date is in the future, a refund isn't larger than the order).
- A regular expression (regex) is a pattern for text. Use
fullmatchso the whole value must fit the pattern, not just part of it. - Validate on the server. Validation reduces risk, but it is not the main defence against injection: valid data can still break a sink (Problem 4).
Demo 3: denylist vs allowlist
# Validating a display name: block the bad, or allow only the good?
import re
def denylist(name): # block what we know is bad
for bad in ("<script>", "javascript:", "onerror"):
if bad in name:
return "blocked"
return "accepted"
NAME = re.compile(r"[A-Za-z][A-Za-z .'-]{0,29}")
def allowlist(name): # allow only what we expect
return "accepted" if NAME.fullmatch(name) else "rejected"
for name in ("Neha Sharma", "D'Souza", "<script>x</script>",
"<SCRIPT>x</SCRIPT>", "<img src=1 OnError=x>"):
print(f"{name:22} deny: {denylist(name):8} allow: {allowlist(name)}")
Real output:
Neha Sharma deny: accepted allow: accepted
D'Souza deny: accepted allow: accepted
<script>x</script> deny: blocked allow: rejected
<SCRIPT>x</SCRIPT> deny: accepted allow: rejected
<img src=1 OnError=x> deny: accepted allow: rejected
The denylist caught only the exact tag it knew; <SCRIPT> and OnError walked in. The allowlist accepted the two real names and rejected all three attacks.
Problem 3: canonicalisation before validation
- The same text can be written in different ways:
Adminvsadmin, full-widthadmin(the wide letters used in Chinese and Japanese text) vsadmin,%2e%2e%2fvs../. - Canonicalisation (also normalisation) means turning input into its one standard form before you use it. Examples: Unicode NFKC normalisation (turns full-width and other look-alike "compatibility" characters into plain ones),
casefold()(lower case for comparisons), URL-decoding, resolving a file path withrealpath(episode 47). - The bug: validate one form, then use another. The rule: canonicalise first, then validate, then use exactly the value you validated.
Demo 4: check first, or normalise first?
# Sign-up must refuse reserved usernames like "admin".
import unicodedata
RESERVED = {"admin", "root", "support"}
ACCOUNTS = {}
def canonical(name): # one standard form of the text
return unicodedata.normalize("NFKC", name).casefold().strip()
def signup_v1(name): # check first, normalise later
if name in RESERVED:
return "reserved"
ACCOUNTS[canonical(name)] = "new user" # stored in standard form
return f"created {canonical(name)!r}"
def signup_v2(name): # normalise first, then check
name = canonical(name)
if name in RESERVED or name in ACCOUNTS:
return "reserved or taken"
ACCOUNTS[name] = "new user"
return f"created {name!r}"
FULLWIDTH = "\uff41\uff44\uff4d\uff49\uff4e" # "admin", wide letters
for name in ("admin", "Admin", FULLWIDTH):
ACCOUNTS.clear()
print(f"{name!r:9} v1: {signup_v1(name):17} v2: {signup_v2(name)}")
Real output:
'admin' v1: reserved v2: reserved or taken
'Admin' v1: created 'admin' v2: reserved or taken
'admin' v1: created 'admin' v2: reserved or taken
signup_v1 refused plain admin but created an account named admin from both disguises, because the check ran on the raw text and the database got the tidied text. signup_v2 canonicalises first and refuses all three.
Problem 4: output encoding and parameterisation
Real-life examples: when you pass on a message you say it in the listener's language (output encoding); a form with separate boxes stops your name spilling into the amount box (parameterisation).
- Output encoding (escaping) turns special characters into a safe form for the exact context the data is going into. The context matters: HTML body text, an HTML attribute, JavaScript, a URL and CSS each have different special characters. Example:
html.escape("O'Neil")givesO'Neil. - Parameterisation keeps data separate from the command, so data can never be read as code: SQL placeholders (
?,%s,:name) in a prepared statement, or running a program with an argument list and no shell (subprocess.run(["echo", name])). - Apply them at the sink, every time, even for data that passed validation.
Demo 5: one valid name, three sinks
# One VALID name, three sinks: a web page, SQL and a command.
import html, sqlite3, subprocess
name = "Ravi O'Neil" # passes the allowlist: it's real
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE users (name TEXT)")
print("--- v1: glue the text into each sink")
print("html:", f"<p title='{name}'>Hi</p>")
try:
db.execute(f"INSERT INTO users VALUES ('{name}')")
except sqlite3.Error as e:
print("sql :", type(e).__name__, "-", e)
r = subprocess.run(f"echo label for {name}", shell=True,
capture_output=True, text=True)
print("cmd :", (r.stdout or r.stderr).strip())
print("--- v2: encode or parameterise for each sink")
print("html:", f"<p title='{html.escape(name)}'>Hi</p>")
db.execute("INSERT INTO users VALUES (?)", (name,)) # a placeholder
print("sql :", db.execute("SELECT name FROM users").fetchone()[0])
r = subprocess.run(["echo", "label for", name], # no shell
capture_output=True, text=True)
print("cmd :", r.stdout.strip())
Real output:
--- v1: glue the text into each sink
html: <p title='Ravi O'Neil'>Hi</p>
sql : OperationalError - near "Neil": syntax error
cmd : /bin/sh: 1: Syntax error: Unterminated quoted string
--- v2: encode or parameterise for each sink
html: <p title='Ravi O'Neil'>Hi</p>
sql : Ravi O'Neil
cmd : label for Ravi O'Neil
A perfectly valid name broke all three sinks in v1: the apostrophe ends the HTML attribute early, SQLite reports OperationalError - near "Neil": syntax error, and the shell reports Syntax error: Unterminated quoted string. If an apostrophe can break the command, an attacker's text can rewrite it: that is injection (episodes 38-40). In v2 the HTML gets O'Neil, and SQL and the command receive Ravi O'Neil exactly.
Problem 5: safe error handling
Real-life example: a bank clerk who reads the internal memo aloud when the system breaks, versus one who says "a system issue, here is token 4512" and sends the details to the back office.
- A stack trace (traceback) is the list of function calls that led to an error, with file names, line numbers and source lines. Useful to developers, and a map of your code for an attacker.
- A verbose error message shows internals to the user: stack traces, file paths, SQL, versions, secrets.
- A connection string is the address plus username and password a program uses to reach a database. It is a secret.
- Safe error handling: catch errors; show the user a generic message (plus a random reference id); write the details to a server-side log only your team can read; never put secrets in either.
Demo 6: errors that leak
# What does the user see when something breaks?
import traceback, uuid
DB_URL = "postgres://shop_admin:toy-S3cret@10.0.0.5/shop" # toy secret
def get_order(order_id):
return {"501": "2 chai mugs"}[order_id] # KeyError if missing
def handle_v1(order_id): # show the error to the user
try:
return get_order(order_id)
except Exception:
return traceback.format_exc() + f"(db: {DB_URL})"
def handle_v2(order_id): # generic message, details logged
try:
return get_order(order_id)
except KeyError:
return "Order not found."
except Exception as e: # details go to OUR log only
ref = uuid.uuid4().hex[:8]
print(f"[server log] ref={ref} {type(e).__name__}: {e}")
return f"Something went wrong. Reference: {ref}"
print("v1:", handle_v1("999"))
print("v2:", handle_v2("999"))
print("v2:", handle_v2(["501"])) # a list: TypeError
Real output (the folder name and reference id are random each run):
v1: Traceback (most recent call last):
File "/tmp/tmp2xs4x8vw/main.py", line 10, in handle_v1
return get_order(order_id)
File "/tmp/tmp2xs4x8vw/main.py", line 6, in get_order
return {"501": "2 chai mugs"}[order_id] # KeyError if missing
~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^
KeyError: '999'
(db: postgres://shop_admin:toy-S3cret@10.0.0.5/shop)
v2: Order not found.
[server log] ref=d780ed3a TypeError: unhashable type: 'list'
v2: Something went wrong. Reference: d780ed3a
v1 showed the server's file path, a line of source code and the database password. v2 gave a clear message for the expected case and a generic message with a reference for the unexpected one; the details went to the log line with the same reference.
Problem 5b: fail closed and secure defaults
Real-life examples: in a power cut a bank locker stays locked; a new phone asks you to set a screen lock before you change any settings.
- Fail open: when a security check can't decide (error, timeout, missing data), it answers yes. Outages become break-ins.
- Fail closed: when a check can't decide, it answers no, and raises an alert. (Episode 3 compared fail secure and fail safe for physical doors; for access decisions, fail closed is the default choice.)
- A secure default is a setting whose default value is the safe one, so doing nothing is safe: TLS certificate checks on, debug mode off, new accounts with the fewest rights.
- Secure by default applies to your own functions too: the safe behaviour should need no extra argument.
Demo 7: fail open vs fail closed, and defaults
# Can this user refund an order? The permission service may be down.
class PermissionServiceDown(Exception): pass
def ask_permission_service(user, action):
raise PermissionServiceDown("timeout after 2 s") # it's down today
def can_v1(user, action): # fail OPEN
try:
return ask_permission_service(user, action)
except Exception:
return True # "don't block the shop"
def can_v2(user, action): # fail CLOSED
try:
return ask_permission_service(user, action) is True
except Exception:
return False # unsure -> deny, and alert
def connect_v1(host, verify_tls=False): # insecure default
return f"{host}: TLS check {'on' if verify_tls else 'OFF'}"
def connect_v2(host, verify_tls=True): # secure default
return f"{host}: TLS check {'on' if verify_tls else 'OFF'}"
print("v1 ravi may refund:", can_v1("ravi", "refund"))
print("v2 ravi may refund:", can_v2("ravi", "refund"))
print("v1", connect_v1("pay.example"))
print("v2", connect_v2("pay.example"))
Real output:
v1 ravi may refund: True
v2 ravi may refund: False
v1 pay.example: TLS check OFF
v2 pay.example: TLS check on
Problem 6: least privilege in code
Real-life example: a valet key drives and parks the car but can't open the boot.
- Least privilege (episode 3) means giving each part of a system only the rights its job needs, for as long as it needs them.
- In code: a read-only database connection or database user for reports; a database user that can only
INSERTorders for the checkout; files created readable only by the owner (0o600); cloud roles and API tokens with only the scopes needed; services that don't run as root/Administrator. - It doesn't prevent the bug; it shrinks the blast radius, the damage one bug can do.
Demo 8: a read-only report
# The daily sales report only READS. What if its query is ever hijacked?
import sqlite3, os, tempfile
path = os.path.join(tempfile.mkdtemp(), "shop.db")
with sqlite3.connect(path) as db: # set up toy data
db.execute("CREATE TABLE orders (id INT, total INT)")
db.execute("INSERT INTO orders VALUES (501, 500), (502, 400)")
def report(conn, query):
try:
conn.execute(query)
conn.commit()
n = conn.execute("SELECT COUNT(*) FROM orders").fetchone()[0]
return f"ok, orders left: {n}"
except sqlite3.Error as e:
return f"{type(e).__name__}: {e}"
evil = "DELETE FROM orders" # a hijacked query
rw = sqlite3.connect(path) # v1: full rights
ro = sqlite3.connect(f"file:{path}?mode=ro", uri=True) # v2: read-only
print("v2 read-only :", report(ro, evil))
print("v1 read-write:", report(rw, evil))
Real output:
v2 read-only : OperationalError: attempt to write a readonly database
v1 read-write: ok, orders left: 0
The same hijacked DELETE ran against both connections. The read-only one refused with attempt to write a readonly database; the full-rights one deleted every order.
Problem 6b: defensive programming
- Defensive programming means writing each function as if every caller and every input may be wrong.
- Check preconditions (what must be true before the function runs) at the start, and refuse clearly when they fail.
- Handle every error path; put limits (sizes, counts) and timeouts on everything that waits or grows.
- Python's
assertis removed when Python runs with-O, so it must never be a security check:
def refund(amount):
assert amount > 0, "refund must be positive"
return f"refunded {amount}"
print(refund(-500))
Real output with python3 a.py and with python3 -O a.py:
AssertionError: refund must be positive
refunded -500
- Numbers have limits. An integer overflow happens when a result is too big for its type. Java's
intholds up to 2,147,483,647, and the SEI CERT Java rule NUM00-J, "Detect or prevent integer overflow", notes that "Java's built-in integer operators silently wrap the result without indicating overflow".Math.addExactandMath.multiplyExact"either return a mathematically correct value or throw ArithmeticException".
Demo 9 (Java): a bulk order that wraps around
// Java: a bulk order of chai mugs. Prices are in paise (1 rupee = 100).
public class Main {
static int totalV1(int qty, int pricePaise) {
return qty * pricePaise; // may silently wrap
}
static int totalV2(int qty, int pricePaise) {
if (qty < 1 || qty > 1_000_000) // defensive: check input
throw new IllegalArgumentException("qty out of range: " + qty);
return Math.multiplyExact(qty, pricePaise); // throws on overflow
}
public static void main(String[] args) {
System.out.println("v1 10 mugs : " + totalV1(10, 25_000));
System.out.println("v1 90,000 mugs : " + totalV1(90_000, 25_000));
try {
System.out.println("v2 90,000 mugs : " + totalV2(90_000, 25_000));
} catch (ArithmeticException e) {
System.out.println("v2 90,000 mugs : refused, " + e.getMessage());
}
try {
totalV2(-3, 25_000);
} catch (IllegalArgumentException e) {
System.out.println("v2 -3 mugs : refused, " + e.getMessage());
}
}
}
Real output:
v1 10 mugs : 250000
v1 90,000 mugs : -2044967296
v2 90,000 mugs : refused, integer overflow
v2 -3 mugs : refused, qty out of range: -3
Ninety thousand mugs at 250 rupees (25,000 paise) is 2,250,000,000 paise, more than an int can hold, so v1 silently wrapped to -2044967296. v2 refused with integer overflow, and refused -3 before multiplying. C and C++ have the same problem, and worse, because signed overflow there is undefined behaviour (episodes 52-54).
The habits across languages
| Habit | Python | Java | JavaScript (Node) | C / C++ |
|---|---|---|---|---|
| Allowlist validation | re.fullmatch, schema libraries |
Pattern.matches, Bean Validation |
regex ^...$, schema libraries |
check every length and range yourself |
| Canonicalise | unicodedata.normalize, os.path.realpath |
Normalizer.normalize, Path.toRealPath |
str.normalize("NFKC"), path.resolve |
realpath |
| Parameterise SQL | execute(sql, params) |
PreparedStatement |
driver placeholders | prepared statements in the DB library |
| No shell | subprocess.run([...]) |
ProcessBuilder(list) |
execFile / spawn (not exec) |
execv family (not system) |
| Encode output | html.escape, auto-escaping templates |
template engines, OWASP Java Encoder | textContent, framework escaping |
encode before writing HTML |
| Safe numbers | big ints by default | Math.*Exact |
Number.isSafeInteger, BigInt |
checked arithmetic, compiler builtins |
The standards: where the rules are written down
- OWASP ASVS (Application Security Verification Standard) is a checklist of security requirements you can verify an application against: for developers to build to, testers to test against, and buyers to ask for. "The latest stable version is version 5.0.0 (dated May 2025)." It has three levels: L1 low assurance (simple, low-risk apps such as brochure sites or MVPs), L2 standard assurance (apps with personal data or business logic, the usual target), L3 high assurance (financial systems, healthcare and other high-value systems).
- The OWASP Cheat Sheet Series gives "concise, practical application security guidance that developers and defenders can apply in real projects": short, self-contained guides, one per topic (input validation, error handling, logging, SQL injection prevention...). The OWASP Developer Guide counted "91 of them as of March 2024".
- The SEI CERT coding standards, from Carnegie Mellon University's Software Engineering Institute, are numbered secure-coding rules per language: C, C++, Oracle Java, Perl, Fortran, plus Android. Example: NUM00-J above.
- The CWE Top 25 Most Dangerous Software Weaknesses, published by MITRE, ranks weakness types (CWEs, episode 8) using real vulnerability data. The 2025 list used "39,080 CVE Records for vulnerabilities published between June 1, 2024 and June 1, 2025", scoring each CWE as frequency × average CVSS severity (both normalised) × 100.
CWE Top 25 (2025): the top ten, and where this course covers them
| Rank | CWE | Weakness | Episode |
|---|---|---|---|
| 1 | CWE-79 | Cross-site scripting (XSS) | 40 |
| 2 | CWE-89 | SQL injection | 38 |
| 3 | CWE-352 | Cross-site request forgery (CSRF) | 42 |
| 4 | CWE-862 | Missing authorization | 37 |
| 5 | CWE-787 | Out-of-bounds write | 53 |
| 6 | CWE-22 | Path traversal | 47 |
| 7 | CWE-416 | Use after free | 53 |
| 8 | CWE-125 | Out-of-bounds read | 53 |
| 9 | CWE-78 | OS command injection | 39 |
| 10 | CWE-94 | Code injection | 39 |
Further down: 18 CWE-20 Improper Input Validation, 22 CWE-918 SSRF (episode 43), 24 CWE-639 Authorization Bypass Through User-Controlled Key (IDOR/BOLA, episodes 37 and 49), 25 CWE-770 Allocation of Resources Without Limits or Throttling (episode 50). Three of the top eight are memory-safety bugs, which input validation alone can't fix: that is where the course goes next.
The whole chain
- A bill of -1,000 → check at the trust boundary, follow taint from sources to sinks.
<SCRIPT>got past a denylist → allowlist validation, on the server.- Admin in disguise → canonicalise, then validate.
- O'Neil broke three sinks → encode or parameterise at the sink.
- Errors leaked, an outage granted a refund → generic errors, fail closed, secure defaults.
- A report could delete orders, a total wrapped → least privilege and defensive programming.
...and you just invented secure coding.
Common mistakes (and what they cause)
| Mistake | Real message / result | Why it's wrong | Fix |
|---|---|---|---|
| Trusting a request field | edited : -1000 |
the client can edit anything | validate at the trust boundary, on the server |
| Denylist filter | <SCRIPT>x</SCRIPT> deny: accepted |
denylists miss variants | allowlist + fullmatch |
| Validate, then normalise | 'Admin' v1: created 'admin' |
the checked text isn't the used text | canonicalise first |
| Gluing data into SQL | OperationalError - near "Neil": syntax error |
data mixed into code | placeholders VALUES (?) |
| Gluing data into a shell command | /bin/sh: 1: Syntax error: Unterminated quoted string |
the shell parses the data | argument list, no shell |
| Traceback shown to users | (db: postgres://shop_admin:toy-S3cret@...) |
leaks code, paths, secrets | generic message + reference id, details in the log |
except: return True |
v1 ravi may refund: True |
fails open on outages | fail closed, alert |
| Unsafe default parameter | v1 pay.example: TLS check OFF |
doing nothing is unsafe | secure default verify_tls=True |
| Full rights for a read-only job | v1 read-write: ok, orders left: 0 |
one bug deletes everything | read-only / least-privilege connection |
Plain int multiplication |
v1 90,000 mugs : -2044967296 |
silent wraparound | Math.multiplyExact, range checks |
assert as a security check |
refunded -500 (with python -O) |
asserts are removed | real if checks that raise |
Mini project: a small order service with every habit
# Mini project: a small order service that uses every habit from episode 51.
import html, sqlite3, unicodedata, uuid, json
PRICE = {"chai-mug": 250, "tea-box": 400}
def log(event): # structured, no secrets
print("[log]", json.dumps(event, separators=(",", ":")))
def canonical(text): # 1. canonicalise first
return unicodedata.normalize("NFKC", text).strip()
def validate(req): # 2. allowlist validation
item, qty = canonical(req.get("item", "")), canonical(req.get("qty", ""))
name = canonical(req.get("name", ""))
if item not in PRICE:
raise ValueError("unknown item")
if not (qty.isascii() and qty.isdigit() and 1 <= int(qty) <= 10):
raise ValueError("qty must be 1-10")
if not (1 <= len(name) <= 30 and
all(c.isalpha() or c in " .'-" for c in name)):
raise ValueError("bad name")
return item, int(qty), name
def place_order(db, req):
try:
item, qty, name = validate(req)
total = PRICE[item] * qty
db.execute("INSERT INTO orders VALUES (?, ?, ?)", # 3. parameterise
(name, item, total))
return f"<p>Thanks {html.escape(name)}: {total} rupees</p>" # 4. encode
except ValueError as e: # expected: tell the user why
log({"ev": "order_rejected", "why": str(e)})
return f"<p>Order rejected: {html.escape(str(e))}</p>"
except Exception as e: # 5. safe errors, fail closed
ref = uuid.uuid4().hex[:8]
log({"ev": "order_error", "ref": ref, "type": type(e).__name__})
return f"<p>Something went wrong. Reference: {ref}</p>"
db = sqlite3.connect(":memory:") # 6. least privilege: in a real
db.execute("CREATE TABLE orders (name TEXT, item TEXT, total INT)") # app, a
# login that can only INSERT
for req in ({"item": "chai-mug", "qty": "2", "name": "Ravi O'Neil"},
{"item": "chai-mug", "qty": "-4", "name": "Neha"},
{"item": "tea-box", "qty": "3", "name": "Zoë"},
{"item": "tea-box", "qty": "1", "name": "<b>x</b>"}):
print(place_order(db, req))
print(db.execute("SELECT * FROM orders").fetchall())
Real output:
<p>Thanks Ravi O'Neil: 500 rupees</p>
[log] {"ev":"order_rejected","why":"qty must be 1-10"}
<p>Order rejected: qty must be 1-10</p>
<p>Thanks Zoë: 1200 rupees</p>
[log] {"ev":"order_rejected","why":"bad name"}
<p>Order rejected: bad name</p>
[("Ravi O'Neil", 'chai-mug', 500), ('Zoë', 'tea-box', 1200)]
Note how the full-width digit 3 became 3 before validation, the apostrophe was encoded for HTML but stored exactly, and Zoë was accepted while <b>x</b> was not.
Practice
- Add a SQL sink to the taint tracker: tainted text must never become part of the query, but it may be passed as a parameter.
- Make the name allowlist accept accented and non-English names like
Zoë,Joséandनेहा, while still rejecting<b>x</b>and digits. - In Java, write a cart sum that uses
Math.addExactand rejects negative lines. - Which ASVS level fits (a) a college fest website, (b) a food-delivery app, (c) a UPI payments app? Why?
Practice 1 solution
# Practice 1: a SQL sink for the taint tracker, and a safe way through it.
import sqlite3
class Tainted(str):
def __add__(self, other): return Tainted(str(self) + str(other))
def __radd__(self, other): return Tainted(str(other) + str(self))
def source(value): return Tainted(value)
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE users (name TEXT)")
def sql_sink(query, params=()):
if isinstance(query, Tainted): # the QUERY text must be ours
raise RuntimeError("tainted data reached the SQL sink")
return db.execute(query, params) # params may be tainted: safe
name = source("Ravi O'Neil")
try:
sql_sink("INSERT INTO users VALUES ('" + name + "')")
except RuntimeError as e:
print("glued :", e)
sql_sink("INSERT INTO users VALUES (?)", (name,))
print("params:", sql_sink("SELECT name FROM users").fetchall())
glued : tainted data reached the SQL sink
params: [("Ravi O'Neil",)]
Practice 2 solution
isalpha() alone rejects नेहा, because Devanagari vowel signs are combining marks (Unicode category M), not letters: "नेहा" is 4 code points ['न', 'े', 'ह', 'ा']. Allow categories L (letter) and M (mark).
# Practice 2: accept accented and non-English letters, still allowlisted.
import unicodedata
def ok_char(c): # L = letter, M = mark (e.g. a vowel sign)
return unicodedata.category(c)[0] in "LM" or c in " .'-"
def valid_name(name):
name = unicodedata.normalize("NFKC", name).strip() # canonicalise first
return (1 <= len(name) <= 30 and name[0].isalpha()
and all(ok_char(c) for c in name))
for n in ("Zoë", "José", "नेहा", "D'Souza", "<b>x</b>", "Neha1"):
print(f"{n:9} {valid_name(n)}")
Zoë True
José True
नेहा True
D'Souza True
<b>x</b> False
Neha1 False
Practice 3 solution
// Practice 3: a cart sum that refuses to overflow.
public class Main {
static int cartTotal(int[] linePaise) {
int total = 0;
for (int line : linePaise) {
if (line < 0) throw new IllegalArgumentException("negative line");
total = Math.addExact(total, line); // throws on overflow
}
return total;
}
public static void main(String[] args) {
System.out.println(cartTotal(new int[]{50_000, 40_000}));
try {
cartTotal(new int[]{2_000_000_000, 2_000_000_000});
} catch (ArithmeticException e) {
System.out.println("refused: " + e.getMessage());
}
}
}
90000
refused: integer overflow
Practice 4 discussion
(a) A fest site with no logins or personal data: L1. (b) A food-delivery app holds addresses, phone numbers, orders and payments through a provider: L2. (c) A payments app moves money and is a high-value target: L3. The level follows the risk: what data the app holds and what an attacker could gain.
Quick quiz
import unicodedata
def safe_path(name):
if ".." in name:
raise ValueError("no ..")
name = unicodedata.normalize("NFKC", name)
return "/shop/files/" + name
What is wrong? A: nothing, it blocks ... B: it validates before it normalises. C: NFKC is too slow. D: it should use a denylist.
Answer
B. NFKC turns look-alike characters into plain ones; for example U+2025 TWO DOT LEADER ‥ becomes .. (checked with Python 3.13). So a name with no .. during the check can contain .. after normalising. Canonicalise first, then validate, then use exactly what you validated, and resolve the real path and check it stays inside the folder (episode 47).
Interview questions
- What is a trust boundary? Give examples. The line where data moves from less trusted to more trusted code: an HTTP request reaching the server, a file upload, a message from another service, a third-party API response. Validate there.
- Explain sources, sinks and taint. Sources bring untrusted data in, sinks perform actions (SQL, shell, HTML, file paths, eval); taint marks unchecked data, and a bug is tainted data reaching a sink unchecked. Taint analysis tools trace these paths.
- Allowlist or denylist validation, and why? Allowlist: good input has few shapes, bad input has endless ones; denylists are always incomplete.
- Is input validation enough to stop SQL injection or XSS? No. Valid data like
O'Neilstill breaks a query; the fix is at the sink: parameterised queries and contextual output encoding. Validation is defence in depth. - What is canonicalisation and why must it come before validation? Converting input to one standard form (Unicode normalisation, case folding, URL-decoding, real paths). If you validate the raw form and use the canonical form, disguised input bypasses the check.
- What does "contextual output encoding" mean? Escaping for the exact destination: HTML body, HTML attribute, JavaScript, URL and CSS each need different encoding.
- How should errors be shown to users? A generic message and a reference id; full details only in server logs; never secrets, stack traces or SQL in responses.
- Fail open vs fail closed? On an error or timeout, a security decision should deny (fail closed) and alert, not allow.
- What are secure defaults? Give an example. Defaults that are safe without configuration: TLS verification on, debug off, minimal permissions for new users and tokens.
- How do you apply least privilege inside an application? Separate, minimal database users or read-only connections, narrow file permissions, scoped tokens and cloud roles, no root.
- How do you prevent integer overflow in Java? Range-check inputs, use
Math.addExact/multiplyExact, a wider type with checks, orBigInteger(SEI CERT NUM00-J). - What are OWASP ASVS levels? L1 low assurance, L2 standard (most apps with personal data), L3 high assurance (finance, healthcare, critical systems); ASVS 5.0.0 was released in May 2025.
- What is the CWE Top 25 and how is it built? MITRE's ranking of the most dangerous weakness types, scored from frequency and average CVSS severity across tens of thousands of CVE records; 2025's top three: XSS, SQL injection, CSRF.
Glossary
| Term | Meaning, with an example |
|---|---|
| Secure coding | Writing software so that it resists attack, using habits like those in this episode. |
| Untrusted data | Data from outside your control, e.g. a form field or a cookie. |
| Trust boundary | The line where data enters more trusted code, e.g. a request reaching the server. |
| Source | Where untrusted data enters a program, e.g. request.args, input(), a file read. |
| Sink | Where data becomes an action, e.g. a SQL query, a shell command, HTML, a file path. |
| Taint | A mark on data meaning "from a source, not checked yet"; it spreads when data is copied or joined. |
| Taint analysis | Tracing tainted data from sources to sinks to find unchecked paths. |
| Static analysis | Checking code without running it, e.g. a tool that flags SQL built from request data. |
| Input validation | Checking input has the expected form and meaning before use. |
| Denylist (blocklist) | A list of known-bad input to reject; always incomplete. |
| Allowlist | A definition of known-good input; everything else is rejected. |
| Syntactic validation | Checking form: type, length, range, format, e.g. six digits for a pincode. |
| Semantic validation | Checking meaning, e.g. a delivery date must be in the future. |
| Regular expression (regex) | A pattern for text, e.g. [A-Za-z][A-Za-z .'-]{0,29}. |
fullmatch |
A regex match that must cover the whole string. |
| Canonicalisation | Converting input to one standard form before checking it, e.g. admin → admin. |
| Unicode normalisation (NFKC) | A standard way to turn look-alike and full-width characters into plain ones. |
| Case folding | Converting text to a form for case-insensitive comparison, e.g. Admin → admin. |
| Full-width characters | Wide versions of Latin letters and digits used in East Asian text, e.g. a, 3. |
| Output encoding (escaping) | Converting special characters into a safe form for a specific context, e.g. ' → ' in HTML. |
| Context (for encoding) | Where the data goes: HTML body, attribute, JavaScript, URL or CSS. |
| Parameterisation | Sending data separately from a command, e.g. SQL placeholders or an argument list. |
| Placeholder | A marker like ? in a SQL statement that the database fills with data, never code. |
| Prepared statement | A SQL statement compiled with placeholders, then run with separate values. |
| Argument list | Running a program with each argument as its own item, with no shell parsing. |
| Injection | Untrusted data changing the meaning of a command or query (episodes 38-40). |
| Stack trace (traceback) | The chain of function calls that led to an error, with files and lines. |
| Verbose error | An error message that reveals internals to the user. |
| Connection string | The address, username and password used to reach a database. |
| Safe error handling | Generic messages to users, details in server logs, no secrets anywhere. |
| Reference id | A random id shown with a generic error that matches a log entry. |
| Fail open | On an error, a security check allows the action. |
| Fail closed | On an error, a security check denies the action. |
| Secure default | A default setting that is safe without any change, e.g. TLS checks on. |
| Secure by default | Designing so that the out-of-the-box behaviour is the safe one. |
| Least privilege | Giving each part only the rights it needs, e.g. a read-only report connection. |
| Blast radius | How much damage one bug or stolen credential can do. |
| Defensive programming | Writing code that assumes callers and inputs may be wrong. |
| Precondition | Something that must be true before a function runs, e.g. qty >= 1. |
assert |
A debugging check in Python, removed by python -O; not a security control. |
| Integer overflow | A result too big for its number type, e.g. Java int wrapping to a negative value. |
Math.multiplyExact |
Java method that multiplies or throws ArithmeticException on overflow. |
| Paise | Hundredths of a rupee; money is stored in whole paise to avoid fractions. |
| OWASP | The Open Worldwide Application Security Project, a non-profit that publishes free security guidance. |
| OWASP ASVS | The Application Security Verification Standard: verifiable security requirements; 5.0.0 (May 2025). |
| ASVS levels | L1 low assurance, L2 standard, L3 high assurance (finance, healthcare). |
| OWASP Cheat Sheet Series | Short, practical OWASP guides, one per security topic. |
| SEI CERT coding standards | Carnegie Mellon SEI's numbered secure-coding rules for C, C++, Java, Perl, Fortran and Android. |
| CWE | Common Weakness Enumeration: a named type of weakness, e.g. CWE-89 SQL injection (episode 8). |
| CVE | A record of one specific vulnerability in one product (episode 8). |
| CWE Top 25 | MITRE's yearly ranking of the most dangerous weakness types. |
| Memory safety | Protection against bugs like out-of-bounds writes and use after free (next episodes). |
Summary
- Find your trust boundaries and treat everything from outside as untrusted; follow taint from sources to sinks.
- Validate with allowlists, on the server, after canonicalising.
- Encode or parameterise at every sink, even for valid data.
- Errors: generic for users, detailed in logs, never secrets. Fail closed, and make the defaults safe.
- Give each piece of code least privilege, and program defensively (preconditions, limits, overflow-safe arithmetic; never
assertfor security). - Check your work against OWASP ASVS (L1/L2/L3), use the OWASP Cheat Sheet Series and SEI CERT rules, and know the CWE Top 25 (2025: XSS, SQL injection, CSRF at the top; three memory bugs in the top eight).
Next episode: How programs use memory: the process memory layout, stack frames, the heap, pointers and undefined behaviour.