These are the notes for Cybersecurity Fundamentals (defensive), episode 46. Episode 45 fixed the design. Today the code is fine, but it becomes unsafe because of how it is set up (factory passwords, debug mode, directory listing, an XML parser setting) and how it behaves when something goes wrong (an error that becomes "allowed", a transfer that stops halfway). Every demo runs live, every fix is shown, and every term is explained the first time it appears; the Glossary at the end defines them all again.
Neha, Ravi, the shop and every value are made up. Every server is a toy started by the program itself on 127.0.0.1 (this same machine), every password is fake, and the "secret" file is a toy file the program writes itself. Nothing outside the machine is contacted. Python samples run on 11 Nov 2026 with Python 3.13 and defusedxml 0.7.1 (pip install defusedxml); every output below is copied from a real run. Random values (reference ids, temporary paths) differ each run.
The problems you'll solve
| Problem | Idea it teaches |
|---|---|
| The shop goes live with factory settings | security misconfiguration, default credentials, hardening, hardening checklists |
| An error page shows our SQL and file paths | verbose error messages, stack traces, reference ids, logging |
| The server lists every file in a folder | directory listing, unnecessary features |
| Developer helpers left on | debug mode in production, unneeded ports and services |
| An XML upload reads a file on our server | XML external entities (XXE), DTDs, safe XML parser settings, defusedxml |
| Three identical servers, a year later | configuration drift, baselines, infrastructure as code |
| An outage turns "deny" into "allow" | mishandling of exceptional conditions, fail open vs fail closed |
| A transfer stops halfway | transactions and rollback |
Problem 1: factory settings
Basic words first:
- Configuration is every setting outside the code: passwords, feature switches, ports, file locations, cloud permissions.
- Security misconfiguration means unsafe settings anywhere in the stack: app, framework, web server, database, operating system or cloud. In the OWASP Top 10 it was A05 in 2021 (OWASP found some form of misconfiguration in 90% of the applications tested) and rose to A02 in 2025.
- Default credentials are the factory username and password (
admin/admin), the same on every copy and printed in every manual. OWASP: default accounts "still enabled and unchanged". - Hardening means removing everything unneeded and locking down every setting. A hardening checklist lists those steps; the CIS Benchmarks (episode 9) are well-known ones for operating systems, databases and cloud services.
Demo 1: a start-up hardening check
The same checklist, written as code, runs before the server starts and refuses to start if anything fails.
# The shop's production settings, and a start-up check against a hardening checklist
CONFIG = {"admin_user": "admin", "admin_password": "admin", # factory default
"debug": True, # left on from testing
"directory_listing": True,
"error_detail": "full", # stack traces to users
"open_ports": [443, 8080, 5432], # 8080 = old test server
"sample_app_installed": True}
CHECKLIST = [
("default credentials", lambda c: c["admin_password"] in {"admin", "password"}),
("debug mode on", lambda c: c["debug"]),
("directory listing", lambda c: c["directory_listing"]),
("verbose errors", lambda c: c["error_detail"] != "generic"),
("unneeded ports", lambda c: set(c["open_ports"]) - {443}),
("sample app present", lambda c: c["sample_app_installed"]),
]
problems = [name for name, bad in CHECKLIST if bad(CONFIG)]
for p in problems:
print("FAIL:", p)
if problems:
raise SystemExit(f"refusing to start: {len(problems)} misconfigurations")
print("all checks passed, starting")
Output:
FAIL: default credentials
FAIL: debug mode on
FAIL: directory listing
FAIL: verbose errors
FAIL: unneeded ports
FAIL: sample app present
refusing to start: 6 misconfigurations
Why the settings were wrong: nothing in the code changed; the deployment did. A repeatable, automated check catches it every time. OWASP: "A repeatable hardening process makes it fast and easy to deploy another environment that is appropriately locked down."
Problem 2: verbose error messages and stack traces
- A stack trace (Python calls it a traceback) lists the functions that were running when an error happened, with file names, line numbers and source lines.
- A verbose error message reveals internal details: SQL queries, table names, file paths, library versions. It is reconnaissance for an attacker.
- A reference id is a short random code shown to the user and written in the log next to the full error, so support can find the real error without showing it to anyone.
Demo 2: a stack trace sent to the user
order is a reserved word in SQL (as in ORDER BY), so the query fails.
# An order lookup that crashes on bad input. What does the USER see?
import traceback, secrets, sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders (id INTEGER, item TEXT)")
def handle_v1(order_id): # sends the whole error to the user
try:
return db.execute("SELECT item FROM order WHERE id = ?",
(int(order_id),)).fetchone()
except Exception:
return traceback.format_exc()
def handle_v2(order_id): # details go to the log, not the user
try:
return db.execute("SELECT item FROM order WHERE id = ?",
(int(order_id),)).fetchone()
except Exception as e:
ref = secrets.token_hex(4)
LOG.append(f"[{ref}] {type(e).__name__}: {e} id={order_id!r}")
return f"Sorry, something went wrong. Reference: {ref}"
LOG = []
print("USER SEES (v1):\n" + handle_v1("501"))
print("USER SEES (v2):", handle_v2("501"))
print("SERVER LOG :", LOG[0])
Output:
USER SEES (v1):
Traceback (most recent call last):
File "/tmp/claude-0/run_main.py", line 8, in handle_v1
return db.execute("SELECT item FROM order WHERE id = ?",
~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(int(order_id),)).fetchone()
^^^^^^^^^^^^^^^^^
sqlite3.OperationalError: near "order": syntax error
USER SEES (v2): Sorry, something went wrong. Reference: 037712ec
SERVER LOG : [037712ec] OperationalError: near "order": syntax error id='501'
Why it matters: version 1 tells everyone the file, the line, the exact SQL and the database library. OWASP lists "Error handling reveals stack traces or other overly informative error messages to users" as a classic misconfiguration. Version 2 gives users a polite message and keeps the details in the log.
Problem 3: directory listing
Directory listing is a web server feature that shows a page listing every file in a folder when the folder has no home page (index.html). Like leaving the stockroom door open.
Demo 3: Python's http.server lists a folder
# Python's built-in web server, pointed at the shop's upload folder
import http.server, threading, urllib.request, tempfile, os, re, functools
site = tempfile.mkdtemp()
for name in ["index.html", "logo.png", "backup-2026-11.zip", ".env"]:
open(os.path.join(site, name), "w").write("toy file")
os.remove(os.path.join(site, "index.html")) # someone deleted the home page
def serve(handler, port):
h = functools.partial(handler, directory=site)
srv = http.server.HTTPServer(("127.0.0.1", port), h)
threading.Thread(target=srv.serve_forever, daemon=True).start()
class NoListing(http.server.SimpleHTTPRequestHandler):
def list_directory(self, path): # turn the feature off
self.send_error(404, "Not Found"); return None
def log_message(self, *a): pass
class Default(http.server.SimpleHTTPRequestHandler):
def log_message(self, *a): pass
serve(Default, 8941); serve(NoListing, 8942)
page = urllib.request.urlopen("http://127.0.0.1:8941/").read().decode()
print("default :", re.findall(r'href="([^"]+)"', page))
try:
urllib.request.urlopen("http://127.0.0.1:8942/")
except urllib.error.HTTPError as e:
print("fixed :", e.code, e.reason)
Output:
default : ['.env', 'backup-2026-11.zip', 'logo.png']
fixed : 404 Not Found
Why it matters: the .env file (which usually holds passwords and keys) and the backup are now one click away. OWASP's own scenario: directory listing let an attacker download an app's compiled classes, reverse engineer them and find an access-control flaw. Turn the feature off and keep backups and secrets out of the web folder entirely.
Problem 3b: debug mode and unneeded features
- Debug mode gives developers extra help: detailed error pages, settings dumps, sometimes an interactive console in the browser. The Werkzeug debugger (used by Flask) documents: "The debugger allows the execution of arbitrary code which makes it a major security risk" and "The debugger must never be used on production machines."
- Unneeded features and ports: a port is a numbered network door on a server (episode 17). A leftover test server on 8080, a database port open to the internet, sample apps, admin consoles, old APIs: each is more attack surface (all the places an attacker can try). OWASP's first scenario is sample applications with an admin console and default accounts left on a production server.
- Production means the real, live system that customers use (as opposed to development and test).
Rule: if you don't use it, turn it off or remove it, and check that in code.
Problem 4: XML external entities (XXE)
- XML is a text format for data with tags:
<order><item>charger</item></order>. - A DTD (document type definition) is an optional block at the top of an XML document,
<!DOCTYPE ...>, that can declare entities: named shortcuts replaced by text, like¬e;. - An external entity says "fetch this text from a file or URL":
<!ENTITY note SYSTEM "file://...">. - XXE (XML external entity injection). OWASP: "XML External Entity (XXE) injection occurs when an XML processor resolves an external entity from untrusted input." The parser can then read files on the server, or make requests to internal addresses (an SSRF, episode 43).
Demo 4: one parser setting reads a toy secret file
# XXE: an XML parser that fetches "external entities". All local and toy.
import xml.sax, io, os, tempfile
secret = os.path.join(tempfile.mkdtemp(), "secret.txt")
open(secret, "w").write("DB_PASSWORD=toy-pass-123") # a toy secret file
order_xml = f"""<?xml version="1.0"?>
<!DOCTYPE order [ <!ENTITY note SYSTEM "file://{secret}"> ]>
<order><item>charger</item><note>¬e;</note></order>"""
class Reader(xml.sax.ContentHandler):
def __init__(self): super().__init__(); self.text = ""
def characters(self, data): self.text += data.strip()
def parse(xml_text, external_entities):
parser = xml.sax.make_parser()
parser.setFeature(xml.sax.handler.feature_external_ges, external_entities)
r = Reader(); parser.setContentHandler(r)
parser.parse(io.StringIO(xml_text))
return r.text
print("misconfigured:", parse(order_xml, True)) # someone turned it ON
print("default :", parse(order_xml, False)) # off since Python 3.7.1
import defusedxml.ElementTree as safe_et
try:
safe_et.fromstring(order_xml)
except Exception as e:
print("defusedxml :", type(e).__name__)
Output (the temporary path differs each run):
misconfigured: chargerDB_PASSWORD=toy-pass-123
default : charger
defusedxml : EntitiesForbidden
Why: one setting, feature_external_ges (external general entities), turned on. That's why XXE (CWE-611) was folded into security misconfiguration in the 2021 Top 10.
Safe XML parser settings
- OWASP: "Disable document type definitions (DTDs) whenever possible."
- Python: since Python 3.7.1,
xml.saxandxml.dom.pulldomno longer process external general entities by default;xml.etree.ElementTreedoesn't expand external entities and raisesParseError. Never turn these on for untrusted input. - The Python docs recommend defusedxml "for any server code that parses untrusted XML data"; OWASP says the same. It refuses DTD tricks with errors like
EntitiesForbidden. - Other languages: Java → set the feature
http://apache.org/xml/features/disallow-doctype-decltotrue; .NET →DtdProcessing.Prohibit; PHP → don't enableLIBXML_NOENT,LIBXML_DTDLOADorLIBXML_DTDVALIDfor untrusted XML (OWASP). - Better still: accept JSON with a schema when you don't need XML.
Problem 5: configuration drift
- A baseline is the approved configuration, reviewed and stored in version control (Git).
- Configuration drift is the slow change of live systems away from the baseline through hand edits: "just turn debug on for a minute".
- Infrastructure as code (IaC) builds servers only from files in Git, using tools (tools such as Terraform or Ansible), so every server can be rebuilt identically.
Demo 5: detecting drift
# Configuration drift: compare each live server with the approved baseline
BASELINE = {"debug": False, "tls_min": "1.2", "ssh_pw": False, "ports": [443]}
LIVE = {"web-1": {"debug": False, "tls_min": "1.2", "ssh_pw": False, "ports": [443]},
"web-2": {"debug": True, "tls_min": "1.2", "ssh_pw": False, "ports": [443]},
"web-3": {"debug": False, "tls_min": "1.0", "ssh_pw": True, "ports": [443, 22]}}
def drift(live):
return [f"{k}: {live.get(k)!r} (should be {v!r})" for k, v in BASELINE.items()
if live.get(k) != v]
for server, cfg in LIVE.items():
diffs = drift(cfg)
print(server, "OK" if not diffs else "DRIFT")
for d in diffs:
print(" ", d)
Output:
web-1 OK
web-2 DRIFT
debug: True (should be False)
web-3 DRIFT
tls_min: '1.0' (should be '1.2')
ssh_pw: True (should be False)
ports: [443, 22] (should be [443])
Run a check like this every day, and rebuild a drifted server from the baseline instead of patching it by hand again.
Problem 6: exceptional conditions and fail open vs fail closed
- An exception is Python's way of signalling an error (
TimeoutError,ConnectionError). An exceptional condition is anything unusual: a service that doesn't answer, a full disk, a dropped connection, a strange input. - Mishandling of exceptional conditions is a new OWASP category in 2025, A10: "improper error handling, logical errors, and failing open scenarios"; applications that "fail to prevent, detect or respond to unusual situations".
- Fail open: when a check can't be done, allow. Fail closed: when a check can't be done, deny. (Episode 3: fire exits fail safe and unlock; a bank vault fails secure and stays shut.) Security checks should fail closed.
Demo 6: fail open vs fail closed
# Can this user see the refunds page? We ask the permission service.
def permission_service(user):
raise TimeoutError("permission service did not answer in 2 s") # it's down
def can_view_refunds_v1(user):
try:
return permission_service(user)
except Exception:
return True # "don't block people when the service is down"
def can_view_refunds_v2(user):
try:
return permission_service(user) is True
except TimeoutError:
return False # unknown answer = no access (fail closed)
for check in (can_view_refunds_v1, can_view_refunds_v2):
print(f"{check.__name__}('ravi') ->", check("ravi"))
Output:
can_view_refunds_v1('ravi') -> True
can_view_refunds_v2('ravi') -> False
Why: version 1 turned an error into access, and except Exception also swallows real bugs. Catch only the errors you expect, deny by default, and log them so someone fixes the service.
Demo 7: a transfer that stops halfway
A transaction is a group of database changes that either all happen or none do. Rollback undoes every change in the transaction. In Python's sqlite3, with db: commits on success and rolls back on an exception.
# Move Rs 500 from the wallet to the shop. Halfway through, something fails.
import sqlite3
def setup():
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE acct (name TEXT PRIMARY KEY, bal INTEGER)")
db.executemany("INSERT INTO acct VALUES (?, ?)", [("ravi", 1000), ("shop", 0)])
db.commit(); return db
def transfer(db, amount, crash):
db.execute("UPDATE acct SET bal = bal - ? WHERE name = 'ravi'", (amount,))
if crash: raise ConnectionError("network dropped") # the exceptional condition
db.execute("UPDATE acct SET bal = bal + ? WHERE name = 'shop'", (amount,))
db = setup() # v1: commits each step
try:
transfer(db, 500, crash=True)
except ConnectionError as e:
db.commit(); print("v1 error:", e)
print("v1:", db.execute("SELECT * FROM acct").fetchall(), "<- Rs 500 vanished")
db = setup() # v2: one transaction
try:
with db: # commit if OK, ROLLBACK on error
transfer(db, 500, crash=True)
except ConnectionError as e:
print("v2 error:", e)
print("v2:", db.execute("SELECT * FROM acct").fetchall(), "<- nothing changed")
Output:
v1 error: network dropped
v1: [('ravi', 500), ('shop', 0)] <- Rs 500 vanished
v2 error: network dropped
v2: [('ravi', 1000), ('shop', 0)] <- nothing changed
OWASP's advice for A10: "Implement secure error handling, test edge cases, enforce resource limits, avoid exposing stack traces, and ensure applications fail securely." Ask of every step: what if it fails right here?
The whole chain
- Factory settings shipped → hardening checklist as code, refuse to start.
- A stack trace reached users → generic message + reference id, details in the log.
- Every file listed, debug on → turn off unused features, ports and sample apps.
- One parser setting read a file → XXE: no DTDs, safe defaults, defusedxml.
- Hand edits → configuration drift: baseline in Git, rebuild with IaC.
- An error became "allowed", a transfer stopped halfway → fail closed and roll back.
Common mistakes (and what they cause)
| Mistake | What happens (real output) | Why | Fix |
|---|---|---|---|
| Default admin password | FAIL: default credentials |
factory passwords are public | unique secret set at install |
| Returning the traceback | sqlite3.OperationalError: near "order": syntax error shown to users |
users see SQL, files, lines | generic message + reference id |
| Directory listing on | default : ['.env', 'backup-2026-11.zip', 'logo.png'] |
a feature left on | turn it off; secrets out of the web root |
| Debug mode in production | interactive console, settings pages | a developer tool | debug: False, checked at start-up |
feature_external_ges on |
misconfigured: chargerDB_PASSWORD=toy-pass-123 |
the parser fetched a file | keep defaults off, use defusedxml |
| Hand-editing servers | web-3 DRIFT tls_min: '1.0' |
drift from the baseline | IaC, daily drift checks, rebuild |
except Exception: return True |
can_view_refunds_v1('ravi') -> True |
fails open on any error | expected errors only, deny |
| Committing step by step | v1: [('ravi', 500), ('shop', 0)] |
half-done work | one transaction, rollback |
Mini project: a request handler that is safe by configuration and fails closed
A decorator that turns any unexpected error into a generic 500 with a reference id (details only in the log), an authorization check that fails closed when the roles service times out, and XML imports through defusedxml.
# Mini project: a request handler that is safe by configuration and fails closed
import secrets, defusedxml.ElementTree as ET
LOG = []
SETTINGS = {"debug": False, "error_detail": "generic"}
def safe_endpoint(fn):
"""Wrap an endpoint: generic errors to users, details to the log."""
def run(user, body):
try:
return fn(user, body)
except PermissionError:
return "403 Forbidden"
except Exception as e: # last resort, never shown to users
ref = secrets.token_hex(4)
LOG.append(f"[{ref}] {fn.__name__}: {type(e).__name__}: {e}")
return f"500 Something went wrong. Reference: {ref}"
return run
def allowed(user, action, roles_api):
try:
return roles_api(user) == "admin" and action in {"refund"}
except TimeoutError:
LOG.append(f"roles API timeout for {user}: denied")
return False # fail closed
def roles_down(user): raise TimeoutError("no answer in 2 s")
def roles_up(user): return "admin" if user == "neha" else "customer"
@safe_endpoint
def refund(user, body):
roles = roles_down if body.get("outage") else roles_up
if not allowed(user, "refund", roles):
raise PermissionError
return "200 refund issued"
@safe_endpoint
def import_order(user, xml_text):
order = ET.fromstring(xml_text) # defusedxml: no DTD tricks
return "200 imported " + order.findtext("item")
print(refund("neha", {}))
print(refund("ravi", {}))
print(refund("neha", {"outage": True}))
print(import_order("ravi", "<order><item>charger</item></order>"))
print(import_order("ravi", '<!DOCTYPE o [<!ENTITY x SYSTEM "file:///toy/secret.txt">]><order>&x;</order>'))
print(import_order("ravi", "<order><item>charger</order>"))
print("LOG:", *LOG, sep="\n ")
Output (reference ids differ each run):
200 refund issued
403 Forbidden
403 Forbidden
200 imported charger
500 Something went wrong. Reference: 6602191a
500 Something went wrong. Reference: 0ccd0604
LOG:
roles API timeout for neha: denied
[6602191a] import_order: EntitiesForbidden: EntitiesForbidden(name='x', system_id='file:///toy/secret.txt', public_id=None)
[0ccd0604] import_order: ParseError: mismatched tag: line 1, column 22
Practice
- Add two rules to the start-up checklist: old TLS versions allowed, and missing security headers (episode 41).
- Make
drift()also report settings that are missing from, or not in, the baseline. - Make version 1 of the transfer safe without
with db:. - When is failing open the right choice?
Solution 1
# Practice 1 solution: two more rules for the start-up checklist
CONFIG = {"admin_password": "S7#q-long-random", "debug": False, "tls_min": "1.0",
"security_headers": ["Strict-Transport-Security"]}
NEEDED_HEADERS = {"Strict-Transport-Security", "Content-Security-Policy",
"X-Content-Type-Options"}
CHECKLIST = [
("default credentials", lambda c: c["admin_password"] in {"admin", "password"}),
("debug mode on", lambda c: c["debug"]),
("old TLS allowed", lambda c: c["tls_min"] not in {"1.2", "1.3"}),
("missing headers", lambda c: sorted(NEEDED_HEADERS - set(c["security_headers"]))),
]
for name, bad in CHECKLIST:
result = bad(CONFIG)
print(("FAIL: " if result else "ok: ") + name, result if result and result is not True else "")
Output:
ok: default credentials
ok: debug mode on
FAIL: old TLS allowed
FAIL: missing headers ['Content-Security-Policy', 'X-Content-Type-Options']
Solution 2
live.get(k) already reports a missing key as None; the extra line reports keys the baseline doesn't have.
# Practice 2 solution: drift() also reports keys that are missing or unexpected
BASELINE = {"debug": False, "tls_min": "1.2", "ports": [443]}
def drift(live):
out = [f"{k}: {live.get(k)!r} (should be {v!r})" for k, v in BASELINE.items()
if live.get(k) != v]
out += [f"{k}: unexpected setting {live[k]!r}" for k in live.keys() - BASELINE.keys()]
return out
print(drift({"debug": False, "tls_min": "1.2", "ports": [443]}))
print(drift({"debug": False, "ports": [443], "admin_console": True}))
Output:
[]
["tls_min: None (should be '1.2')", 'admin_console: unexpected setting True']
Solution 3
# Practice 3 solution: the transfer made safe with an explicit rollback
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE acct (name TEXT PRIMARY KEY, bal INTEGER)")
db.executemany("INSERT INTO acct VALUES (?, ?)", [("ravi", 1000), ("shop", 0)])
db.commit()
def transfer(amount, crash):
try:
db.execute("UPDATE acct SET bal = bal - ? WHERE name = 'ravi'", (amount,))
if crash: raise ConnectionError("network dropped")
db.execute("UPDATE acct SET bal = bal + ? WHERE name = 'shop'", (amount,))
db.commit()
return "done"
except ConnectionError as e:
db.rollback() # undo every change since the last commit
return f"rolled back ({e})"
print(transfer(500, crash=True), db.execute("SELECT * FROM acct").fetchall())
print(transfer(500, crash=False), db.execute("SELECT * FROM acct").fetchall())
Output:
rolled back (network dropped) [('ravi', 1000), ('shop', 0)]
done [('ravi', 500), ('shop', 500)]
Solution 4
When safety of people or availability matters more than secrecy, and the feature isn't a security control: fire exits and emergency door releases, a product-recommendation widget (show none or a default list), a spell checker. For authentication, authorization, payments, input validation and anything that protects data, fail closed. If a business truly needs a fallback, make it explicit, limited and logged (for example, a cached decision that expires in minutes), never "allow everything".
Quick quiz
def is_admin(user):
try:
return roles_api.get(user) == "admin"
except Exception:
log.warning("roles API down")
return user in CACHED_ADMINS or True
When the roles API is down, which way does this fail? A: fails closed B: fails open C: never fails D: depends on the log
Answer
B. user in CACHED_ADMINS or True is always True, so any error makes every user an admin: it fails open. Logging the warning doesn't change the decision. Return False (or only a fresh cached answer) when the roles API can't be reached.
Interview questions
- What is security misconfiguration? Examples? Unsafe settings anywhere in the stack: default credentials, debug mode, directory listing, verbose errors, open cloud storage, unneeded ports (OWASP A05:2021, A02:2025).
- Why are verbose errors dangerous? They reveal queries, paths, versions and structure that help attackers plan.
- How should an app handle unexpected errors? Log full details with a reference id; show users a generic message with the id; never a stack trace.
- What is XXE and how do you prevent it? An XML parser resolving external entities from untrusted input; disable DTDs, keep safe defaults, use hardened parsers like defusedxml, or use JSON.
- What is configuration drift and how do you stop it? Live systems changing away from the approved baseline; IaC, no hand edits, automated drift detection, rebuild.
- What is a hardening checklist? A list of secure settings to apply and verify (CIS Benchmarks); best automated in CI and at start-up.
- What is A10:2025? Mishandling of exceptional conditions: improper error handling, logic errors and failing open.
- Fail open vs fail closed? On failure, allow vs deny. Security controls fail closed.
- Why is
except Exceptionrisky? It hides real bugs and makes it easy to fail open; catch specific, expected exceptions. - How do transactions help with exceptional conditions? All-or-nothing changes: an error mid-way rolls everything back, so no half-done state.
Glossary
| Term | Meaning, with an example |
|---|---|
| Configuration | Settings outside the code: passwords, switches, ports. |
| Security misconfiguration | Unsafe settings anywhere in the stack (OWASP A05:2021, A02:2025). |
| Default credentials | Factory username and password: admin / admin. |
| Hardening | Removing what's unneeded and locking down every setting. |
| Hardening checklist | A list of secure settings to apply and check; CIS Benchmarks are well-known ones. |
| CIS Benchmarks | Free hardening guides from the Center for Internet Security (episode 9). |
| Production | The live system real customers use. |
| Stack trace / traceback | The list of running functions, files and lines at an error. |
| Verbose error message | An error that reveals internal details like SQL or file paths. |
| Reference id | A short random code linking a generic error message to the full log entry. |
| Log | A record of events kept on the server for operators. |
| Directory listing | A server page listing every file in a folder. |
.env file |
A file that commonly holds environment settings such as passwords and keys. |
| Debug mode | Developer helpers: detailed errors, settings, consoles; never in production. |
| Werkzeug | The Python web toolkit behind Flask; its debugger can run arbitrary code. |
| Port | A numbered network door on a server: 443 for HTTPS. |
| Attack surface | All the places an attacker can try: ports, pages, APIs, features. |
| XML | A tagged text data format: <order><item>charger</item></order>. |
| DTD | Document type definition: an optional <!DOCTYPE> block that can declare entities. |
| Entity | A named shortcut in XML, like ¬e;. |
| External entity | An entity whose text is fetched from a file or URL. |
| XXE | XML external entity injection: a parser resolving external entities from untrusted input. |
| defusedxml | A Python package of hardened XML parsers that refuse DTD tricks (EntitiesForbidden). |
feature_external_ges |
The SAX setting for external general entities; off by default since Python 3.7.1. |
| Baseline | The approved configuration, stored in Git. |
| Configuration drift | Live systems slowly changing away from the baseline. |
| Infrastructure as code (IaC) | Building servers only from files in version control, with tools. |
| Exception | Python's error signal: TimeoutError, ConnectionError. |
| Exceptional condition | Anything unusual: timeouts, full disks, dropped connections, strange input. |
| Mishandling of exceptional conditions | OWASP A10:2025: improper error handling, logic errors, failing open. |
| Fail open | On failure, allow. |
| Fail closed | On failure, deny. |
| Transaction | A group of database changes that all happen or none do. |
| Rollback | Undoing every change in a failed transaction. |
Summary
- Security misconfiguration (OWASP A05:2021, A02:2025): change default credentials, turn off debug mode, directory listing, sample apps and unneeded ports, and check it all in code with a hardening checklist.
- Users get generic errors with a reference id; stack traces stay in the log.
- XXE: disable DTDs, keep safe parser defaults, use defusedxml for untrusted XML.
- Stop configuration drift: baseline in Git, IaC, daily drift checks, rebuild.
- Mishandling of exceptional conditions (A10:2025): catch expected errors, fail closed, and use transactions so failures never leave half-done work.
Next episode: file uploads, path traversal and insecure deserialisation.