Business Logic Flaws
Every vulnerability so far had a technical signature: a quote in SQL, a script tag in HTML, a ../ in a path. Business logic flaws have none. The requests are well-formed, authenticated and authorised; the application does exactly what its code says. The problem is that the code doesn't enforce the rules of the business: a quantity can be negative, a coupon can be used twice, the payment step can be skipped, a refund can exceed the purchase. Scanners can't find these, because finding them requires knowing what the application is for. In the OWASP Top 10 2025 they sit mostly under A06 Insecure Design, and the API Security Top 10 2023 has API6 Unrestricted Access to Sensitive Business Flows for the automated kind (scalping, mass account creation). This lesson attacks a toy checkout four ways and then rewrites it around explicit invariants.
Definitions
- Invariant: a statement that must always hold: "an order total is never negative", "a coupon is redeemed at most once per account", "an order is shipped only after it is paid", "the sum of refunds ≤ the amount paid".
- Workflow (state machine): the allowed sequence of steps (cart → checkout → paid → shipped). Logic flaws often skip or repeat a step by calling its endpoint directly.
- Trust in client-side values: prices, discounts, totals or step indicators sent back by the client.
- Abuse of a legitimate flow: doing the allowed thing at a scale or speed the business never intended (API6).
A checkout with four logic bugs
The toy shop computes the total from items, applies coupons and ships paid orders. Each attack is an ordinary request a curious user could send with an intercepting proxy.
CATALOG = {"tea": 12.00, "pot": 30.00}
COUPONS = {"WELCOME10": 10.00}
class NaiveShop:
def __init__(self):
self.orders = {}
def checkout(self, order_id, items, coupons, client_price=None):
total = sum((client_price or CATALOG[sku]) * qty for sku, qty in items) # bug 1, bug 2
for c in coupons: # bug 3: stacking/reuse
total -= COUPONS.get(c, 0)
self.orders[order_id] = {"total": round(total, 2), "state": "unpaid"}
return self.orders[order_id]
def ship(self, order_id): # bug 4: no state check
self.orders[order_id]["state"] = "shipped"
return self.orders[order_id]
shop = NaiveShop()
print("1 normal order: ", shop.checkout("o1", [("tea", 2)], ["WELCOME10"]))
print("2 negative quantity: ", shop.checkout("o2", [("pot", 1), ("tea", -2)], []))
print("3 client-sent price: ", shop.checkout("o3", [("pot", 3)], [], client_price=0.01))
print("4 coupon three times: ", shop.checkout("o4", [("tea", 2)], ["WELCOME10"] * 3))
print("5 ship without paying:", shop.ship("o3"))1 normal order: {'total': 14.0, 'state': 'unpaid'}
2 negative quantity: {'total': 6.0, 'state': 'unpaid'}
3 client-sent price: {'total': 0.03, 'state': 'unpaid'}
4 coupon three times: {'total': -6.0, 'state': 'unpaid'}
5 ship without paying: {'total': 0.03, 'state': 'shipped'}
None of these requests is malformed. The negative quantity turned two teas into a discount on the pot; the price field the front end sent "for display" was used for billing; one coupon applied three times produced a negative total (in some systems, a payout to the customer); and ship happily shipped an unpaid order. Each would pass every injection test.
The same shop, built around invariants
The fixed shop validates each input against business rules, takes prices only from the catalogue, records coupon redemptions per account, and moves orders through an explicit state machine where every transition checks its precondition.
CATALOG = {"tea": 12.00, "pot": 30.00}
COUPONS = {"WELCOME10": {"amount": 10.00, "min_total": 20.00, "once_per_account": True}}
TRANSITIONS = {"unpaid": {"paid", "cancelled"}, "paid": {"shipped", "refunded"}, "shipped": set()}
class Shop:
def __init__(self):
self.orders, self.redeemed = {}, set()
def checkout(self, account, order_id, items, coupons):
if not items or len(items) > 50:
return "422 1-50 items"
subtotal = 0.0
for sku, qty in items:
if sku not in CATALOG or not isinstance(qty, int) or not 1 <= qty <= 20:
return f"422 invalid item {sku!r} x {qty!r}"
subtotal += CATALOG[sku] * qty # price from the server only
if len(set(coupons)) != len(coupons) or len(coupons) > 1:
return "422 at most one coupon"
discount = 0.0
for c in coupons:
rule = COUPONS.get(c)
if rule is None or subtotal < rule["min_total"] or (account, c) in self.redeemed:
return f"422 coupon {c} not applicable"
discount = rule["amount"]
self.redeemed.add((account, c)) # in a database: a unique constraint
total = round(subtotal - discount, 2)
assert total >= 0, "invariant: totals are never negative"
self.orders[order_id] = {"account": account, "total": total, "state": "unpaid"}
return self.orders[order_id]
def move(self, order_id, new_state):
o = self.orders[order_id]
if new_state not in TRANSITIONS[o["state"]]:
return f"409 cannot go from {o['state']} to {new_state}"
o["state"] = new_state
return o
shop = Shop()
print("normal order: ", shop.checkout("ana", "o1", [("tea", 2)], ["WELCOME10"]))
print("negative quantity: ", shop.checkout("ana", "o2", [("pot", 1), ("tea", -2)], []))
print("coupon three times: ", shop.checkout("ana", "o3", [("tea", 2)], ["WELCOME10"] * 3))
print("coupon again, later: ", shop.checkout("ana", "o4", [("tea", 2)], ["WELCOME10"]))
print("ship without paying: ", shop.move("o1", "shipped"))
print("pay, then ship: ", shop.move("o1", "paid")["state"], "->", shop.move("o1", "shipped")["state"])normal order: {'account': 'ana', 'total': 14.0, 'state': 'unpaid'}
negative quantity: 422 invalid item 'tea' x -2
coupon three times: 422 at most one coupon
coupon again, later: 422 coupon WELCOME10 not applicable
ship without paying: 409 cannot go from unpaid to shipped
pay, then ship: paid -> shipped
The assert is a last line of defence: if any future change breaks the "never negative" rule, the order fails loudly instead of paying the customer. In a real system the coupon rule is a unique constraint in the database, which also holds under concurrency (race conditions are the next lesson, and logic flaws and races often meet at exactly this point).
How logic flaws are found (detection)
- Testing needs the business rules: read the documentation, terms and help pages; list each flow's invariants; then break them one at a time with a proxy: negative, zero, huge and fractional numbers; repeated steps; skipped steps (call step 3 directly); steps in a different order; parameters from one user's flow in another's; two flows at once (race). OWASP WSTG has a whole chapter, Business Logic Testing (WSTG-BUSL).
- Monitoring and analytics: invariant violations as alerts (negative totals, refunds > payments, coupons per account > 1, orders shipped unpaid), unusual ratios (orders with discount > 50 %), and velocity on sensitive flows (sign-ups per device, purchases per minute for limited stock) for API6-style automation.
- Design review: threat modelling each flow with "what if a user did this 1,000 times? backwards? halfway?" before it is built (Threat Modelling).
How they are prevented
- Write the invariants down and enforce them on the server, in one place per rule (domain model, database constraints).
- Model workflows as state machines with checked transitions; keep state on the server.
- Take prices, discounts and limits from server-side data only.
- Limit sensitive flows by account, device and velocity; add friction (CAPTCHA, verification) where automation is the threat.
- Turn invariants into tests and monitors.
Pitfalls
- Validating in the front end only: the API is the boundary.
- Floating-point money: use integer cents or
Decimal; rounding errors repeated many times are a logic flaw too. - Rules that hold per request but not across requests (one coupon per order, but many orders).
Practice
1. A refund endpoint takes {"order": "o1", "amount": 14.0}. List the invariants it must check.
The order belongs to the caller (or the caller is support staff); it is in a refundable state; the amount is positive; the sum of all refunds for the order, including this one, is ≤ the amount paid; the refund goes to the original payment method; and concurrent refund requests can't both pass the check.
2. A ticket site sells 500 seats; bots buy them all in two seconds. Which category is this, and which controls help?
API6 Unrestricted Access to Sensitive Business Flows (automation of a legitimate flow). Controls: per-account and per-payment-card limits, queues with verification, bot detection and CAPTCHAs at the hot moment, and holding seats for a short time before payment.
Test yourself
Why don't scanners find business logic flaws?
- They are rare
- The requests are well-formed; finding the flaw needs knowledge of the business rules
- They need root
- They only affect mobile apps
In the naive shop, what produced a negative total?
- SQL injection
- One coupon applied three times
- A rounding error
- The client price
What enforces 'ship only after payment' in the fixed shop?
- A comment
- A state machine with allowed transitions checked on every move
- The UI hides the button
- An assert on the total
Which OWASP WSTG chapter covers this?
- WSTG-INPV
- WSTG-BUSL Business Logic Testing
- WSTG-CRYP
- WSTG-CLNT