Flash CTF - Ratchet

Ratchet Writeup

Overview

We get one file: a stripped 64-bit ELF that reads 32 bytes, prints one word, and says nothing else. Inside it are 32 small functions that look related but never quite the same. They turn out to be one algorithm written 32 different ways, so most of the work is refusing to read the second spelling as new information. The rest is noticing that the check threads a 32-bit state through the positions. The expected byte at any position is fixed by the bytes before it, so the only way in is to walk left to right.

Solution

What we are holding

$ file dist/ratchet
dist/ratchet: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically
linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=1a609bbe5b0e..., for
GNU/Linux 3.2.0, stripped
$ ls -l dist/ratchet
-rwxr-xr-x 1 user user 14472 dist/ratchet
$ nm dist/ratchet
nm: dist/ratchet: no symbols

14 KB and no symbols, so every function will be an address. Let's feed it things.

$ printf 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n' | dist/ratchet
wrong
$ printf 'short\n' | dist/ratchet
wrong
$ printf 'SkillBit{aaaaaaaaaaaaaaaaaaaaaa}\n' | dist/ratchet
wrong

One word back, every time. No position, no partial credit, nothing to measure. Looking for anything readable comes up empty too.

$ strings -a dist/ratchet | grep -iE 'correct|wrong|skillbit'
wrong
correct

Those two strings are the program's entire vocabulary. The flag is not stored anywhere we can read it out, so we will have to reconstruct it.

Finding the driver

_start hands the entry function to libc in rdi, which gives us main without needing any symbols.

$ objdump -d -M intel dist/ratchet | grep -A11 '^ *1220:'
   1220:  endbr64
   1224:  xor    ebp,ebp
   1226:  mov    r9,rdx
   1229:  pop    rsi
   122a:  mov    rdx,rsp
   122d:  and    rsp,0xfffffffffffffff0
   1231:  push   rax
   1232:  push   rsp
   1233:  xor    r8d,r8d
   1236:  xor    ecx,ecx
   1238:  lea    rdi,[rip+0xfffffffffffffe61]        # 10a0
   123f:  call   QWORD PTR [rip+0x2d93]

So the program proper starts at 0x10a0:

   10a0:  endbr64
   10a4:  push   rbp
   10a5:  xor    edi,edi
   10a7:  mov    edx,0x40
   10ac:  sub    rsp,0x50
   ...
   10c3:  mov    rsi,rbp
   10c6:  call   1090 <read@plt>
   10cb:  cmp    rax,0x20
   10cf:  jle    10d8
   10d1:  cmp    BYTE PTR [rsp+0x20],0xa
   10d6:  je     1100
   10d8:  lea    rdi,[rip+0xf25]        # 2004
   10df:  call   1070 <puts@plt>

One read of up to 0x40 bytes, then two gates. At least 33 bytes have to arrive, and byte 32 has to be 0x0a. That explains the rejection of a bare 32-byte string with no newline. The accepting path is at 0x1100:

   1100:  mov    rsi,rbp
   1103:  mov    edi,0x243f6a88
   1108:  mov    DWORD PTR [rip+0x2f06],0x85a308d3        # 4018
   1112:  mov    BYTE PTR [rip+0x2efb],0x0                # 4014
   1119:  call   1310
   111e:  mov    edi,eax
   1120:  call   1360
   1125:  mov    edi,eax
   1127:  call   13a0
   112c:  mov    edi,eax
   ...

Three things get set up. edi starts at 0x243f6a88, a global at 0x4018 starts at 0x85a308d3, and a byte at 0x4014 is cleared. Then a long run of calls, each followed by mov edi,eax, so every function takes the previous one's return value as its first argument. rsi points at our input and never changes.

$ objdump -d -M intel dist/ratchet | sed -n '/^ *1100:/,/call.*puts/p' | grep -c 'call '
33

32 of those are the chain and the last is the puts that prints the verdict. No branch leaves the chain early, so a wrong byte does not stop anything. The program just keeps going with a ruined argument.

Reading the first one

