A file-upload endpoint takes a lock before parsing, a parser throws on a malformed file, and nobody releases the lock. Repeat that request a few times and the service is dead for everyone else — not because of a clever exploit, but because of a missing finally. This is the kind of bug OWASP folded into a brand-new 2025 Top 10 category, and it shows up everywhere: file processors, payment flows, debug endpoints that were "only for dev."

In this article you’ll stand up a small Flask app with two of these bugs on purpose, exploit both, then fix them with a global exception handler, guaranteed cleanup, and a transactional rollback — plus a runnable lab to try it yourself.

What is A10:2025 — Mishandling of Exceptional Conditions

A10:2025 is new in the 2025 OWASP Top 10. Previous editions lumped these bugs into a vague "poor code quality" bucket alongside unrelated issues like dead code and naming conventions. OWASP split it out for 2025 because the data justified a dedicated category: this single class of defect — how code behaves when something unexpected happens — maps to 24 CWEs, with a 20.67% maximum incidence rate in at least one CWE, an average incidence rate of 2.95% across the mapped CWEs, 769,581 total occurrences, and 3,416 CVEs. That’s a lot of real-world vulnerabilities caused not by missing input validation or broken crypto, but by what happens after something has already gone wrong.

OWASP’s own description: the category covers "improper error handling, logical errors, failing open, and other related scenarios stemming from abnormal conditions." Representative CWEs include CWE-209 (error messages exposing sensitive information — stack traces, file paths, SQL, secrets), CWE-234 (failure to handle missing parameters), CWE-274 (improper handling of insufficient privileges), CWE-476 (NULL/None dereference), and CWE-636 (failing insecurely — failing open instead of closed).

The common thread: an application hits an abnormal condition — a malformed file, a missing field, a database timeout, a null lookup — and either doesn’t catch it, catches it the wrong way, or catches it but leaks internals or leaves state inconsistent in the process.

The fail-closed principle

The mitigation OWASP keeps coming back to is fail closed, not open. When something exceptional happens — an exception, a timeout, an unexpected None — the safe default is to deny access and reveal nothing, not to continue in an undefined state or hand the caller a diagnostic dump. A login check that throws should not fall through to "access granted." A payment step that crashes mid-transfer should not leave money half-moved. Concretely, that means:

The lab below builds one app that violates every one of these, then a second that fixes all four.

Lab setup: a file processor with two bugs

Hands-on lab · A10
A file processor with two bugs
A self-contained practice lab that runs only on your own machine. Attack it, fix it, and prove each fix works.
Download the lab (zip) Sign in to downloadstack-traces-stuck-locks-lab-1.zip · 7 KB
Requirements
Python 3.9+ with pip, and curl for the exploit script. The run scripts install Flask for you; free port 5000.
SHA-256
343a4dd3764fa0fd8cc5193e5dec01036b9cf22ddd30edc384d7a235f7f499c0
How to check the file is genuine
Run the command for your system in the folder you downloaded to. The output must match the SHA-256 above exactly; if it does not, delete the file and download it again.
Linuxsha256sum stack-traces-stuck-locks-lab-1.zip
macOSshasum -a 256 stack-traces-stuck-locks-lab-1.zip
WindowsGet-FileHash stack-traces-stuck-locks-lab-1.zip
How to run it, what is inside and how to clean up are in the lab reference at the end.

The app is a small Flask service with three endpoints: /upload (parses a file after reserving one of a limited number of "processing slots"), /transfer (a toy funds-transfer endpoint backed by SQLite), and /status (reports how many slots are in use). Two things are wrong with it on purpose.

Bug 1: a lock acquired without a matching finally

MAX_SLOTS = 3
slots_lock = threading.Lock()
slots_in_use = 0

@app.route("/upload", methods=["POST"])
def upload():
    global slots_in_use

    if slots_in_use >= MAX_SLOTS:
        return jsonify({"error": "server busy"}), 503

    with slots_lock:
        slots_in_use += 1

    raw = request.files["file"].read()
    count = parse_report(raw)          # <-- throws on malformed input

    with slots_lock:
        slots_in_use -= 1              # <-- never reached if parse_report() raises

    return jsonify({"status": "ok", "parsed_count": count})

parse_report() expects the first line of the file to be an integer and calls int() on it directly — any non-numeric first line raises ValueError. The decrement lives after the parsing call with no try/finally, so an exception skips it entirely and the slot is gone forever. MAX_SLOTS is deliberately small (3) so you can exhaust it in a handful of requests, the same way a real resource pool (DB connections, worker threads, semaphore-gated jobs) gets exhausted in production — just slower.

