Writeup · 31 Nights of Root

Session Cache

forensicseasysolvedFlag: r00t{REDACTED}

Overview

A browser process memory capture (memdump.bin, exactly 5 MiB) contains a cache of session records somewhere inside it. FORMAT_SPEC.txt describes the container only loosely:

  • A marker SESSCACHE_v2 precedes a 4-byte little-endian record count, then that many fixed-size records.
  • Each record has a plain record_id, a plain timestamp, an obfuscated username, an obfuscated session_token, and a plain trailing checksum (sum of the decoded username + token bytes, mod 2³²).
  • The obfuscated region is XOR’d with a keystream derived from the record’s own ID:
key_byte(record_id, i) = ((record_id * 2654435761 + i * 40503) & 0xFFFFFFFF) & 0xFF

Field order, field sizes and the record length are intentionally not given. The job is to reverse the layout, decode every record, and find the one that does not belong.

Prerequisites / Setup

  • Python 3 (struct, re)
  • memdump.bin in the working directory

Recon

Step 1 — Locate the marker

Goal: Find the SESSCACHE_v2 marker offset in the dump.

strings | grep confirms the marker exists once, but strings only shows printable runs and gives no offsets. Switch to a byte-level search:

grep -obUaP "SESSCACHE_v2" memdump.bin
2234639:SESSCACHE_v2

A single hit at offset 2234639 (0x22190f). Dumping the bytes after it:

xxd -s 2234639 -l 64 memdump.bin
0022190f: 5345 5353 4341 4348 455f 7632 0000 0000  SESSCACHE_v2....
0022191f: 1200 0000 e803 0000 800e 8069 00e6 b760  ...........i...`
0022192f: 2516 dd9d 4f57 8ec5 fc33 6aa1 ab6a 350e  %...OW...3j..j5.

Enumeration

Step 2 — Work out the record layout

Goal: Determine header padding, record count, record length, and field order.

Reading the bytes after the marker:

Offset from marker end Bytes Meaning
+0 00 00 00 00 4 bytes of padding (a naive read here gives count = 0)
+4 12 00 00 00 record count = 0x12 = 18
+8 e8 03 00 00 first record_id = 0x3e8 = 1000
+12 80 0e 80 69 timestamp = 0x69800e80 = 1770000000
+16 00 e6 b7 60 ... high-entropy bytes: the obfuscated region

To find the record length, scan forward for the next plausible timestamp. Timestamps are consecutive multiples of 300 s apart, so they show up as 0x698..... values at a constant stride:

offset  4  800e8069  1770000000
offset 80  ac0f8069  1770000300
offset 156 d8108069  1770000600
offset 232 04128069  1770000900

The stride is 76 bytes per record. Subtracting the plain fields leaves the layout:

+0   u32  record_id        (plain, LE)
+4   u32  timestamp        (plain, LE)
+8   64B  obfuscated       (XOR with keystream(record_id, i), i = 0..63)
        +0..15   username  (NUL padded, 16 bytes)
        +16..63  token     (NUL padded, 48 bytes)
+72  u32  checksum         (plain, LE) = sum(decoded 64 bytes) mod 2^32

Exploitation

Step 3 — Decode each record

Goal: Rebuild the keystream from each record’s own record_id and XOR over all 64 obfuscated bytes (index i runs over the whole region, not restarting at the token).

def keystream(rid, n):
    return bytes(((rid * 2654435761 + i * 40503) & 0xFFFFFFFF) & 0xFF for i in range(n))

dec = bytes(a ^ b for a, b in zip(obf, keystream(rid, len(obf))))
assert sum(dec) & 0xFFFFFFFF == checksum   # layout + decoding confirmed

All 18 records pass the checksum, which confirms the record length, field order, and that i is indexed from the start of the obfuscated region.

Step 4 — Find the anomalous record

Goal: Identify which record holds the flag instead of a normal sess_ token.

Tokens are shown as placeholders; only the structure matters.

id timestamp user token
1000 1770000000 hyamamoto sess_<32 hex>
1009 1770000300 rpatel sess_<32 hex>
1017 1770000600 tnguyen sess_<32 hex>
1023 1770000900 hyamamoto sess_<32 hex>
1030 1770001200 rpatel sess_<32 hex>
1037 1770001500 kwilliams sess_<32 hex>
1043 1770001800 kwilliams sess_<32 hex>
1049 1770002100 hyamamoto sess_<32 hex>
1058 1770002400 dcohen sess_<32 hex>
1066 1770002700 sokafor sess_<32 hex>
1073 1770003000 asingh sess_<32 hex>
1077 1770003300 fibrahim r00t{REDACTED} (not a sess_` token)
1086 1770003600 dcohen sess_<32 hex>
1091 1770003900 jmartinez sess_<32 hex>
1100 1770004200 sokafor sess_<32 hex>
1108 1770004500 bchen sess_<32 hex>
1113 1770004800 mrossi sess_<32 hex>
1122 1770005100 bchen sess_<32 hex>