The function at 0x1310, in full:

   1310:  movzx  edx,BYTE PTR [rsi]
   1313:  mov    ecx,edx
   1315:  xor    edx,edi
   1317:  mov    eax,edx
   1319:  shl    eax,0x7
   131c:  shr    edx,0x19
   131f:  or     eax,edx
   1321:  add    eax,0x4f1bbcdc
   1326:  add    eax,0x4f1bbcdd
   132b:  mov    edx,DWORD PTR [rip+0x2ce7]        # 4018
   1331:  shl    edi,0x15
   1334:  shr    edi,0x18
   1337:  xor    edx,0xac5c0ab9
   133d:  rol    edx,0x3
   1340:  mov    DWORD PTR [rip+0x2cd2],edx        # 4018
   1346:  shr    edx,0xb
   1349:  xor    edi,edx
   134b:  cmp    cl,dil
   134e:  je     1357
   1350:  mov    BYTE PTR [rip+0x2cbd],0x1         # 4014
   1357:  ret

Short enough to read in one sitting. ecx keeps a copy of our byte 0. edx gets that byte xored into the argument, and the next four instructions take the result apart and put it back together: shift left by 7, shift right by 25, or the halves. That is a left rotation by 7 written the long way. Then two constants are added, 0x4f1bbcdc and 0x4f1bbcdd, which sum to 0x9e3779b9, the golden ratio constant. eax is what the function returns, so this is how the argument reaches the next position. Call that value the state.

The three lines in the middle touch the global at 0x4018. It is xored with 0xac5c0ab9, rotated left by 3, and written back. Our input appears nowhere in that, so a second value is running alongside the state, indifferent to what we type.

The last lines build the comparison. shl edi,0x15 then shr edi,0x18 keeps bits 3 to 10 of the argument, which is the state before the advance. shr edx,0xb keeps bits 11 to 18 of the freshly updated global. The two are xored and the low byte is compared against ours. On a mismatch the byte at 0x4014 is set to 1, which is the verdict byte cleared back in the driver.

So position 0 wants ((R >> 11) ^ (s >> 3)) & 0xff, and then advances s using the byte we gave it.

The same three steps in different handwriting

Reading the next function suggests we are in for 31 more of these. It is not the same code.

   1360:  movzx  eax,BYTE PTR [rsi+0x1]
   1364:  mov    ecx,eax
   1366:  xor    eax,edi
   1368:  rol    eax,0x7
   136b:  mov    edx,0x9e3779b9
   1370:  add    eax,edx
   1372:  mov    edx,DWORD PTR [rip+0x2ca0]        # 4018
   1378:  shr    edi,0x3
   137b:  xor    edx,0xac59ab69
   1381:  rol    edx,0x5
   1384:  mov    DWORD PTR [rip+0x2c8e],edx        # 4018
   138a:  shr    edx,0xb
   138d:  xor    edx,edi
   138f:  xor    edx,0x62
   1392:  cmp    cl,dl

Four things moved. The rotation is a plain rol eax,0x7. The constant arrives in a register instead of as an immediate. The keystream is shr edi,0x3, which keeps the same bits as the shift pair in the first block. And there is an extra step before the compare, xor edx,0x62, which was not in block one at all.

That last one is worth a pause, because our model of position 0 did not have it. Every other block has a byte there, so the honest reading is that position 0's stored byte is zero and the compiler dropped the instruction. Each position has its own stored byte, and position 0 drew 0x00.

Three more, trimmed to the parts that differ:

   1550:  xor    eax,edi
   1558:  ror    eax,0x19
   155b:  add    eax,0x9e3779b9
   1566:  shr    edi,0x3
   157d:  xor    edx,0x3

   1890:  xor    eax,edi
   1898:  rol    eax,0x4
   189b:  rol    eax,0x3
   189e:  sub    eax,0x61c88647
   18a9:  shr    edi,0x3
   18c0:  xor    edx,0x73

   14c0:  xor    edx,edi
   14c8:  ror    edi,0x3
   14cb:  mov    eax,edx
   14cd:  shl    eax,0x7
   14d0:  shr    edx,0x19
   14d3:  or     eax,edx
   14d5:  sub    eax,0x61c88647
   14f3:  xor    edx,0xffffff93

