These are the notes for Cybersecurity Fundamentals (defensive), episode 45. Episode 44 protected the data itself. Today's bugs survive any amount of encryption and input filtering, because the plan itself was wrong: a shop that lets the browser set the price, ships unpaid orders, lets one gift card be spent twice, and lets a bot try every coupon. Each one runs live, then we fix it, then we see why OWASP calls this insecure design, and how teams catch it before writing code. Every term is explained the first time it appears, and the Glossary at the end defines them all again.
Neha, Ravi, the shop, the prices and the codes are made up. Every program is a small local toy and contacts nothing outside the machine. Python samples run on 11 Nov 2026 with Python 3.13; every output below is copied from a real run.
The problems you'll solve
| Problem | Idea it teaches |
|---|---|
| The browser sends the total, and the server charges it | trust in client-side calculations, plausibility checks |
| A quantity of -3 becomes a refund | business-logic flaws |
| An order ships without being paid | workflow bypass, state machines |
| A Rs 500 gift card is spent twice | race conditions, TOCTOU, locks, atomic updates |
| A bot tries every coupon code | rate limiting, anti-automation |
| None of it was a typo | insecure design vs insecure implementation (OWASP A04:2021, A06:2025) |
| Catch it before coding | security requirements, abuse cases, misuse cases, secure design patterns, reference architectures |
Problem 1: the browser sets the price
Basic words first:
- The client is the user's side: the browser or mobile app. The server is the shop's computer that stores orders and takes payments.
- DevTools are the developer tools built into every browser. They let anyone see and change what the page sends.
- A client-side calculation is a value worked out in the browser or app (a cart total, a discount). Trust in client-side calculations means the server accepts such a value instead of computing it itself.
- A plausibility check asks "could this value be real?": a quantity between 1 and 10, a price from our own table, a date not in the past.
Demo 1: a checkout that trusts the browser
# Checkout v1: the browser sends the cart AND the total. The server trusts it.
PRICES = {"headphones": 1499, "charger": 499} # the shop's real prices (rupees)
def checkout_v1(cart): # cart = JSON from the browser
return f"charged Rs {cart['total']} for {cart['qty']} x {cart['item']}"
def checkout_v2(cart): # the server decides everything
item, qty = cart["item"], cart["qty"]
if item not in PRICES:
return "rejected: unknown item"
if not isinstance(qty, int) or not 1 <= qty <= 10:
return f"rejected: quantity {qty} not allowed"
return f"charged Rs {PRICES[item] * qty} for {qty} x {item}"
carts = [{"item": "headphones", "qty": 1, "total": 1499}, # honest
{"item": "headphones", "qty": 1, "total": 1}, # edited in DevTools
{"item": "charger", "qty": -3, "total": -1497}] # negative quantity
for c in carts:
print("v1:", checkout_v1(c))
print()
for c in carts:
print("v2:", checkout_v2(c))
Output:
v1: charged Rs 1499 for 1 x headphones
v1: charged Rs 1 for 1 x headphones
v1: charged Rs -1497 for -3 x charger
v2: charged Rs 1499 for 1 x headphones
v2: charged Rs 1499 for 1 x headphones
v2: rejected: quantity -3 not allowed
Why it failed: version 1 was designed to trust the client. The browser belongs to the customer, so its checks are only for convenience. The server must be the authority for prices, totals, discounts and roles, and check that every value is plausible. OWASP: "Integrate plausibility checks at each tier of your application (from frontend to backend)."
What a business-logic flaw is
- Business logic is the set of rules a business runs on: how prices and discounts work, which steps come in which order, what the limits are.
- A business-logic flaw is when valid-looking requests break those rules.
qty = -3contains no strange characters, so input filters and automated scanners usually miss it. Only someone who knows how the shop should behave can spot it, by asking "what must never be possible here?"
Problem 2: workflow bypass
- A workflow is a fixed series of steps, like book, pay, board for a train, or created → paid → shipped for an order.
- A workflow bypass is skipping a required step by calling a later one directly. Each step is just a URL (like
/ship), and anyone can call any URL. - A state machine models something as having one current state and a fixed list of allowed moves (transitions) between states. Anything not on the list is refused.
Demo 2: shipping an unpaid order
# An order goes: created -> paid -> shipped. Version 1 just has three functions.
orders = {}
def create(oid): orders[oid] = "created"
def pay(oid): orders[oid] = "paid"
def ship_v1(oid): # nobody checks the step before
orders[oid] = "shipped"; return f"order {oid}: shipped"
create(701)
print(ship_v1(701), "| was it paid? no") # the attacker calls /ship directly
# Version 2: a state machine. Only these moves exist.
ALLOWED = {("created", "paid"), ("paid", "shipped"),
("created", "cancelled"), ("paid", "refunded")}
def move(oid, new):
old = orders[oid]
if (old, new) not in ALLOWED:
return f"order {oid}: {old} -> {new} REFUSED"
orders[oid] = new
return f"order {oid}: {old} -> {new}"
create(702)
print(move(702, "shipped"))
print(move(702, "paid"))
print(move(702, "shipped"))
print(move(702, "refunded"))
Output:
order 701: shipped | was it paid? no
order 702: created -> shipped REFUSED
order 702: created -> paid
order 702: paid -> shipped
order 702: shipped -> refunded REFUSED
Why it failed: each step trusted that the step before had happened. The fix: design the allowed moves once, in one place, and check the current state on the server at every step.
pay ship
created ───────▶ paid ───────────▶ shipped
│ │
│ cancel │ refund
▼ ▼
cancelled refunded
Problem 3: race conditions and TOCTOU
- A thread is a separate line of work running at the same time as others in one program; a server handles many requests at once like this.
- A race condition is a bug where the result depends on the timing of things running at the same time.
- TOCTOU (time of check to time of use) is a race where something is checked, then changes before it is used. We met it as DNS rebinding in episode 43.
- A lock lets only one thread into a piece of code at a time.
- An atomic operation happens all at once, with nothing able to run in between.
Demo 3: one gift card, two phones
# A Rs 500 gift card. Ravi taps "redeem" on two phones at the same moment.
import threading, time
card = {"balance": 500}; spent = []
def redeem_v1(amount):
if card["balance"] >= amount: # time of CHECK
time.sleep(0.1) # payment API call, DB write...
card["balance"] -= amount # time of USE
spent.append(amount)
def race(fn):
ts = [threading.Thread(target=fn, args=(500,)) for _ in range(2)]
for t in ts: t.start()
for t in ts: t.join()
print(f"spent Rs {sum(spent)}, balance left Rs {card['balance']}")
race(redeem_v1)
lock = threading.Lock()
def redeem_v2(amount):
with lock: # check and use as ONE step
if card["balance"] >= amount:
time.sleep(0.1)
card["balance"] -= amount
spent.append(amount)
card["balance"] = 500; spent.clear()
race(redeem_v2)
Output:
spent Rs 1000, balance left Rs -500
spent Rs 500, balance left Rs 0
Why it failed: both requests checked "balance ≥ 500" before either subtracted. Version 2 makes check-and-use one step with a lock.
Demo 4: the same fix in the database
A lock only works inside one program, and real shops run many servers. So the database must do it. SQLite is a small database built into Python.
# The same idea in a database: one atomic UPDATE that checks and spends
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE cards (id TEXT PRIMARY KEY, balance INTEGER)")
db.execute("INSERT INTO cards VALUES ('GIFT-77', 500)")
def redeem(amount):
cur = db.execute("UPDATE cards SET balance = balance - ? "
"WHERE id = 'GIFT-77' AND balance >= ?", (amount, amount))
db.commit()
return "redeemed" if cur.rowcount == 1 else "refused: not enough balance"
print("phone 1:", redeem(500))
print("phone 2:", redeem(500))
print("balance:", db.execute("SELECT balance FROM cards").fetchone()[0])
Output:
phone 1: redeemed
phone 2: refused: not enough balance
balance: 0
UPDATE ... WHERE balance >= ? checks and spends in one atomic statement; rowcount tells us whether a row changed. Other tools for the same job: transactions with row locks (SELECT ... FOR UPDATE in PostgreSQL/MySQL), unique constraints so the same coupon can't be recorded twice, and CHECK constraints like balance >= 0.
Problem 4: bots and automation
- A bot is a program that uses a website automatically, far faster than a person.
- Rate limiting allows only a set number of requests per user, per IP address, per card or per minute. Over the limit, the server answers
429 Too Many Requests, the HTTP status code for this. - Anti-automation is the set of controls that spot and slow down bots: CAPTCHAs (puzzles that are easy for people and hard for programs), device and behaviour checks, per-customer purchase limits, and flagging orders made seconds after a sale opens. OWASP's example: scalpers' bots buying every high-end video card on release.
Demo 5: a bot and a rate limit
# Coupon codes are 4 digits. A bot tries them all. Then: a rate limit.
import time
VALID = {"7342"} # the one real code this week
def try_coupon_v1(user, code):
return code in VALID
found = [f"{n:04d}" for n in range(10000) if try_coupon_v1("bot", f"{n:04d}")]
print("v1: bot tried 10000 codes, found", found)
WINDOW, LIMIT = 60, 5 # at most 5 tries per minute
attempts = {} # user -> recent try times
def try_coupon_v2(user, code, now):
recent = [t for t in attempts.get(user, []) if now - t < WINDOW]
if len(recent) >= LIMIT:
return "429 Too Many Requests"
attempts[user] = recent + [now]
return "valid" if code in VALID else "invalid"
now = time.time()
results = [try_coupon_v2("bot", f"{n:04d}", now) for n in range(10000)]
print("v2: tries 5 and 6 ->", results[4:6])
blocked = results.count("429 Too Many Requests")
print("v2: invalid", results.count("invalid"), "| blocked", blocked,
"| valid", results.count("valid"))
Output:
v1: bot tried 10000 codes, found ['7342']
v2: tries 5 and 6 -> ['invalid', '429 Too Many Requests']
v2: invalid 5 | blocked 9995 | valid 0
Why it failed: nobody asked how many tries a real person needs. At 5 tries a minute, 10,000 codes take more than 33 hours, and the code changes weekly. A determined attacker uses many accounts and IPs, so limit on several keys (user, IP, coupon), use long random codes from secrets, and add anti-automation for high-value flows. OWASP: "Limit resource consumption by user or service."
Why: insecure design vs insecure implementation
Not one line of today's code had a typo. Each program did exactly what it was designed to do. OWASP: "There is a difference between insecure design and insecure implementation."
| Insecure implementation | Insecure design | |
|---|---|---|
| What's wrong | the plan had a control, the code built it wrongly | the control was never planned |
| Example | string-built SQL query (episode 38) | trusting the browser's total; no step order; no try limit |
| Fix | fix the code | fix the design, then the code |
A perfect implementation of an insecure design is still insecure, because the needed controls were never created. Insecure design entered the OWASP Top 10 in 2021 as A04 ("A new category for 2021 focuses on risks related to design and architectural flaws") and is A06 in 2025. OWASP: "Secure design is neither an add-on nor a tool that you can add to software."
Fix 1: security requirements
A security requirement is a written rule the system must follow, or a thing it must never allow, agreed with the business before coding, like any other requirement. Good ones are testable: each becomes an automated test.
| Requirement | Test |
|---|---|
| Price and total are computed on the server | send total: 1 → charged the real price |
An order ships only from the paid state |
move(created → shipped) → refused |
| A gift card balance never goes below 0 | two concurrent redeems → one refused |
| At most 5 coupon tries per user per minute | 6th try → 429 |
OWASP suggests writing security requirements straight into the user stories.
Fix 2: abuse cases and misuse cases
- A use case (or user story) describes how a feature is meant to be used: "As a customer, I can apply a coupon code so that I get a discount."
- An abuse case is its evil twin. OWASP's Abuse Case Cheat Sheet: "A way to use a feature that was not expected by the implementer, allowing an attacker to influence the feature or outcome of use of the feature based on the attacker action (or input)."
- A misuse case is the same idea drawn from the use-case world. OWASP (quoting SAMM) uses the two together: "Misuse and abuse cases describe unintended and malicious use scenarios of the application", so misuse also covers accidents, like Ravi tapping Redeem on two phones without meaning harm.
| Use case | Abuse / misuse case | Control |
|---|---|---|
| Apply a coupon | try every code until one works | rate limit, long random codes |
| Redeem a gift card | redeem on two phones at once | atomic update |
| Check out a cart | send a lower total, a negative quantity | server pricing, plausibility checks |
| Ship an order | call /ship before /pay |
state machine |
Write them in the design meeting, together with the threat model (episode 7).
Fix 3: secure design patterns and reference architectures
A secure design pattern is a proven, reusable answer to a common security problem:
| Pattern | Solves |
|---|---|
| Server is the authority | client-side trust |
| State machine | workflow bypass |
| Atomic operations / transactions | race conditions on money and stock |
| Rate limiter | guessing and automation |
| Idempotency key | double taps and retries: the client sends a unique id with each payment, the server processes each id only once |
A reference architecture is an approved blueprint for a whole system (which login service, which API gateway, which database setup, how logging works) with security already built in. OWASP recommends a "library of secure design patterns or paved road ready to use components": the paved road idea is to make the secure way the easy way.
OWASP's other prevention advice: a secure development lifecycle with security people involved from the start, threat modelling for critical flows (login, access control, business logic), tests for both use and misuse cases, and separating tiers and tenants.
The whole chain
- The browser set the total → the server is the authority, with plausibility checks.
/shipwithout/pay→ state machine.- A card spent twice → lock, then one atomic UPDATE (TOCTOU).
- A bot tried every coupon → rate limits and anti-automation.
- No typo anywhere → insecure design.
- Security requirements, abuse and misuse cases, secure design patterns, reference architectures.
Common mistakes (and what they cause)
| Mistake | What happens (real output) | Why | Fix |
|---|---|---|---|
| Using the client's total | v1: charged Rs 1 for 1 x headphones |
the browser is the user's | server prices |
| No plausibility checks | v1: charged Rs -1497 for -3 x charger |
negative quantity accepted | 1 ≤ qty ≤ 10, integers only |
| Steps as separate URLs | order 701: shipped \| was it paid? no |
no step checks the one before | state machine on the server |
| Check, then use, separately | spent Rs 1000, balance left Rs -500 |
TOCTOU race | atomic UPDATE ... WHERE balance >= ? |
| A lock in one process only | still races across several servers | each server has its own lock | let the database decide |
| Unlimited tries | v1: bot tried 10000 codes, found ['7342'] |
nobody asked how many tries | rate limit on several keys + anti-automation |
| Retry charges twice | double payment | no idempotency | idempotency key |
Mini project: a gift-card checkout built from secure design patterns
Server pricing, plausibility checks, a rate limiter, an idempotency key enforced by a PRIMARY KEY, an atomic balance update, a CHECK constraint, and one transaction so a refused payment leaves nothing behind.
# Mini project: a gift-card checkout that applies today's design patterns
import sqlite3, time
PRICES = {"headphones": 1499, "charger": 499}
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE cards (id TEXT PRIMARY KEY, balance INTEGER CHECK (balance >= 0));
CREATE TABLE payments (idem_key TEXT PRIMARY KEY, card TEXT, amount INTEGER);
INSERT INTO cards VALUES ('GIFT-77', 2000);
""")
tries = {}
def rate_ok(user, now, limit=5, window=60): # pattern: rate limiter
recent = [t for t in tries.get(user, []) if now - t < window]
tries[user] = recent + [now]
return len(recent) < limit
def pay(user, card, item, qty, idem_key):
if not rate_ok(user, time.time()):
return "429 Too Many Requests"
if item not in PRICES or not isinstance(qty, int) or not 1 <= qty <= 10:
return "rejected: implausible order" # pattern: plausibility checks
amount = PRICES[item] * qty # pattern: server is the authority
try:
with db: # one transaction
db.execute("INSERT INTO payments VALUES (?, ?, ?)", (idem_key, card, amount))
cur = db.execute("UPDATE cards SET balance = balance - ? "
"WHERE id = ? AND balance >= ?", (amount, card, amount))
if cur.rowcount != 1:
raise ValueError("not enough balance") # rolls back the payment row
except sqlite3.IntegrityError:
return f"already processed {idem_key} (idempotency key)"
except ValueError as e:
return f"refused: {e}"
return f"paid Rs {amount}"
print(pay("ravi", "GIFT-77", "headphones", 1, "k-1"))
print(pay("ravi", "GIFT-77", "headphones", 1, "k-1")) # double tap / retry
print(pay("ravi", "GIFT-77", "charger", -3, "k-2"))
print(pay("ravi", "GIFT-77", "headphones", 1, "k-3")) # 1499 > 501 left
print(pay("ravi", "GIFT-77", "charger", 1, "k-4"))
print(pay("ravi", "GIFT-77", "charger", 1, "k-5")) # 6th try this minute
print("balance:", db.execute("SELECT balance FROM cards").fetchone()[0])
Output:
paid Rs 1499
already processed k-1 (idempotency key)
rejected: implausible order
refused: not enough balance
paid Rs 499
429 Too Many Requests
balance: 2
The retry with the same key is not charged again, the negative quantity is rejected, the over-balance payment is refused and rolled back, and the sixth try in a minute is rate limited. 2000 − 1499 − 499 = 2 rupees left.
Practice
- Make sure a cancelled order can never be paid or shipped.
- Run the race with five phones, with and without the lock.
- Write three abuse cases for a "refer a friend, both get Rs 100" feature.
- Misuse case vs abuse case: what's the difference?
Solution 1
cancelled has no outgoing moves in ALLOWED, so every move from it is refused.
# Practice 1 solution: once cancelled, an order can never be paid or shipped
orders = {}
ALLOWED = {("created", "paid"), ("paid", "shipped"),
("created", "cancelled"), ("paid", "refunded")}
def move(oid, new):
old = orders[oid]
if (old, new) not in ALLOWED:
return f"order {oid}: {old} -> {new} REFUSED"
orders[oid] = new
return f"order {oid}: {old} -> {new}"
orders[703] = "created"
for step in ["cancelled", "paid", "shipped"]:
print(move(703, step))
Output:
order 703: created -> cancelled
order 703: cancelled -> paid REFUSED
order 703: cancelled -> shipped REFUSED
Solution 2
# Practice 2 solution: five phones at once, without and with the lock
import threading, time
card = {"balance": 500}; spent = []; lock = threading.Lock()
def redeem_v1(amount):
if card["balance"] >= amount:
time.sleep(0.1)
card["balance"] -= amount; spent.append(amount)
def redeem_v2(amount):
with lock:
if card["balance"] >= amount:
time.sleep(0.1)
card["balance"] -= amount; spent.append(amount)
for fn in (redeem_v1, redeem_v2):
card["balance"] = 500; spent.clear()
ts = [threading.Thread(target=fn, args=(500,)) for _ in range(5)]
for t in ts: t.start()
for t in ts: t.join()
print(f"{fn.__name__}: spent Rs {sum(spent)}, balance Rs {card['balance']}")
Output:
redeem_v1: spent Rs 2500, balance Rs -2000
redeem_v2: spent Rs 500, balance Rs 0
Solution 3
| Abuse case | Control |
|---|---|
| As an attacker, I create 100 fake accounts and refer myself to collect Rs 10,000. | bonus only after the friend's first paid order; limit per device, phone and payment method |
| As an attacker, I refer a friend, then cancel and refund the first order, keeping the bonus. | bonus after the return window; claw back on refund (state machine) |
| As an attacker, I submit the same referral claim from two tabs at once. | atomic insert with a unique constraint on (referrer, friend) |
Solution 4
Both describe how a feature can be used against its purpose. Abuse case usually means a deliberate attacker. Misuse case comes from use-case modelling and, as OWASP SAMM puts it, covers "unintended and malicious use", so it also includes honest mistakes. In practice teams write both in the same list; the important part is that each one names the control that stops it.
Quick quiz
A cinema gives a group discount for bookings of up to 15 people, with no deposit. An attacker books hundreds of seats across all cinemas in a few requests, then never pays. Which control fixes this design?
A: encrypt the booking API with TLS 1.3 B: escape all input against injection C: per-customer limits and deposit rules, written as requirements D: a longer session timeout
Answer
C. This is one of OWASP's own insecure design scenarios. Every request was valid and nothing was injected, so TLS and escaping don't help. It's a business-logic flaw, fixed by design rules: booking limits per customer and per show, a deposit above a size, and abuse cases written before building.
Interview questions
- What is insecure design? Missing or ineffective security controls because they were never planned (OWASP A04:2021, A06:2025), as opposed to a bug in implementing a planned control.
- Give three business-logic flaws. Trusting a client-side price; negative quantities; skipping a workflow step; reusing a coupon; races on balances.
- Why can't scanners find most logic flaws? The requests are valid; only someone who knows the business rules can tell they're wrong.
- What is TOCTOU? Give an example. A value is checked, then changes before use: two redeems both see the full balance.
- How do you fix a race on a balance? One atomic conditional update, or a transaction with row locks; constraints as a safety net.
- Rate limiting vs anti-automation? Rate limiting caps requests per key and time; anti-automation detects and slows bots (CAPTCHA, device signals, purchase limits).
- What is an abuse case? A way to use a feature not expected by its builder that lets an attacker influence the outcome; each one should name its control.
- What is an idempotency key? A unique id sent with a request so the server processes it only once, even if it is retried.
- What is a reference architecture? An approved, reusable blueprint for a whole system with security built in.
- Where in the lifecycle is insecure design fixed most cheaply? At requirements and design: threat modelling, security requirements, abuse cases.
Glossary
| Term | Meaning, with an example |
|---|---|
| Client | The user's side: browser or app. |
| Server | The shop's computer that stores orders and takes payments. |
| DevTools | Browser developer tools; can change anything a page sends. |
| Client-side calculation | A value computed in the browser, like a cart total. |
| Trust in client-side calculations | Accepting such a value on the server instead of computing it: charged Rs 1. |
| Plausibility check | Checking a value could be real: 1 ≤ quantity ≤ 10. |
| Business logic | The business's rules: prices, discounts, steps, limits. |
| Business-logic flaw | Valid-looking requests that break those rules: qty = -3 becomes a refund. |
| Workflow | A fixed series of steps: created → paid → shipped. |
| Workflow bypass | Skipping a required step: calling /ship before /pay. |
| State machine | One current state plus a fixed list of allowed moves; everything else refused. |
| Thread | A line of work running at the same time as others in one program. |
| Race condition | A result that depends on the timing of things running at once. |
| TOCTOU | Time of check to time of use: checked, then changed before use. |
| Lock | Lets only one thread into a piece of code at a time (threading.Lock). |
| Atomic operation | Happens all at once with nothing in between: one UPDATE ... WHERE balance >= ?. |
| Transaction | A group of database changes that all happen or none do. |
| SQLite | A small database engine built into Python (sqlite3). |
| Bot | A program that uses a website automatically. |
| Rate limiting | Allowing only N requests per key per time window; over it, 429 Too Many Requests. |
| Anti-automation | Controls that detect and slow bots: CAPTCHA, device checks, purchase limits. |
| CAPTCHA | A test easy for people and hard for programs. |
| Insecure design | Security controls missing because they were never planned (OWASP A04:2021, A06:2025). |
| Insecure implementation | A planned control built wrongly in code. |
| Security requirement | A written, testable rule: "a gift card balance never goes below 0". |
| Use case / user story | How a feature is meant to be used: "As a customer, I can apply a coupon". |
| Abuse case | An unexpected use of a feature that lets an attacker influence the outcome. |
| Misuse case | Unintended or malicious use of a feature, written like a use case; covers accidents too. |
| Threat model | A structured look at what can go wrong and what to do about it (episode 7). |
| Secure design pattern | A proven, reusable answer to a security problem: state machine, atomic update. |
| Idempotency key | A unique request id so a retried request is processed only once. |
| Reference architecture | An approved blueprint for a whole system with security built in. |
| Paved road | Ready-made secure components that make the secure way the easy way. |
Summary
- Insecure design (OWASP A04:2021, A06:2025): the control was never planned, so perfect code can't save it.
- Never trust client-side calculations: the server computes prices and runs plausibility checks.
- Model workflows as state machines checked on the server.
- Fix race conditions / TOCTOU with atomic updates, transactions and constraints.
- Rate limit anything guessable and add anti-automation for valuable flows.
- Catch it early: security requirements, abuse and misuse cases, secure design patterns and reference architectures.
Next episode: security misconfiguration, XXE and exceptional conditions.