Bug 2: debug mode leaks everything

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=5000, debug=True)

With debug=True, Flask’s Werkzeug debugger intercepts any unhandled exception and returns an interactive HTML page: exception type and message, every stack frame, the source around each frame, and the full server-side file path for each one — CWE-209 in its purest form. It’s meant for local development only, but it’s a one-line config mistake away from shipping to production.

Bug 3: a transfer with no atomicity

@app.route("/transfer", methods=["POST"])
def transfer():
    data = request.get_json(force=True)
    sender, receiver, amount = data["from"], data["to"], int(data["amount"])

    conn = sqlite3.connect(DB_PATH)
    conn.execute("UPDATE accounts SET balance = balance - ? WHERE name = ?", (amount, sender))
    conn.commit()                      # debit committed immediately

    row = conn.execute("SELECT balance FROM accounts WHERE name = ?", (receiver,)).fetchone()
    receiver_balance = row[0]          # raises TypeError if receiver doesn't exist

    conn.execute("UPDATE accounts SET balance = balance + ? WHERE name = ?", (amount, receiver))
    conn.commit()
    conn.close()
    return jsonify({"status": "ok"})

The debit is committed before the credit is even attempted. If anything between those two commits throws — an unknown receiver account, a timeout, a bad amount — the sender has already lost the money and the receiver never gets it, with no rollback or compensating action. This is the "stolen funds" scenario OWASP calls out directly: financial transaction corruption from exceptions that aren’t handled with proper rollback.

Exploiting it

Start the vulnerable app (python app.py inside vulnerable/) and run the slot-leak attack: send a handful of malformed uploads, then watch a legitimate upload get rejected.

# fresh state
curl -s http://127.0.0.1:5000/status
# {"max_slots": 3, "slots_in_use": 0}

# three malformed uploads, each leaks one slot
for i in 1 2 3; do
  echo "not-a-number" > bad-$i.txt
  curl -s -o /dev/null -w "upload $i -> HTTP %{http_code}\n" -F "file=@bad-$i.txt" http://127.0.0.1:5000/upload
  curl -s http://127.0.0.1:5000/status
done

# a legitimate upload, after the pool is exhausted
echo "5" > good.txt
curl -s -i -F "[email protected]" http://127.0.0.1:5000/upload | head -n 1
# HTTP/1.1 503 SERVICE UNAVAILABLE

Each malformed upload returns HTTP 500 and slots_in_use climbs by one and never comes back down. After three requests the pool is full, and the fourth — completely valid — upload is rejected with 503. That’s a real denial of service caused entirely by a missing finally.

Three malformed uploads leak the slot pool to exhaustion; a legitimate upload then gets 503, and /transfer leaks a full stack trace with server file paths

Now trigger the second bug by sending a transfer to an account that doesn’t exist:

curl -s -X POST http://127.0.0.1:5000/transfer \
  -H "Content-Type: application/json" \
  -d '{"from":"alice","to":"does-not-exist","amount":100}'

The response is the full Werkzeug debugger page — exception type, traceback, and absolute file paths on the server, including the application’s own install location:

The live Werkzeug debugger page rendered in a browser: full TypeError traceback with absolute server file paths, served directly to the client

And check the damage:

curl -s http://127.0.0.1:5000/balances
# before: {"alice": 500, "bob": 500}
# after a failed transfer to a bad account:
# {"alice": 400, "bob": 500}

Alice was debited 100 and it went nowhere. Bob never received it. The crash happened between the two commits, and there was nothing to undo the first one.

Fixing it

Fix 1: try/finally guarantees the slot is released

@app.route("/upload", methods=["POST"])
def upload():
    global slots_in_use

    if slots_in_use >= MAX_SLOTS:
        return jsonify({"error": "server busy"}), 503

    with slots_lock:
        slots_in_use += 1

    try:
        raw = request.files["file"].read()
        count = parse_report(raw)
    finally:
        with slots_lock:
            slots_in_use -= 1       # always runs, success or exception

    return jsonify({"status": "ok", "parsed_count": count})

The decrement now lives in finally, so it runs whether parse_report() succeeds or raises. This is the general pattern for any acquire/release pair — locks, semaphores, file handles, DB connections: acquire, then immediately set up the matching release in finally before doing any work that might fail.

Fix 2: a global exception handler that fails closed