ror eax,0x19 is a right rotation by 25, which on 32 bits is the same left rotation by 7. rol 0x4 then rol 0x3 gets there in two steps. Subtracting 0x61c88647 is adding 0x9e3779b9, because the two sum to 2^32. And ror edi,0x3 leaves the same low byte as shr edi,0x3.

At this point it pays to count rather than keep reading. Every block starts by xoring our byte into the state, so grep around that:

$ objdump -d -M intel dist/ratchet | grep -A3 -E 'xor +e[a-z]{2},edi' \
   | grep -oE '(rol|ror|shl) +e[a-z]{2},0x[0-9a-f]+' | grep -v edi \
   | sed -E 's/ +e[a-z]{2},/ /' | sort | uniq -c
     9 rol 0x3
     9 rol 0x4
     9 rol 0x7
     5 ror 0x19
     9 shl 0x7

rol 0x4 and rol 0x3 are the same nine blocks doing it in two steps, so that is four spellings of one rotation. The constant tells the same story:

$ objdump -d -M intel dist/ratchet \
   | grep -oE '(add|sub|mov) +e[a-z]+,0x(9e3779b9|61c88647|4f1bbcdc|4f1bbcdd)' \
   | sed 's/ *e[a-z]*,/ /' | sort | uniq -c
     8 add 0x4f1bbcdc
     8 add 0x4f1bbcdd
     7 add 0x9e3779b9
     9 mov 0x9e3779b9
     8 sub 0x61c88647

Eight blocks split it, seven add it outright, nine load it into a register first, eight subtract the complement. And the keystream:

$ objdump -d -M intel dist/ratchet | grep -oE '(shr|shl|ror) +edi,0x[0-9a-f]+' \
   | sort | uniq -c
     9 ror    edi,0x3
    12 shl    edi,0x15
    12 shr    edi,0x18
    11 shr    edi,0x3

Three ways of taking bits 3 to 10. None of this is a different algorithm. It is one advance, one keystream and one add, dressed 32 ways, and no two positions are dressed the same. Once we accept that, the other 31 functions stop being work and turn into confirmation.

The chain that ignores us

The global at 0x4018 deserves its own pass, because it is the only thing standing between the stored bytes and the comparison.

$ objdump -d -M intel dist/ratchet | grep -cE 'xor +e[a-z]{2},0xac[0-9a-f]{6}'
32
$ objdump -d -M intel dist/ratchet | grep -oE 'xor +e[a-z]{2},0xac[0-9a-f]{6}' | sort -u | wc -l
32
$ objdump -d -M intel dist/ratchet | grep -cE 'shr +e[a-z]{2},0xb'
32

32 distinct constants, all with 0xac on top, one per block, each followed by a rotation with its own small immediate, each contributing bits 11 to 18. The chain starts from 0x85a308d3 and never reads our input, so we can reproduce it on its own. What it buys is that the stored bytes in the binary are not the comparison targets. They are the targets masked by this chain.

Walking it forward

Each position needs three constants we can read statically: the mask a, its rotation amount n, and the stored byte e. With s starting at 0x243f6a88 and R at 0x85a308d3, every position is:

ks   = (s >> 3) & 0xff
R    = rotl32(R ^ a, n)
byte = e ^ ((R >> 11) & 0xff) ^ ks
s    = (rotl32(s ^ byte, 7) + 0x9e3779b9) & 0xffffffff

The last line is why this is a ratchet. byte needs s, and s needs the byte before it. There is no jumping to position 17 and there is no going back.

That also kills the idea of reading the stored bytes straight out of the binary. The solver's --static mode prints what the shortcuts produce:

$ python3 solve.py --static
...
[!] static read of the shipped constant bytes, raw:
   00627fa9c610937d03c7b78412458b15479f54732bbd1e87f9967ccf6ec45fb5
   printable=False