Seventeen records hold a normal sess_ + 32 hex characters token. Record 1077 (fibrahim) holds a r00t{...} string in the token slot. That is the flag.

Step 5 — Run the full solver

Goal: Auto-detect header padding and record length by brute-forcing until every checksum validates, then flag any non-sess_ token.

Full script (shipped as solve.py):

#!/usr/bin/env python3
"""
Session Cache (31 Nights, forensics) - solver

Usage: python3 solve.py [memdump.bin]

Locates the SESSCACHE_v2 marker, auto-detects the header padding and the
fixed record length by validating the per-record checksum, decodes every
record, and prints a table plus any token that does not match a normal
"sess_<32 hex>" value (that's where the flag hides).
"""
import re
import struct
import sys

MARKER = b"SESSCACHE_v2"
MULT, STEP = 2654435761, 40503
USER_LEN = 16  # obfuscated region = 16-byte username + remaining bytes token


def keystream(rid: int, n: int) -> bytes:
    return bytes(((rid * MULT + i * STEP) & 0xFFFFFFFF) & 0xFF for i in range(n))


def decode(rec: bytes):
    """rec = id(4) | ts(4) | obfuscated(N) | checksum(4). Returns tuple or None."""
    rid, ts = struct.unpack_from("<II", rec, 0)
    ob, ck = rec[8:-4], struct.unpack_from("<I", rec, len(rec) - 4)[0]
    dec = bytes(a ^ b for a, b in zip(ob, keystream(rid, len(ob))))
    if sum(dec) & 0xFFFFFFFF != ck:
        return None
    user = dec[:USER_LEN].split(b"\x00")[0].decode(errors="replace")
    tok = dec[USER_LEN:].split(b"\x00")[0].decode(errors="replace")
    return rid, ts, user, tok


def find_layout(data: bytes, m: int):
    """Try header paddings and record lengths until every checksum validates."""
    base = m + len(MARKER)
    for pad in range(0, 32):
        cnt_off = base + pad
        count = struct.unpack_from("<I", data, cnt_off)[0]
        if not 1 <= count <= 100000:
            continue
        start = cnt_off + 4
        for rlen in range(16, 512):
            if start + rlen * count > len(data):
                break
            out = []
            for k in range(count):  # bail out at the first bad checksum
                d = decode(data[start + k * rlen : start + (k + 1) * rlen])
                if not d:
                    break
                out.append(d)
            else:
                return pad, count, rlen, start, out
    return None


def main():
    path = sys.argv[1] if len(sys.argv) > 1 else "memdump.bin"
    data = open(path, "rb").read()

    hits = [x.start() for x in re.finditer(re.escape(MARKER), data)]
    print(f"[*] marker hits: {hits}")
    for m in hits:
        res = find_layout(data, m)
        if not res:
            continue
        pad, count, rlen, start, recs = res
        print(f"[+] marker @ {m:#x}, header padding={pad}, count={count}, "
              f"record_len={rlen}, first record @ {start:#x}")
        print(f"{'id':>5}  {'timestamp':>10}  {'user':<10} token")
        for rid, ts, user, tok in recs:
            print(f"{rid:>5}  {ts:>10}  {user:<10} {tok}")
        print()
        for rid, ts, user, tok in recs:
            if not re.fullmatch(r"sess_[0-9a-f]{32}", tok):
                print(f"[!] anomalous token in record {rid} ({user}): {tok}")
        return
    print("[-] no valid layout found")


if __name__ == "__main__":
    main()
python3 solve.py memdump.bin

Flag

r00t{REDACTED}

Record 1077 (fibrahim) holds `r00t{REDACTED} in its token slot.

Mitigations

  • Apply proper input validation and sanitization for all user-supplied data.
  • Use parameterized queries or prepared statements for database operations.
  • Implement proper authentication and authorization checks.
  • Follow the principle of least privilege for all application components.

Lessons / Takeaways

  • A keystream that is a pure function of plaintext-adjacent data (record_id) is obfuscation, not encryption — the keystream can be rebuilt without any key material.
  • A checksum is a powerful layout oracle: brute-force header padding and record length until every record’s checksum validates.
  • One anomalous record among many identical-format records is usually where the secret hides.

Techniques

  • XOR Obfuscation
  • Checksum Oracle

References