247CTF // Cereal Logger - Unserialize to /dev/null, SQLi to the Flag

247CTF // Cereal Logger - Unserialize to /dev/null, SQLi to the Flag

Category: deserialization, blind SQLi, type juggling

Stack: PHP 7.x, SQLite3, unserialize, base64_decode


STEPS
  1. Craft the cookie: base64(serialized insert_log) + '.0e' - the 0e suffix makes the loose comparison parse as 0.0 == '0'
  2. Serialize an insert_log whose new_data breaks out of the INSERT with '); ... ;-- - stacked queries work in SQLite
  3. Calibrate the oracle: SELECT 1 = randomblob(N) WHERE <cond> - find the largest N that stays under the gateway timeout (~0.5s signal)
  4. Enumerate blind: sqlite_master name/sql counts find the flag table and its column
  5. Extract each character by binary-searching its nibbles - 4 probes per hex digit
  6. Vote 3x per condition - single-probe timing lies; majority voting doesn't - then verify the assembled string with one equality probe

1. The target


class insert_log {

    public $new_data = "Valid access logged!";

    public function __destruct() {

        $this->pdo = new SQLite3("/tmp/log.db");

        $this->pdo->exec(

            "INSERT INTO log (message) VALUES ('".$this->new_data."');"

        );

    }

}



if (isset($_COOKIE["247"]) && explode(".", $_COOKIE["247"])[1].rand(0,247247247) == "0") {

    file_put_contents("/dev/null", unserialize(base64_decode(explode(".", $_COOKIE["247"]")[0])));

} else {

    echo highlight_file(__FILE__, true);

}

Three gates stand between you and the gadget:

  1. 1. The juggling gate. The cookie is split on .; the second segment concatenated with

a random number must loosely-equal the string "0".

  1. 2. The deserialize gadget. Your base64 becomes an object; when the request ends, its

destructor runs.

  1. 3. The data sink. The write goes to /dev/null and the response tells you nothing.

The challenge text - *"you can write data to /dev/null"* - is a confession disguised as a

brag. The write itself is theater. The destructor is the payload.

2. Gate 1: the type-juggling bypass

explode(".", $cookie)[1] . rand(0, 247247247) == "0" - concatenation binds tighter

than ==, so this is (segment . rand) == "0".

If segment is 0e, the concatenation is 0e<digits> - a numeric string in scientific

notation, i.e. the float 0.0. 0.0 == "0" is true under loose comparison because the

right side is also numeric.

The whole gate reduces to: cookie = <base64>.0e. Deterministic, no race against

rand() needed.

Why this works at all: PHP 7 compares a numeric string to "0" numerically. (In PHP 8

the semantics changed - "0e123" == "0" still holds because both are numeric, so the

trick survives, but this is the kind of comparison that === exists to kill.)

3. Gate 2: the gadget

The only class available is insert_log, and its destructor string-concatenates

new_data into an INSERT. Serialize one with an injected payload:


O:10:"insert_log":1:{s:8:"new_data";s:34:"x'); <stacked SQL>;-- ";}

SQLite3::exec() happily executes stacked statements - this is the one PHP database

API that does.

4. Gate 3: the blind, time-based oracle

Nothing comes back. The channel that remains is response latency, and the primitive

that produces latency on demand in SQLite is randomblob(N) - building an N-byte blob

of randomness costs real CPU.

The shape of one probe:


x'); SELECT 1 = randomblob(99999999) WHERE <condition>;-- 

  • WHERE is evaluated *before* the SELECT list, so a false condition never builds the

blob -> fast response.

  • A true condition -> ~0.5s penalty at N=1e8.
  • Sizing matters. The front proxy (nginx or the platform LB) will 502 a request

that hangs past a few seconds. randomblob(999999999) (the value many public

writeups use) blows straight past the gateway timeout. Tune N until a true-condition

response is reliably ~0.5-0.7s against a ~0.15-0.2s baseline, then threshold at the

midpoint.

Schema discovery, blind

Same oracle, different conditions:


-- does a 'flag' table exist?

(SELECT count(*) FROM sqlite_master WHERE name='flag') = 1



-- its columns?

(SELECT count(*) FROM pragma_table_info('flag')) > 0

-- (older SQLite lacks pragma_table_info; fall back to a guessed column name)

Extraction

The flag is 40 chars: a 7-char known prefix, 32 hex digits, a closing brace. For the hex

body, binary-search each character's nibble values:


substr((SELECT flag FROM flag LIMIT 1), i, 1) > '8'   -- then 4s, 2s, 1s

Four requests per character, ~128 probes total - comfortable against any rate limit,

and each probe is independent so they can be parallelized with a thread pool.

5. The part that actually bites: measurement discipline

Single-request timing is a liar. Network jitter of ?150ms against a 500ms signal sounds

fine until a CDN hop adds 400ms to a probe and your extractor silently reads a hex digit

wrong, and every subsequent character is garbage. The fix is boring and non-negotiable:

Vote three times per condition, accept the majority. In practice this caught ~5

wrong characters out of 32 in the fast pass; a targeted re-extract of just those

positions with voting converged immediately.

Calibration workflow that keeps the oracle honest:

  1. 1. Measure the no-delay baseline (median of 8).
  2. 2. Measure the always-true delay (median of 3) - this finds your N and your ceiling.
  3. 3. Threshold at the midpoint; re-verify the threshold before long runs.
  4. 4. Never trust a single probe: 3x majority.
  5. 5. After assembly, verify the *whole string* with one equality probe. If it fails,

audit characters rather than re-extracting everything.

6. Why this challenge is hard (and what it teaches)

The difficulty is not any single bug - each is textbook. It's that the attack is a

pipeline of three silent gates, and the framework gives you zero feedback between

them:

gatefailure mode if wrongobservable?
juggling suffixhighlight_file source pageyes - obvious
serialization formatnothing stored, destructor never runsno - looks identical to success
oracle thresholdplausible-looking garbage flagno - only the verify probe reveals it

The serialize gate deserves its own note: PHP accepts and ignores extra properties, but

a wrong string length inside s:N:"..." invalidates the whole object silently. When a

chain has a silent middle, gate each stage on an observable you control - e.g. make the

first SQL probe a condition you *know* is true and confirm the delay appears, before

spending an hour extracting noise.

Takeaways:

  • unserialize(user_input) is a gadget delivery service regardless of where the

result is written. /dev/null is not a mitigation; it's a punchline.

  • == against attacker-influenced strings is a vulnerability class. The fix is

=== and a non-numeric token.

  • Time-based oracles are viable at sub-second granularity, but only with calibration

and voting. Single-probe timing is fiction.

Comments

Popular Posts