[!] constant bytes xored with the initial state everywhere:
   51332ef89741c22c5296e6d54314da4416ce05227aec4fd6a8c72d9e3f950ee4
   printable=False binary says: wrong

The first row is the 32 stored bytes as they ship, starting with the 0x00 from position 0. The second is what we get if we spot the keystream but assume the state never moves, so position 0's keystream applies everywhere. Neither decodes.

Getting the rotation backwards is the more realistic mistake. The same rotation is spelled rol 0x7 in one block, ror 0x19 in another and a shift pair in a third, so it is easy to carry the wrong direction into the model:

[!] mirror with rotate right instead of rotate left:
   53931e19df56c3ce0e695a64830450aa0aaf7c0b59a8e56f2bb29277b1c534b8
   printable=False wrapped=False binary says: wrong

Byte 0 survives, because position 0's keystream only depends on the starting state. Everything after it is noise, and the binary answers a wrong model with the same word it uses for garbage. There is no fake flag in the file to catch us either way.

The line that run prints first is the one that matters. With the fold done correctly, the walk lands on the answer without executing a single block:

[!] static mirror walk from disassembled constants:
   536b696c6c4269747b73743474335f31735f7468335f306e31795f6b3379217d
   printable=True wrapped=True binary says: correct

Letting the binary do the folding

There is a second way in that skips the fold, and it is worth knowing because it also proves the answer is unique. Each block is an ordinary function. It takes the state in rdi and our buffer in rsi, and it reports failure by writing one known byte. So we can drive the blocks ourselves under an emulator, offer all 256 values at a position, and keep whichever one leaves that byte clear. Carry the returned state and the updated chain into the next position and repeat.

$ python3 solve.py
[*] recovered 32 bytes
[+] FLAG SkillBit{st4t3_1s_th3_0n1y_k3y!}
[*] binary says: correct

That is 8192 emulated calls of about twenty instructions each, so it finishes in a little over a second. Exactly one byte is accepted at every position, which is what makes the greedy walk safe, and the solver asserts it at each step instead of assuming it. The binary ends up being its own oracle and we never reimplement the advance at all. Folding the listings still matters, because that is what tells us the greedy walk is sound before we write it.

The solver

Put this next to the handout and run it. It needs pyelftools, capstone and unicorn, and the handout has to be executable, because the last thing it does is feed the recovered bytes back to the binary and check the verdict.

"""
Ratchet solver
==============
Static challenge: there is no instance to connect to, so the solver reads the
handout from disk instead of taking -u/--url.

Usage:
  python3 solve.py                     # reads ./ratchet
  python3 solve.py -f path/to/ratchet  # any other copy of the handout
  python3 solve.py --static            # also run the static mirror walk
                                       # (SOLVE_STATIC=1 does the same)

Needs pyelftools, capstone and unicorn. The handout must be executable, since
the solver runs it to confirm the recovered bytes.
"""

import argparse
import os
import struct
import subprocess
from pathlib import Path

from elftools.elf.elffile import ELFFile

HANDOUT = Path(__file__).resolve().parent / "ratchet"

BASE = 0x400000
STACK = 0x7FF000000000
SCRATCH = 0x10000000
SENTINEL = 0x5E5E0000
M32 = 0xFFFFFFFF


def rotl(x, n):
    n &= 31
    if n == 0:
        return x
    return ((x << n) | (x >> (32 - n))) & M32


def load_elf(path):
    with open(path, "rb") as f:
        elf = ELFFile(f)
        entry = elf.header.e_entry
        segs = []
        for seg in elf.iter_segments():
            if seg.header.p_type == "PT_LOAD":
                segs.append((seg.header.p_vaddr, seg.data()))
        rodata = None
        for s in elf.iter_sections():
            if s.name == ".rodata":
                rodata = (s.header.sh_addr, s.data())
        assert rodata is not None
    return entry, segs, rodata


def disasm(data, addr):
    from capstone import CS_ARCH_X86, CS_MODE_64, Cs

    cs = Cs(CS_ARCH_X86, CS_MODE_64)
    cs.detail = True
    return list(cs.disasm(data, addr))