@app.errorhandler(Exception)
def handle_exception(exc):
    log.exception(
        "unhandled_exception",
        extra={"path": request.path, "method": request.method, "remote_addr": request.remote_addr},
    )
    return jsonify({"error": "internal error, please try again later"}), 500

Combined with debug=False, every unhandled exception now flows through one place. The client gets a generic, safe message; the full exception is still captured, but only in the server’s own structured log — never in the HTTP response. That’s the fail-closed principle applied directly: when something goes wrong unexpectedly, default to revealing nothing and granting nothing.

Fix 3: wrap the transfer in a transaction with rollback

@app.route("/transfer", methods=["POST"])
def transfer():
    data = request.get_json(force=True)
    sender, receiver, amount = data["from"], data["to"], int(data["amount"])

    conn = sqlite3.connect(DB_PATH)
    try:
        conn.execute("BEGIN")
        conn.execute("UPDATE accounts SET balance = balance - ? WHERE name = ?", (amount, sender))
        row = conn.execute("SELECT balance FROM accounts WHERE name = ?", (receiver,)).fetchone()
        if row is None:
            raise ValueError(f"unknown receiver account: {receiver!r}")
        conn.execute("UPDATE accounts SET balance = balance + ? WHERE name = ?", (amount, receiver))
        conn.commit()
    except Exception:
        conn.rollback()
        raise                        # let the global handler log it and return a generic 500
    finally:
        conn.close()

    return jsonify({"status": "ok"})

The debit and credit are now one atomic unit: either both happen, or neither does. The explicit if row is None check also fixes CWE-476 directly — instead of a None reaching a subscript and raising a confusing TypeError deep in the stack, it becomes a clear, handled ValueError right where the bad state is detected.

Re-testing the fixes

Running the identical attacks against the fixed app:

Same attacks against the fixed app: slots return to 0 after every failed upload, legitimate uploads keep working, /transfer returns a generic error, and balances stay consistent after rollback

slots_in_use drops back to 0 after every malformed upload, so a legitimate upload right after still succeeds. /transfer to an unknown account returns a generic error with no trace, and /balances is unchanged afterward — the rollback held. The real traceback is still there, just server-side, in the application log.

Vulnerable vs. fixed

Vulnerable Fixed
Slot release After the parsing call, no finally In finally, always runs
Error response debug=True, full Werkzeug debugger HTML Global handler, generic JSON {"error": ...}
File paths / source Leaked in every unhandled exception Never sent to the client
Funds transfer Two separate commits, no rollback Single transaction, rollback on any exception
Result of a crash mid-transfer Sender debited, receiver never credited No balance change; operation fails atomically
Repeated malformed uploads Pool exhausted after MAX_SLOTS requests → DoS Pool never exhausted; service stays available

Detecting this class of bug: monitor exception rates

The fixes above close the hole, but you also want to know when something is going wrong in production. A sudden spike in unhandled exceptions or 5xx responses is one of the cleanest signals you have, often visible before anyone files a support ticket. Structured logging (as in Fix 2 — an unhandled_exception event with path, method, and timestamp as fields, not a free-text blob) lets you graph exception rate over time and alert when it crosses a baseline, the same way you’d alert on CPU or latency. A slot-leak DoS shows up as a rising count of 500s on /upload well before /status would tell you the pool is empty — if you’re watching for it.

Key takeaways

Lab reference: files, run steps and clean-up

What’s inside:

stack-traces-stuck-locks/
├── vulnerable/
│   ├── app.py        # leaky slot, debug=True, no transaction rollback
│   └── exploit.sh     # scripted slot-leak DoS + stack-trace leak
├── fixed/
│   └── app.py        # try/finally, global handler, transactional rollback
├── requirements.txt
├── run.sh             # ./run.sh vulnerable | ./run.sh fixed
└── run.ps1            # Windows equivalent

Run it:

unzip stack-traces-stuck-locks-lab.zip
cd stack-traces-stuck-locks

./run.sh vulnerable          # installs Flask, starts on http://127.0.0.1:5000
# in a second terminal:
cd vulnerable && bash exploit.sh

You should see three HTTP 500 uploads each leak a slot, a fourth legitimate upload get HTTP 503, and the /transfer call return a full Werkzeug debugger page. Stop the app with Ctrl+C, then run the fixed version the same way (./run.sh fixed) and repeat the attacks — the slot count returns to 0 after every failure and /transfer returns a generic error with balances unchanged.

Clean up: stop either app with Ctrl+C and delete the generated bank.db file in vulnerable/ and fixed/ to reset balances. Both apps bind to 127.0.0.1 only — local, authorized practice only.

References