Flash CTF - Skillbits

Skillbits Writeup

Overview

The credential migration dashboard shows eight archived integration records and a locked Operations archive. Each record uses the same inversive credential function, but the dashboard retains only the upper 890 bits of ordinary credentials. Recover the hidden function from those eight truncated values, evaluate it at the archive's public ID, and submit the complete credential.

Solution

The credential function

For a public 1536 bit prime pp, the service samples secret u,vu,v and computes

R(t)=v(u+t)−1(modp).R(t)=v(u+t)−1(modp).

The source is white box: chal/app.py shows the function, the truncation, the eight IDs, and the final check. Only the runtime values of u,vu,v and the full archive credential are secret. This is a Modular Inversion Double Hidden Number Problem. The lattice attack we want is the determinant elimination method of Ding et al..

What the dashboard hands us

The dashboard calls GET /api/batch. Its response contains pp, the bit widths, eight records (id, prefix), and the archive ID. The same data are available through the UI. In the source, the relevant lines are:‍

def credential(t):
    return v * pow((u + t) % p, -1, p) % p

records = [
    {"id": t, "name": name, "prefix": str(credential(t) >> missing)}
    for t, name in enumerate(names)
]

‍The IDs are 0,1,…,70,1,…,7 and the target ID is 88. Since keep = 890 and missing = 646, each visible prefix hihi​ defines a narrow interval for its full credential:

zi=hi2646+xi,0≤xi<2646.zi​=hi​2646+xi​,0≤xi​<2646.

Removing the two unbounded unknowns

Every record satisfies zi(u+ti)≡v(modp)zi​(u+ti​)≡v(modp). A lattice built directly in u,v,x0,…,x7u,v,x0​,…,x7​ has two unbounded variables. So we first eliminate u,vu,v with determinants of the rows

(tiqzi,…,zi,tiq−1,…,1),(tiq​zi​,…,zi​,tiq−1​,…,1),

using 2q+12q+1 records at depth q=1,2q=1,2. The resulting fundamental polynomials vanish modulo pqpq. We normalize by the known factors from the distinct titi​ and build shifts for the squarefree monomials of degree at most three. The basis contains

1+(81)+(82)+(83)=931+(18​)+(28​)+(38​)=93

monomials. We scale a degree rr column by BrBr, where B=2646B=2646, and run LLL on the 93×9393×93 integer lattice. The short rows become integer equations satisfied by the actual low parts.

We solve those equations over several small prime fields, and for the primes where the ideal has a unique root we combine each coordinate with CRT. When the CRT modulus exceeds BB, every xixi​ is determined in its allowed interval. The full zizi​ values are then known.

Two complete records recover the hidden pair:

u=(tjzj−tizi)(zi−zj)−1(modp),v=zi(u+ti)(modp).u=(tj​zj​−ti​zi​)(zi​−zj​)−1(modp),v=zi​(u+ti​)(modp).

We check the pair against all eight records, then compute R(8)R(8). The solver at the end of this writeup does the whole calculation with SageMath and submits the resulting credential through the HTTP API.

Submitting the credential

With the credential in hand, the last request is:‍

curl -s -X POST http://<host>/api/report \
  -H 'Content-Type: application/json' \
  -d "{\"credential\":\"$CREDENTIAL\"}"

‍
The response contains the flag:

{"report":"Migration exception cleared.","flag":"SkillBit{OOOOOO_I_h0pe_yUo_h4d_fun_s0Lvin6_ThisxD}"}

Run it with sage -python solve.py -u http://<host>.

The solver

It needs SageMath, plus requests and rich inside Sage's Python.

import argparse
import re
from itertools import combinations

import requests
from rich.console import Console
from sage.all import GF, ZZ, Matrix, PolynomialRing, prime_range

count = 8
depth = 2
console = Console()


def build_session(args):
    """House solver CLI: -k drops cert checks, -x routes traffic through Burp."""
    session = requests.Session()
    session.verify = not args.no_ssl
    if args.proxy:
        session.proxies = {
            "http": f"http://{args.proxy}",
            "https": f"http://{args.proxy}",
        }
    return session


def build_url(target, use_ssl):
    """Accept a full URL or a bare host:port. Only default the port when the
    target has neither a scheme nor a colon, so an ingress URL on 443 is never
    rewritten to :1337."""
    if "://" not in target:
        if ":" not in target:
            target = f"{target}:1337"
        target = f"{'https' if use_ssl else 'http'}://{target}"
    return target.rstrip("/")