def rip_target(insn, op):
    from capstone.x86 import X86_OP_MEM, X86_REG_RIP

    if op.type != X86_OP_MEM:
        return None
    if op.mem.base != X86_REG_RIP:
        return None
    return insn.address + insn.size + op.mem.disp


def find_blocks(path):
    entry, segs, _ = load_elf(path)
    lo = min(BASE + v for v, _ in segs)
    hi = max(BASE + v + len(d) for v, d in segs)
    blob = bytearray(hi - lo)
    for v, d in segs:
        blob[BASE + v - lo : BASE + v - lo + len(d)] = d

    def read(va, n):
        return bytes(blob[va - lo : va - lo + n])

    start = BASE + entry
    ins = disasm(read(start, 0x80), start)
    main_va = None
    from capstone.x86 import X86_OP_MEM, X86_REG_RIP

    for insn in ins:
        if insn.mnemonic == "lea" and "rdi" in insn.op_str and "rip" in insn.op_str:
            op = insn.operands[1]
            if op.type == X86_OP_MEM and op.mem.base == X86_REG_RIP:
                main_va = insn.address + insn.size + op.mem.disp
                break
    assert main_va, "main not found from entry"
    main_len = (BASE + entry) - main_va
    assert 0 < main_len <= 0x400, "unexpected main placement"
    mins = disasm(read(main_va, main_len), main_va)
    calls = []
    r_va = None
    c0 = None
    s0 = None
    for insn in mins:
        if insn.mnemonic == "call":
            calls.append(insn.operands[0].imm)
        if insn.mnemonic == "mov" and len(insn.operands) == 2:
            dst, src = insn.operands
            from capstone.x86 import X86_OP_IMM, X86_OP_MEM, X86_REG_RIP

            if (
                src.type == X86_OP_IMM
                and dst.type == X86_OP_MEM
                and dst.mem.base == X86_REG_RIP
                and dst.size == 4
                and src.imm != 0
            ):
                r_va = rip_target(insn, dst)
                c0 = src.imm & M32
            if src.type == X86_OP_IMM and src.imm == 0x243F6A88:
                s0 = src.imm
    blocks = [c for c in calls if c > main_va]
    assert len(blocks) == 32, "expected 32 direct block calls, got %d" % len(blocks)
    assert len(set(blocks)) == 32, "block targets are not distinct"
    assert s0 is not None and r_va is not None and c0 is not None, (
        "state constants not located"
    )
    b0 = disasm(read(blocks[0], 0x100), blocks[0])
    bad_va = None
    from capstone.x86 import X86_OP_IMM, X86_OP_MEM, X86_REG_RIP

    for insn in b0:
        if len(insn.operands) != 2:
            continue
        dst, src = insn.operands
        if (
            insn.mnemonic == "mov"
            and src.type == X86_OP_IMM
            and src.imm == 1
            and dst.type == X86_OP_MEM
            and dst.mem.base == X86_REG_RIP
        ):
            bad_va = rip_target(insn, dst)
    assert bad_va, "bad flag global not located"
    return dict(blocks=blocks, bad=bad_va, raddr=r_va, c0=c0, s0=s0, lo=lo, blob=blob)


