<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rynvasis on Medium]]></title>
        <description><![CDATA[Stories by Rynvasis on Medium]]></description>
        <link>https://medium.com/@rynvasis?source=rss-a480ee56e6d7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_VDQ9RnabA3lnr1PYaay-g.jpeg</url>
            <title>Stories by Rynvasis on Medium</title>
            <link>https://medium.com/@rynvasis?source=rss-a480ee56e6d7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 23:39:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rynvasis/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[UofTCTF 2026 Reverse Engineering Challenges]]></title>
            <link>https://rynvasis.medium.com/uoftctf-2026-reverse-engineering-challenges-0df23147ca87?source=rss-a480ee56e6d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/0df23147ca87</guid>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Rynvasis]]></dc:creator>
            <pubDate>Fri, 30 Jan 2026 16:58:14 GMT</pubDate>
            <atom:updated>2026-01-30T16:58:14.834Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everybody, this is Rynvasis.<br>In this writeup, I will explain all the reverse engineering challenges I solved during UofTCTF 2026.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*eWtI2b0omu-RmU95YwFtAw.png" /></figure><h3>1) Baby (Obfuscated) Flag Checker</h3><blockquote><strong>Challenge Description</strong><br> All this obfuscation has left Han Shangyan seeing double. Even Grunt refuses to untangle this mess for him, so it’s up to you to do the real <em>grunt</em> work (hahaha get it???).</blockquote><p><strong>Summary<br></strong>We are given an obfuscated Python script (baby.py) that prompts for a flag and prints <strong>“You got the flag!”</strong> on success. Although the file is packed with noise (random names, pointless loops, and constants built through messy expressions), the <strong>real verification logic is simple</strong>:</p><ol><li>A <strong>length check</strong> on the input.</li><li>Several <strong>substring (slice) checks</strong> that compare parts of the input against hidden constant strings.</li></ol><p>Instead of statically reversing all obfuscation, we can use <strong>dynamic analysis</strong>: run the program and intercept execution at the verification lines to extract the real values at runtime.</p><p><strong>Running </strong><strong>baby.py and the flag prompt:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A3TjgkWd2TPZ5gMo0lkicw.png" /></figure><p><strong>What the program actually checks</strong></p><h4><strong>1. Length check</strong></h4><p>Somewhere in the script there is a line equivalent to:</p><pre>if len(g0go) == &lt;obfuscated_expression&gt;:<br>    ...<br>else:<br>    fail</pre><p>The right-hand side is not a literal number; it’s an expression produced by obfuscation. However, at runtime it evaluates to a concrete integer. We can capture it directly from the running frame.</p><p>From our run we extracted:</p><ul><li><strong>Required length = 74</strong></li></ul><h4><strong>2. Slice checks</strong></h4><p>After the length check, the program performs checks like:</p><pre>if g0G0SQuid(g0go[a:b], key) == g0G0SQuid(expected, key):<br>    ...<br>else:<br>    fail</pre><p>The important observation is that:</p><ul><li>The same function g0G0SQuid(…, key) is applied to both sides, using the same key.</li><li>g0G0SQuid behaves as a reversible (bijective) transformation (e.g., identity/reverse-like), so equality of outputs implies equality of inputs.</li></ul><p>So each check effectively reduces to:</p><blockquote><strong><em>g0go[a:b] == expected</em></strong></blockquote><p>Meaning: the program embeds the flag as multiple constant chunks, each required to appear at a specific range [a:b] in the input.</p><h4>Why dynamic tracing works (and avoids deobfuscation)</h4><p>Static reversing would require unraveling:</p><ul><li>how a and b are computed (often via obfuscated arithmetic),</li><li>how the expected string is constructed.</li></ul><p>Instead, we let Python execute the file and <strong>hook line execution</strong> using sys.settrace(). When the program reaches a verification line, we:</p><ul><li>read the line text using linecache,</li><li>extract expressions for a, b, and expected,</li><li>evaluate them <em>inside the program’s own runtime environment</em> via:</li></ul><pre>eval(expr, frame.f_globals, frame.f_locals)</pre><p>This returns the real values <strong>after</strong> all obfuscation has been computed.</p><h4><strong>Solution strategy (algorithm)</strong></h4><ol><li>Run the program once and stop when reaching the length check line to extract the required length n.</li><li>Create a placeholder candidate: candidate = [&quot;?&quot;] * n.</li><li>Run the program repeatedly:<br><strong>.</strong> Stop at the first failing slice check line.<br><strong>.</strong> Extract (a, b, expected).<br><strong>.</strong> Fill candidate[a:b] = expected.<br><strong>.</strong> Abort execution and repeat.</li><li>When no more fills occur, the candidate is the full flag.</li><li>Verify by executing baby.py normally with the recovered candidate.</li></ol><p><strong>Solver (dynamic tracing)</strong></p><pre>import builtins<br>import contextlib<br>import io<br>import linecache<br>import re<br>import runpy<br>import subprocess<br>import sys<br>from pathlib import Path<br><br>class StopNow(Exception):<br>    pass<br><br>def get_required_length(target_path: str) -&gt; int:<br>    &quot;&quot;&quot;<br>    Run the program once and stop at:<br>        if len(g0go) == &lt;expr&gt;:<br>    Evaluate &lt;expr&gt; inside the program frame to get the required length.<br>    &quot;&quot;&quot;<br>    target_path = str(Path(target_path).resolve())<br><br>    def fake_input(prompt=&quot;&quot;):<br>        return &quot;&quot;  # input does not matter; we stop at length check<br><br>    old_input = builtins.input<br>    builtins.input = fake_input<br>    need = None<br><br>    def tracer(frame, event, arg):<br>        nonlocal need<br>        if event != &quot;line&quot;:<br>            return tracer<br><br>        if not frame.f_code.co_filename.endswith(&quot;baby.py&quot;):<br>            return tracer<br><br>        line = linecache.getline(frame.f_code.co_filename, frame.f_lineno)<br>        if &quot;len(g0go)&quot; in line and &quot;==&quot; in line and line.lstrip().startswith(&quot;if &quot;):<br>            rhs = line.split(&quot;==&quot;, 1)[1].split(&quot;:&quot;, 1)[0].strip()<br>            need = int(eval(rhs, frame.f_globals, frame.f_locals))<br>            raise StopNow<br>        return tracer<br><br>    old_trace = sys.gettrace()<br>    sys.settrace(tracer)<br><br>    buf = io.StringIO()<br>    try:<br>        with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf):<br>            runpy.run_path(target_path, run_name=&quot;__main__&quot;)<br>    except (StopNow, SystemExit):<br>        pass<br>    finally:<br>        sys.settrace(old_trace)<br>        builtins.input = old_input<br><br>    if need is None:<br>        raise RuntimeError(&quot;Couldn&#39;t find length check!&quot;)<br>    return need<br><br><br>def run_until_next_fill(target_path: str, candidate: list[str]):<br>    &quot;&quot;&quot;<br>    Run with input=&#39;&#39;.join(candidate).<br>    Stop at the first failing check like:<br>        if g0G0SQuid(g0go[a:b], key) == g0G0SQuid(expected, key):<br>    Extract (a, b, expected), fill candidate[a:b], then stop.<br>    &quot;&quot;&quot;<br>    target_path = str(Path(target_path).resolve())<br>    inp = &quot;&quot;.join(candidate)<br><br>    def fake_input(prompt=&quot;&quot;):<br>        return inp<br><br>    old_input = builtins.input<br>    builtins.input = fake_input<br>    fill = None<br><br>    def tracer(frame, event, arg):<br>        nonlocal fill<br>        if event != &quot;line&quot;:<br>            return tracer<br><br>        if not frame.f_code.co_filename.endswith(&quot;baby.py&quot;):<br>            return tracer<br><br>        line = linecache.getline(frame.f_code.co_filename, frame.f_lineno)<br><br>        if &quot;if g0G0SQuid(g0go[&quot; in line and &quot;==&quot; in line:<br>            # Extract slice g0go[a:b]<br>            m = re.search(r&quot;g0go\[(.*?)\]&quot;, line)<br>            if not m:<br>                return tracer<br>            sl = m.group(1)<br>            if &quot;:&quot; not in sl:<br>                return tracer<br><br>            a_expr, b_expr = sl.split(&quot;:&quot;, 1)<br>            a = int(eval(a_expr.strip(), frame.f_globals, frame.f_locals))<br>            b = int(eval(b_expr.strip(), frame.f_globals, frame.f_locals))<br><br>            # Extract RHS argument: g0G0SQuid(expected, ...)<br>            rhs = line.split(&quot;==&quot;, 1)[1]<br>            m2 = re.search(r&quot;g0G0SQuid\((.*?),&quot;, rhs)<br>            if not m2:<br>                return tracer<br><br>            expected_expr = m2.group(1).strip()<br>            expected = eval(expected_expr, frame.f_globals, frame.f_locals)<br>            if not isinstance(expected, str):<br>                return tracer<br><br>            # Already correct? keep running to find the next missing one<br>            if inp[a:b] == expected:<br>                return tracer<br><br>            # Fill and stop<br>            fill = (a, b, expected)<br>            for i, ch in enumerate(expected):<br>                candidate[a + i] = ch<br><br>            raise StopNow<br><br>        return tracer<br><br>    old_trace = sys.gettrace()<br>    sys.settrace(tracer)<br><br>    buf = io.StringIO()<br>    try:<br>        with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf):<br>            runpy.run_path(target_path, run_name=&quot;__main__&quot;)<br>    except (StopNow, SystemExit):<br>        pass<br>    finally:<br>        sys.settrace(old_trace)<br>        builtins.input = old_input<br><br>    return fill<br><br><br>def main():<br>    target = sys.argv[1] if len(sys.argv) &gt; 1 else &quot;baby.py&quot;<br><br>    n = get_required_length(target)<br>    print(f&quot;[+] Required length = {n}&quot;)<br><br>    candidate = [&quot;?&quot;] * n<br><br>    while True:<br>        f = run_until_next_fill(target, candidate)<br>        if not f:<br>            break<br>        a, b, s = f<br>        print(f&quot;[+] Filled g0go[{a}:{b}] = {s!r}&quot;)<br><br>    flag = &quot;&quot;.join(candidate)<br>    print(&quot;\n[+] Final candidate:&quot;)<br>    print(flag)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p><strong>Output and Verify</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LVvvNFMQhRxDjwRoSY1oQw.png" /></figure><h4><strong>Flag</strong></h4><blockquote><strong>uoftctf{d1d_y0u_m0nk3Y_p4TcH_d3BuG_r3v_0r_0n3_sh07_th15_w17h_4n_1LM_XD???}</strong></blockquote><h3>2) Symbol of Hope</h3><blockquote><strong>Challenge Description</strong><br>Like a beacon in the dark, Go Go Squid! stands as a symbol of hope to those who seek to be healed.</blockquote><p>We are given a binary named checker. The goal is to recover the correct input (flag) accepted by the checker.</p><p>Before starting the analysis, the provided binary was found to be <strong>packed with UPX </strong>when loaded file in<strong> Detect It Easy (DIE)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*3xhzUcdo_2PRYkgD_esWwA.png" /></figure><p>The binary was unpacked using:</p><pre>upx -d checker</pre><p><strong>Running </strong><strong>checker :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*SEXmeR6dFQEo_AU6fzw6uA.png" /></figure><h4><strong>1. Recon: what the binary does</strong></h4><p>Running the binary shows it asks for input and prints Yes/No.</p><p>Static reversing (Ghidra/IDA/decompiler) reveals a classic structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F6lpEzjwEusBhb75XMDQDQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*Iz9L_WJcDFE46_e5-U0Tpg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*9lpC9bksNZLTpimivN_fFQ.png" /></figure><ol><li>Read user input with fgets.</li><li>Require an exact length of <strong>42 bytes</strong> (0x2A).</li><li>Apply a large chain of tiny byte-wise operations (f_0, f_1, ..., f_4200) to the buffer.</li><li>Compare the final transformed buffer to a fixed <strong>expected 42-byte constant</strong> using memcmp.</li><li>Print Yes if equal, else No.</li></ol><p>Key observation: the checker never uses crypto libraries or complex control flow — just a massive pipeline of byte transforms then one memcmp.</p><h4><strong>2. Important observation: per-byte independence</strong></h4><p>A critical step was to test whether the transformation is independent per byte index.</p><p>A critical step was to test whether the transformation is independent per byte index.</p><ul><li>Run with input of 42 &#39;A&#39;s.</li><li>Change only one position (e.g., index 10 from &#39;A&#39; to &#39;B&#39;).</li><li>Observe the buffer that reaches memcmp.</li></ul><p>Result:</p><ul><li>Only the corresponding output byte changes.</li><li>Other positions stay unchanged.</li></ul><p>This means the transformation is <strong>position-wise</strong> and does not mix bytes across indices.</p><p>So for each index i:</p><pre>T_i(x) -&gt; y</pre><p>where x is the input byte at index i, y is the transformed byte at index i.</p><p>That makes inversion easy using an oracle: brute force each byte independently.</p><h4><strong>3. Extract the target: expected bytes</strong></h4><p>The final comparison is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*xjcfU4VoT-Bjr4Zbu3Ny_w.png" /></figure><p>The expected array is a constant in .rodata. Extracted as hex:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*pWklQyDYpGOpGa8CCwQ8wA.png" /></figure><pre>65b68960c23304fbcb37d1bc511c897bb26d34aeaeb48f231f330c5c12ab51516d08c9d06de2f0fc7240</pre><p>This is 42 bytes.</p><h4><strong>4. Oracle Approach with </strong><strong>LD_PRELOAD</strong></h4><p>Instead of symbolically inverting more than 4,000 tiny transformation functions — which is both tedious and fragile due to signed/unsigned edge cases — I treated the binary as a <strong>runtime oracle</strong>.</p><p>The checker ultimately validates the input by performing a single comparison:</p><pre>memcmp(transformed_input, expected_bytes, 42)</pre><p>If we can observe the contents of transformed_input at this point, the entire transformation pipeline becomes transparent.</p><h4><strong>4.1 Hooking </strong><strong>memcmp</strong></h4><p>To achieve this, I created a shared library (hook.so) and injected it using <strong>LD_PRELOAD</strong> to intercept calls to memcmp.</p><p>Inside the custom memcmp implementation:</p><ul><li>The real libc memcmp is resolved using:</li></ul><pre>dlsym(RTLD_NEXT, &quot;memcmp&quot;)</pre><ul><li>Only calls where n == 42 are intercepted, corresponding to the final validation check</li><li>For these calls, the first argument (s1), which contains the fully transformed input buffer, is printed to stderr as <strong>42 bytes of hexadecimal data</strong></li><li>The original memcmp is then called and its return value is forwarded unchanged to preserve normal program behavior</li></ul><p>This provides direct visibility into the transformed buffer for any chosen input, effectively turning the checker into a runtime oracle.</p><h4><strong>4.2 Hook Implementation</strong></h4><pre>#define _GNU_SOURCE<br>#include &lt;dlfcn.h&gt;<br>#include &lt;stdio.h&gt;<br>#include &lt;string.h&gt;<br>#include &lt;stdint.h&gt;<br><br>typedef int (*memcmp_t)(const void*, const void*, size_t);<br><br>int memcmp(const void* s1, const void* s2, size_t n) {<br>    static memcmp_t real_memcmp = NULL;<br>    if (!real_memcmp) real_memcmp = (memcmp_t)dlsym(RTLD_NEXT, &quot;memcmp&quot;);<br><br>    if (n == 42) {<br>        const unsigned char* a = (const unsigned char*)s1;<br>        fprintf(stderr, &quot;A=&quot;);<br>        for (size_t i = 0; i &lt; n; i++) fprintf(stderr, &quot;%02x&quot;, a[i]);<br>        fprintf(stderr, &quot;\n&quot;);<br>        fflush(stderr);<br>    }<br><br>    return real_memcmp(s1, s2, n);<br>}</pre><p><strong>Compilation</strong></p><pre>gcc -shared -fPIC -O2 -ldl -o hook.so hook.c</pre><h4><strong>5. Solve: brute-force each position independently</strong></h4><p>Because T_i is independent per position, we solve each byte like this:</p><p>For index i:</p><ul><li>Try every possible byte c (we skip 0x00, \n, \r due to fgets/string handling).</li><li>Run checker with LD_PRELOAD=hook.so.</li><li>Capture transformed output buffer A.</li><li>If A[i] == expected[i], then that c is the correct input byte at position i.</li></ul><p>Total complexity: about 42 * 254 ≈ 10k runs.</p><h4><strong>5.1 Solver (</strong><strong>solve_preload.py)</strong></h4><pre>import os, re, subprocess, sys<br><br>EXPECTED = bytes.fromhex(<br>    &quot;65b68960c23304fbcb37d1bc511c897bb26d34aeaeb48f231f330c5c12ab5151&quot;<br>    &quot;6d08c9d06de2f0fc7240&quot;<br>)<br>N = 42<br>HEX_LINE_RE = re.compile(r&quot;A=([0-9a-fA-F]{84})&quot;)<br><br>def get_transformed(binary: str, hook_so: str, inp42: bytes) -&gt; bytes:<br>    env = os.environ.copy()<br>    env[&quot;LD_PRELOAD&quot;] = os.path.abspath(hook_so)<br><br>    p = subprocess.run(<br>        [binary],<br>        input=inp42 + b&quot;\n&quot;,<br>        stdout=subprocess.DEVNULL,<br>        stderr=subprocess.PIPE,<br>        env=env,<br>        timeout=2<br>    )<br>    err = p.stderr.decode(errors=&quot;replace&quot;)<br>    m = HEX_LINE_RE.findall(err)<br>    if not m:<br>        raise RuntimeError(&quot;Didn&#39;t capture A=... from hook. stderr was:\n&quot; + err)<br>    return bytes.fromhex(m[-1])<br><br>def main():<br>    binary = sys.argv[1] if len(sys.argv) &gt; 1 else &quot;./checker&quot;<br>    hook_so = sys.argv[2] if len(sys.argv) &gt; 2 else &quot;./hook.so&quot;<br><br>    allowed = [i for i in range(1, 256) if i not in (0x0a, 0x0d)]<br>    base = bytearray(b&quot;A&quot; * N)<br>    sol  = bytearray(b&quot;?&quot; * N)<br><br>    for i in range(N):<br>        target = EXPECTED[i]<br>        for c in allowed:<br>            base[i] = c<br>            out = get_transformed(binary, hook_so, bytes(base))<br>            if out[i] == target:<br>                sol[i] = c<br>                break<br>        base[i] = sol[i]<br>        print(f&quot;[{i:02d}] {sol[i]:02x}  {sol.decode(&#39;ascii&#39;, errors=&#39;replace&#39;)}&quot;, flush=True)<br><br>    print(&quot;\nRESULT:&quot;, sol.decode(&quot;ascii&quot;, errors=&quot;replace&quot;))<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p><strong>Run</strong></p><pre>python solve_preload.py ./checker ./hook.so</pre><p><strong>Output and Verify</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fjNLKeIggZhzuRgTkKKXBw.png" /></figure><h4><strong>Flag</strong></h4><blockquote><strong>uoftctf{5ymb0l1c_3x3cu710n_15_v3ry_u53ful}</strong></blockquote><h3>3) Will u Accept Some Magic?</h3><blockquote><strong>Challenge Description</strong><br>How does Kotlin compile to wasm so well? Where did my heap go? Wrap the password in uoftctf{}</blockquote><h4><strong>Challenge Overview</strong></h4><p>The challenge consists of <strong>two files</strong>:</p><ul><li>runner.mjs — a Node.js script that loads and executes the WebAssembly module</li><li>program.wasm — the WebAssembly binary that implements the actual password verification logic</li></ul><p>The JavaScript file acts mainly as a wrapper: it reads user input, passes it into the WASM module, and prints the result.<br> The real validation logic is therefore hidden inside the WebAssembly binary.</p><p>To start the challenge, we simply run:</p><pre>node runner.mjs</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W5Dni3258LklGAcJafARgQ.png" /></figure><h4><strong>1. Recon</strong></h4><p>The challenge is executed using Node.js and It reads a password from <strong>stdin</strong> and prints messages such as:</p><ul><li>Enter password:</li><li>You typed: ...</li><li>Password: INCORRECT</li></ul><p>Key observation: the real verification logic runs inside <strong>WebAssembly</strong>, not JavaScript.<br> So classic tricks like strings, grep, or scanning JS source won’t directly reveal the secret.</p><h4><strong>2. Strategy: Trace WebAssembly at Runtime</strong></h4><p>Node offers a powerful runtime tracer:</p><pre>node --trace-wasm runner.mjs</pre><p>This prints a trace of WASM function calls and their return values.<br> If the expected password is built or referenced as <strong>ASCII codes</strong>, then characters may appear as return values in the trace.</p><p>To make the trace deterministic and avoid guesswork, we feed a controlled input:</p><pre>python3 -c &quot;print(&#39;A&#39;*30)&quot; | node --trace-wasm runner.mjs &gt; traceA.txt 2&gt;&amp;1</pre><p>Using a fixed-length input helps reduce noise and makes repeated comparisons easier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5DX-pG3v5kQ-huyTKfTiXg.png" /></figure><h4>3. Extracting Printable ASCII from the Trace</h4><p>We post-process the trace and keep only returns that look like printable ASCII:</p><ul><li>ASCII range: 32..126</li><li>Track which ~wasm-function[...] was active per trace “block”</li><li>When a line returns } -&gt; N, interpret N as a potential character</li></ul><p>AWK script:</p><pre>awk &#39;<br>/^[[:space:]]*[0-9]+:[[:space:]]+~wasm-function\[/ {<br>    match($0, /^[[:space:]]*[0-9]+:/, blk)<br>    match($0, /~wasm-function\[[0-9]+\]/, fn)<br>    last_fn[blk[0]] = fn[0]<br>}<br><br>/} -&gt; [0-9]+$/ {<br>    match($0, /^[[:space:]]*[0-9]+:/, blk)<br>    match($0, /-&gt; ([0-9]+)$/, v)<br><br>    if (last_fn[blk[0]] != &quot;&quot; &amp;&amp; v[1] &gt;= 32 &amp;&amp; v[1] &lt;= 126) {<br>        printf &quot;%-4s  %s -&gt; %3d -&gt; %c\n&quot;,<br>               blk[0], last_fn[blk[0]], v[1], v[1]<br>    }<br>}<br>&#39; traceA.txt</pre><p>Output:</p><pre>   3:  ~wasm-function[80] -&gt;  69 -&gt; E<br>   3:  ~wasm-function[80] -&gt; 110 -&gt; n<br>   3:  ~wasm-function[80] -&gt; 116 -&gt; t<br>   3:  ~wasm-function[80] -&gt; 101 -&gt; e<br>   3:  ~wasm-function[80] -&gt; 114 -&gt; r<br>   3:  ~wasm-function[80] -&gt;  32 -&gt;  <br>   3:  ~wasm-function[80] -&gt; 112 -&gt; p<br>   3:  ~wasm-function[80] -&gt;  97 -&gt; a<br>   3:  ~wasm-function[80] -&gt; 115 -&gt; s<br>   3:  ~wasm-function[80] -&gt; 115 -&gt; s<br>   3:  ~wasm-function[80] -&gt; 119 -&gt; w<br>   3:  ~wasm-function[80] -&gt; 111 -&gt; o<br>   3:  ~wasm-function[80] -&gt; 114 -&gt; r<br>   3:  ~wasm-function[80] -&gt; 100 -&gt; d<br>   3:  ~wasm-function[80] -&gt;  58 -&gt; :<br>   4:  ~wasm-function[43] -&gt;  33 -&gt; !<br>   5:  ~wasm-function[43] -&gt;  33 -&gt; !<br>   2:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   2:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  89 -&gt; Y<br>   3:  ~wasm-function[80] -&gt; 111 -&gt; o<br>   3:  ~wasm-function[80] -&gt; 117 -&gt; u<br>   3:  ~wasm-function[80] -&gt;  32 -&gt;  <br>   3:  ~wasm-function[80] -&gt; 116 -&gt; t<br>   3:  ~wasm-function[80] -&gt; 121 -&gt; y<br>   3:  ~wasm-function[80] -&gt; 112 -&gt; p<br>   3:  ~wasm-function[80] -&gt; 101 -&gt; e<br>   3:  ~wasm-function[80] -&gt; 100 -&gt; d<br>   3:  ~wasm-function[80] -&gt;  58 -&gt; :<br>   3:  ~wasm-function[80] -&gt;  32 -&gt;  <br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[117] -&gt;  48 -&gt; 0<br>   3:  ~wasm-function[117] -&gt;  56 -&gt; 8<br>   2:  ~wasm-function[139] -&gt;  48 -&gt; 0<br>   2:  ~wasm-function[143] -&gt;  81 -&gt; Q<br>   2:  ~wasm-function[147] -&gt;  71 -&gt; G<br>   2:  ~wasm-function[151] -&gt;  70 -&gt; F<br>   2:  ~wasm-function[155] -&gt;  67 -&gt; C<br>   2:  ~wasm-function[159] -&gt;  66 -&gt; B<br>   2:  ~wasm-function[163] -&gt;  82 -&gt; R<br>   2:  ~wasm-function[167] -&gt;  69 -&gt; E<br>   2:  ~wasm-function[167] -&gt;  69 -&gt; E<br>   2:  ~wasm-function[174] -&gt;  78 -&gt; N<br>   2:  ~wasm-function[178] -&gt;  68 -&gt; D<br>   2:  ~wasm-function[151] -&gt;  70 -&gt; F<br>   2:  ~wasm-function[178] -&gt;  68 -&gt; D<br>   2:  ~wasm-function[188] -&gt;  79 -&gt; O<br>   2:  ~wasm-function[174] -&gt;  78 -&gt; N<br>   2:  ~wasm-function[195] -&gt;  90 -&gt; Z<br>   2:  ~wasm-function[163] -&gt;  82 -&gt; R<br>   2:  ~wasm-function[155] -&gt;  67 -&gt; C<br>   2:  ~wasm-function[205] -&gt;  51 -&gt; 3<br>   2:  ~wasm-function[209] -&gt;  57 -&gt; 9<br>   2:  ~wasm-function[159] -&gt;  66 -&gt; B<br>   2:  ~wasm-function[178] -&gt;  68 -&gt; D<br>   2:  ~wasm-function[219] -&gt;  83 -&gt; S<br>   2:  ~wasm-function[205] -&gt;  51 -&gt; 3<br>   2:  ~wasm-function[178] -&gt;  68 -&gt; D<br>   2:  ~wasm-function[229] -&gt;  77 -&gt; M<br>   2:  ~wasm-function[167] -&gt;  69 -&gt; E<br>   2:  ~wasm-function[236] -&gt;  72 -&gt; H<br>   2:  ~wasm-function[205] -&gt;  51 -&gt; 3<br>   2:  ~wasm-function[167] -&gt;  69 -&gt; E<br>   2:  ~wasm-function[80] -&gt;  65 -&gt; A<br>   3:  ~wasm-function[80] -&gt;  80 -&gt; P<br>   3:  ~wasm-function[80] -&gt;  97 -&gt; a<br>   3:  ~wasm-function[80] -&gt; 115 -&gt; s<br>   3:  ~wasm-function[80] -&gt; 115 -&gt; s<br>   3:  ~wasm-function[80] -&gt; 119 -&gt; w<br>   3:  ~wasm-function[80] -&gt; 111 -&gt; o<br>   3:  ~wasm-function[80] -&gt; 114 -&gt; r<br>   3:  ~wasm-function[80] -&gt; 100 -&gt; d<br>   3:  ~wasm-function[80] -&gt;  58 -&gt; :<br>   3:  ~wasm-function[80] -&gt;  32 -&gt;  <br>   3:  ~wasm-function[80] -&gt;  73 -&gt; I<br>   3:  ~wasm-function[80] -&gt;  78 -&gt; N<br>   3:  ~wasm-function[80] -&gt;  67 -&gt; C<br>   3:  ~wasm-function[80] -&gt;  79 -&gt; O<br>   3:  ~wasm-function[80] -&gt;  82 -&gt; R<br>   3:  ~wasm-function[80] -&gt;  82 -&gt; R<br>   3:  ~wasm-function[80] -&gt;  69 -&gt; E<br>   3:  ~wasm-function[80] -&gt;  67 -&gt; C<br>   3:  ~wasm-function[80] -&gt;  84 -&gt; T<br>   3:  ~wasm-function[117] -&gt;  32 -&gt;  </pre><h4>4. Interpreting the Output: Noise vs Signal</h4><p>After filtering, printable characters fall into predictable groups.</p><h4><strong>A) UI / Prompt Strings (Not the Password)</strong></h4><p>Examples seen in the trace:</p><ul><li>Enter password:</li><li>You typed:</li><li>Password: INCORRECT</li></ul><p>These are clearly user-facing messages. In the trace, most of these characters appear via ~wasm-function[80].</p><p>This strongly suggests <strong>func[80] behaves like a print/putchar routine</strong>: it outputs what the program wants to display.</p><p>So these strings are not secret; they are UI.</p><h4><strong>B) Echo of the User Input (Not the Password)</strong></h4><p>Since the program prints:</p><p>You typed: &lt;input&gt;</p><p>the input (AAAA...) appears in the trace too.<br>This is expected and should not be confused with the secret.</p><h4><strong>C) A Stable Internal Sequence (This Is the Password)</strong></h4><p>Most importantly, the trace reveals a long structured sequence that <strong>does not match the input</strong> and still appears even when the input is all As:</p><pre>0QGFCBREENDFDONZRC39BDS3DMEH3E</pre><p>Why this looks like the password:</p><ul><li>It appears even when the input is junk (e.g., AAAA...)</li><li>It is a long ordered sequence (not random punctuation)</li><li>It is deterministic (repeats across runs)</li><li>It is distinct from prompt text and echo output</li></ul><p>This strongly indicates the WASM module is internally producing or referencing the <strong>expected password</strong> used in the comparison.</p><h4><strong>5. Why We Did Not “Count” func[80], func[43], func[117]</strong></h4><p>Important clarification: <strong>we do not exclude a function by its number</strong>.<br> We exclude <strong>characters that do not belong to the stable contiguous password stream</strong>.</p><p><strong>wasm-function[80] — Output Plumbing (Not a Secret Source)</strong></p><p>func[80] is responsible for printing:</p><ul><li>the prompt</li><li>“You typed:”</li><li>the echoed input</li><li>status messages (“INCORRECT”, etc.)</li></ul><p>So func[80] is useful because it shows what gets printed, but it does not <em>generate</em> the secret. It’s output plumbing.</p><p><strong>Conclusion:</strong> func[80] characters are UI/echo, not password material.</p><p><strong>wasm-function[43] — UI Punctuation / Formatting</strong></p><p>In the trace, func[43] returns things like:</p><ul><li>33 -&gt; &#39;!&#39;</li></ul><p>This appears around UI output and does not form part of the long deterministic secret sequence.</p><p><strong>Conclusion:</strong> it is formatting/punctuation noise.</p><p><strong>wasm-function[117] — Helper Returns (Only Included If In-Stream)</strong></p><p>func[117] sometimes returns printable characters (e.g., &#39;0&#39;, &#39;8&#39;, space).<br> But the key point is:</p><ul><li>Some of these returns appear <strong>isolated</strong></li><li>They do not necessarily appear <strong>in-order</strong> as part of the password stream</li><li>They may be counters, formatting helpers, or control logic</li></ul><p><strong>We did not exclude func[117] categorically.</strong><br> If a character from func[117] appears <strong>in the correct order inside the stable password sequence</strong>, we include it.</p><p>In our run, the final password is determined by the <strong>contiguous, input-independent stream</strong>, not by isolated one-off characters.</p><p><strong>Conclusion:</strong> func[117] is “context-based”: include only if it participates in the stable password stream.</p><h4>6. Final Password and Verify</h4><pre>0QGFCBREENDFDONZRC39BDS3DMEH3E</pre><pre>printf &quot;0QGFCBREENDFDONZRC39BDS3DMEH3E\n&quot; | node runner.mjs</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lFAfTdT1KqzQkuWxX73r9g.png" /></figure><h4>Flag</h4><blockquote><strong>uoftctf{0QGFCBREENDFDONZRC39BDS3DMEH3E}</strong></blockquote><h3>4) Bring Your Own Program</h3><blockquote><strong>Challenge Description</strong><br>Team K&amp;K discovered a mysterious emulator for an unknown architecture. I wonder what kind of programs it can run… nc 35.245.96.82 5000</blockquote><h4>1. Challenge Overview</h4><p>We are given an interactive service:</p><pre>nc 35.245.96.82 5000</pre><p>The service expects a <strong>single line of hex</strong> input. This input is:</p><ol><li>Decoded into raw bytes (Uint8Array)</li><li>Parsed as a small VM program (register count, constants, bytecode)</li><li>Checked by a verifier (“safety” checker)</li><li>Executed inside a custom JavaScript virtual machine</li></ol><p>The entire challenge logic is implemented in a single JavaScript file (chal.js),which contains the hex decoder, program parser, verifier, and VM interpreter.</p><p>Although the sandbox is designed to prevent arbitrary file access, a mismatch between verification and execution allows reading the real flag from /flag.txt.</p><h4>2. Quick Map (Limits, Allowed Globals, Whitelist, Opcodes)</h4><p><strong>Limits / Constraints</strong></p><p>The VM enforces strict bounds:</p><ul><li>a.r = 0x40 → max registers</li><li>a.c = 0x80 → max constants</li><li>a.b = 0x4000 → max bytecode length</li><li>a.a = 0x8 → max arguments per call</li><li>a.ic = 0x4 → max inline-cache entries per instruction site</li></ul><p><strong>Allowed Globals</strong></p><p>Only one global is allowed:</p><pre>const e = new Set([&#39;caps&#39;])</pre><p>So the bytecode can only load the global named &quot;caps&quot;.</p><p><strong>Allowed Keys (Whitelist)</strong></p><p>The verifier only permits these numeric keys:</p><pre>A = new Set([1,2,3,4,10,11])</pre><p>From chal.js</p><pre>const a = h,<br>    e = new Set([&#39;caps&#39;]),<br>    n = {};<br>n[&#39;a&#39;] = 0x1, n[&#39;b&#39;] = 0x2, n[&#39;c&#39;] = 0x3, n[&#39;d&#39;] = 0x4, n[&#39;e&#39;] = 0xa, n[&#39;f&#39;] = 0xb;<br>const y = n,<br>    A = new Set([y[&#39;a&#39;], y[&#39;b&#39;], y[&#39;c&#39;], y[&#39;d&#39;], y[&#39;e&#39;], y[&#39;f&#39;]]),</pre><p>So <strong>key </strong><strong>0 is forbidden</strong> in bytecode.</p><p><strong>Opcode Table (from </strong><strong>chal.js)</strong></p><pre>Name    Hex    Meaning<br>-----   ----   ---------------------------------------------------------------<br>u.a     0x01   LOAD_CONST      (constant → register)<br>u.b     0x02   LOAD_GLOBAL     (string constant name)<br>u.c     0x20   GET             from scope: v.g(key)<br>u.d     0x21   LOOKUP_IC       cached lookup → returns (fn, this)<br>u.e     0x30   CALL            function call<br>u.f     0x31   RET             return register<br>u.g     0x32   RETURN_UNDEF    return undefined<br>u.h     0x60   JMP             relative jump<br>u.i     0x61   JMP_IF          jump if register is truthy<br>u.j     0x40   ADD             numeric addition<br>u.k     0x70   DEMAT           dematerialization trigger (core bug path)</pre><h4>3. VM Program Format (What We Need to Send)</h4><p>The service expects <strong>one line of hex</strong>. Internally it:</p><ol><li>converts hex → bytes (Uint8Array)</li><li>parses bytes into a VM “program” consisting of:</li></ol><ul><li>a <strong>header</strong> (nr, cs_len)</li><li>a <strong>constant pool</strong></li><li>the <strong>bytecode</strong> (remaining bytes)</li></ul><ol><li>runs a <strong>verifier</strong> on the bytecode before execution</li></ol><h4><strong>3.1 Hex → bytes (</strong><strong>Uint8Array)</strong></h4><p>The function Y() takes the input line, validates it is hex, and builds a Uint8Array by decoding two hex chars at a time:</p><pre>function Y(b) {<br>    const N = b[&#39;trim&#39;]();<br>    ...<br>    const FN = new Uint8Array(N[&#39;length&#39;] &gt;&gt; 1);<br>    for (let Fi = 0; Fi &lt; FN[&#39;length&#39;]; Fi++)<br>        FN[Fi] = parseInt(N[&#39;slice&#39;](Fi*2, Fi*2 + 2), 16);<br>    return FN;<br>}</pre><p>So the user input is truly treated as raw bytes.</p><h4><strong>3.2 Parsing the program: header + constants + code</strong></h4><p>The function z(N) parses the byte array into a program object.</p><h4><strong>(A) Header: </strong><strong>nr and </strong><strong>cs_len</strong></h4><p>The first two bytes are read as:</p><pre>const Fq = N[FN++],   // nr (register count)<br>      Ft = N[FN++];   // cs_len (number of constants)</pre><p>So:</p><ul><li><strong>byte 0</strong> = nr (1 byte)</li><li><strong>byte 1</strong> = cs_len (1 byte)</li></ul><h4><strong>(B) Constant encoding: </strong><strong>0x01 float64, </strong><strong>0x02 string</strong></h4><p>For each constant, z() reads a <strong>type byte</strong> and decodes accordingly:</p><pre>const FZ = N[FN++];<br><br>if (FZ === 0x01) {           // float64<br>    const Fh = m(N, FN);<br>    FN += 8;<br>    FH.push(Fh);<br><br>} else if (FZ === 0x02) {    // string<br>    const Fa = k(N, FN);     // uint16 length<br>    FN += 2;<br>    const Fe = Buffer.from(N.slice(FN, FN + Fa)).toString(&#39;utf8&#39;);<br>    FN += Fa;<br>    FH.push(Fe);<br>}</pre><p>And m() confirms float decoding is little-endian:</p><pre>function m(N, FN) {<br>    const Fi = new DataView(N[&#39;buffer&#39;], N[&#39;byteOffset&#39;], N[&#39;byteLength&#39;]);<br>    return Fi.getFloat64(FN, true);<br>}</pre><p>So the constant formats are exactly:</p><ul><li>0x01 → <strong>float64</strong> (8 bytes LE)</li><li>0x02 → <strong>string</strong> (uint16_le length + bytes)</li></ul><h4><strong>(c) Code section: “remaining bytes” are bytecode</strong></h4><p>After constants are parsed, the rest of the input is stored as the bytecode:</p><pre>const Fj = N.slice(FN);<br>FG[&#39;code&#39;] = Fj;</pre><p>And it enforces a maximum bytecode length:</p><pre>if (Fj[&#39;length&#39;] &gt; a[&#39;b&#39;]) throw ...</pre><h4>3.3 Verifier: what is enforced before execution</h4><p>The verifier is U(program). It enforces:</p><h4><strong>(A) register / constant bounds</strong></h4><pre>if (b[&#39;nr&#39;] &gt; a[&#39;r&#39;]) throw ...<br>if (b[&#39;cs&#39;][&#39;length&#39;] &gt; a[&#39;c&#39;]) throw ...</pre><h4><strong>(B) allowed globals / allowed numeric keys / valid opcode structure</strong></h4><p>It scans bytecode opcodes and checks operands. For example:</p><ul><li>keys must satisfy A.has(key) in key-using opcodes</li><li>globals must satisfy e.has(name) in LOAD_GLOBAL</li></ul><p>You can see checks like:</p><pre>if (!A[&#39;has&#39;](FB)) throw ...<br>if (!e[&#39;has&#39;](Fs)) throw ...</pre><p>That is the source of “restrictions on allowed globals and allowed numeric keys”.</p><h4>4. The Sandbox: caps and the Scope System — with code evidence</h4><p>The VM’s sandbox is exposed through a single allowed global object: <strong>caps</strong>. Capabilities are stored in a custom “scope” structure (class v) that uses a <strong>shape+slots</strong> layout.</p><h4><strong>4.1 Scope layout (</strong><strong>class v)</strong></h4><p>The constructor shows the important fields:</p><pre>class v {<br>    constructor(b = null) {<br>        this[&#39;p&#39;] = b;                // parent scope pointer<br>        this[&#39;sh&#39;] = new o(new Map()); // shape map (key -&gt; slot index)<br>        this[&#39;sl&#39;] = [];              // slots array<br>        this[&#39;dm&#39;] = false;           // dematerialized flag<br>        this[&#39;d&#39;] = null;             // Map used after demat<br>        this[&#39;z&#39;] = false;            // sealed flag<br>    }<br>    [&#39;x&#39;]() { this[&#39;z&#39;] = true; }     // seal<br>    [&#39;o&#39;](b, N) { ... }               // set<br>    [&#39;g&#39;](b) { ... }                  // get<br>}</pre><p>So:</p><ul><li>sh.m (inside the o wrapper) maps <strong>key → slotIndex</strong></li><li>sl stores the actual values in an array (slots)</li><li>p chains scopes (parents)</li><li>z indicates the scope is sealed</li><li>dm indicates dematerialized mode</li></ul><p>This is what the writeup means by “shape + slots”.</p><h4><strong>4.2 File reading primitives (safe vs dangerous)</strong></h4><p>Two distinct readers exist:</p><p><strong>F0: absolute-path reader (dangerous)</strong></p><pre>function F0(b) {<br>    const N = String(b);<br>    if (!t.isAbsolute(N)) return &#39;&#39;;<br>    return c(N);<br>}</pre><p><strong>F1: restricted reader inside </strong><strong>/data/public (safe)</strong></p><pre>function F1(b) {<br>    const N = String(b);<br>    if (t.isAbsolute(N)) return &#39;&#39;;<br>    const FN = t.resolve(s, N);              // s = &#39;/data/public&#39;<br>    if (!FN.startsWith(s + t.sep)) return &#39;&#39;;<br>    return c(FN);<br>}</pre><p>So F1 prevents absolute paths and enforces a /data/public prefix, while F0 allows reading any absolute path.</p><h4><strong>4.3 IO scope mapping (key 10 vs key 0)</strong></h4><p>The IO scope is built like this:</p><pre>const F5 = new v(null);<br>F5.o(y[&#39;e&#39;], new g(F1));   // key 10 -&gt; safe reader<br>F5.o(F4,     new g(F0));   // key 0  -&gt; absolute reader<br>F5.x();                    // seal</pre><p>Since:</p><ul><li>y[&#39;e&#39;] = 0xa → <strong>10</strong></li><li>F4 evaluates to <strong>0</strong></li></ul><p>the IO scope contains:</p><pre><br>Key   Function   Meaning<br>---   --------   -----------------------------<br>10    F1         safe read_public()<br>0     F0         dangerous read_absolute()</pre><p>Therefore, <strong>if we can ever obtain the function stored under key </strong><strong>0</strong>, we can read &quot;/flag.txt&quot; directly.</p><h4>5. Vulnerability: Inline Cache vs Slot Reordering</h4><p>This VM has an optimization: an <strong>inline cache</strong> for a lookup opcode. The verifier checks <strong>keys</strong>, but the interpreter sometimes returns values using a cached <strong>slot index</strong> instead of re-checking the key mapping. A separate opcode (“dematerialization”) can <strong>rebuild the slot array in a new order</strong>, leaving the cache stale.</p><p>That mismatch is the bug.</p><h4>5.1 Inline Cache stores a slot index (si), not the key mapping</h4><p>Inside FT.run(), the interpreter creates an inline cache map:</p><pre>this[&#39;ic&#39;] = new Map();</pre><p>When a lookup happens (opcode u.d / 0x21), the runtime uses helper functions to cache and reuse lookups.</p><p><strong>Cache entry fields (what the VM remembers)</strong></p><p>When a cache miss occurs, the VM stores an entry with:</p><ul><li>rs: receiver shape id (scope.sh.id)</li><li>k: the numeric key</li><li>v: a version value x</li><li>d: how many parents to walk</li><li>si: the <strong>slot index</strong> to read on hits</li></ul><p>You can see these exact fields being created in the cache-population function (FZ):</p><pre>FA[&#39;rs&#39;] = Fe[&#39;sh&#39;][&#39;id&#39;], <br>FA[&#39;k&#39;]  = Fn, <br>FA[&#39;v&#39;]  = x, <br>FA[&#39;d&#39;]  = Fy[&#39;d&#39;], <br>FA[&#39;si&#39;] = Fy[&#39;si&#39;];</pre><p><strong>Cache-hit returns from </strong><strong>sl[si] directly</strong></p><p>On a cache hit, the VM does <strong>not</strong> re-run a proper “key → slot index” lookup.<br> Instead it walks up d parents, then returns:</p><pre>const FI = Fp[&#39;sl&#39;][FA[&#39;si&#39;]];<br>return Fu[&#39;fn&#39;] = FI, Fu[&#39;th&#39;] = Fe, Fu;</pre><p>This is the critical line: it returns the function by reading sl[si] directly.</p><p>So conceptually, the cache-hit path is:</p><blockquote><em>“Return </em><em>parent.sl[cached.si]”<br> (where </em><em>Fp is the parent scope reached after walking </em><em>d levels)</em></blockquote><p><strong>Cache is keyed by instruction site (program counter)</strong></p><p>Lookups are cached per-instruction position. In the main loop:</p><pre>const Fa = Fq;   // site = program counter before reading opcode<br>const Fe = FH(); // opcode<br>...<br>const Fc = Fs(Fa, FS, Fm); // try cache hit using site Fa</pre><p>So: <strong>same key, same scope, but different bytecode offset → different cache site → no hit</strong>.</p><h4>5.2 Dematerialization rebuilds slots by sorting keys (reorders sl)</h4><p>The dematerialization logic is inside the helper Fh() and is triggered by opcode u.k / 0x70 (your writeup calls it DEMAT).</p><p>When it runs on a scope, it:</p><ol><li>extracts entries into an array</li><li>sorts them by numeric key</li><li>rebuilds the sl array from the sorted list</li></ol><p>Direct evidence from the code:</p><pre>FB[&#39;sort&#39;]((Fu, FY) =&gt; Fu[0] - FY[0]),<br>Fy[&#39;sl&#39;] = FB[&#39;map&#39;](Fu =&gt; Fu[1]);</pre><p>This means the slot array sl becomes <strong>sorted by key</strong>, not by original insertion order.</p><p>That breaks the assumption “slot index for a given key is stable”.</p><h4><strong>5.3 The mismatch: how key 10 effectively becomes key 0</strong></h4><p><strong>IO scope insertion order (before demat)</strong></p><p>The IO scope is built like this:</p><pre>F5[&#39;o&#39;](y[&#39;e&#39;], new g(F1)); // key 10 -&gt; F1<br>F5[&#39;o&#39;](F4,     new g(F0)); // key 0  -&gt; F0</pre><p>So insertion order is:</p><ol><li>key 10 first</li><li>key 0 second</li></ol><p>Before dematerialization, slots match insertion order, so:</p><ul><li>sl[0] = F1 (key 10)</li><li>sl[1] = F0 (key 0)</li></ul><p><strong>First lookup caches </strong><strong>si=0 for key 10</strong></p><p>On the first run of the cached lookup opcode (0x21) with key 10:</p><ul><li>cache miss happens</li><li>the VM computes the slot index for key 10</li><li>it stores si = 0 in the inline cache entry (because key 10 was inserted first)</li></ul><p><strong>Dematerialization flips slot order by sorting keys</strong></p><p>After demat runs, keys are sorted: [0, 10].<br> So slots become:</p><ul><li>sl[0] = F0</li><li>sl[1] = F1</li></ul><p><strong>Second lookup hits cache and returns wrong slot</strong></p><p>Now, when we execute the <em>same lookup instruction site</em> again:</p><ul><li>cache hit happens</li><li>VM returns Fp[&#39;sl&#39;][FA[&#39;si&#39;]]</li><li>but FA[&#39;si&#39;] is still 0</li><li>and after the reorder, sl[0] is now <strong>F0</strong> (key 0 absolute reader)</li></ul><p>So a lookup that the verifier thinks is “key 10” ends up returning the forbidden function (key 0).</p><p><strong>In one sentence:</strong><br> The verifier validates the <em>key operand</em> (10), but the runtime returns by a cached <em>slot index</em> (0), and dematerialization changes what sl[0] means.</p><p>This verifier/runtime mismatch is easiest to understand visually:</p><pre>Before DEMAT:<br>slots = [ key=10 | key=0 ]<br>          ↑<br>       cached si=0<br><br>After DEMAT:<br>slots = [ key=0 | key=10 ]<br>          ↑<br>       cached si=0  --&gt; returns forbidden function</pre><h4>6. Exploit Strategy</h4><p>We need to force:</p><ol><li>A lookup for key 10 to run once (cache miss → cache stores si=0)</li><li>Trigger dematerialization (reorder slots [10,0] → [0,10])</li><li>Execute the <strong>same lookup instruction at the same site</strong> again (cache hit)</li><li>Call the returned function with &quot;/flag.txt&quot;</li><li>Return output</li></ol><p><strong>Why the “same site” matters</strong></p><p>The inline cache is stored <strong>per instruction address</strong> (program counter).<br> If the second lookup happens at a different bytecode offset, it becomes a cache miss and the exploit fails.<br> So the payload must jump back to the exact same LOOKUP_IC instruction.</p><h4>7. Payload Generator Script</h4><pre>import struct<br><br># Opcodes from chal.js<br>OP_LOAD_CONST  = 0x01<br>OP_LOAD_GLOBAL = 0x02<br>OP_GET         = 0x20<br>OP_LOOKUP_IC   = 0x21<br>OP_CALL        = 0x30<br>OP_RET         = 0x31<br>OP_JMP         = 0x60<br>OP_JMP_IF      = 0x61<br>OP_DEMAT       = 0x70<br><br>def enc_u16(x):  return struct.pack(&quot;&lt;H&quot;, x &amp; 0xFFFF)<br>def enc_i16(x):  return struct.pack(&quot;&lt;h&quot;, x)  # signed 16-bit<br>def enc_f64(x):  return struct.pack(&quot;&lt;d&quot;, float(x))<br><br>def c_string(s: str) -&gt; bytes:<br>    b = s.encode(&quot;utf-8&quot;)<br>    return bytes([0x02]) + enc_u16(len(b)) + b<br><br>def c_float(x: float) -&gt; bytes:<br>    return bytes([0x01]) + enc_f64(x)<br><br>def asm():<br>    consts = [<br>        c_string(&quot;caps&quot;),<br>        c_string(&quot;/flag.txt&quot;),<br>        c_float(1.0),<br>        c_float(0.0),<br>    ]<br><br>    code = bytearray()<br>    labels = {}<br><br>    def label(name): labels[name] = len(code)<br>    def emit(b: bytes): code.extend(b)<br><br>    emit(bytes([OP_LOAD_GLOBAL, 0, 0]))   # r0 = globals[&quot;caps&quot;]<br>    emit(bytes([OP_GET, 1, 0, 3]))        # r1 = caps.io<br>    emit(bytes([OP_LOAD_CONST, 4, 2]))    # r4 = 1.0<br><br>    label(&quot;lookup_site&quot;)<br>    emit(bytes([OP_LOOKUP_IC, 2, 3, 1, 10]))  # (r2,r3)=lookup(key=10)<br><br>    jmp_if_pos = len(code)<br>    emit(bytes([OP_JMP_IF, 4, 0, 0]))     # patch later<br><br>    emit(bytes([OP_LOAD_CONST, 5, 1]))    # r5=&quot;/flag.txt&quot;<br>    emit(bytes([OP_CALL, 6, 2, 3, 1, 5])) # r6 = r2.call(this=r3,[r5])<br>    emit(bytes([OP_RET, 6]))              # return r6<br><br>    label(&quot;demat&quot;)<br>    emit(bytes([OP_DEMAT, 1, 10]))        # reorder slots<br>    emit(bytes([OP_LOAD_CONST, 4, 3]))    # r4=0.0<br><br>    jmp_pos = len(code)<br>    emit(bytes([OP_JMP, 0, 0]))           # patch later<br><br>    # patch JMP_IF to demat<br>    after_jmp_if = jmp_if_pos + 4<br>    off_to_demat = labels[&quot;demat&quot;] - after_jmp_if<br>    code[jmp_if_pos+2:jmp_if_pos+4] = enc_i16(off_to_demat)<br><br>    # patch JMP back to lookup_site<br>    after_jmp = jmp_pos + 3<br>    off_back = labels[&quot;lookup_site&quot;] - after_jmp<br>    code[jmp_pos+1:jmp_pos+3] = enc_i16(off_back)<br><br>    program = bytearray([7, len(consts)]) # nr=7, cs_len=4<br>    for c in consts:<br>        program.extend(c)<br>    program.extend(code)<br>    return bytes(program)<br><br>def main():<br>    print(asm().hex())<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p><strong>Output</strong></p><pre>0704020400636170730209002f666c61672e74787401000000000000f03f01000000000000000002000020010003010402210203010a61040b00010501300602030105310670010a01040360e3ff</pre><p><strong>Constant Pool (cs)</strong></p><pre>Index   Type    Value<br>-----   ------  ----------<br>0       string  &quot;caps&quot;<br>1       string  &quot;/flag.txt&quot;<br>2       float   1.0<br>3       float   0.0</pre><p><strong>Disassembly Table (Bytecode / Code Section)</strong></p><p><strong>Legend</strong></p><ul><li><strong>CodeOff</strong>: offset inside the code section</li><li><strong>AbsOff</strong>: absolute offset inside the full program (from the first byte of the payload)</li><li><strong>Bytes</strong>: raw bytes for the instruction</li></ul><pre><br>CodeOff  AbsOff  Bytes              Opcode        Operands                       Comment<br>------   ------  -----------------  ------------  -----------------------------  ----------------------------------------------<br>0x00     0x27    02 00 00            LOAD_GLOBAL   r0, const=0                    r0 = global[&quot;caps&quot;]<br>0x03     0x2A    20 01 00 03         GET           r1, r0, key=3                  r1 = r0.g(3) → (this is caps.io)<br>0x07     0x2E    01 04 02            LOAD_CONST    r4, const=2                    r4 = 1.0 (truthy)<br><br>0x0A     0x31    21 02 03 01 0A      LOOKUP_IC     r2, r3, r1, key=10              (r2,r3) = lookup_ic(r1, key=10) (cache site)<br>0x0F     0x36    61 04 0B 00         JMP_IF        r4, off=+11                    if r4 truthy → jump to 0x1E (skip call on 1st pass)<br><br>0x13     0x3A    01 05 01            LOAD_CONST    r5, const=1                    r5 = &quot;/flag.txt&quot;<br>0x16     0x3D    30 06 02 03 01 05   CALL          r6, r2, r3, argc=1, [r5]        r6 = call r2(this=r3, args=[r5])<br>0x1C     0x43    31 06               RET           r6                             return r6 (prints file content)<br><br>0x1E     0x45    70 01 0A            DEMAT         r1, key=10                     demat(r1, key=10) → rebuild slots &amp; reorder<br>0x21     0x48    01 04 03            LOAD_CONST    r4, const=3                    r4 = 0.0 (falsey)<br>0x24     0x4B    60 E3 FF            JMP           off=-29                        jump back to 0x0A (same LOOKUP_IC site)</pre><p>Run:</p><pre>nc 35.245.96.82 5000<br># paste hex and press Enter</pre><h4>Flag</h4><blockquote><strong>uoftctf{c4ch3_m3_1n11n3_h0w_80u7_d4h??}</strong></blockquote><h3>5) ML Connoisseur</h3><blockquote><strong>Challenge Description</strong><br>Tong Nian is a talented machine learning student. She claims to have built a classifier, but never revealed what it is supposed to recognize. The model behaves oddly, and its purpose is unclear. Can you figure out what it’s really classifying?</blockquote><h4>Goal (what the challenge wants)</h4><p>You’re given an obfuscated PyTorch model + weights and a runner script (chal.py).<br> When you run:</p><pre>python chal.py &lt;image.png&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b1DNpKvS8_o3I1w9UABE0w.png" /></figure><p>it prints either:</p><ul><li>a digit 0..9 (normal behavior), or</li><li><strong>a special success message</strong> (<strong>win condition</strong>), meaning you found the “secret” input.</li></ul><p><strong>Important:</strong> there is <strong>no server</strong> in this challenge. It’s fully local: chal.py reads a local image path and loads weights.pt from disk (no networking imports or socket usage). Proof: it reads sys.argv and checks file existence via Path(...).exists()</p><h4>1. Understanding the Obfuscation in chal.py</h4><p>The file chal.py is intentionally obfuscated to prevent simple string searching (e.g., grep &quot;weights.pt&quot; or grep &quot;you got it&quot;). Instead of writing important strings directly, the script stores them as integer arrays and reconstructs them at runtime.</p><h4>1.1 The XOR String Decoder: __s</h4><p>At the very top of chal.py, there is a helper function that decodes hidden strings:</p><pre>def __s(a, k=42):<br>    return bytes([x ^ k for x in a]).decode(&#39;utf-8&#39;)</pre><h4>What it does</h4><ul><li>a is a list of integers (bytes), such as [83, 69, 95, ...]</li><li>each element is XOR’ed with 42</li><li>the resulting bytes are decoded into a normal UTF-8 string</li></ul><p>So if the file contains something like:</p><pre>__s([83,69,95,10,77,69,94,10,67,94,11])</pre><p>it will reconstruct the real runtime string (in this case, it becomes &quot;you got it!&quot;).</p><p>This means strings never appear in plaintext inside the script, so searching the file for them will not work.</p><h4>1.2 Dynamic Imports via Obfuscated Helpers (__gi and __bi)</h4><p>Instead of writing normal imports like:</p><pre>import importlib<br>import builtins</pre><p>the challenge hides imports behind helper functions and obfuscated names.</p><p>At the top of the file, chal.py defines two wrappers:</p><ul><li>__gi(...) is used for importing modules dynamically</li><li>__bi(...) is used for accessing Python builtins dynamically (like print)</li></ul><p>These wrappers appear in the import/utility section of chal.py. Proof:</p><h4>Why this matters</h4><p>This technique makes it harder to understand the script quickly because:</p><ol><li>you cannot see clean import statements</li><li>even function names like print, load, no_grad, item, etc. are hidden and reconstructed using __s([...])</li></ol><p>For example, later in the file, instead of calling print(&quot;...&quot;), the script effectively does:</p><pre>__bi(__s([...]))(__s([...]))</pre><p>Where:</p><ul><li>__s([...]) decodes to &quot;print&quot;</li><li>the second __s([...]) decodes to the text to print</li></ul><p>This is exactly how the success message is printed in the win branch.</p><h4>1.3 Why this obfuscation is used</h4><p>The obfuscation is not meant to be cryptographically secure — it is simply meant to:</p><ul><li>break string-based analysis (grep/search)</li><li>hide key filenames like weights.pt</li><li>hide important text like &quot;you got it!&quot;</li><li>make the control flow harder to read at a glance</li></ul><p>However, once you identify __s() as XOR(42), the rest of the script becomes readable, because every hidden keyword is just:</p><pre>real_string = __s([ ... ])</pre><h4>2. What Input Does the Program Expect?</h4><p>chal.py is meant to be executed from the command line and expects <strong>exactly one user argument</strong>: a path to an image file.</p><h4>2.1 Command-line argument check (exact evidence)</h4><p>In the main function, chal.py checks the length of sys.argv and exits if it is not exactly 2 (script name + one argument). This is the exact obfuscated code:</p><pre>if len(getattr(sys, __s([75, 88, 77, 92]))) != 2:<br>    __bi(__s([90, 88, 67, 68, 94]))(__s([26]))<br>    return</pre><p>Because __s([...]) is XOR-decoding strings (key 42), __s([75, 88, 77, 92]) decodes to &quot;argv&quot;, meaning this line is effectively checking len(sys.argv).</p><p><strong>Clean equivalent:</strong></p><pre>if len(sys.argv) != 2:<br>    print(&quot;usage / error&quot;)<br>    return</pre><h4>2.2 The argument is a local filesystem path</h4><p>After passing the argument count check, the script constructs a Path object from sys.argv[1]:</p><pre>vc91053b95402ebe9 = Path(getattr(sys, __s([75, 88, 77, 92]))[1])</pre><p>Then it verifies that the file exists using Path.exists():</p><pre>if not getattr(vc91053b95402ebe9, __s([79, 82, 67, 89, 94, 89]))():<br>    __bi(__s([90, 88, 67, 68, 94]))(__s([26]))<br>    return</pre><p>Here, __s([79, 82, 67, 89, 94, 89]) decodes to &quot;exists&quot;, so this is literally calling path.exists().</p><p><strong>Clean equivalent:</strong></p><pre>path = Path(sys.argv[1])<br>if not path.exists():<br>    print(&quot;file not found / error&quot;)<br>    return</pre><h4>2.3 Why this proves the challenge is fully local</h4><p>This input handling proves the challenge is <strong>100% local</strong>:</p><ul><li>It reads the filename from sys.argv[1]</li><li>It treats it as a Path and checks exists() on your machine</li></ul><p>Additionally, the script imports only local/inference-related modules (Torch, PIL, numpy, pathlib, etc.) and does not use any networking libraries like socket or requests.</p><p>So the workflow is:</p><p><strong>Local PNG path → load image from disk → run inference → print output</strong></p><h4>3) Image Preprocessing (How the PNG Becomes a Torch Tensor)</h4><p>Before inference, chal.py converts the input PNG into the exact tensor format the model expects. This preprocessing happens inside the obfuscated function v39194d9e8c3d1b19(...).</p><h4>3.1 Open image, convert to RGB, resize to 256×256</h4><p>Inside v39194d9e8c3d1b19, the script opens the file using PIL, converts to RGB, and resizes to (256, 256). The following lines show this sequence:</p><pre>v6ed6203f66ce0fcc = getattr(Image, __s([69, 90, 79, 68]))(v7b312d3792e942a1)<br>v6ed6203f66ce0fcc = getattr(v6ed6203f66ce0fcc, __s([73, 69, 68, 92, 79, 88, 94]))(__s([120, 104, 105]))<br>v6ed6203f66ce0fcc = getattr(v6ed6203f66ce0fcc, __s([88, 79, 89, 67, 84, 79]))((256, 256))</pre><p>Explanation of decoded method names:</p><ul><li>Image.__s([...]) decodes to &quot;open&quot;</li><li>.convert(&quot;RGB&quot;)</li><li>.resize((256,256))</li></ul><h4>3.2 Convert to float array and normalize by 255.0</h4><p>Right after resizing, the image is converted into a NumPy array and normalized:</p><pre>v6ed6203f66ce0fcc = getattr(np, __s([75, 88, 88, 75, 83]))(v6ed6203f66ce0fcc, dtype=np.float32) / 255.0</pre><p>This is equivalent to:</p><pre>arr = np.array(img, dtype=np.float32) / 255.0</pre><p>So pixel values become floats in the range <strong>[0, 1]</strong>.</p><h4>3.3 Convert to torch tensor, permute to CHW, make contiguous, add batch dimension (exact evidence)</h4><p>Finally, the NumPy array is converted to a Torch tensor and reshaped into the model input format:</p><pre>v6ed6203f66ce0fcc = getattr(torch, __s([94, 79, 68, 89, 69, 88]))(v6ed6203f66ce0fcc)<br>v6ed6203f66ce0fcc = getattr(getattr(v6ed6203f66ce0fcc, __s([90, 79, 88, 71, 95, 94, 79]))(2, 0, 1), __s([73, 69, 68, 94, 67, 77, 95, 69, 95, 89]))()<br>v6ed6203f66ce0fcc = getattr(v6ed6203f66ce0fcc, __s([95, 68, 89, 83, 95, 79, 79, 94]))(0)</pre><p>This corresponds to the standard PyTorch pipeline:</p><pre>x = torch.tensor(arr)          # HWC<br>x = x.permute(2, 0, 1)         # CHW<br>x = x.contiguous()<br>x = x.unsqueeze(0)             # add batch dimension</pre><h3>3.4 Final input format (what the model receives)</h3><p>From the code above, we can conclude the model input is:</p><ul><li><strong>dtype:</strong> float32</li><li><strong>range:</strong> [0, 1]</li><li><strong>shape:</strong> (1, 3, 256, 256)</li><li>batch = 1</li><li>channels = 3 (RGB)</li><li>height = 256</li><li>width = 256</li></ul><p>So your PNG is always transformed into a normalized RGB tensor of fixed size before inference.</p><h4>4. How the Model Class Is Chosen + How Weights Are Loaded</h4><p>chal.py does not directly import a specific class name from model.py. Instead, it dynamically discovers the correct model class at runtime and then loads the weights from weights.pt.</p><h4>4.1 Entry-class discovery via __entry__</h4><p>After importing the obfuscated model module, chal.py scans through everything inside the module dictionary and selects the first class that has the attribute __entry__ set to True:</p><pre>for v3383db94992ed0a1 in v4e9d910e79ac8742.__dict__.values():<br>    if isinstance(v3383db94992ed0a1, type) and hasattr(v3383db94992ed0a1, __s([117, 117, 79, 68, 94, 88, 83, 83, 117, 117])) and getattr(v3383db94992ed0a1, __s([117, 117, 79, 68, 94, 88, 83, 83, 117, 117])) is True:<br>        v40a3a950ba2cb738 = v3383db94992ed0a1<br>        break</pre><p>Here, the obfuscated string:</p><ul><li>__s([117,117,79,68,94,88,83,83,117,117])</li></ul><p>decodes (XOR 42) to:</p><p>&quot;__entry__&quot;</p><p>So the logic is exactly equivalent to:</p><pre>for obj in model_module.__dict__.values():<br>    if isinstance(obj, type) and hasattr(obj, &quot;__entry__&quot;) and obj.__entry__ is True:<br>        Entry = obj<br>        break</pre><h4>4.1.1 Confirming the entry class in model.py</h4><p>In model.py, the entry class is explicitly marked with __entry__ = True:</p><pre>class G0G0sQuid(SQUID.Module):<br>    __entry__ = True</pre><p>So chal.py is guaranteed to select this class.</p><h4>4.2 Loading weights.pt and running inference</h4><p>Once the entry class is found, chal.py:</p><ol><li>Instantiates it</li><li>Loads weights.pt using torch.load(..., map_location=&quot;cpu&quot;)</li><li>Calls load_state_dict(...)</li><li>Calls eval()</li><li>Preprocesses the image (Section 3)</li><li>Runs inference under torch.no_grad()</li></ol><p>This sequence appears in the following block:</p><pre>v3383db94992ed0a1 = v40a3a950ba2cb738()<br>v2e7813aa1aa9df6c = getattr(torch, __s([70, 69, 75, 78]))(__s([93, 79, 67, 77, 66, 94, 89, 4, 90, 94]), map_location=__s([73, 90, 95]))<br>getattr(v3383db94992ed0a1, __s([70, 69, 75, 78, 117, 89, 94, 75, 94, 79, 117, 78, 67, 73, 94]))(v2e7813aa1aa9df6c)<br>getattr(v3383db94992ed0a1, __s([79, 92, 75, 70]))()<br>v6ed6203f66ce0fcc = v39194d9e8c3d1b19(vc91053b95402ebe9)<br>with getattr(torch, __s([68, 69, 117, 77, 88, 75, 78]))():<br>    v2809dcbced78ba5 = v3383db94992ed0a1(v6ed6203f66ce0fcc)</pre><p>Decoded meaning (what the above block really is):</p><ul><li>__s([70,69,75,78]) → &quot;load&quot; → torch.load(...)</li><li>__s([93,79,67,77,66,94,89,4,90,94]) → &quot;weights.pt&quot;</li><li>__s([73,90,95]) → &quot;cpu&quot; → map_location=&quot;cpu&quot;</li><li>__s([70,69,75,78,117,89,94,75,94,79,117,78,67,73,94]) → &quot;load_state_dict&quot;</li><li>__s([79,92,75,70]) → &quot;eval&quot;</li><li>__s([68,69,117,77,88,75,78]) → &quot;no_grad&quot;</li></ul><p>So in clean form, it becomes:</p><pre>net = Entry()<br>state = torch.load(&quot;weights.pt&quot;, map_location=&quot;cpu&quot;)<br>net.load_state_dict(state)<br>net.eval()<br>x = preprocess(path)<br>with torch.no_grad():<br>    out = net(x)</pre><h4>5. The Win Condition (Why “&gt; 9” Means Success)</h4><p>After the model produces an output, chal.py converts it to an integer and checks whether it is greater than 9. If yes, it prints the special success message; otherwise it prints the digit.</p><h4>5.1 The &gt; 9 check (exact evidence from chal.py)</h4><p>This is the win-branch in the real (obfuscated) file:</p><pre>if int(getattr(v2809dcbced78ba5, __s([67, 94, 79, 71]))()) &gt; 9:<br>    __bi(__s([90, 88, 67, 68, 94]))(__s([83, 69, 95, 10, 77, 69, 94, 10, 67, 94, 11]))<br>else:<br>    __bi(__s([90, 88, 67, 68, 94]))(int(getattr(v2809dcbced78ba5, __s([67, 94, 79, 71]))()))</pre><p>What this means:</p><ul><li>__s([67,94,79,71]) decodes to &quot;item&quot;, so getattr(out, &quot;item&quot;)() is out.item()</li><li>__s([90,88,67,68,94]) decodes to &quot;print&quot;, so it is calling print(...)</li></ul><p><strong>Clean equivalent:</strong></p><pre>if int(out.item()) &gt; 9:<br>    print(&quot;you got it!&quot;)<br>else:<br>    print(int(out.item()))</pre><h4>5.2 Proving the success string is literally &quot;you got it!&quot;</h4><p>The success message is stored as an integer array and decoded at runtime:</p><pre>__s([83, 69, 95, 10, 77, 69, 94, 10, 67, 94, 11])</pre><p>Since __s is XOR with key 42, this decodes to:</p><p>&quot;you got it!&quot;</p><p>So the win condition is <strong>literally implemented in </strong><strong>chal.py</strong>:</p><blockquote><strong><em>Output &gt; 9 ⇒ print “you got it!”</em></strong></blockquote><h3>6. Why Model Inversion Is the Correct Attack</h3><p>If this were only a normal digit classifier, the output would always be one of the digits 0..9.<br> But chal.py explicitly treats <strong>values &gt; 9</strong> as special success values. This strongly indicates a <strong>hidden trigger / backdoor path</strong> exists inside the model.</p><p>Since this challenge provides:</p><ul><li>full model code (model.py)</li><li>full weights (weights.pt)</li><li>and runs locally</li></ul><p>we can use a white-box approach: <strong>gradient-based reconstruction</strong>.</p><h4>6.1 Evidence in model.py: it uses a hidden “reference” tensor</h4><p>The biggest giveaway in model.py is that the forward path uses two things:</p><h4>(A) It computes internal features from the input image using self.G0gosqu1d(...)</h4><p>Inside the entry model’s forward pass:</p><pre>GOG0SQUiD = self.G0gosqu1d(G0G0SQuId)</pre><p>This indicates G0gosqu1d is a feature-producing submodule (it maps the image tensor to an internal representation).</p><h4><strong>(B) It retrieves a fixed hidden reference using </strong><strong>get_ref()</strong></h4><p>In the same forward logic, the model explicitly calls:</p><pre>goG0sQUId = self.G0gosqu1d.get_ref()</pre><p>This is extremely important: it means the model contains a <strong>secret reference tensor</strong> and uses it during inference. In other words, the model is not only doing “digit classification”; it has logic that depends on matching a hidden reference.</p><p>That observation directly motivates the attack:</p><ul><li>extract the reference (get_ref())</li><li>force our input image to produce features that match that reference</li></ul><h4>6.2 The strategy (derived directly from the code)</h4><p>Because the model provides both:</p><ul><li>a feature extractor G0gosqu1d(x)</li><li>a secret target representation G0gosqu1d.get_ref()</li></ul><p>we can solve it by optimization:</p><ol><li>Load the model and weights locally (same as chal.py)</li><li>Extract ref = net.G0gosqu1d.get_ref()</li><li>Create a trainable image tensor x</li><li>Minimize the difference between G0gosqu1d(x) and ref</li></ol><p>This is exactly <strong>Model Inversion</strong>: reconstructing an input that matches a hidden internal state.</p><h4>7. Solving Idea (High-Level Math + Why It Works)</h4><p>We treat the image itself as the variable and minimize:</p><pre>loss = || G0gosqu1d(x) - ref ||²</pre><p>Where:</p><ul><li>xxx is the input image tensor (pixels)</li><li>G0gosqu1d(x)G0gosqu1d(x)G0gosqu1d(x) is the model’s internal feature representation of the image</li><li>refrefref is the hidden reference tensor extracted via get_ref()</li></ul><p>As the loss becomes very small, the internal “matching” condition inside the model is satisfied, causing the final output to land in the special success range (&gt; 9). Then chal.py prints the success message due to the explicit check in Section 5.</p><p>Finally, the optimized image is saved as trigger.png, and in this challenge the generated trigger image visibly contains the flag text</p><h4>8. Full solver script (builds trigger.png and tests it)</h4><pre>#!/usr/bin/env python3<br>import importlib.util<br>import subprocess<br>from pathlib import Path<br><br>import numpy as np<br>from PIL import Image<br><br>import torch<br>import torch.nn.init as init<br><br># --- Speedup: disable expensive init routines (important with obfuscated nets)<br>def _noop(t, *a, **k): return t<br>for fn in [&quot;orthogonal_&quot;,&quot;kaiming_uniform_&quot;,&quot;kaiming_normal_&quot;,&quot;xavier_uniform_&quot;,&quot;xavier_normal_&quot;,&quot;uniform_&quot;,&quot;normal_&quot;]:<br>    if hasattr(init, fn):<br>        setattr(init, fn, _noop)<br><br>HERE = Path(__file__).resolve().parent<br><br># --- Load model.py dynamically (same idea as chal.py)<br>spec = importlib.util.spec_from_file_location(&quot;m&quot;, str(HERE / &quot;model.py&quot;))<br>m = importlib.util.module_from_spec(spec)<br>spec.loader.exec_module(m)<br><br>Entry = None<br>for v in m.__dict__.values():<br>    if isinstance(v, type) and getattr(v, &quot;__entry__&quot;, False):<br>        Entry = v<br>        break<br>if Entry is None:<br>    raise RuntimeError(&quot;Couldn&#39;t find __entry__ class in model.py&quot;)<br><br>net = Entry()<br>sd = torch.load(str(HERE / &quot;weights.pt&quot;), map_location=&quot;cpu&quot;)<br>net.load_state_dict(sd)<br>net.eval()<br>torch.set_num_threads(1)<br><br># --- Find the submodule that has get_ref()<br>target_mod = None<br>for name in dir(net):<br>    obj = getattr(net, name)<br>    if hasattr(obj, &quot;get_ref&quot;) and callable(getattr(obj, &quot;get_ref&quot;)):<br>        target_mod = obj<br>        target_name = name<br>        break<br>if target_mod is None:<br>    raise RuntimeError(&quot;Couldn&#39;t find a submodule with get_ref()&quot;)<br><br>with torch.no_grad():<br>    ref = target_mod.get_ref().detach()<br><br>print(f&quot;[+] Using submodule: net.{target_name}  (has get_ref())&quot;)<br>print(&quot;[+] ref shape:&quot;, tuple(ref.shape))<br><br># --- Optimize input image (model inversion / feature matching)<br>x = torch.rand((1, 3, 256, 256), requires_grad=True)<br>opt = torch.optim.Adam([x], lr=0.08)<br><br>THRESH = 9e-4<br>MAX_IT = 600<br><br>for it in range(MAX_IT):<br>    opt.zero_grad()<br>    feat = target_mod(x)<br>    loss = (feat - ref).pow(2).mean()<br>    loss.backward()<br>    opt.step()<br>    with torch.no_grad():<br>        x.clamp_(0, 1)<br><br>    if it % 20 == 0:<br>        print(&quot;iter&quot;, it, &quot;loss&quot;, float(loss.item()))<br><br>    if float(loss.item()) &lt; THRESH:<br>        print(&quot;[+] FOUND trigger image! loss =&quot;, float(loss.item()))<br>        break<br><br># --- Save trigger.png<br>arr = (x.detach().squeeze(0).permute(1, 2, 0).cpu().numpy() * 255).astype(np.uint8)<br>out_path = HERE / &quot;trigger.png&quot;<br>Image.fromarray(arr).save(out_path)<br>print(&quot;[+] saved&quot;, out_path)<br><br># --- Run the official checker<br>print(&quot;[*] Running chal.py on trigger.png ...&quot;)<br>subprocess.run([&quot;python&quot;, str(HERE / &quot;chal.py&quot;), str(out_path)])</pre><p>This script automatically generates a trigger image that activates the model’s hidden success path. It loads model.py dynamically, finds the entry network class marked with __entry__ = True, loads the trained parameters from weights.pt, and switches the model to evaluation mode. To avoid slow startup caused by heavy initializers in the obfuscated model, it patches several torch.nn.init routines to no-ops (the real weights are loaded from weights.pt anyway).</p><p>Next, it searches the instantiated network for the submodule that exposes get_ref(), which returns a fixed, secret reference representation used by the backdoor logic. The script then performs <strong>model inversion</strong>: it treats the input image tensor x as an optimizable variable and uses Adam to minimize the mean squared error between the current features target_mod(x) and the hidden reference ref. Pixel values are clamped to [0,1] after each update to keep the image valid. Once the loss drops below a small threshold, the optimized image is saved as trigger.png and tested by running the official checker chal.py on it, which prints the success message when the model output becomes greater than 9.</p><h4>Output</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XhRH35GUrvcA3luWrY6vbA.png" /></figure><h4>trigger.png</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*pahCzQqjsXTvPGDSiuutHw.png" /></figure><h4>Flag</h4><blockquote><strong>uoftctf{m0d3l_1nv3r5i0N}</strong></blockquote><p>I know that Write Up may be long, but I Hope You Benefit From This Writeup</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0df23147ca87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Install And Use The CAPA Plugin In IDA Pro And Ghidra]]></title>
            <link>https://rynvasis.medium.com/how-to-install-and-use-the-capa-plugin-in-ida-pro-f2785fea2e16?source=rss-a480ee56e6d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2785fea2e16</guid>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[malware-analysis]]></category>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Rynvasis]]></dc:creator>
            <pubDate>Wed, 25 Dec 2024 00:47:28 GMT</pubDate>
            <atom:updated>2025-02-12T15:51:01.304Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi Every Body, This is Rynvasis</p><p>In the world of reverse engineering, <strong>IDA Pro</strong> and <strong>Ghidra</strong> stand as two of the most powerful tools available. By enhancing these tools with plugins like <strong>CAPA</strong>, you can significantly extend their functionality. This guide will walk you through the process of installing and using the <strong>CAPA Plugin</strong> in both <strong>IDA Pro</strong> and <strong>Ghidra</strong> to analyze code more efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*shZk7YXSlEGpHcaZF9c5Pg.png" /></figure><h3>What is CAPA?</h3><p><strong>CAPA</strong>, developed by the FLARE team, is a tool for automatically identifying malware capabilities. It analyzes executable files (PE, ELF, .NET, shellcode) and reports to detect functions like acting as a backdoor, installing services, or using HTTP for communication. Integrating <strong>CAPA </strong>with both <strong>IDA Pro</strong> and <strong>Ghidra</strong> streamlines malware analysis, making the reverse engineering process more efficient for analysts.</p><h3><strong>1. Install In IDA Pro</strong></h3><h3>Prerequisites</h3><ol><li>IDA PRO Installed</li><li>Python version must be 3.10 or later. To be able to download the latest version of CAPA</li></ol><h3>Step-by-Step Installation Guide</h3><h4>Step 1: Download the CAPA Repository</h4><ol><li>Clone the repository using Git:</li></ol><pre>git clone <a href="https://github.com/mandiant/capa.git">https://github.com/mandiant/capa.git</a></pre><p>2. Alternatively, download the repository as a ZIP file from the <a href="https://github.com/mandiant/capa">CAPA GitHub page</a>, then extract it to a folder on your machine.</p><h4>Step 2: Install CAPA</h4><pre>cd capa<br>python -m pip install .</pre><h4>Step 3: Configure CAPA for IDA Pro</h4><p>Copy File capa_explorer.py To Plugin in IDA Pro, Example:</p><pre>copy &quot;C:\capa\capa\ida\plugin\capa_explorer.py&quot; &quot;C:\Program Files\IDA Pro\plugins&quot;</pre><h4>Step 3: Install The Latest Version oF CAPA Rules</h4><p>From This Link:</p><pre><a href="https://github.com/mandiant/capa-rules/releases">https://github.com/mandiant/capa-rules/releases</a></pre><h3>Using CAPA in IDA Pro</h3><ol><li><strong>Load a Binary</strong>: Open the malware binary or executable you want to analyze in IDA Pro.</li><li><strong>Run CAPA</strong>: From the Edit -&gt; Plugins -&gt; CAPA. The plugin will prompt you to specify the path to the capa-rules directory. Navigate to the directory where you downloaded the CAPA rules and select it.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*2tz93eOLOWaEyWN3Zs27-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*iuciZZU7g0xJHnOTHiSZbg.png" /></figure><p>3. <strong>Review Results</strong>: CAPA will analyze the binary using the specified rules and generate a detailed report, highlighting detected malware functionalities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IJOlsEW87sBg_7m56Pnhvw.png" /></figure><h3>Errors And Solutions</h3><pre>&quot;C:\Users\Rynvasis\AppData\Local\Programs\Python\Python311\Lib\site-packages\capa\ida\plugin\__init__.py&quot;, line 13, in &lt;module&gt;<br>    from capa.ida.plugin.form import CapaExplorerForm<br>  File &quot;C:\Users\Rynvasis\AppData\Local\Programs\Python\Python311\Lib\site-packages\capa\ida\plugin\form.py&quot;, line 18, in &lt;module&gt;<br>    import ida_settings<br>  File &quot;C:\Users\Rynvasis\AppData\Local\Programs\Python\Python311\Lib\site-packages\ida_settings\__init__.py&quot;, line 1, in &lt;module&gt;<br>    from .ida_settings import IDASettings, PermissionError<br>  File &quot;C:\Users\Rynvasis\AppData\Local\Programs\Python\Python311\Lib\site-packages\ida_settings\ida_settings.py&quot;, line 168, in &lt;module&gt;<br>    QtCore = import_qtcore()<br>             ^^^^^^^^^^^^^^^<br>  File &quot;C:\Users\Rynvasis\AppData\Local\Programs\Python\Python311\Lib\site-packages\ida_settings\ida_settings.py&quot;, line 141, in import_qtcore<br>    from PyQt5 import QtCore<br>ImportError: DLL load failed while importing sip: The specified module could not be found.</pre><p>Solution:</p><p>Run EXE File In IDA Pro Path Named idapyswitch.exe, To Set Python Path Example Path To EXE:</p><pre>&quot;C:\Program Files\IDA Pro\idapyswitch.exe&quot;</pre><h3><strong>2. Install In Ghidra</strong></h3><h3>Prerequisites</h3><ol><li>Ghidra Installed</li><li>Python version must be 3.10 or later. To be able to download the latest version of CAPA</li><li><a href="https://github.com/mandiant/Ghidrathon/releases">Ghidrathon</a></li></ol><h3><strong>Install Ghidrathon</strong></h3><h3>Prerequisites</h3><ol><li><a href="https://www.oracle.com/eg/java/technologies/downloads/">Java JDK</a>, And After Installed Make Sure java and javac are Found<br>With Using Command:<br>a. java --version <br>b. javac --version <br>If Not Found, Add Path To Environment<br>C:\Program Files\Common Files\Oracle\Java\javapath or<br>C:\Program Files\Java\jdk-&lt;version&gt;\bin<br>c. set the environment variable JAVA_HOME <br> Variable Name : JAVA_HOME<br> Variable Value : C:\Program Files\Java\jdk-&lt;version&gt;</li><li><a href="https://visualstudio.microsoft.com/visual-cpp-build-tools/">Microsoft C/C++ Build Tools</a>, then run program and choose <br>Desktop Development With C++</li></ol><h3>Step-by-Step Installation Guide</h3><ol><li>Download and unzip the latest Ghidrathon <a href="https://github.com/mandiant/Ghidrathon/releases">release</a></li><li>After unzip, go to the directory and run this command:</li></ol><pre>python -m pip install -r requirements.txt<br>python ghidrathon_configure.py &lt;absolute_path_to_ghidra_install_dir&gt;</pre><p>3. After unzip , You Will Find Another <strong>zip </strong>File, You will take it copy to extension in Ghidra</p><pre>copy &quot;C:\Rynvasis\Downloads\Ghidrathon-&lt;version&gt;\Ghidrathon-&lt;version&gt;.zip&quot; &quot;C:\Program Files\g<br>hidra\Extensions\Ghidra&quot;</pre><p>4. After copy, open Ghidra and Choose File =&gt; Install Extensions and Choose <strong>zip </strong>that copied to extension in Ghidra</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*ARoKQg4wPVqmg14PGhKwgw.png" /></figure><p>And so it was installed Ghidrathon</p><p>Go to Window -&gt; Ghidrathon</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*0HepQR-Url0i-58zF7j3tA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*ygNs79qHNRBwUQoeSxyvXQ.png" /></figure><p><strong>Now we will complete install CAPA in Ghidra</strong></p><h3>Step-by-Step Installation Guide</h3><h4>Step 1: Download the CAPA Repository</h4><ol><li>Clone the repository using Git:</li></ol><pre>git clone <a href="https://github.com/mandiant/capa.git">https://github.com/mandiant/capa.git</a></pre><p>2. Alternatively, download the repository as a ZIP file from the <a href="https://github.com/mandiant/capa">CAPA GitHub page</a>, then extract it to a folder on your machine.</p><h4>Step 2: Install CAPA</h4><pre>cd capa<br>python -m pip install .</pre><h4>Step 3: Configure CAPA for Ghidra</h4><p>Copy File capa_explorer.py &amp; capa_ghidra.pyTo Plugin in Ghidra , Example:</p><pre>copy &quot;C:\capa\capa\ghidra\capa_explorer.py&quot; &quot;C:\Program Files\ghidra\Ghidra\Features\BytePatterns\ghidra_scripts&quot;<br>copy &quot;C:\capa\capa\ghidra\capa_ghidra.py&quot; &quot;C:\Program Files\ghidra\Ghidra\Features\BytePatterns\ghidra_scripts&quot;</pre><h4>Step 3: Install The Latest Version oF CAPA Rules</h4><p>From This Link:</p><pre><a href="https://github.com/mandiant/capa-rules/releases">https://github.com/mandiant/capa-rules/releases</a></pre><h3>Using CAPA in Ghidra</h3><ol><li><strong>Load a Binary</strong>: Open the malware binary or executable you want to analyze in Ghidra.</li><li><strong>Run CAPA</strong>: From the Window -&gt; Script Manager. Then Search about capa_ghidra.py Then right click, Choose Run Script , will appear window to choose capa_rules</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*k-8aLgP-qZccig0FcZ2vcw.png" /></figure><p>After Choose capa_rules , will appear anaylsis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U4AKaiHn1nbLdN5I5EZA_A.png" /></figure><p>Now we run script capa_explorer.py , After Finished to see results , go to Bookmark window (CTRL+ B) or Namespace section:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K2crJprnlxcT3Fdsv6blKQ.png" /></figure><h3>Errors And Solutions</h3><pre>Traceback (most recent call last):<br>  File &quot;C:\Users\Rynvasis\AppData\Roaming\ghidra\ghidra_11.2_PUBLIC\Extensions\Ghidrathon\data\python\jeprunscript.py&quot;, line 31, in jep_runscript<br>    exec(compile(source, path, &quot;exec&quot;), {**globals(), **additional_globals})<br>  File &quot;C:\ghidra_11.2_PUBLIC_20240926\ghidra_11.2_PUBLIC\Ghidra\Features\BytePatterns\ghidra_scripts\capa_ghidra.py&quot;, line 167, in &lt;module&gt;<br>    sys.exit(main())<br>  File &quot;C:\ghidra_11.2_PUBLIC_20240926\ghidra_11.2_PUBLIC\Ghidra\Features\BytePatterns\ghidra_scripts\capa_ghidra.py&quot;, line 159, in main<br>    return run_ui()<br>  File &quot;C:\ghidra_11.2_PUBLIC_20240926\ghidra_11.2_PUBLIC\Ghidra\Features\BytePatterns\ghidra_scripts\capa_ghidra.py&quot;, line 124, in run_ui<br>    meta = capa.ghidra.helpers.collect_metadata([rules_path])<br>  File &quot;C:\Users\Rynvasis\AppData\Local\Programs\Python\Python310\lib\site-packages\capa\ghidra\helpers.py&quot;, line 152, in collect_metadata<br>    base_address=capa.features.freeze.Address.from_capa(AbsoluteVirtualAddress(currentProgram().getImageBase().getOffset())),  # type: ignore [name-defined] # noqa: F821<br>NameError: name &#39;AbsoluteVirtualAddress&#39; is not defined</pre><p>Solution:</p><p>Install last version From capa or go to file helpers.py in path to python<br>This Path:</p><pre>C:\Users\Rynvasis\AppData\Local\Programs\Python\Python310\Lib\site-packages\capa\ghidra</pre><p>and open file helpers.py add line:</p><pre>from capa.features.address import AbsoluteVirtualAddress</pre><h3>Conclusion</h3><p>The <strong>capa plugin</strong> transforms how reverse engineers analyze malware, offering a quick and reliable way to identify malicious capabilities. By integrating <strong>capa</strong> into <strong>IDA Pro</strong> and <strong>Ghidra</strong>, you unlock the potential to automate tedious analysis tasks and gain deeper insights into complex binaries. Follow this guide to set up <strong>capa</strong> in your environment and take your malware analysis skills to the next level.</p><p>Happy reversing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2785fea2e16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reverse Engineering Challenge]]></title>
            <link>https://rynvasis.medium.com/reverse-engineering-challenge-573f0bb77f82?source=rss-a480ee56e6d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/573f0bb77f82</guid>
            <category><![CDATA[malware-analysis]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[writeup]]></category>
            <dc:creator><![CDATA[Rynvasis]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 23:03:17 GMT</pubDate>
            <atom:updated>2024-12-23T23:03:17.624Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi Every Body , This is Rynvasis</p><p>In This Writeup, I will talk about the first reverse challenge I tried</p><p>First look of the challenge, I Find that, The Challenge is aEXE File<br> Then I run this File, And this was the output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*euI1RR3L4IyUwFxLkSdSSA.png" /></figure><p>From output form , The program is encrypting the output , As long as there is encryption, there will be reverse :)</p><p>I will load File in IDA to see code in disassembler:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aj4DWqt3cNWrr8FUzSigSA.png" /></figure><p>Okay , We Have The Main Function And Another Function Called “encrypt_flag”, So Let’s Analysis Them :</p><p>main <strong>Function</strong></p><p><strong>Variable Declarations:</strong></p><ul><li>v3 Store values returned by the time</li><li>v8Store random number with time → random number from 1 to 30</li><li>v4It is used to return a pointer to a standard I/O stream , in this case the argument is 0 , which means stdin</li><li>Bufferstore input form user</li><li>Str1 store output after encrypted it</li></ul><p><strong>Seeding the Random Number Generator:</strong></p><ul><li>v3 = time(0i64);<strong> </strong>generates a seed for srand() using the current time.</li><li>srand(v3);<strong> </strong>initializes the random number generator with this seed, use rand() to generate random number form 1 to 30, because from 1 to 30 when became rand() % 30 means generate random number from 0 to 29 and increment one to become from 1 to 30</li></ul><p><strong>Encryption of the User Input:</strong></p><ul><li>encrypt_flag(Buffer,Str1, v8);<strong> </strong>call<strong> </strong>encrypt_flag<strong>, </strong>passing user input Buffer and output that will store it Str1 and random number from seed v8</li></ul><p><strong>Condition:</strong></p><ul><li>strcmp(Str1,”0897ba0537fee426f348eeed08ecb1e98728721d654f064bfe81d308c427e85337016df54e6008d495c137b0fc768e4f8a4a6943eda4d14de557cfc76a76ee671c8a8546&quot;) call<strong> </strong>strcmp<strong> , </strong>passing output is input after encrypted<strong> </strong>Str1<strong> </strong>compare between the second argument if it equals return 0</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*it9Avn_051IGJiySY1hhTg.png" /></figure><p>encrypt_flag <strong>Function</strong></p><p><strong>Function Parameters:</strong></p><ul><li>a1<strong> </strong>A pointer to the string to be encrypted.</li><li>a2 A pointer to the buffer where the encrypted result (in hexadecimal) will be stored.</li><li>a3 A pointer to the random number.</li></ul><p><strong>Local Variables:</strong></p><ul><li>v7 store length to input a1by using call strlen(a1)</li><li>key The encryption key generated by generate_key(a3).</li><li>v4<strong> </strong>A temporary buffer to store a working copy of the input string a1</li><li>v5<strong> </strong>A single-byte intermediate value used in the encryption loop</li><li>result A pointer to the end of the encrypted string in the buffer.</li><li>Other variables (m, k, j, i) use to loop counters</li></ul><p><strong>First Loop:</strong></p><ul><li>for (i = 0; i &lt; v7; ++i) Iterates over each byte of the string.</li><li>v5 = key &gt;&gt; (i % 24); A part of the key is extracted by right-shifting it by (i % 24) bits.</li><li>v4[i] ^= v5; The current byte of v4 is XORed with v5.</li><li>v4[i] = (16 * v4[i]) | (v4[i] &gt;&gt; 4); The byte is multiplied by 16 (left shift by 4 bits). and Right shift by 4 Then OR</li><li>v4[i] ^= 90 * i; The current byte of v4 is XOR with 90 * i.</li></ul><p><strong>Second Loop:</strong></p><ul><li>for (j = 0; j &lt; v7 - 1; ++j) Iterates over all bytes except the last one.</li><li>v4[j + 1] ^= v4[j]; Each byte is XOR with the previous byte.</li></ul><p><strong>Third Loop:</strong></p><ul><li>for (k = 0; k &lt; v7; ++k) Iterates over all bytes of v4.</li><li>v4[k] = (key ^ v4[k]) + 7 * a3; Each byte is XORed with the key and then incremented by 7 * a3.</li></ul><p><strong>Fourth Loop:</strong></p><ul><li>for (m = 0; m &lt; v7; ++m) Iterates over all bytes of the encrypted buffer.</li><li>sprintf((char *const)(a2 + 2 * m), “%02x”, v4[m]);Each byte is converted to a 2-character hexadecimal string and stored in the output buffer a2.</li></ul><p><strong>Null-Terminate the Output:</strong></p><ul><li>result =(a2 + 2 * v7); A pointer to the end of the encrypted string in a2 is calculated.</li><li>*result = 0; The output buffer is null-terminated to mark the end of the string.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YYAeMznSMXVYSsD-om6psg.png" /></figure><p>generate_key <strong>Function</strong>:</p><ul><li>(1103515245 * ((1103515245 * a1 + 12345) &amp; 0x7FFFFFFF) + 12345) &amp; 0x7FFFFFFF use to generate number by using random number a1</li></ul><p>Now I Will Reverse The Encryption Algorithm and Brute Force The Random number</p><pre>#include &lt;string.h&gt;<br>#include &lt;stdio.h&gt;<br>#include &lt;stdint.h&gt;<br>#include &lt;stdlib.h&gt;<br><br>// Function prototype for generate_key (same as encryption)<br>int generate_key(int random_number) {<br>    return (1103515245 * ((1103515245 * random_number + 12345) &amp; 0x7FFFFFFF) + 12345) &amp; 0x7FFFFFFF;<br>}<br><br>unsigned char* decrypt_flag(const char *encrypted_hex, char *output, unsigned int random_number) {<br>    unsigned int key;             // Decryption key<br>    int input_len;                // Length of the input<br>    unsigned char *decrypted;     // Decrypted byte array<br>    char v5;                      // Temporary variable for bit manipulation<br>    int i, j, k, m;               // Loop counters<br><br>    // Calculate input length (hex string length / 2)<br>    input_len = strlen(encrypted_hex) / 2;<br><br>    // Allocate memory for decrypted bytes<br>    decrypted = malloc(input_len + 1);<br>    if (!decrypted) return NULL;<br><br>    // Convert hex string to bytes<br>    for (m = 0; m &lt; input_len; m++) {<br>        sscanf(encrypted_hex + 2*m, &quot;%2hhx&quot;, &amp;decrypted[m]);<br>    }<br><br>    // Generate the decryption key<br>    key = generate_key(random_number);<br><br>    // Reverse third encryption loop<br>    for (k = input_len - 1; k &gt;= 0; k--) {<br>        decrypted[k] = (key ^ (decrypted[k] - 7 * random_number));<br>    }<br><br>    // Reverse second encryption loop<br>    for (j = input_len - 2; j &gt;= 0; j--) {<br>        decrypted[j + 1] ^= decrypted[j];<br>    }<br><br>    // Reverse first encryption loop<br>    for (i = input_len - 1; i &gt;= 0; i--) {<br>        decrypted[i] ^= 90 * (unsigned char)i;<br>        <br>        // Reverse bit rotation (rotate back)<br>        decrypted[i] = ((decrypted[i] &gt;&gt; 4) | (decrypted[i] &lt;&lt; 4)) ;<br>        <br>        // Reverse XOR with v5<br>        v5 = key &gt;&gt; (i % 24);<br>        decrypted[i] ^= v5;<br>    }<br><br>    // Copy decrypted bytes to output<br>    memcpy(output, decrypted, input_len);<br>    output[input_len] = &#39;\0&#39;;<br><br>    // Free allocated memory<br>    free(decrypted);<br><br>    return output;<br>}<br><br>int main() {<br>  <br>    char *encrypted_hex = &quot;0897ba0537fee426f348eeed08ecb1e98728721d654f064bfe81d308c427e85337016df54e6008d495c137b0fc768e4f8a4a6943eda4d14de557cfc76a76ee671c8a8546&quot;;<br>    char output[103];<br>    memset(output, 0, sizeof(output));<br><br>    for(int i= 1 ; i&lt;=30; i++){<br>        decrypt_flag(encrypted_hex, output, i);<br>        printf(&quot;Random number %d: Decrypted: %s\n&quot;, i, output);<br>    }<br>    <br>    return 0;<br>}</pre><p>After Run code, This was output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*8ep-hy7LmMJvcmehR-iAkQ.png" /></figure><p>Let’s see that random number is<em> 18</em> and flag is :</p><p><em>Flag{0hh!!_Br00tf0r53_S33d_&amp;_R3v3r53_Th3_F10w_Ar3_C001_Op3r4t1on5!!}</em></p><p>I know that Write Up may be long, but I Hope You Benefit From This Writeup</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=573f0bb77f82" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>