def as_json(response):
    """Surface the status code and first body line when the reply is not JSON,
    so a wrong URL reads as a wrong URL and not as a broken challenge."""
    try:
        return response.json()
    except ValueError:
        head = response.text.strip().splitlines()
        raise SystemExit(
            f"[-] {response.url} returned HTTP {response.status_code}, not JSON: "
            f"{head[0] if head else '<empty body>'}"
        )


def monomial(ring, xs, support):
    value = ring.one()
    for i in support:
        value *= xs[i]
    return value


def compositions(total, parts):
    if parts == 1:
        yield (total,)
        return
    for first in range(1, total - parts + 2):
        for tail in compositions(total - first, parts - 1):
            yield (first,) + tail


def partitions(values, sizes):
    if not sizes:
        yield []
        return
    for head in combinations(values, sizes[0]):
        left = tuple(x for x in values if x not in head)
        for tail in partitions(left, sizes[1:]):
            yield [head] + tail


def decompose(support, overlap):
    support = tuple(sorted(support))
    for sizes in compositions(len(support), len(support) - overlap):
        for chunks in partitions(support, sizes):
            used = set(support)
            blocks = []
            for chunk in chunks:
                need = len(chunk) - 1
                extra = [i for i in range(min(chunk)) if i not in used][:need]
                if len(extra) != need:
                    break
                used.update(extra)
                blocks.append(tuple(sorted(chunk + tuple(extra))))
            else:
                return blocks


def vandermonde(values):
    value = 1
    for i in range(len(values)):
        for j in range(i + 1, len(values)):
            value *= values[j] - values[i]
    return value


def centered(ring, polynomial, modulus):
    out = ring.zero()
    for exponent, coefficient in polynomial.dict().items():
        coefficient = int(coefficient) % modulus
        if coefficient > modulus // 2:
            coefficient -= modulus
        term = ring(coefficient)
        for i, power in enumerate(exponent):
            term *= ring.gen(i) ** power
        out += term
    return out


def fundamental_polynomials(ring, xs, ts, prefixes, p):
    cache = {(0, (i,)): xs[i] for i in range(count)}
    for q in (1, 2):
        modulus = p**q
        for indexes in combinations(range(count), 2 * q + 1):
            rows = []
            for i in indexes:
                value = xs[i] + prefixes[i]
                rows.append(
                    [ts[i] ** e * value for e in range(q, -1, -1)]
                    + [ts[i] ** e for e in range(q - 1, -1, -1)]
                )
            determinant = Matrix(ring, rows).det()
            divisor = vandermonde([ts[i] for i in indexes[:q]])
            divisor *= vandermonde([ts[i] for i in indexes[q:]])
            inverse = pow(divisor % modulus, -1, modulus)
            cache[(q, indexes)] = centered(ring, inverse * determinant, modulus)
    return cache


def build_shifts(ring, xs, ts, prefixes, p):
    fundamental = fundamental_polynomials(ring, xs, ts, prefixes, p)
    shifts = {}

    for degree in range(depth + 2):
        for support in combinations(range(count), degree):
            if degree <= 1:
                shifts[support] = p**depth * monomial(ring, xs, support)
                continue

            blocks = decompose(support, degree - 1)
            if blocks:
                block = blocks[0]
                q = (len(block) - 1) // 2
                shifts[support] = p ** (depth - degree + 1) * fundamental[(q, block)]
                continue

            for overlap in range(degree - 2, -1, -1):
                blocks = decompose(support, overlap)
                if blocks and not decompose(support, overlap + 1):
                    value = ring.one()
                    for block in blocks:
                        q = (len(block) - 1) // 2
                        value *= fundamental[(q, block)]
                    shifts[support] = p ** (depth - overlap) * value
                    break

    return shifts


def lattice_rows(ring, xs, shifts, bound):
    basis = [
        support
        for degree in range(depth + 2)
        for support in combinations(range(count), degree)
    ]
    exponents = {
        tuple(int(i in support) for i in range(count)): column
        for column, support in enumerate(basis)
    }
    rows = []

    for support in basis:
        row = [0] * len(basis)
        for exponent, coefficient in shifts[support].dict().items():
            column = exponents[tuple(exponent)]
            row[column] = int(coefficient) * bound ** sum(exponent)
        rows.append(row)

    return basis, rows