def static_constants(path, lay):
    from capstone.x86 import X86_OP_IMM, X86_OP_MEM, X86_OP_REG

    order = sorted(range(32), key=lambda k: lay["blocks"][k])
    out = [None] * 32
    for pos in range(32):
        idx = order[pos]
        bva = lay["blocks"][idx]
        if pos + 1 < 32:
            nxt = lay["blocks"][order[pos + 1]]
            window = min(0x100, nxt - bva)
        else:
            window = 0x80
        code = lay["blob"][bva - lay["lo"] : bva - lay["lo"] + window]
        ins = disasm(code, bva)
        # A block ends at its first ret. The window can run past that into
        # padding and into the next function, and those bytes must not
        # contribute constants.
        for n, insn in enumerate(ins):
            if insn.mnemonic == "ret":
                ins = ins[: n + 1]
                break
        a = None
        a_insn = None
        a_reg = None
        r_store = None
        b = 0
        ebyte = None
        for n, insn in enumerate(ins):
            if len(insn.operands) != 2:
                continue
            dst, src = insn.operands
            if (
                insn.mnemonic == "mov"
                and dst.type == X86_OP_MEM
                and "rip" in insn.op_str
                and src.type == X86_OP_REG
            ):
                r_store = n
        for n, insn in enumerate(ins):
            if len(insn.operands) != 2:
                continue
            dst, src = insn.operands
            if src.type == X86_OP_IMM and 0xAC000000 <= src.imm <= 0xACFFFFFF:
                a = src.imm & M32
                a_insn = n
                a_reg = dst.reg
            if (
                insn.mnemonic in ("rol", "shl")
                and src.type == X86_OP_IMM
                and 0 < src.imm < 16
                and a_insn is not None
                and r_store is not None
                and a_insn < n < r_store
                and dst.reg == a_reg
            ):
                b = src.imm
            # The stored byte is folded into the compared register after the
            # mask chain is written back, so only look past that store. gcc
            # writes it as `xor $imm` here, but for some byte values it picks
            # `add`/`sub` with an immediate instead, which is the same thing
            # modulo 256, so accept all three.
            if (
                r_store is not None
                and n > r_store
                and insn.mnemonic in ("xor", "add", "sub")
                and src.type == X86_OP_IMM
            ):
                ebyte = (-src.imm if insn.mnemonic == "sub" else src.imm) & 0xFF
        if ebyte is None and r_store is not None:
            ebyte = 0  # a zero stored byte folds away entirely
        assert a is not None and ebyte is not None and r_store is not None, (
            "block %d constants not extracted" % idx
        )
        out[idx] = (a, b, ebyte)
    return out


def table_bytes(consts):
    return bytes(e for _, _, e in consts)


class Emu:
    def __init__(self, path, lay):
        from unicorn import UC_ARCH_X86, UC_MODE_64, Uc

        entry, segs, _ = load_elf(path)
        self.uc = Uc(UC_ARCH_X86, UC_MODE_64)
        for v, d in segs:
            start = (BASE + v) & ~0xFFF
            end = (BASE + v + len(d) + 0xFFF) & ~0xFFF
            try:
                self.uc.mem_map(start, end - start, 7)
            except Exception:
                pass
            self.uc.mem_write(BASE + v, d)
        self.uc.mem_map(STACK, 0x100000, 7)
        self.uc.mem_map(SCRATCH, 0x1000, 7)
        self.blob = lay["blob"]
        self.lo = lay["lo"]
        self.lay = lay
        self.rsp = STACK + 0x80000

    def call_block(self, bva, s, input_bytes):
        from unicorn.x86_const import (
            UC_X86_REG_RAX,
            UC_X86_REG_RDI,
            UC_X86_REG_RSI,
            UC_X86_REG_RSP,
        )

        uc = self.uc
        uc.mem_write(SCRATCH, input_bytes.ljust(64, b"\x00"))
        uc.mem_write(self.rsp - 8, struct.pack("<Q", SENTINEL))
        uc.reg_write(UC_X86_REG_RSP, self.rsp - 8)
        uc.reg_write(UC_X86_REG_RDI, s)
        uc.reg_write(UC_X86_REG_RSI, SCRATCH)
        uc.emu_start(bva, SENTINEL, timeout=4_000_000)
        return uc.reg_read(UC_X86_REG_RAX) & M32

    def set_u32(self, va, val):
        self.uc.mem_write(va, struct.pack("<I", val & M32))

    def get_u32(self, va):
        return struct.unpack("<I", self.uc.mem_read(va, 4))[0]

    def set_u8(self, va, val):
        self.uc.mem_write(va, bytes([val]))

    def get_u8(self, va):
        return self.uc.mem_read(va, 1)[0]


