Writeup · 31 Nights of Root

Wraith

reversingmediumsolvedFlag: r00t{REDACTED}

Overview

A single WebAssembly module exporting check_flag and memory, and importing js_print_ok / js_print_fail. The check is a small bytecode VM: the program is stored XOR-encrypted in the data section, decrypted onto the stack at runtime, then interpreted. Each flag character has its own check, so every check inverts independently.

flowchart LR
    A[input ptr] --> B[scan length, max 64]
    B --> C[decrypt 331 B program, key = 4 B repeating XOR]
    C --> D[VM loop: opcode dispatch, br_table on op - 0x41]
    D --> E{all checks true?}
    E -->|yes| F[js_print_ok]
    E -->|no| G[js_print_fail]

Prerequisites / Setup

  • Python 3
  • wabt (wasm2wat, wasm-decompile) or radare2 or plain Node — optional; the Python solver is self-contained
  • wraith.wasm in the working directory

Recon

Step 1 — Inspect the module

Goal: Confirm the file type and identify exports/imports.

file wraith.wasm
strings -n 4 wraith.wasm
js_print_ok
js_print_fail
memory
check_flag

Takeaways: two host callbacks that report the verdict, one exported checker, one memory. No flag in the clear.

Step 2 — Static analysis

Goal: Understand the module structure with radare2 (untested commands — verify on your own copy).

cp wraith.wasm work.wasm
r2 -w -A work.wasm   # -w so we can patch the copy; -A analyses
[0x00000000]> iS            # sections: note the data section (id 11)
[0x00000000]> iE            # exports: check_flag
[0x00000000]> afl           # function list
[0x00000000]> pdf @ sym.check_flag   # or the fcn.* name shown by afl

What the disassembly shows (also readable with wasm2wat):

  • One big function with a 0x3a0 (928) byte frame (global.get 0; i32.const 928; i32.sub).
  • A first loop reading four bytes at a time from the input until it hits a NUL: this is the length scan, capped at 64.
  • A second loop stack[i] = mem[0x400 + (i & 3)] ^ mem[0x410 + i] for i in 0..330: a repeating 4-byte XOR decryption of the data blob into the stack frame.
  • A loop containing a br_table on opcode - 0x41: the interpreter. Eight handlers, selected by opcodes 0x41..0x48, plus special cases for 0xad and 0xde.
  • After the loop, a load of one i32 from the frame decides between call js_print_ok and call js_print_fail.

Step 3 — Get the encrypted program

Goal: Extract the encrypted program from the data section.

The data section content starts at file offset 0x603, with an 8-byte segment header. Memory address 0x400 therefore maps to file offset 0x60b:

0x603  01 00 41 80 08 0b db 02   <- segment header: 1 segment, active, offset const 0x400, size 347
0x60b  90 63 09 d2               <- 4-byte XOR key (memory 0x400)
0x60f  00 x12                    <- padding (memory 0x404-0x40f)
0x61b  4e 21 09 93 ...           <- ciphertext (memory 0x410), 331 bytes

Confirm these offsets with iS and px on your own copy before relying on them.

In r2, decrypt in place on the copy and look at the result:

[0x0]> s 0x61b
[0x61b]> wox 906309d2 @ 0x61b!331     # XOR the 331 bytes with the repeating key
[0x61b]> px 331

You should now see a regular repeating pattern starting de 42 00 41 c2 43 45 07 41 58 46 .... That regularity is the sign that the XOR was right (the ciphertext looks random).

Exploitation

Step 4 — Understand the VM

Goal: Recover the instruction set from the handler blocks.

Opcode Mnemonic Effect
0x41 PUSH imm push constant
0x42 LOAD imm push input[imm] (0 if past the string end)
0x43 XOR pop two, push a ^ b
0x44 ADD imm add constant to top of stack
0x45 ROTL imm rotate the top byte left by imm & 7
0x46 EQ pop two, push a == b
0x47 AND pop two, push a & b
0x48 HALT stop, publish result
0xde reset clear the VM stack

The decrypted program

The program is 29 copies of the same six-instruction template, with different constants. Disassembled:

LOAD 0      ; input[0]
PUSH 0xc2
XOR
ROTL 7
PUSH 0x58
EQ          ; ((input[0] ^ 0xc2) rotl 7) == 0x58
LOAD 1
PUSH 0xa4
XOR
ROTL 4
PUSH 0x49
EQ
...
AND AND AND ... HALT   ; fold the 29 booleans together

Every check has the form rotl8(input[i] ^ c, n) == t, and the result is the AND of all of them. Because each check involves exactly one input byte, invert each one on its own:

input[i] = rotr8(t, n) ^ c

Worked example for the first character: rotr8(0x58, 7) = 0xb0, and 0xb0 ^ 0xc2 = 0x72, which is r.

Step 5 — Solve

Goal: Parse the data section, decrypt the program, walk the bytecode and invert every check.

The full script is in wraith_solver.py next to this note. It parses the data section, decrypts the program, walks the bytecode and inverts every check.

def solve(prog):
    flag, cur, k = {}, [], 0
    while k < len(prog):
        op = prog[k]
        if op in (OP_PUSH, OP_LOAD, OP_ROTL):      # 1-byte immediate
            if op == OP_LOAD:
                cur = []                            # a LOAD starts a new check
            cur.append((op, prog[k + 1])); k += 2
            continue
        if op == OP_XOR:
            cur.append((op, None))
        elif op == OP_EQ:
            idx = cur[0][1]; c = cur[1][1]; n = cur[3][1]; t = cur[4][1]
            flag[idx] = rotr8(t, n) ^ c             # invert the check
        elif op == OP_RESET:
            cur = []
        k += 1
    return bytes(flag[i] for i in sorted(flag))
python3 -I wraith_solver.py wraith.wasm --check
r00t{REDACTED}
check_flag -> OK

(The real script prints the full flag. It is masked here per the vault rules.)

Confirming dynamically

Node can call the export directly. Write the candidate into memory, pass its address, and read the return value:

const b = require('fs').readFileSync('wraith.wasm');
WebAssembly.instantiate(b, {
  env: {
    js_print_ok() {
      console.log('OK');
    },
    js_print_fail() {
      console.log('FAIL');
    },
  },
}).then(({ instance: i }) => {
  const m = new Uint8Array(i.exports.memory.buffer);
  m.set(Buffer.from('r00t{REDACTED}\0'), 2048); // substitute the recovered flag
  console.log(i.exports.check_flag(2048)); // 1 = correct
});

A correct flag prints OK and returns 1; a wrong one prints FAIL and returns 0.

Flag

r00t{REDACTED}

Lessons / Takeaways

  • A small wasm file with a br_table inside a loop is almost always an interpreter. Find the dispatcher first, then the program it runs.
  • Look for the decrypt loop before the dispatch loop: a short repeating XOR key over a blob in the data section is the usual packer.
  • When the checks are per-character, invert them instead of searching. Each ((x ^ c) rotl n) == t has exactly one solution per byte.
  • Always confirm by running the real export in Node. It is cheap and catches parsing mistakes. My first solver version mixed constants from neighbouring checks because it did not reset its state on each LOAD, and the Node check caught it immediately.

Techniques

  • WebAssembly Reversing
  • Custom VM Reversing
  • XOR Decryption
  • Radare2

References