def short_polynomials(ring, xs, basis, reduced, bound, p):
    limit = p ** (2 * depth)
    rows = [
        list(map(int, row))
        for row in reduced.rows()
        if sum(int(x) ** 2 for x in row) * reduced.nrows() < limit
    ]
    if len(rows) < count + 1:
        rows = [list(map(int, row)) for row in reduced.rows()[:80]]

    polynomials = []
    for row in rows:
        polynomial = ring.zero()
        for coefficient, support in zip(row, basis):
            polynomial += (coefficient // bound ** len(support)) * monomial(
                ring, xs, support
            )
        if polynomial.total_degree():
            polynomials.append(polynomial)

    polynomials.sort(key=lambda f: (f.total_degree(), f.number_of_terms()))
    return polynomials[:48]


def crt_pair(a, m, b, n):
    return a + m * (((b - a) % n) * pow(m % n, -1, n) % n)


def recover_low_parts(polynomials, bound):
    names = [f"x{i}" for i in range(count)]
    modulus = 1
    values = [0] * count

    for prime in prime_range(101, 5000):
        ring = PolynomialRing(GF(prime), names=names, order="lex")
        try:
            roots = ring.ideal([ring(f) for f in polynomials]).variety()
        except Exception as exc:  # noqa: BLE001 - some prime fields have no usable variety
            console.print(f"[yellow]Skipping prime {prime}: {exc}[/yellow]")
            continue
        if len(roots) != 1:
            continue

        current = [int(roots[0][x]) for x in ring.gens()]
        if modulus == 1:
            values = current
        else:
            values = [
                crt_pair(values[i], modulus, current[i], int(prime))
                for i in range(count)
            ]
        modulus *= int(prime)
        if modulus > bound:
            return [value % modulus for value in values]


def collect(session, url):
    batch = as_json(session.get(f"{url}/api/batch"))
    records = batch["records"]
    ts = [record["id"] for record in records]
    leaks = [int(record["prefix"]) for record in records]
    return (
        int(batch["p"]),
        batch["bits"],
        batch["keep"],
        ts,
        leaks,
        batch["privileged"]["id"],
    )


def solve(session, url):
    p, bits, keep, ts, leaks, target = collect(session, url)
    bound = 1 << (bits - keep)
    ring = PolynomialRing(ZZ, names=[f"x{i}" for i in range(count)], order="degrevlex")
    xs = ring.gens()
    prefixes = [value << (bits - keep) for value in leaks]

    console.print("[*] Building the determinant lattice")
    shifts = build_shifts(ring, xs, ts, prefixes, p)
    basis, rows = lattice_rows(ring, xs, shifts, bound)
    reduced = Matrix(ZZ, rows).LLL()

    console.print("[*] Recovering the hidden low bits")
    polynomials = short_polynomials(ring, xs, basis, reduced, bound, p)
    low = recover_low_parts(polynomials, bound)
    z = [(prefixes[i] + low[i]) % p for i in range(count)]

    u = (ts[1] * z[1] - ts[0] * z[0]) * pow((z[0] - z[1]) % p, -1, p) % p
    v = z[0] * (u + ts[0]) % p
    assert all(z[i] * (u + ts[i]) % p == v for i in range(count))

    credential = v * pow((u + target) % p, -1, p) % p
    response = session.post(f"{url}/api/report", json={"credential": str(credential)})
    match = re.search(r"SkillBit\{.*?\}", response.text)
    if not match:
        raise SystemExit(
            f"[-] no flag in the report reply (HTTP {response.status_code}): {response.text[:200]}"
        )
    console.print(f"[bold green][+] Flag: {match.group(0)}[/bold green]")


def main():
    parser = argparse.ArgumentParser(description="Skillbits solver")
    parser.add_argument(
        "-u", "--url", required=True, help="Challenge instance URL or host:port"
    )
    parser.add_argument(
        "-k",
        "--no-ssl",
        action="store_true",
        help="Disable SSL certificate verification",
    )
    parser.add_argument(
        "-x",
        "--proxy",
        nargs="?",
        const="127.0.0.1:8080",
        help="Route HTTP traffic through a proxy (default 127.0.0.1:8080)",
    )
    parser.add_argument(
        "-s", "--ssl", action="store_true", help="Use TLS for the connection"
    )
    args = parser.parse_args()
    solve(build_session(args), build_url(args.url, args.ssl))


if __name__ == "__main__":
    main()
Trust our customers

Interested in joining our team? Let’s connect!