def recover(path):
    lay = find_blocks(path)
    emu = Emu(path, lay)
    s = lay["s0"]
    r = lay["c0"]
    flag = bytearray()
    for i, bva in enumerate(lay["blocks"]):
        found = None
        for cand in range(256):
            trial = bytes(flag) + bytes([cand])
            emu.set_u32(lay["raddr"], r)
            emu.set_u8(lay["bad"], 0)
            s_new = emu.call_block(bva, s, trial)
            if emu.get_u8(lay["bad"]) == 0:
                assert found is None, "position %d has multiple accepted bytes" % i
                found = (cand, s_new, emu.get_u32(lay["raddr"]))
        assert found is not None, "position %d has no accepted byte" % i
        flag.append(found[0])
        s = found[1]
        r = found[2]
    print("[*] recovered 32 bytes")
    return bytes(flag), lay, emu


def static_walk(path, lay, consts, broken=False):
    ebytes = table_bytes(consts)
    s = lay["s0"]
    r = lay["c0"]
    out = bytearray()
    for i, (a, b, ebyte) in enumerate(consts):
        ks = (s >> 3) & 0xFF
        r = rotl((r ^ a) & M32, b)
        rb = (r >> 11) & 0xFF
        out.append(ebyte ^ rb ^ ks)
        x = (s ^ out[i]) & M32
        if broken:
            x = ((x >> 7) | (x << 25)) & M32
        else:
            x = rotl(x, 7)
        s = (x + 0x9E3779B9) & M32
    return bytes(out)


def run_native(path, candidate):
    p = subprocess.run([path], input=candidate + b"\n", capture_output=True)
    return p.stdout.decode().strip()


def parse_args():
    ap = argparse.ArgumentParser(description="reven-ratchet solver")
    ap.add_argument(
        "-f",
        "--file",
        type=Path,
        default=HANDOUT,
        help="Path to the handout binary (default: ./ratchet)",
    )
    ap.add_argument(
        "--static",
        action="store_true",
        help="Also run the static mirror walk and the naive reads",
    )
    return ap.parse_args()


def main():
    args = parse_args()
    path = str(args.file.resolve())
    flag, lay, emu = recover(path)
    print("[+] FLAG %s" % flag.decode())
    verdict = run_native(path, flag)
    print("[*] binary says: %s" % verdict)
    assert verdict == "correct"

    if args.static or os.environ.get("SOLVE_STATIC"):
        consts = static_constants(path, lay)
        cand = static_walk(path, lay, consts)
        print("[!] static mirror walk from disassembled constants:")
        print("    %s" % cand.hex())
        printable = all(32 <= c < 127 for c in cand)
        wrapped = printable and cand.startswith(b"SkillBit{") and cand.endswith(b"}")
        print(
            "    printable=%s wrapped=%s binary says: %s"
            % (printable, wrapped, run_native(path, cand))
        )
        assert cand == flag, "static mirror disagrees with the oracle"
        print("[!] static read of the shipped constant bytes, raw:")
        raw = table_bytes(consts)
        print("    %s" % raw.hex())
        print("    printable=%s" % all(32 <= c < 127 for c in raw))
        naive = bytes(e ^ ((lay["s0"] >> 3) & 0xFF) for e in raw)
        print("[!] constant bytes xored with the initial state everywhere:")
        print("    %s" % naive.hex())
        print(
            "    printable=%s binary says: %s"
            % (all(32 <= c < 127 for c in naive), run_native(path, naive))
        )
        broken = static_walk(path, lay, consts, broken=True)
        print("[!] mirror with rotate right instead of rotate left:")
        print("    %s" % broken.hex())
        bp = all(32 <= c < 127 for c in broken)
        print(
            "    printable=%s wrapped=%s binary says: %s"
            % (
                bp,
                bp and broken.startswith(b"SkillBit{") and broken.endswith(b"}"),
                run_native(path, broken),
            )
        )
        assert not (bp and broken.startswith(b"SkillBit{"))
        print("[!] no wrong model and no raw read produces a submittable flag")


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

Interested in joining our team? Let’s connect!