<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.9.5">Jekyll</generator><link href="https://maschell.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://maschell.github.io/" rel="alternate" type="text/html" /><updated>2024-08-02T16:38:32+00:00</updated><id>https://maschell.github.io/feed.xml</id><title type="html">Random homebrew developing</title><subtitle>This blog is about random stuff that happens in my life as a homebrew dev.</subtitle><entry><title type="html">Why some homebrew apps are incompatible with Aroma and how to fix them</title><link href="https://maschell.github.io/homebrew/2023/04/30/incompatible-homebrews.html" rel="alternate" type="text/html" title="Why some homebrew apps are incompatible with Aroma and how to fix them" /><published>2023-04-30T16:30:00+00:00</published><updated>2023-04-30T16:30:00+00:00</updated><id>https://maschell.github.io/homebrew/2023/04/30/incompatible-homebrews</id><content type="html" xml:base="https://maschell.github.io/homebrew/2023/04/30/incompatible-homebrews.html"><![CDATA[<p>The <a href="https://aroma.foryour.cafe/">Aroma</a> homebrew environment has now been out for 8 months, with many people trying it out since. Almost every day I get reports of people asking why their homebrew does not appear in the Wii U Menu or why their apps crash when exiting; in this blog post, I want to give you more details about why these things happen and how developers can fix their apps.</p>

<h2 id="early-days-of-launching-homebrew">Early days of launching homebrew</h2>
<p>Back in 2016, when the homebrew launcher (HBL) for the Wii U launched, it was only possible to load homebrew specially designed for it. Any already-existing homebrew applications had to be ported. Today, these “HBL compatible homebrews” are commonly known as <code class="language-plaintext highlighter-rouge">.elf</code>-homebrew. They are statically linked to a specific address in memory (which was dedicated to the homebrew launcher), which means in order to execute them, they need to be copied to a specific position in memory. This meant it was impossible to run multiple <code class="language-plaintext highlighter-rouge">.elf</code> homebrews at the same time. Loading a second one, would simply overwrite the first one. (For example, it was impossible to use SDCafiine and TCPGecko at the same time without combining them into a single homebrew app.)</p>

<p>To execute these applications, the homebrew launcher hooked into the Mii Maker (the only system app with SD card access) and redirected code execution to the loaded <code class="language-plaintext highlighter-rouge">.elf</code> in memory. To provide further information to the homebrew apps (like the system version, or function pointers to important system functions), the HBL placed them in a dedicated area in memory. Almost all of the <code class="language-plaintext highlighter-rouge">.elf</code>-homebrews heavily rely on this information and won’t run without it.</p>

<p>Over time, toolchains have improved (e.g. <a href="https://github.com/devkitPro/wut">wut</a>) and are now able to create homebrew in the native binary format of the Wii U, also known as <code class="language-plaintext highlighter-rouge">.rpx</code>. Unlike <code class="language-plaintext highlighter-rouge">.elf</code> homebrew, which had to be loaded manually into memory, loading <code class="language-plaintext highlighter-rouge">.rpx</code> files is handled by the OS. The Homebrew Launcher hooked into the loader and replaced the data on the fly. Aroma redirects the file loading to the SD card on the IOSU side. But both don’t have to care how the files are actually loaded or where the executable is stored. Additionally, <code class="language-plaintext highlighter-rouge">.rpx</code>-homebrews are dynamically linked, which means it’s possible to load them anywhere in memory, making them much more future-proof.</p>

<h2 id="not-every-rpx-is-implemented-properly">Not every .rpx is implemented properly</h2>
<p>Each application on the Wii U can be in one of two states: the foreground, or the background. Whenever the Home Menu or any applet (like the Friend List, Browser, etc.) is running, the application will be in the background state. To properly support this, applications can use the ProcUI library to manage their state. On every frame, the application checks whether it should leave the foreground, come back from the background, or exit. Only if this is implemented can the application react to things like pressing the home button on the gamepad or the power button on the console.</p>

<p>In the early days of <code class="language-plaintext highlighter-rouge">.rpx</code>-homebrew, not many applications actually implemented the ProcUI-loop. People barely understood it, and there was zero documentation about it. The only way to learn about this was by looking at existing code or by reverse engineering official applications. Even today, this knowledge is not really widespread.</p>

<p>Because of the way the Homebrew Launcher is injected into the Mii Maker and how it’s loading <code class="language-plaintext highlighter-rouge">.rpx</code>-homebrew, it’s actually fine to run homebrew without a ProcUI-loop with the Homebrew Launcher. The home button was used to exit to the Homebrew Launcher instead of opening the Home Menu. Developers had no real incentive to implement it, because everything (except shutting down the console by pressing the power button) was working and only a few apps did it properly. It only became a problem when these <code class="language-plaintext highlighter-rouge">.rpx</code> homebrews were loaded as installed titles: Often opening the Home Menu didn’t work, and exiting softlocked the console.</p>

<h1 id="compatibility-with-aroma">Compatibility with Aroma</h1>

<p>How does all of this affect Aroma? As we have learned before: <code class="language-plaintext highlighter-rouge">.elf</code>-homebrews are hardcoded to be launched from a specific address in memory and rely on some magic values in memory. Unfortunately, that specific address is exactly the same address that Aroma uses for its module system. This means we have to decide between supporting the old <code class="language-plaintext highlighter-rouge">.elf</code>-homebrew from &lt;= 2016 or having all the cool new features Aroma introduced. For me, the choice was obvious. Almost every <code class="language-plaintext highlighter-rouge">.elf</code> nowadays has been replaced by a <code class="language-plaintext highlighter-rouge">.rpx</code>/<code class="language-plaintext highlighter-rouge">.wuhb</code> homebrew or is now a plugin.</p>

<p>Technically, it might be possible to bring back support for <code class="language-plaintext highlighter-rouge">.elf</code>-homebrew. But it either means I have to rewrite parts of Aroma (to avoid the memory region used by <code class="language-plaintext highlighter-rouge">.elf</code>-homebrew) or every existing <code class="language-plaintext highlighter-rouge">.elf</code>-homebrew has to be adjusted (or at least re-compiled). At this point, it just makes much much much more sense to just port it to <code class="language-plaintext highlighter-rouge">.rpx</code> (or to be a plugin).</p>

<p><strong>TLDR: Aroma will probably never support <code class="language-plaintext highlighter-rouge">.elf</code> homebrew because launching them would mean overwriting parts of Aroma.</strong></p>

<p>With Aroma, the way of loading <code class="language-plaintext highlighter-rouge">.rpx</code> files also changed. Loading homebrew is now directly integrated into the Wii U Menu and every homebrew acts and appears like a real installed title on the system. So loading a <code class="language-plaintext highlighter-rouge">.rpx</code> with Aroma that doesn’t implement the ProcUI-loop has the same issues as installing it as a channel: Opening the Home Menu doesn’t work properly, and exiting would softlock the console.</p>

<p>Additionally, some older <code class="language-plaintext highlighter-rouge">.rpx</code>-homebrews are bundling exploits that overwrite parts of Aroma in memory. This results in undefined behavior or even crashes.</p>

<p><strong>TLDR: Some existing <code class="language-plaintext highlighter-rouge">.rpx</code> have not been implemented properly; they were just good enough to work with the Homebrew Launcher and now need to be updated.</strong></p>

<p>(It’s the same for <code class="language-plaintext highlighter-rouge">.wuhb</code>-homebrew. Every <code class="language-plaintext highlighter-rouge">.wuhb</code> is basically like a <code class="language-plaintext highlighter-rouge">.zip</code> containing a <code class="language-plaintext highlighter-rouge">.rpx</code> and metadata like icons. Having a <code class="language-plaintext highlighter-rouge">.wuhb</code> doesn’t mean it’ll work in Aroma, it’s all about the <code class="language-plaintext highlighter-rouge">.rpx</code>’s implementation inside the <code class="language-plaintext highlighter-rouge">.wuhb</code>.)</p>

<h2 id="how-to-make-a-rpx-compatible-with-aroma">How to make a <code class="language-plaintext highlighter-rouge">.rpx</code> compatible with Aroma</h2>
<p>As a rule of thumb: every <code class="language-plaintext highlighter-rouge">.rpx</code> that would run as an installed title (and does not bundle any exploits) will work with Aroma.</p>

<p>This means it has to implement the ProcUI-loop properly. ProcUI is a set of functions to manage transitions between the different states of an application. Each application can either be in the <strong>foreground</strong> (when you actually see the application running) or in the <strong>background</strong> (when something else is in the foreground, like the Home Menu or an applet like the Browser). To react to requests from the OS, the application can use the ProcUI library. <strong>If the application doesn’t react to the request to transit to the background or exit, the OS is still waiting for a response, even if the application has actually already exited, resulting in a softlock.</strong></p>

<h4 id="check-for-procui-status">Check for ProcUI Status:</h4>
<p>In order to have a responsive application and to react quickly to events, it should check for its current state <strong>on every frame</strong>. The current state can be checked by calling <code class="language-plaintext highlighter-rouge">ProcUIProcessMessages()</code>, which returns one of:</p>
<ul>
  <li><code class="language-plaintext highlighter-rouge">PROCUI_STATUS_IN_FOREGROUND</code>: The application is in the foreground (default state). All system resources and hardware are available, and the application runs without any serious restrictions.</li>
  <li><code class="language-plaintext highlighter-rouge">PROCUI_STATUS_IN_BACKGROUND</code>: The application is in the background and something else runs in the foreground (Home Menu, Internet Browser, etc.). Background applications are heavily restricted: they lose access to MEM1 and the foreground bucket, get a small amount of CPU time on core 2 (all other threads are suspended), access to filesystems, and some network IO. They have no access to graphics, inputs, or user interaction of any kind.</li>
  <li><code class="language-plaintext highlighter-rouge">PROCUI_STATUS_RELEASE_FOREGROUND</code>: The application is in the foreground, but the OS wants to put it in the background. This either happens when the user opens an applet like the Home Menu (via the home button), Friend List, Browser, etc. or the application closes (e.g. by pressing the power button of the console). The application needs to release all foreground-only resources like MEM1 memory or the Foreground Bucket. If it’s ready to release the foreground, it needs to call <code class="language-plaintext highlighter-rouge">ProcUIDrawDoneRelease()</code>.</li>
  <li><code class="language-plaintext highlighter-rouge">PROCUI_STATUS_EXITING</code>: The application is in the background, and the OS wants to exit it completely. When receiving this message, the application needs to clean up all resources it’s using and can then exit safely by returning from the main function. ProcUI needs to be shutdown via <code class="language-plaintext highlighter-rouge">ProcUIShutdown()</code>.</li>
</ul>

<h4 id="how-to-deal-with-losing-access-to-memory-regions-while-in-the-background">How to deal with losing access to memory regions while in the background</h4>
<p>While the application is running in the background, it only has limited access to system resources. This includes access to the MEM1-region and the foreground bucket. Before the application goes into the background, you need to release all the memory in those regions. When the application goes into the foreground, the memory can be allocated again.</p>

<p>ProcUI offers two solutions for this:</p>
<ul>
  <li>A callback can be registered, which will be called once the application releases or acquires the foreground. An example implementation that frees/allocates MEM1 via callbacks can be found <a href="https://github.com/devkitPro/wut/blob/4a98cd4797d3b87a9f38a3999e471d3eebd850f5/libraries/libwhb/src/gfx.c#L354">here</a>.</li>
  <li>As an alternative solution, <code class="language-plaintext highlighter-rouge">ProcUISetMEM1Storage</code> and <code class="language-plaintext highlighter-rouge">ProcUISetBucketStorage</code> can be used. These functions take a buffer (which needs to be allocated from MEM2) which will be used to preserve MEM1/Bucket memory while the application is in the background.</li>
</ul>

<h4 id="how-to-handle-switching-to-different-applications">How to handle switching to different applications</h4>
<p>On the Wii U, you never just return from the <code class="language-plaintext highlighter-rouge">main</code> function when you want to exit the application. The OS always needs to know what to launch next, and exiting always happens via the ProcUI-loop. For most cases, you can use the <a href="https://wut.devkitpro.org/group__sysapp.html">sysapp</a> library for this.</p>

<p>Example: If you want to open the Wii U Menu, simply call <code class="language-plaintext highlighter-rouge">SYSLaunchMenu()</code> <strong>once</strong>. This will trigger a ProcUI event, which the application will then react to.</p>

<h4 id="interesting-links-related-to-procui">Interesting links related to ProcUI:</h4>
<ul>
  <li>To switch to another application or to open an applet, you can use the <a href="https://wut.devkitpro.org/group__sysapp.html">sysapp</a> library.</li>
  <li>An example of a ProcUI-loop implementation can be found in <a href="https://github.com/wiiu-env/launchiine/blob/bd31cbe4f4487851e6a2aa79ad30fba5b73107d3/src/Application.cpp#L133">launchiine</a>.</li>
  <li>To simplify things, <a href="https://github.com/devkitPro/wut">wut</a> provides some wrapper functions (<code class="language-plaintext highlighter-rouge">WHBProcIsRunning</code>) to handle ProcUI for you. Example implementations can be found at the <a href="https://github.com/devkitPro/wut/tree/master/samples">wut samples</a>.</li>
  <li>See the <a href="https://wut.devkitpro.org/group__proc__ui__procui.html">wut documentation</a> for further information about the ProcUI library.</li>
</ul>

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

<p>In conclusion, <code class="language-plaintext highlighter-rouge">.elf</code>-homebrews are not compatible with Aroma for technical reasons, and the ProcUI library plays a crucial role in nicely integrating homebrew apps with the rest of the system. Without implementing the ProcUI-loop, homebrew apps won’t be able to properly manage their foreground and background states. This results in a lack of responsiveness to user actions like pressing the home button or power button, which results in softlocking on exit. While it may have been fine to run these apps with the Homebrew Launcher, these applications are now causing trouble when launched in Aroma. It’s easier to fix these few applications instead of putting many hours into supporting old legacy homebrew, which can be easily used by dualbooting into <a href="https://tiramisu.foryour.cafe/">Tiramisu</a>.</p>

<p>If you’re a developer and have questions about fixing apps to be compatible with Aroma, feel free to ask on the <a href="https://discord.com/invite/bZ2rep2">Aroma Discord</a>.</p>]]></content><author><name></name></author><category term="homebrew" /><summary type="html"><![CDATA[The Aroma homebrew environment has now been out for 8 months, with many people trying it out since. Almost every day I get reports of people asking why their homebrew does not appear in the Wii U Menu or why their apps crash when exiting; in this blog post, I want to give you more details about why these things happen and how developers can fix their apps.]]></summary></entry><entry><title type="html">Aroma</title><link href="https://maschell.github.io/homebrew/2022/09/05/aroma.html" rel="alternate" type="text/html" title="Aroma" /><published>2022-09-05T21:00:00+00:00</published><updated>2022-09-05T21:00:00+00:00</updated><id>https://maschell.github.io/homebrew/2022/09/05/aroma</id><content type="html" xml:base="https://maschell.github.io/homebrew/2022/09/05/aroma.html"><![CDATA[<p>In the past few years I have worked on improving the homebrew experience for users and developers on the Wii U. What started as “Would be cool to run 2 homebrews at the same time, let’s try to make a plugin system”, turned into “I want to understand existing exploits”, and then “coldbooting into plugins would be cool” turned into discovering a new major exploit (<a href="/homebrew/2020/12/02/failst.html">FailST</a>) and basically rewriting every bit of homebrew I was interested in. Over time, the scope kept growing and growing and it was getting hard to actually finish it. In the meantime I released some parts of it together with <a href="/homebrew/2021/12/31/tiramisu.html">Tiramisu</a>, but at the time of writing this blog post there are still <strong>25</strong> private repositories related to Aroma.</p>

<p>I wanted to have the perfect release, but this would take a lot of time. A lot of time to explain all the cool features in detail, a lot of time to talk about the design choices I’ve made, a lot of time to document everything and a lot of time to make it the best possible experience for users and homebrew developers. But while working on this perfection, nobody else can enjoy the already existing features of Aroma, which is really sad. It happens again and again that a user or developer asks for feature X and in many cases the answer is “It would be possible, but only with Aroma”.</p>

<p>Long story short, there will be a public beta of Aroma. But before I get into details, let’s discuss what Aroma exactly is.</p>

<h2 id="whats-aroma">What’s Aroma?</h2>

<p>The good news is: The migration to Aroma will be really simple, especially if you’re already coldbooting into the <a href="https://github.com/wiiu-env/EnvironmentLoader">EnvironmentLoader</a> (e.g. booting into <a href="https://github.com/wiiu-env/Tiramisu">Tiramisu</a>). Aroma is just another Environment that will be installed by copy pasting a new directory on to the SD card. The installation of the EnvironmentLoader is exactly the same as for Tiramisu.</p>

<p>Given these similarities between Aroma and Tiramisu, they share the basic feature set. Both are built on top of the same Mocha version, updates are blocked, Bloopair is supported, and the AutobootModule including the quick start menu are working too.</p>

<h3 id="introducing-aroma-modules">Introducing Aroma Modules</h3>
<p>Tiramisu provides a very basic environment which only includes <a href="https://github.com/wiiu-env/MochaPayload">Mocha</a>, the autoboot module, and a module for injecting the Homebrew Launcher into the Mii Maker. Aroma on the other hand ships with its own module loader, which is more powerful than what the “setup modules” in the EnvironmentLoader offers.</p>

<p>Aroma Modules can best be compared to <code class="language-plaintext highlighter-rouge">.rpl</code> files (in non Cafe OS terms, a <code class="language-plaintext highlighter-rouge">.dll</code>). They stay loaded in memory, as opposed to “setup modules”. Each Aroma Module can export functions which may be utilised by other modules or plugins. For example, there is a KernelModule to read/write data with PPC kernel permissions and a FunctionPatcherModule which allows you to easily patch Cafe OS functions.</p>

<h3 id="enhance-the-console-with-plugins">Enhance the console with plugins</h3>
<p>One of the most important Aroma Modules is the backend of the Wii U Plugin System. This is an evolution of the original Plugin System which I started to work on in early 2018. The Aroma port is way more stable (e.g. plugins now have their own heap instead of stealing memory from games) and plugins can be (re)-loaded at runtime, speeding up development.</p>

<p>Plugins are a very flexible way to improve the features of the console. For example, I have already worked on  plugins which allow you do to the following things:</p>
<ul>
  <li>Run homebrew directly from the Wii U Menu.</li>
  <li>Always run a FTP server in the background to access the filesystem.</li>
  <li>Pair gamepads and boot games from other regions.</li>
  <li>Launch homebrew/plugins at any time via the network (wiiload).</li>
  <li>Debug games and your homebrew with the help of a port of Kinnay’s Wii-U-Debugger.</li>
  <li>Mod your games by redirecting file accesses to your SD card (SDCafiine).</li>
  <li>Take screenshots everywhere and save them to the SD card.</li>
  <li>Enable logging via a USB Serial adapter on retail consoles with full support of the cos shell.</li>
</ul>

<p>All of these plugins will release over the next days and weeks. At the moment there is no documentation for the new version of the Plugin System. If you need any help with the development of your plugin, please join the <a href="https://discord.com/invite/bZ2rep2">Aroma Discord</a>.</p>

<h3 id="loading-homebrew-from-the-wii-u-menu--wuhb-wii-u-homebrew-bundle">Loading homebrew from the Wii U Menu / WUHB (Wii U Homebrew Bundle)</h3>

<p>This feature has been teased and discussed quite a lot already. With Aroma the way of loading homebrew will change. Previously it was loaded by a dedicated homebrew launcher, which loaded the executable in the memory and then ran it (in the case of a <code class="language-plaintext highlighter-rouge">.rpx</code> it’s a bit more complicated though). Now with the latest version of Mocha it’s really easy and clean to run homebrew with just a few lines of code. Instead of having to rely on the homebrew launcher, we can now explore options.</p>

<p>In a time where a forwarder channel gets created for every single homebrew, it’s an obvious choice to support this form of loading homebrew. Aroma will provide a plugin, which scans the <code class="language-plaintext highlighter-rouge">.rpx</code> and <code class="language-plaintext highlighter-rouge">.wuhb</code> files on your SD card and display them on your Wii U Menu. Thus, you would be able to launch homebrew from the home menu, <strong>without</strong> actually installing anything!</p>

<p>This is where WUHB, the <strong>W</strong>ii <strong>U</strong> <strong>H</strong>omebrew <strong>B</strong>undle format, comes into play. It allows homebrew applications together with additional data to be stored in a single file. This simplifies distribution and installation. Besides the executable (<code class="language-plaintext highlighter-rouge">.rpx</code>), a WUHB file embeds meta information (splash screen, icon, name of application/author) and can hold up to 4GiB of additional files. These additional files can be accessed via <code class="language-plaintext highlighter-rouge">/vol/content</code> like a “real” channel. The homebrew toolchain <a href="https://github.com/devkitPro/wut">wut</a> has built-in support for creating <code class="language-plaintext highlighter-rouge">.wuhb</code> files, please take a look at the wut examples.</p>

<p>At the time of writing this, it will <strong>only</strong> be possible to load homebrew directly from the Wii U Menu. Creating a homebrew launcher alternative would be possible, but I decided to not spend any time on that. Parsing the metadata from a <code class="language-plaintext highlighter-rouge">.wuhb</code> and launching a <code class="language-plaintext highlighter-rouge">.rpx</code>/<code class="language-plaintext highlighter-rouge">.wuhb</code> is really straight forward, so if anybody wants to create a “modern” homebrew launcher and needs assistance, let me know on the <a href="https://discord.com/invite/bZ2rep2">Aroma Discord</a>.</p>

<p><strong>Note 1:</strong><code class="language-plaintext highlighter-rouge">.elf</code> homebrew are not and will never be supported by Aroma due to technical limitations. To continue using these homebrew apps, you need to launch into <a href="https://github.com/wiiu-env/Tiramisu">Tiramisu</a>.
<strong>Note 2:</strong> Not all <code class="language-plaintext highlighter-rouge">.rpx</code> files will be compatible out of the box. Make sure the application doesn’t launch its own exploits and implements the ProcUI loop properly. If you have trouble with this please join the <a href="https://discord.com/invite/bZ2rep2">Aroma Discord</a>.</p>

<h2 id="where-can-i-get-aroma">Where can I get Aroma?!?!</h2>

<p>Back in April 2021 I made a private beta of Aroma. A beta which was leaked and a lot of the beta testers never gave any form of feedback. This is why this new beta will be public now. It doesn’t really make a difference anyway :)</p>

<p>The public beta Aroma can be downloaded <a href="https://aroma.foryour.cafe/">here</a>. When this blogpost gets released, not every single plugin I mentioned will be available, but I’ll try to add them as soon as I can.</p>

<p>Tiramisu and Aroma share the same EnvironmentLoader. If you’re already running Tiramisu, all you need to do is download new files, extract them to your SD Card and boot into the Aroma Environment. If you don’t have a way to run the EnvironmentLoader yet, I would recommend following the <a href="https://wiiu.hacks.guide/#/">Tiramisu guides</a> and install Aroma on top.</p>

<h2 id="thanks">Thanks</h2>
<p>Special thanks to dimok798, marcan, smealum, plutoo, yellows8, naehrwert, derrek, Marionumber1, TheKit, Hykem, Relys, Mathew_Wi, FIX94, hexkyz, exjam and every other person who discovered the exploits, documented the hardware/software and implemented the first homebrew ecosystem. Without the work of these people, I would never have been able to implement any part of Aroma.</p>

<p>But I’ve also met a lot of other talented people over the years. Aroma would not be Aroma if these people didn’t exist: Thanks (in no particular order) GaryOderNichts, quarky, rw-r-r-0644, vgmoose, exjam, Crementif, fincs, Wintermute, pwsincd, Koopa, Kinnay, jam1garner, Lazr and many more.</p>

<p>Thanks for helping me implement Aroma, thanks for your contributions and for not blocking me when I lost my mind while fixing a memory corruption for 14 months.</p>

<h2 id="links">Links</h2>

<ul>
  <li><a href="https://aroma.foryour.cafe/">Download Aroma</a></li>
  <li><a href="https://wiiu.hacks.guide/#/">Wii U Hacking Guide</a></li>
  <li><a href="https://github.com/wiiu-env/EnvironmentLoader">EnvironmentLoader</a></li>
  <li><a href="https://github.com/wiiu-env/Aroma">Aroma Environment</a></li>
</ul>]]></content><author><name></name></author><category term="homebrew" /><summary type="html"><![CDATA[In the past few years I have worked on improving the homebrew experience for users and developers on the Wii U. What started as “Would be cool to run 2 homebrews at the same time, let’s try to make a plugin system”, turned into “I want to understand existing exploits”, and then “coldbooting into plugins would be cool” turned into discovering a new major exploit (FailST) and basically rewriting every bit of homebrew I was interested in. Over time, the scope kept growing and growing and it was getting hard to actually finish it. In the meantime I released some parts of it together with Tiramisu, but at the time of writing this blog post there are still 25 private repositories related to Aroma.]]></summary></entry><entry><title type="html">Tiramisu</title><link href="https://maschell.github.io/homebrew/2021/12/31/tiramisu.html" rel="alternate" type="text/html" title="Tiramisu" /><published>2021-12-31T13:00:00+00:00</published><updated>2021-12-31T13:00:00+00:00</updated><id>https://maschell.github.io/homebrew/2021/12/31/tiramisu</id><content type="html" xml:base="https://maschell.github.io/homebrew/2021/12/31/tiramisu.html"><![CDATA[<p>Tiramisu is <strong>not</strong> Aroma. Aroma will still take some time.</p>

<p>TL;DR: <a href="https://github.com/GaryOderNichts">GaryOderNichts</a> and I worked over the past few days on <a href="https://github.com/wiiu-env/Tiramisu">Tiramisu</a>, a homebrew environment to mimic a free haxchi/cbhc with some extra features.</p>

<h2 id="background">Background</h2>

<p>In my <a href="/homebrew/2020/12/02/failst.html">last blogpost</a> I talked about FailST, an exploit to bypass runtime signature checks for a title on the Wii U. My initial plan was to release it together with my upcoming homebrew environment, because without a payload it wouldn’t be really useful. Unfortunately FailST got leaked before Aroma (name for the upcoming homebrew environment) actually was finished. Since then FailST was floating around without anyone actually using it, giving Nintendo plenty of time to patch it, which is… really stupid. Luckily they didn’t fix it (yet).</p>

<p>However: At the end of this blogpost I promised to release a user-friendly installer “as soon as possible” to be a free haxchi alternative. Now, over a year later, it’s finally time to release it with some extra bits. 🎉</p>

<h2 id="why-did-the-release-take-over-a-year">Why did the release take over a year?</h2>
<p>Like I’ve already mentioned before, FailST is only useful with a payload that’s taking advantage of it. Back in early 2019 I introduced the concept of abstracting payloads into a separate file (<code class="language-plaintext highlighter-rouge">payload.elf</code>) which every exploit could load in a standardized way to allow a constant experience between all entrypoints. This also allows easy updating, because all you need to do, is replace a file on the sd card. So it only makes sense to use FailST to turn an application into a generic <code class="language-plaintext highlighter-rouge">payload.elf</code> loader too.</p>

<p>The “problem” with this is that you still need a <code class="language-plaintext highlighter-rouge">payload.elf</code> that does any of the cool things for you. Until today there were only a handful of <code class="language-plaintext highlighter-rouge">payload.elf</code>-implementations, for example the <a href="https://github.com/wiiu-env/homebrew_launcher_installer">homebrew launcher installer</a> everyone is using for the browser exploit. But this is really only injecting the Homebrew Launcher into the Mii Maker, not doing anything else.</p>

<p>I decided to focus on finishing Aroma (didn’t turn out well 🙈) instead of creating a <code class="language-plaintext highlighter-rouge">payload.elf</code> that will actually match the feature set of hachxi/cbhc. At the time I didn’t think Aroma would actually take so much longer and I wanted to avoid releasing something that will be obsolete 2 weeks later because of an actual Aroma release.</p>

<blockquote class="twitter-tweet"><p lang="en" dir="ltr">I didn&#39;t work on Aroma for over 2 1/2 months now and at the moment don&#39;t have any motivation to continue in the near future. Therefore I decided to at least make some aroma-unspecific repositorys public.</p>&mdash; MaschellDev (@MaschellDev) <a href="https://twitter.com/MaschellDev/status/1410955174324080641?ref_src=twsrc%5Etfw">July 2, 2021</a></blockquote>
<script async="" src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

<p>But in early july I realized that Aroma won’t happen anytime soon, so figured it might be useful to make some repositories related to <code class="language-plaintext highlighter-rouge">payload.elf</code>-loading public. This included <a href="https://github.com/wiiu-env/PayloadFromRPX">PayloadFromRPX</a>, a custom .rpx that could chainload a <code class="language-plaintext highlighter-rouge">payload.rpx</code> which makes it perfect to inject into a title via FailST.</p>

<p>With this “only” a user-friendly (and safe) installer was missing and the public would have a free and generic entrypoint with built-in (and well tested) coldboot capabilities.</p>

<h2 id="environments">Environments?!?!</h2>

<p>Together with Tiramisu an <a href="https://github.com/wiiu-env/EnvironmentLoader">EnvironmentLoader</a> will be released, which is a payload that allows you to load into different environments. An environment is a collection of one-time executables (setup modules) that’ll run in a specific order.</p>

<p>Because an environment is just a collection of files, it’s really easy to customize and extend it. All you need to do is add/remove files on your sd card.</p>

<h2 id="tiramisu-environment">Tiramisu Environment</h2>
<p><a href="https://github.com/wiiu-env/Tiramisu">Tiramisu</a> is an environment for the <a href="https://github.com/wiiu-env/EnvironmentLoader">EnvironmentLoader</a> which has the following (base) features:</p>
<ul>
  <li>CFW based on mocha with slighty more features</li>
  <li>Homebrew launcher injected into Mii Maker</li>
  <li>Autoboot Menu based on CBHC</li>
  <li>Full quick boot menu support of the Gamepad</li>
</ul>

<p>It’s possible to extend this features set by adding new setup modules. For example <a href="https://github.com/GaryOderNichts/Bloopair">Bloopair</a> has been ported to be a setup module, which allows coldbooting into Bloopair 🚀!</p>

<h2 id="payloadloader-installer-environment">PayloadLoader Installer Environment</h2>
<p>The other environment that will be released together with Tiramisu is an environment to launch the PayloadLoader Installer.</p>

<p>The PayloadLoader Installer is a user-friendly and safe installer that injects <a href="https://github.com/wiiu-env/PayloadFromRPX">PayloadFromRPX</a> into the Health and Safety Application. It also has an option to activate coldbooting into it.</p>

<p>This allows us to coldboot into the <a href="https://github.com/wiiu-env/EnvironmentLoader">EnvironmentLoader</a> and thus into Tiramisu (or any other environment)</p>

<h2 id="the-future-of-aroma">The future of Aroma</h2>
<p>I’ll continue to work on Aroma and have already ported it to be compatible with the <a href="EnvironmentLoader">EnvironmentLoader</a>. This means migrating from Tiramisu to Aroma will be done by putting new files on the sd card and change the default environment in the EnvironmentLoader.</p>

<p>I really hope to get Aroma done quickly because it has some really cool features that are not possible with legacy homebrew. I’ll keep you updated!</p>

<h2 id="links">Links</h2>

<ul>
  <li><a href="https://wiiu.hacks.guide/#/">Wii U Hacking Guide</a></li>
  <li><a href="https://github.com/wiiu-env/EnvironmentLoader">EnvironmentLoader</a></li>
  <li><a href="https://github.com/wiiu-env/Tiramisu">Tiramisu Environment</a></li>
  <li><a href="https://github.com/wiiu-env/PayloadLoaderInstallerEnvironment">PayloadLoader Installer Environment</a></li>
</ul>]]></content><author><name></name></author><category term="homebrew" /><summary type="html"><![CDATA[Tiramisu is not Aroma. Aroma will still take some time.]]></summary></entry><entry><title type="html">FailST aka contenthax 2.0</title><link href="https://maschell.github.io/homebrew/2020/12/02/failst.html" rel="alternate" type="text/html" title="FailST aka contenthax 2.0" /><published>2020-12-02T18:00:00+00:00</published><updated>2020-12-02T18:00:00+00:00</updated><id>https://maschell.github.io/homebrew/2020/12/02/failst</id><content type="html" xml:base="https://maschell.github.io/homebrew/2020/12/02/failst.html"><![CDATA[<p>In this blog post I want to tell the story about how I found <em>FailST</em>, a way to bypass runtime signature checks for certain titles on the Wii U.</p>

<p>Back in April I started to rewrite some parts of <a href="https://github.com/Maschell/JNUSLib">JNUSLib</a> and noticed that some flags in the <a href="https://wiiubrew.org/wiki/FST">Filesystem Table</a> were still undocumented. At this point in time I wouldn’t have thought digging into this would lead into a new exploit for the Wii U.</p>

<p>Since the conception of this vulnerability I have shared this with other developers, including Rambo6Glaz/NexoCube, who leaked it. I didn’t intend this to be public until the tools and guides are ready, polished and well tested. It was meant to be released with my new <a href="https://maschell.github.io/homebrew/2019/11/20/new-environment-part1.html">upcoming homebrew environment</a> (including full coldboot features). I will see to that this environment is finished, but for now, here are the details of how the vulnerability works.</p>

<h1 id="the-wii-u-filesystemtable-fst">The Wii U <strong>F</strong>ile<strong>S</strong>ystem<strong>T</strong>able (FST)</h1>

<p>As the name may suggest, the exploit uses a vulnerability in the handling of the FST. First, I want to give you an overview about how the FST works.</p>

<p>A Wii U game disc is divided into multiple partitions. At the bare minimum, they have one <code class="language-plaintext highlighter-rouge">SI</code> (SecurityInformation?) and one <code class="language-plaintext highlighter-rouge">GM</code> (Game?) partition. The <code class="language-plaintext highlighter-rouge">SI</code> partition holds the TitleMetaData (TMD) and Ticket for each of the <code class="language-plaintext highlighter-rouge">GM</code> partition(s). Some games have some additional partitions which contain, for example, updates or DLC.</p>

<p>In all discs I have seen so far, each <code class="language-plaintext highlighter-rouge">GM</code> partition consists of exactly one <code class="language-plaintext highlighter-rouge">volume</code>, which starts with a <code class="language-plaintext highlighter-rouge">VolumeHeader</code>. This header holds information like the address of the FST, a list of <code class="language-plaintext highlighter-rouge">h3-hashes</code> or the sector size.</p>

<p>Each volume is divided into multiple sections, the first of which is always the FST. The FST holds information about the actual game files like names, sizes and where to find them on the disc. For each section the FST includes a small entry to describe the section. Beside the offset, size, owner ID and group ID it also holds one previously unknown field which turns out to be the hash mode. Sections can have two possible hash modes.</p>

<p>Mode 1 hashes the whole section, and saves the hash to the <a href="https://wiiubrew.org/wiki/Title_metadata">TMD</a>. Each section with hash mode 1 only holds one file, typically all files from the <code class="language-plaintext highlighter-rouge">/code</code> folder, including the binary. The whole file/section needs to be decrypted/hashed in order to verify it.</p>

<p>Mode 2 splits up the section into chunks of 0x10000 bytes each. Each chunk starts with 0x400 bytes of hashes and 0xFC00 bytes of actual data. A hash tree is built up and the final hash-layer (h3) of each section is saved in the volume header. The hash of each of the h3-hashes is stored in the TMD. This way it’s possible to access and verfiy the section in chunks of 0xFC00 bytes, so random access is possible without decrypting and hashing the whole section. Sections with hash mode 2 often hold multiple files and can get up to 4GiB in size.</p>

<p>After the section entries, the actual file/directory entries follow. A directory entry stores its parent entry and its children. A file entry stores its size and relative offset inside the section, together with a reference to a section entry.</p>

<p>If a game requests a file and is running from a disc, the Wii U looks through the FST for the corresponding file entry and gets the offset/size and section information. The integrity of the file is checked based on the hash mode of the section.</p>

<h1 id="what-happens-when-you-install-a-game-from-the-eshop">What happens when you install a game from the eShop</h1>
<p>Games downloaded from the eShop are in a slightly different format, but contain exactly the same data. It’s possible to restore this <code class="language-plaintext highlighter-rouge">installable</code> format from an actual disc. Instead of having multiple partitions, the files from the SI partition are shared directly (<code class="language-plaintext highlighter-rouge">title.tmd</code> and <code class="language-plaintext highlighter-rouge">title.tik</code>),  while the GM partition is shared by saving each section as a <code class="language-plaintext highlighter-rouge">.app</code> file. Depending on the hash mode of the section, additonal <code class="language-plaintext highlighter-rouge">.h3</code> files are distributed for sections with hash mode 2. While installing these files, all game files can be verified exactly the same as a disc. After the installation it’s a bit different though.</p>

<p>The Wii U does <strong>not</strong> store the <code class="language-plaintext highlighter-rouge">.h3</code> files (nor the h0-h2 hashes), which makes verifying the integrity of files from section with hash mode 2 impossible. This is commonly known as <code class="language-plaintext highlighter-rouge">contenthax</code>. Effectively, all files from a section with hash mode 2 can be modified <strong>after</strong> installing. <code class="language-plaintext highlighter-rouge">haxchi</code> is exploiting this by using a malformed Nintendo DS rom to exploit the emulator that ships with virtual console games.</p>

<p>Modifying files from sections with hash mode 1 is not possible. Their hash is still saved inside the TMD, which is installed together with the actual game files and the FST. At runtime these hashes may be checked.</p>

<h1 id="search-for-interesting-titles">Search for interesting titles</h1>
<p>In theory <code class="language-plaintext highlighter-rouge">contenthax</code> is not limited to the <code class="language-plaintext highlighter-rouge">/content</code> or <code class="language-plaintext highlighter-rouge">/meta</code> folder but can be used for all files that are in a section with hash mode 2. I quickly fired up JNUSLib and searched for titles that may accidentally have hash mode 2 for files from the <code class="language-plaintext highlighter-rouge">/code</code> folder. I stumbled across some titles where the <code class="language-plaintext highlighter-rouge">app.xml</code> and <code class="language-plaintext highlighter-rouge">cos.xml</code> were in a hash mode 2 section. This is quite a big deal because the <code class="language-plaintext highlighter-rouge">cos.xml</code> defines the filename of the <code class="language-plaintext highlighter-rouge">.rpx</code> and the permissions of the titles. 
Beside giving us full permissions to the SD card and the codegen area, I tried to launch a different <code class="language-plaintext highlighter-rouge">.rpx</code>, one that is not verified during boot. This idea didn’t work, because the new <code class="language-plaintext highlighter-rouge">.rpx</code> is not part of the FST. We also can’t add it, because the FST is signed and checked at runtime…</p>

<h1 id="failst">FailST</h1>
<p>To recap, when installing a game, the FST is copied as <code class="language-plaintext highlighter-rouge">title.fst</code> into the <code class="language-plaintext highlighter-rouge">/code</code> folder. A hash of that file is inside the TMD, so it can be checked when the game is starting up. At least, I always <em>thought</em> that the FST is checked during runtime. I didn’t even try to modify the <code class="language-plaintext highlighter-rouge">title.fst</code> because I was 99.999% sure that this would cause the game not to boot due to the FST hash not matching with the hash in the TMD.</p>

<p>One night though, <a href="https://github.com/rw-r-r-0644">rw-r-r-0644</a> asked me what exactly is checking the FST, so I decided to test it by modifying it and seeing if the game still booted.</p>

<center><img src="/res/failst_chat.png" width="400" /></center>

<p>And it did.</p>

<p>So for installed titles we can now modify the <code class="language-plaintext highlighter-rouge">title.fst</code>. What happens if we modify each file entry inside the FST to point to a section with hash mode 2? 
In theory then it should be possible to modify <strong>all</strong> files, including the binaries.</p>

<p>I tried to replace the binary with homebrew and it worked again :)</p>

<p>sha256(“FailFST aka contenthax 2.0”) = <a href="https://twitter.com/MaschellDev/status/1252746213524492288">c5dad5d79a554bc2759ca01b279d05ce1bb5e7eeaf800e01c6e56091cefdca72</a></p>

<h1 id="faq">FAQ</h1>

<h3 id="what-will-this-allow-us-to-do">What will this allow us to do?</h3>
<p>Bypass the runtime checks of files for all titles that have at least one section in the FST with hash mode 2. This includes replacing the binary of a title and modifying the cos.xml (which allows us to give it more permissions).</p>

<h3 id="what-will-this-not-allows-us">What will this not allows us?</h3>
<p>This <strong>won’t</strong> allow us to modify “code-only” titles like OSv10 or cafe2wii (<code class="language-plaintext highlighter-rouge">fw.img</code> and <code class="language-plaintext highlighter-rouge">kernel.img</code> are still signed separately anyway).</p>

<h3 id="can-this-be-patched">Can this be patched?</h3>
<p>Yes, very easily.</p>

<h3 id="why-does-this-work">Why does this work?</h3>
<p>It’s explained above. 
TL;DR: the FST is used to determine if a file should be hash checked at launch but is not checked at runtime itself.</p>

<h1 id="whats-next">What’s next?</h1>
<p>Like I mentioned earlier this wasn’t meant to be released just yet. Without a proper installer and something actually using it, there is no real gain for the end user.</p>

<p>The plan is to release a safe installer as soon as possible which will turn the <code class="language-plaintext highlighter-rouge">Health and Safety</code> app into a generic <code class="language-plaintext highlighter-rouge">payload.elf</code>-loader. This way the people will have a free haxchi-alternative. Stay tuned for more information. Until then please don’t play around with this unless you know what you’re doing.</p>]]></content><author><name></name></author><category term="homebrew" /><summary type="html"><![CDATA[In this blog post I want to tell the story about how I found FailST, a way to bypass runtime signature checks for certain titles on the Wii U.]]></summary></entry><entry><title type="html">The day I bought 8 “broken” Wii Us</title><link href="https://maschell.github.io/other/2020/11/21/bought-8-consoles.html" rel="alternate" type="text/html" title="The day I bought 8 “broken” Wii Us" /><published>2020-11-21T16:45:00+00:00</published><updated>2020-11-21T16:45:00+00:00</updated><id>https://maschell.github.io/other/2020/11/21/bought-8-consoles</id><content type="html" xml:base="https://maschell.github.io/other/2020/11/21/bought-8-consoles.html"><![CDATA[<p>Sometimes, when I get bored, I scroll through ebay looking for newly listed “buy it now”
 consoles to see if there is something interesting/cheap. Once I came across a box with
 three untested PS1 consoles and ten controllers for 30€. A few years ago my PS1 broke a
 few years ago, so I gave it a try. Even if only one of the three consoles and one controller worked,
 it would have been worth it. When the box full of PS1 consoles and controllers arrived a
 few days later, I tested them all. It turned out that one console couldn’t read any discs
 and two controllers were broken. But I still had two consoles (+ cables) and more controllers
 than I would ever need for 30€. It even included a multitap, so a few days later
 I played Micro Machines for the first time with 4 players on a Playstation!</p>

<p><strong>Update 2024-04-09: For quite some time there a now tools that can be used to <a href="https://github.com/GaryOderNichts/recovery_menu">bypass parental controls via raspberry pi pico</a> or <a href="https://gbatemp.net/threads/ultimate-wii-u-troubleshooting-guide-system-memory-error-160-0103-stuck-wii-u-screen-stuck-factory-reset-black-screen-after-stuck-update.642339/">fix consoles with the 160-0103 system errors</a>.</strong></p>

<h2 id="why-even-bother-to-look-for-broken-consoles">Why even bother to look for broken consoles?</h2>
<p>Since then, I also tend to look specifically for console-related items that have the condition
 <code class="language-plaintext highlighter-rouge">for parts or not working</code>. Even some “broken” consoles can be useful. For my Wii U-related
 coding, I don’t care if the disc drive or HDMI port is broken. I almost never put a disc in
 the console, and 99% of the time I just look at the gamepad screen while coding anyway. Worst
 case scenario, I could use the old CRT I have on my desk for a few casual rounds of NES Tetris.
 Some consoles may be broken for “normal” people, but still useful for me.</p>

<h2 id="buying-8-wii-us">Buying 8 Wii Us…</h2>
<p>A few days ago I finally found a really interesting offer on ebay. A total of 8 “broken” Wii U 
consoles (no cables, no gamepad, but all are the 32GB version) for 119€. Normally you could 
easily spend 50€ for a (working) replacement console in reasonable condition. The listing even 
had some information about the condition of the consoles: (freely translated)</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>2x HDMI port defect
1x No image
3x locked( probably account data and password not known)
1x non-European sales version
1x Defect
</code></pre></div></div>
<p>All of them except the last one sounded like something that <em>could</em> be possible to fix or use.
 Like I said earlier, as long I as can somehow connect a gamepad, I don’t care if the video 
 output is broken. The “locked” consoles sounded like some parental controls are applied, 
 but there is an <a href="https://mkey.salthax.org/">online tool</a> to reset the parental controls, 
 so they also shouldn’t be an issue.</p>

<p><strong>Update 2024-04-09: There are <a href="https://github.com/GaryOderNichts/recovery_menu">new ways</a> to reset the parental controls by using a raspberry pi pico.</strong></p>

<p>In theory only 3 of the 8 console would need to be usable 
 for me until I wouldn’t consider it a waste of money. Without spending too much time on 
 thinking what I even want to do with 8 consoles, I pressed the “Buy it now” button.</p>

<h2 id="36-hours-later">36 hours later</h2>

<p>Just 36 hours later, a large box with 8 Wii U consoles arrived. They all seemed to be in 
pretty good condition (<del>much better than my two main consoles</del>). I stacked them on a big 
“Wii U Tower” and took the picture before testing them one by one.</p>

<blockquote class="twitter-tweet"><p lang="en" dir="ltr">I have no idea what I am doing
 here. <br /><img src="/res/consoles.jpg" width="600" align="middle" /></p>&mdash; MaschellDev
 (@MaschellDev) <a href="https://twitter.com/MaschellDev/status/1329744651889348608?ref_src=twsrc%5Etfw">
 November 20, 2020</a></blockquote>
<script async="" src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

<h4 id="console-1">Console 1</h4>
<p>At first I was interested in the “non-European sales version”. I quickly identified 
the console and the console and gave it a try. It turned out to be a US console, so 
I plugged in my EU gamepad. I always thought the gamepads were region locked, but to 
my surprise I was able to go through the entire  through the entire console setup process. 
The console then restarted and tried to  to update my gamepad - which failed because the 
gamepad region was wrong. It’s  possible to get into the Wii U menu without the gamepad 
(if you are using a Wiimote or  Pro Controller), but most apps won’t launch without the gamepad. 
For quite some time I tried to trick the console into accepting my EU gamepad, 
but to no avail. For  now I am stuck until I get a US gamepad. I would still consider it a 
“success” since this console works. If I really want to use it, I can use <a href="https://github.com/rolandoislas/drc-sim">drc-sim</a> 
to emulate a gamepad with a PC.</p>

<h4 id="console-2">Console 2</h4>
<p>I then picked up the next console. This seemed to be one of the “locked” consoles. When I started the 
console, it presented me with the login screen with a password-protected account. It’s possible to create 
a new account, but it’s locked by the parent controls. Even if I knew the password for the account (NNID), 
I couldn’t log in because the console was offline. To set up the Internet connection, I also needed the PIN 
to bypass the parental controls.</p>

<p>Earlier in the post, I mentioned a website to help reset the parental controls. But I couldn’t use it: In order to reset it,
you need the ‘Inquiry Number’, which can only be accessed through the Parental Controls app (which can only be accessed from
the Wii U Menu). So my only option to get into the Wii U menu was to guess the parental control PIN and create a new account.</p>

<p><strong>Update 2024-04-09: There are <a href="https://github.com/GaryOderNichts/recovery_menu">new ways</a> to reset the parental controls by using a raspberry pi pico.</strong></p>

<p>Luckily the PIN is only 4 digits, in the worst case I have to try 9999 combinations. Annoying, but with enough 
time it can be solved. I gave it a few tries, but moved on to the other consoles. When I came back later, 
I systematically tried all birthdates (this reduced the number of possible PINs to 366!) and after ~30 minutes and 
~250 tries I was in. Apparently the previous owner’s birthdate is November 26th :)</p>

<p>Knowing the PIN, I was able to create a new account and remove the parental controls. Everything else seemed to work 
fine. Another saved console!</p>
<h4 id="console-3">Console 3</h4>

<p>This console looked very promising at first. I turned it on and it didn’t lock up, but after a few seconds of opening 
the Wii U menu, I got an error code of <code class="language-plaintext highlighter-rouge">160-0103</code>. I tried a few more times, but the console kept freezing or giving 
me an error code. Most likely the emmc has died. RIP console 3 =(</p>

<p><strong>Update 2024-04-09: There are now <a href="https://gbatemp.net/threads/ultimate-wii-u-troubleshooting-guide-system-memory-error-160-0103-stuck-wii-u-screen-stuck-factory-reset-black-screen-after-stuck-update.642339/">ways to recover</a> the consoles with these error.</strong></p>

<h4 id="console-4">Console 4</h4>

<p>The next console didn’t output anything over HDMI, but when I tried a composite cable, it worked! I was able to pair
 the gamepad and change the output back to HDMI. This console also seemed to work fine. So far, 3 out of 4 consoles
 working! I have reached my goal of three saved consoles :)</p>

<h4 id="console-5">Console 5</h4>

<p>This console just worked. Well. Maybe this console will have some other problems after playing for a few hours, 
but so far it looks like a normal working Wii U! 4 out of 5!</p>

<h4 id="console-6">Console 6</h4>

<p>Another locked console like console 2. This time it only took me a few tries because the PIN was 0505, which seemed 
like an obvious pattern to try. Probably the old console owner’s birthday was May 5th :D 5 out of 6!</p>

<h4 id="console-7">Console 7</h4>

<p>The next console didn’t output anything over HDMI. I tried the same “composite” trick as on console 4, but still had no 
success. Normally having no video output is fine as long as you can use the gamepad. But to connect the gamepad to the 
console, you have to enter a PIN that is displayed on the TV.  This reminded me of console 6 and 2, but this time I had to guess the
 connection PIN. Bruteforcing this was a bit more painful though, as each attempt took about 10 seconds. The other problem was that 
 the sync dialog closes after some time and I have no way to check if the sync dialog is even open. Worst case, I try to connect, but the console doesn’t even wait for a connection.</p>

<p><strong>Update 2024-04-09: It is <a href="https://github.com/GaryOderNichts/recovery_menu/issues/19">possible</a> to obtain the PIN if you have a raspberry pi pico.</strong></p>

<p>I mentioned <a href="https://github.com/rolandoislas/drc-sim">drc-sim</a> as a possible solution for console 1. To emulate a gamepad, 
you have to go through the same connection process with the PIN. I thought I might be able to automate the bruteforcing, 
but in the end I spent about 5 hours fighting with several ubuntu vms without success. I went back to manual bruteforcing.</p>

<p>After testing ~30 PINs, I remembered that some consoles have a key combination to reset the video mode. Unfortunately, the 
Wii U doesn’t seem to have such a feature, but I came across a random Youtube video that showed how to fix a “no picture on 
TV” problem. Since they had already synced a gamepad, they suggested trying different video output modes until it worked.</p>

<p>That was when I realized that the Wii U has more output options than just HDMI and composite. It also has component output.
 The problem is that I don’t have a component cable to test this. But what I do have is an “AV Multi Out” to HDMI adapter 
 for my Wii, and I gave it a try. The first monitor I tried showed an “invalid hdmi signal” error, but on my slightly more
 expensive one I finally saw the Wii U menu! I checked the settings and apparently the console was set to non-HDMI and 576i.
 After setting it to HDMI and 1080p, the console 
worked perfectly! 6 out of 7!</p>

<h4 id="console-8">Console 8</h4>

<p>The last console had exactly the same problem as console 7. After connecting it using the “AV Multi Out” to 
HDMI adapter, I was able to change the video output to HDMI. Everything seemed to work fine. 7 out of 8 consoles work!</p>

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

<p>In the end, it all worked out much better than I expected. I was able to “rescue” 7 of the
 8 consoles without even opening any of them. The description of the consoles looked very 
 promising and I was very lucky with the outcome. This could have easily been a waste of 119€, 
 ending up with a huge pile of broken Wii Us. <del>Now it was a waste of 119€ with a huge pile of 
pile of working Wii Us.</del></p>

<p>If you’re looking for a “broken” console, here are some tips:</p>
<ul>
  <li>If you enjoy entering 9999 possible PINs, buy a “locked” console.</li>
  <li>In my experience, the “console has no video output” problems are not a real problem, you just need the right 
just need the right cables and monitors to “fix” them.</li>
  <li>Be prepared to end up with a pile of electronic junk.</li>
  <li>Only spend the amount of money you are comfortable with losing.</li>
  <li>Remember that you also need a gamepad (which is even more expensive than the consoles).</li>
</ul>

<p>I even found another “no video ouput” console on ebay for &lt;20€ that sounded very promising, 
but I decided not to buy it even though it probably works fine. I don’t even know what to do
 with the 9 working consoles I currently own.</p>]]></content><author><name></name></author><category term="other" /><summary type="html"><![CDATA[Sometimes, when I get bored, I scroll through ebay looking for newly listed “buy it now” consoles to see if there is something interesting/cheap. Once I came across a box with three untested PS1 consoles and ten controllers for 30€. A few years ago my PS1 broke a few years ago, so I gave it a try. Even if only one of the three consoles and one controller worked, it would have been worth it. When the box full of PS1 consoles and controllers arrived a few days later, I tested them all. It turned out that one console couldn’t read any discs and two controllers were broken. But I still had two consoles (+ cables) and more controllers than I would ever need for 30€. It even included a multitap, so a few days later I played Micro Machines for the first time with 4 players on a Playstation! Update 2024-04-09: For quite some time there a now tools that can be used to bypass parental controls via raspberry pi pico or fix consoles with the 160-0103 system errors.]]></summary></entry><entry><title type="html">Mario Kart 8 as a primary exploit for homebrew on the Wii U</title><link href="https://maschell.github.io/homebrew/2020/02/11/mk8-exploit.html" rel="alternate" type="text/html" title="Mario Kart 8 as a primary exploit for homebrew on the Wii U" /><published>2020-02-11T14:45:00+00:00</published><updated>2020-02-11T14:45:00+00:00</updated><id>https://maschell.github.io/homebrew/2020/02/11/mk8-exploit</id><content type="html" xml:base="https://maschell.github.io/homebrew/2020/02/11/mk8-exploit.html"><![CDATA[<p>This blog post should give you a rough insight into the implementation of the
Mario Kart 8 exploit to be a primary entrypoint for homebrew.
Thereby, both the technical details and the problems that came up during
development should be discussed. This time I also want to tell you about the
ideas that <strong>didn’t</strong> work, instead of just the one that works fine.</p>

<h1 id="the-beginning">The beginning</h1>
<p>At the beginning of this year <a href="https://github.com/NexoDevelopment">Rambo6Glaz</a> made 
<a href="https://github.com/NexoDevelopment/gx2sploit">just another</a> implementation of 
the GX2, which uses a different a different PM4 packet to manipulate the kernel 
heap. This new implementation brought back the idea of implementing a kernel 
exploit inside a rop chain.</p>

<p>Beside the <a href="https://github.com/wiiu-env/JsTypeHax">browser exploit</a> and 
<a href="https://github.com/wiiu-env/haxchi">haxchi</a> there are currently three other 
userland exploits.</p>

<ul>
  <li><a href="https://github.com/jam1garner/ROBChain">ROBChain</a>, an exploit in the main
 character scripting of Super Smash Brothers Wii U</li>
  <li>an <a href="https://github.com/Kinnay/Mario-Kart-8-Exploit">exploit</a> in the network
 protocol of Mario Kart 8</li>
  <li>a <a href="https://github.com/Kinnay/DKCTF-Save-Exploit/">savegame exploit</a> in
 Donkey Kong Tropical Freeze.</li>
</ul>

<p>But there is a problem with all of these exploits: None of them has access to 
the JIT-area. This means no access to an area in memory which is
writeable and executable. This makes arbitrary code execution without a kernel 
exploit impossible.</p>

<p>Out of these exploits the Mario Kart 8 one is special. It can be run on a
previously unmodified console and could be a potential primary entrypoint
into the system. Because of this the focus went to the Mario Kart 8 exploit.</p>

<h1 id="exploiting-the-network-protocol-of-mario-kart-8">Exploiting the network protocol of Mario Kart 8</h1>
<p>Back in 2018 <a href="https://github.com/Kinnay">Kinnay</a> found a bug in the P2P
protocol of Mario Kart 8. He released a PoC which could crash the console of
someone who hosted a friend room displaying the message “rop chains are fun
:)”. 
This initial implementation allows a (remote!) rop chain execution with
maximum length of ~1000 bytes, more than enough to play around which different
payloads.</p>

<p>The <a href="https://github.com/Kinnay/Mario-Kart-8-Exploit">original repository</a>
has detailed information about the exact bug and exploitation. 
In summary it’s possible to achieve a 4 byte arbitrary write due to a bug in
parsing the “identification token”. That’s enough to manipulate a 
<a href="https://en.wikipedia.org/wiki/Virtual_method_table">vtable</a>, and
turn a call of <code class="language-plaintext highlighter-rouge">Md5Context::GetHashSize</code> into a memcpy to the stack,
effectively copying the content of another packet onto the stack, leading
to a rop chain execution.</p>

<h1 id="the-kernel-exploit-in-a-rop-chain---theory">The kernel exploit in a rop chain - theory</h1>
<p>In theory implementating the kernel exploit in a rop chain doesn’t sound that hard. From
the <a href="https://github.com/wiiu-env/wiiuhaxx_common">wiiuhaxx-common</a> repository we
already have rop gadgets we can re-use. This includes for example gadgets to
call a function or write a value to a arbitrary address in memory. Detailed
information about the kernel exploit can be found in 
<a href="/homebrew/2019/12/27/new-environment-part4.html">part 4</a> 
of my “homebrew environment” blog series, but here is a quick overview:</p>

<ol>
  <li>Place a fake heap entry into a specific address in memory</li>
  <li>Create a PM4 packet and send it to the GPU to override the “next id” on the
 kernel heap</li>
  <li>Register an <code class="language-plaintext highlighter-rouge">OSDriver</code> and hope it’s allocating memory using our fake heap 
 entry placed in step 1</li>
  <li>Manipulate the “SaveArea” pointer in the <code class="language-plaintext highlighter-rouge">OSDriver</code> struct (which is now in 
 userland memory) to point into the kernel data.</li>
  <li>Use the <code class="language-plaintext highlighter-rouge">OSDriver_CopyToSaveArea</code> and <code class="language-plaintext highlighter-rouge">OSDriver_CopyFromSaveArea</code> functions
 to get arbitrary read/write with kernel privileges.</li>
</ol>

<p>This doesn’t really seem that complicated. It’s just a few function calls and it
fits relatively easily into a 1000 byte rop chain. We also have the advantage that the 
address of the stack is consistent. This allows us to place data (like the fake 
heap entry or the pm4 packet) at the end of the rop chain and simply calculate 
their positions in memory beforehand. Rambo6Glaz talked about starting to
implement the kernel exploit in the Mario Kart 8 exploit, and I thought I
would give it a shot too. Using the existing gadgets and already knowing the
kernel exploit in detail made me think this would be rather trivial and it
would be done in maybe a few hours.</p>

<p>I started to play around with the exploit and tried to implement the kernel
exploit step by step. Sometimes I had random crashes and testing was quite
annoying. For each try you have restart the console, go online, open a friend
room and send the payload. Then maybe also read the crash log by restarting
again and firing up a CFW to access the crash log. In total each attempt took
like at least 2-3 minutes.</p>

<p>Fast forward a few days. After many hours of testing and trying I still had
nothing. But somehow this whole exploit was quite addicting, it started with one
simple idea and ended (or didn’t end) everyday with “just more one try”. At the
same time Rambo6Glaz was doing the same thing. Slowly but steady we got a better
understanding of what’s going on. Eventually we got a working memory write
using the kernel exploit, but something was still wrong. It turned out that
the exploit was indeed sometimes working (or at least partially working), but 
only in like 20% of the tries. This made testing even more annoying. Each
idea required at least 5 failed attempts to make sure the idea was wrong and
it wasn’t just the exploit randomly failing.</p>

<p>At this point we had collected some facts that helped us understand:</p>
<ul>
  <li>the kernel exploit did sometimes work, but only in rare cases</li>
  <li>the rop chain needed to have a specific length to be stable (otherwise you
 get really strange behaviour and crashes)</li>
  <li>the rop chain is running on core 2, but the main GX2 core is 1 (the
 kernel exploit expects to be run on the GX2 core…)</li>
</ul>

<p>For me personally a unstable exploit was enough, I just wanted to finish
this. Even if performing the exploit would require several attempt, I just
wanted to see it working <strong>once</strong>, so I can finally spent my time on other
projects.</p>

<p>Because of this I tried to split up the exploit into multiple rop chains which
need to be executed one after another. Fitting the kernel exploit in 1000
bytes is doable, but also bundling a real payload and copy/executing won’t
fit anymore. One challenge was to actually restart the game. But from reverse
engineering for <a href="https://github.com/Maschell/hid_to_vpad">HID to VPAD</a> I knew
there was a function to force opening the home menu (<code class="language-plaintext highlighter-rouge">OSSendAppSwitchRequest</code>),
and it indeed worked.</p>

<p>I also tried to improve the success rate of the kernel exploit by adding
some waiting. But every time I waited via <code class="language-plaintext highlighter-rouge">OSSleepTicks</code> or added a
<code class="language-plaintext highlighter-rouge">GX2DrawDone</code> the console crashed. Knowing the kernel exploit would work 
only in rare cases I tried to think of a 
solution to give the user feedback if the exploit was successful or had
failed. In a rop chain “code execution” is really limited, it’s only possible
to run existing chunk of code. Branches and loops are really hard (at least
I haven’t found a way yet to pull it off, I am not a rop chain expert though),
the only option I saw was to manipulate the rop chain itself. I placed a
<code class="language-plaintext highlighter-rouge">OSFatal</code> at the end of the rop chain to make the console crash, but overriding
it with a <code class="language-plaintext highlighter-rouge">OSExitThread</code> using the (hopefully) newly gained kernel write. This
way exiting would mean success and crashing would mean failure. I spent again
too much time on this but never really had anything working.</p>

<p>At this point more than a week and literally dozens of hours were already
wasted on this, without much progress. It was time to change the strategy.
Rambo6Glaz suggested to find a rop gadget to perform stack pivot to somehow have
the possibility to execute a bigger rop chain.</p>

<h2 id="rop-chain-basics">Rop chain basics</h2>
<p>Before working on this I’ve been working with rop chains, but I haven’t found
/written any rop gadgets myself. I wasn’t <strong>really</strong> understanding rop chains, I
was just using the “high level” functions from the <code class="language-plaintext highlighter-rouge">wiiuhaxx_common</code> repository,
so it was time to dig deeper and learn something new.</p>

<p>(If you already are familiar with rop chains you can skip this part.)</p>

<p>Why do we need to use a rop chain? On the Wii U no region in the memory is
executable and writeable at the same time (except for the JIT area, but we have
no access to it in Mario Kart 8), so the idea is to use existing code. If you
can control the stack, you can control the code flow. When calling a
function, the position in the code of the “calling function” is saved on the
stack. Whenever the called function returns, it jumps backs to the address which
was saved on the stack. By manipulating this return address it’s possible to
jump anywhere in the code. Using clever places in the code it’s possible to
chain multiple of these jumps to execute needed instructions.</p>

<p>Functions which use the stack to store local variables have a common pattern.
At the end of the function they are loading the saved return address from the
stack and increase the stack pointer. By carefully crafting a stack we can
jump to parts of code that are written directly before this pattern. Each
address which you jump to is called a “gadget”.</p>

<p>Let’s imagine a stack where currently the stack pointer (r1) is pointing to
address 0x20000000:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># Stack before running the gadget:
0x20000000: 0                   &lt;-- Stackpointer (r1)
0x20000004: 0x10000000          &lt;-- current gadget address
0x20000008: 0                   &lt;-- Stackpointer (r1) + 0x08
0x2000000C: [NEW GADGETADDRESS] &lt;-- Stackpointer (r1) + 0x0C
</code></pre></div></div>
<p>Now we assume that some function was just returning, setting the stack pointer
to <code class="language-plaintext highlighter-rouge">0x20000000</code> and reading the address where to jump to from <code class="language-plaintext highlighter-rouge">0x20000004</code>.
This means at this state the code flow continues at <code class="language-plaintext highlighter-rouge">0x10000000</code>, with <code class="language-plaintext highlighter-rouge">r1 = 0x20000000</code></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># Intructions of the gadget in 0x10000000
0x10000000: [SOME USEFUL INSTRUCTION 1]
0x10000004: [SOME USEFUL INSTRUCTION 2]
0x10000008: [SOME USEFUL INSTRUCTION 3]
0x1000000C: lwz r0, 0xc(r1);        # load return address from stackpoint + 0x0c 
0x10000010: mtlr r0;                # move it to the link register (lr)
0x10000014: addi r1, r1, 8;         # increase the stack pointer by 0x08
0x10000018: blr;                    # branch to link register
</code></pre></div></div>

<p>The first three instructions are be the ones we are <strong>really</strong> interested
in. Using these we want to achieve our planned behaviour. This could be for
example loading values into registers (from the stack, which we can control!),
moving values between registers, calling functions or writing values to memory
and much more.
The instructions from <code class="language-plaintext highlighter-rouge">0x1000000C</code> and <code class="language-plaintext highlighter-rouge">0x10000010</code> read the new return
address from the <code class="language-plaintext highlighter-rouge">stack pointer + 0xC</code>, which is the value we’ve previously
put on the stack (<code class="language-plaintext highlighter-rouge">0x2000000C</code>).</p>

<p>The instruction at <code class="language-plaintext highlighter-rouge">0x10000014</code> will increase the stack pointer by 0x08,
afterwards instruction <code class="language-plaintext highlighter-rouge">0x10000018</code> will branch to the link register which
was set in the previous instructions.</p>

<p>After executing the gadget this stack will look like this.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># Stack after running the gadget:
0x20000000: 0                   &lt;-- 
0x20000004: 0x10000000          &lt;-- 
0x20000008: 0                   &lt;-- Stackpointer (r1)
0x2000000C: [NEW GADGETADDRESS] &lt;-- current gadget address
[...]                           &lt;-- stack data for the gadget in 0x2000000C
</code></pre></div></div>

<p>And a new gadget will be executed. This way chaining multiple gadgets is
possible to achieve an intended behaviour.</p>

<h1 id="how-to-find-rop-gadgets">How to find rop gadgets</h1>

<p>There are several tools that help you find rop gadgets. I had the best luck
with the tool <a href="https://scoding.de/ropper/">Ropper</a>. Before you can use
<code class="language-plaintext highlighter-rouge">Ropper</code> with Wii U binaries, you need to 
<a href="https://github.com/Relys/rpl2elf">convert them to ELF files</a>. <code class="language-plaintext highlighter-rouge">Ropper</code> 
allows you to display and filter all rop gadgets in a binary up to a
specified length.</p>

<p>Beside the actual binary of the exploited application you can also use rop
gadgets of the system libraries (.rpl files). The “core” system libraries are
always at the same location in the memory, which make them easily usable for
rop gadgets. In fact it’s preferred to use gadgets from these executables
to be independent of the application to be exploited.</p>

<p>Here is a list of all system libraries that are at a fixed position on memory
and their location (.text section, FW 5.5.x+)</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>coreinit    101C400 - 1090F00
tve         1090F40 - 10B9BC0
nsysccr     10B9C00 - 10BFD40
nsysnet     10BFD80 - 10CFE60
uvc         10CFEC0 - 10D2120
tcl         10D2180 - 10ED6E0
dc          110D600 - 111FEC0
vpadbase    111FF00 - 1128840
vpad        1128880 - 113D5E0
avm         113D640 - 114EBE0
gx2         114EC40 - 11C3020
snd_core    11C3080 - 11E3820
</code></pre></div></div>

<p>It’s a good idea not to hardcore any of the addresses for rop gadgets, but
instead get them from the binaries either via the ELFSymbols or a hash. For
improving the browser exploit I built a small 
<a href="https://github.com/wiiu-env/RPXGadgetFinder">Java tool</a> that will return a list
of gadgets for a config file. This way the rop gadgets for different versions
of the binary can easily be found.</p>

<h1 id="finding-actual-useful-gadgets">Finding actual useful gadgets</h1>
<p>After some research I finally knew enough to find a rop gadget on my own for
the first time. The goal was to perform a stack pivot to be able to switch to a
different (bigger!) stack. As we have learned in previous sections, the stack
pointer in stored in register <code class="language-plaintext highlighter-rouge">r1</code>. To modify the stack pointer, we need to
find a gadget to modify <code class="language-plaintext highlighter-rouge">r1</code>.</p>

<p>To achieve this, I searched for any gadget that writes a value into <code class="language-plaintext highlighter-rouge">r1</code> without 
any results. But I found a gadget that moves the content of <code class="language-plaintext highlighter-rouge">r12</code> of <code class="language-plaintext highlighter-rouge">r1</code>, so
I started searching for gadgets to control <code class="language-plaintext highlighter-rouge">r12</code>, without any success. But I
found one that moves the content of <code class="language-plaintext highlighter-rouge">r11</code> to <code class="language-plaintext highlighter-rouge">r12</code>… and so on. You see
how this is going to end. The ultimate goal was to find a “chain”, that
starts reading a value from the stack and moves it over several gadgets into
<code class="language-plaintext highlighter-rouge">r1</code>. In the end I really managed to find a working set of gadgets to perform
a stack pivot. It wasn’t the most gorgeous solution, but it worked. As the
project moved on was I able to improve and shorten the chain multiple times.</p>

<p>Beside having the rop size limitation, there was still the problem on being
the wrong CPU core. To switch the affinity of a thread, it needs to be
suspended. This mean it’s not possible for a thread to move itself to another
CPU core. The obvious solution is to create another thread with the affinity to run
on the target core. But there is one problem: The <code class="language-plaintext highlighter-rouge">OSCreateThread</code> function
takes 9 arguments, but with exiting rop gadgets it’s only possible to call a
function with up to 6 arguments.</p>

<p>With motivation from the success of finding a stack pivot gadget, I was trying
to find a rop gadget to create a thread. For quite some time I tried to find a
gadget to call an arbitrary function with 9 arguments, but without success.
Then I realized that <code class="language-plaintext highlighter-rouge">OSCreateThread</code> is just a wrapper for an internal
“create thread” function, where the function call is using register <code class="language-plaintext highlighter-rouge">r25 to r31</code>
as arguments instead of <code class="language-plaintext highlighter-rouge">r3-r9</code>. In the PowerPC architecture arguments of a
function are stored before the call in registers <code class="language-plaintext highlighter-rouge">r3 to r9</code>, setting these on
the end of a function is much more unlikely than the upper registers. The
“upper” registers (e.g <code class="language-plaintext highlighter-rouge">r24 - r31</code>) are often saved on the stack at the
beginning of a function, and restored (loaded from the stack) at the end of a
function. The combination of having an <code class="language-plaintext highlighter-rouge">OSCreateThread</code> gadget which loads
arguments from <code class="language-plaintext highlighter-rouge">r25 to r31</code> and having an easy gadget to set these registers
makes this function call with a huge amount of arguments feasible.</p>

<h1 id="how-to-execute-long-rop-chains">How to execute long rop chains</h1>

<p>At this point it was possible to do a stack pivot and create another thread
on the right core. But there was still the problem of the size limited rop
chain. Rambo6Glaz and I tried to figure out a way to allow bigger rop chains
and came up with two different ideas:</p>

<ul>
  <li>Create a rop chain to load a bigger chain via the network</li>
  <li>Split up the “final” rop chain into multiple chunks, run the exploit multiple
 times and each time save one chunk inside a <code class="language-plaintext highlighter-rouge">OSDriver</code>.</li>
</ul>

<p>While Rambo6Glaz focused on the network solution, I gave the <code class="language-plaintext highlighter-rouge">OSDriver</code> idea a
shot.</p>

<h2 id="running-the-exploit-multiple-times">Running the exploit multiple times!</h2>
<p>The Wii U OS has a feature that allows libraries to install <code class="language-plaintext highlighter-rouge">OSDrivers</code>.
Beside registering callbacks on certain events like acquiring or losing the
foreground, <code class="language-plaintext highlighter-rouge">OSDrivers</code> can also store data inside the kernel. This is useful
to store permanent data that can be used even after restarting or switching
the application. Using the <a href="https://wiiubrew.org/wiki/Cafe_OS_Kernel_Syscalls">kernel syscalls</a>
directly lets us bypass some checks and simplifies the usage.</p>

<p>Here is a general workflow of this idea:</p>
<ol>
  <li>Run the exploit in Mario Kart 8 to get rop chain execution.</li>
  <li>Build a rop chain that registers a new <code class="language-plaintext highlighter-rouge">OSDriver</code> and stores embedded data
(in this case a part of a big rop chain) inside the kernel using
<code class="language-plaintext highlighter-rouge">CopyToSaveArea</code>.</li>
  <li>Open the Home Menu via rop chain and exit the game.</li>
  <li>Go back to step 1 until the whole rop chain is placed in different
 <code class="language-plaintext highlighter-rouge">OSDrivers</code></li>
  <li>Build another rop chain that takes the data saved in the <code class="language-plaintext highlighter-rouge">OSDrivers</code> and
 execute it on a new thread on core 1 (GX2 main core in Mario Kart 8).</li>
</ol>

<p>Using this approach I was able to store 816 bytes inside a <code class="language-plaintext highlighter-rouge">OSDriver</code> with each
restart. I improved the rop chain generation to automatically take care of the
generation of all the different rop chains that are needed.</p>

<p>It worked quite well. Finally I could build a rop chain without thinking
about the size limit. In fact the size of the final rop chain was limited by the
amount of “read data from OSDriver X” gadgets, but I never reached it
(~8000 bytes were possible). The downside: each try took quite long. I had
to run the exploit at least three times to get the “final” rop chain running to
check if it’s working. This leads to a &gt; 5 minutes test cycle. For testing
just some ideas it was enough, but on long term it was really annoying.</p>

<p>Using this I was able to test some ideas that were previously not possible
due to size constraints. One of the first things I tried was to shutdown the
GX2 engine and restart it again to have it in a clean state for the kernel
exploit. This was now possible because we were on the right CPU core. But
this resulted in a crash because the actual game was still running and using the
GX2 engine. A simple solution was to suspend the main thread (which luckily
is on a fixed address which can be easily obtained from the crash logs), and
resume it at the end of the rop chain. Without resuming the main thread exiting
the game wouldn’t be possible. But even with stopping the main thread and a
reinitialization of the GX2 engine the exploit was still not working. Also
adding some waiting in various variations didn’t help.</p>

<p>The best theory at the was that it didn’t work because something in the
background was still running and using the GX2 engine, interfering with the
exploit. At this point I was really desperate and tried to implement every
single implementation in the rop chain, hoping one of them would actually work.
But nothing was working.</p>

<p>From working on the plugin system I knew that threads on the CPU core 2 will
actually keep running when opening the <code class="language-plaintext highlighter-rouge">Home Menu</code>. My idea was to perform
the exploit while the game was suspended in the background, but this also
didn’t work.</p>

<h2 id="we-need-more-gadgets">We need more gadgets!</h2>

<p>Each application implements a <code class="language-plaintext highlighter-rouge">ProcUI</code> loop. <code class="language-plaintext highlighter-rouge">ProcUI</code> is a wrapper library
which allows an easier usage of the system message queue from <code class="language-plaintext highlighter-rouge">Cafe OS</code>. The
<code class="language-plaintext highlighter-rouge">ProcUI</code> loop is the place in the application where it’s decided if the
application is requested to move to the background, just gained the
foreground or should be closed. I thought by sending a “close application” to
the game and keeping our own thread running we would have a chance of running
the rop chain in a pretty clean environment without the actual game running and
interfering with it.</p>

<p>The easiest way to tell a game that it should be closed is by calling the
function <code class="language-plaintext highlighter-rouge">SYSRelaunchTitle</code> from the <code class="language-plaintext highlighter-rouge">sysapp</code> library, but actually using it was
way harder than I thought. In this blog post we’ve already talked about the
system libraries that are always at a fixed address in memory, but <code class="language-plaintext highlighter-rouge">sysapp</code>
is not one of them. The function address can be easily obtained using
<code class="language-plaintext highlighter-rouge">OSDynLoad_Acquire</code> and <code class="language-plaintext highlighter-rouge">OSDynLoad_FindExport</code>. The real problem is using
any of the return values and calling a function not by its address but by
a function address pointer.</p>

<p>To accomplish this once again more rop gadgets needed to be found. The function 
<code class="language-plaintext highlighter-rouge">OSDynLoad_FindExport</code> takes the module handle acquired via
<code class="language-plaintext highlighter-rouge">OSDynLoad_Acquire</code> as its first argument, which dynamically changes after each
restart. So the first needed gadget was a function call where the first
argument is dereferenced from an address. In addition a gadget is needed to
call the function pointer that is returned using the <code class="language-plaintext highlighter-rouge">OSDynLoad_FindExport</code>
function.</p>

<p>After finding these gadgets it was finally possible to call <code class="language-plaintext highlighter-rouge">SYSRelaunchTitle</code>
to trigger a game shutdown, but it turns out it also kills any other existing
threads. The idea of keeping rop chain execution after shutting down the game
didn’t work either.</p>

<p>But these new gadgets really helped to test new things. For example we were
able to test the “magic” <code class="language-plaintext highlighter-rouge">IM_SetDeviceState</code> call which is used in the
browser exploit to shutdown the browser. It turns out that just emulating
pressing the home button is not helping.</p>

<h2 id="loading-bigger-rop-chains-via-the-network">Loading bigger rop chains via the network!</h2>
<p>The whole time I was using my slow “run the exploit multiple times to get a
bigger rop chain”-approach, RamboGlaz6 was working on loading a second
rop chain over the network.</p>

<p>At some point RamboGlaz6 finally managed to get a stable rop chain execution
of a rop chain sent via TCP to the console. The workflow was something like
this:</p>
<ul>
  <li>Create a new thread on CPU core 1</li>
  <li>Inside the thread connect to a TCP server and receive a bigger rop chain</li>
  <li>Do a stack pivot to execute the received rop chain</li>
  <li>Profit!</li>
</ul>

<p>This was really stable and  <strong>massively</strong> sped up the testing of new rop chains.</p>

<h2 id="just-keep-gx2-running">Just keep GX2 running</h2>
<p>Due to the faster testing I tried several new things. One of them was to
stop trying to shutdown and restart GX2 but still suspend the main thread of
Mario Kart 8. This lead to an exception in the kernel, so something was
happening. To perform the kernel exploit we place a fake heap entry and
modify the kernel heap to use this. The crash log suggested the kernel was
indeed trying to read from the right address, but the read data was not the one
we placed there. I wasn’t (and I am still not sure) if this was because of
some weird caching issue, but I went the safe route and modified the exploit
to read the fake heap entry from <code class="language-plaintext highlighter-rouge">0x2F200014</code> instead of <code class="language-plaintext highlighter-rouge">0x1F200014</code> and it
worked first try. 
I gave it a few more shots and it was indeed stable. <strong>Finally</strong>.</p>

<p>From now on we had a stable kernel exploit which granted us read/write access 
with kernel privileges. The JIT-area isn’t just helpful for providing easy
userland code execution, but also provides easy kernel execution. It’s also
the only region in memory which allows write and execute for the kernel, but
we still had no access to this region.</p>

<p>Without kernel execution and the default memory mapping there isn’t really
anything special you can do with kernel privileged writes, only modifying the
kernel .data section and registering a new syscall. Without being able to run
custom code a new syscall isn’t that helpful. But kernel write is enough to
change the tables inside the kernel which are used for the memory mapping and
give us a mapping of a “execute only” region with write privileges. The
downside of this is that we need to restart the application before the
changes take place. So we still do at least one restart.</p>

<p>Before restarting it’s important to revert the changes we did to the kernel heap. 
We also register a new syscall 0x25 which points to a memcpy function
(<code class="language-plaintext highlighter-rouge">0xfff09e44</code> on 5.5.x) to keep an easy way to perform copy operations with
kernel privileges.</p>

<h2 id="userland-code-execution">Userland code execution!</h2>
<p>After performing the kernel exploit, setting up the memcpy syscall, mapping
the memory and restarting Mario Kart 8 we perform the exploit once again. Now we
can finally achieve code execution. Using the new memory mapping we can copy our
executable into the free <code class="language-plaintext highlighter-rouge">0x011DD000...0x011E0000</code> region. Afterwards we
override the “main()” function call with a jump to our code and switch to the
<code class="language-plaintext highlighter-rouge">Mii Maker</code>. This will execution our payload in <code class="language-plaintext highlighter-rouge">Mii Maker</code> context!</p>

<p>But we still have no real control of the kernel without kernel execution.
Unfortunately the free <code class="language-plaintext highlighter-rouge">0x011DD000...0x011E0000</code> region which we are using
for userland code execution has no kernel execution rights. I spent some time
to think of a solution when I remembered the RPX version of the homebrew
launcher. The RPX version of the homebrew launcher was intended to run as a
channel in an environment without kernel access, so it ships with its own kernel
exploit. It also has no access to the JIT-areas, but somehow achieves kernel
execution. Looking at the code reveals that there is a region in memory
(<code class="language-plaintext highlighter-rouge">0x017FF000</code>, just before the JIT area) that is writable using the memory
mapping and also has kernel execution rights. This is enough to have
arbitrary kernel execution by placing a payload in this area and registering it
as a syscall. By changing a IBAT (controls the memory mapping) kernel
execution rights can be provided for any other region in memory.</p>

<h2 id="payloadelf-loader">payload.elf loader</h2>
<p>In previous blog posts I talked about a homebrew environment where all
exploits should be able to load a <code class="language-plaintext highlighter-rouge">payload.elf</code> from the sd card and execute it.
To achieve this we need to fulfill the requirements of the payload loader,
and run the payload loader afterwards. One of the requirements is having a
syscall which allows the modification of IBAT0 to gain kernel code execution.
The other ones are just the “default” <code class="language-plaintext highlighter-rouge">kern_read</code> and <code class="language-plaintext highlighter-rouge">kern_write</code> syscalls.</p>

<p>After installing these syscalls we just need to load the <code class="language-plaintext highlighter-rouge">payload.elf loader</code>
into memory and run it.</p>

<p>Based on the <a href="https://github.com/wiiu-env/JsTypeHax_payload">JsTypeHax_payload</a> 
I created a payload for the Mario Kart 8 exploit which sets up the needed
syscalls for the payload loader and copies the loader into memory.
The <code class="language-plaintext highlighter-rouge">0x011DD000...0x011E0000</code> region is barely enough to fit this “payload
loader installer” and the actual <code class="language-plaintext highlighter-rouge">payload.elf loader</code>, but it somehow fits.</p>

<p>After copying the <code class="language-plaintext highlighter-rouge">payload.elf loader</code> into memory it can be finally executed.
A arbitrary <code class="language-plaintext highlighter-rouge">payload.elf</code> will be loaded from the sd card and executed. We
are finally done.</p>

<h1 id="conclusion">Conclusion</h1>
<p>In the end I spent <strong>way</strong> more time on this than I ever would have thought.
So many times I was so close to just giving up, but somehow the exploit was
really addicting. Once again a big shoutout to Ramboglaz6 (aka NexoCube) who
worked on this at the same time. We shared our ideas and tried to motivate
each other. In the end we both came up with a working solution which is quite
nice.</p>

<p>This blog post may not be the most technical one, and maybe not the most exciting
one, but this is how developing such a exploit really is, at least in my
experience. 95% of the time you’re just failing and trying different ideas.
Several times you will be stuck, but somehow there is always a solution. On
one side it feels like I’ve wasted way too much time on this, but on the
other side I also learned so much. And it feels nice to actually finish such a 
demotivating project. Even if no one will ever actually use it.</p>

<h1 id="how-can-i-find-the-code">How can I find the code</h1>
<p>I put all of the code on Github:</p>
<ul>
  <li>https://github.com/wiiu-env/Mario-Kart-8-Exploit</li>
  <li>https://github.com/wiiu-env/Mario-Kart-8-Exploit_payload</li>
</ul>]]></content><author><name></name></author><category term="homebrew" /><summary type="html"><![CDATA[This blog post should give you a rough insight into the implementation of the Mario Kart 8 exploit to be a primary entrypoint for homebrew. Thereby, both the technical details and the problems that came up during development should be discussed. This time I also want to tell you about the ideas that didn’t work, instead of just the one that works fine.]]></summary></entry><entry><title type="html">Creating a homebrew environment on the Wii U - Part 4</title><link href="https://maschell.github.io/homebrew/2019/12/27/new-environment-part4.html" rel="alternate" type="text/html" title="Creating a homebrew environment on the Wii U - Part 4" /><published>2019-12-27T13:30:00+00:00</published><updated>2019-12-27T13:30:00+00:00</updated><id>https://maschell.github.io/homebrew/2019/12/27/new-environment-part4</id><content type="html" xml:base="https://maschell.github.io/homebrew/2019/12/27/new-environment-part4.html"><![CDATA[<p>This blog entry is intended to discuss the implementation some of the concepts
developed in <a href="/homebrew/2019/12/04/new-environment-part3.html">part 3</a>.
It will focus on getting stable code execution in form of loading a <code class="language-plaintext highlighter-rouge">payload.elf</code> from the sd card.
The implementation discussed in this blog post has already been released back in <a href="https://gbatemp.net/threads/more-stable-webhack-for-5-5-2-5-5-3-5-5-4-released.528757/">january 2019</a>.</p>

<h1 id="initial-code-execution">Initial code execution</h1>

<p>To achieve initial code execution, a bug in the browser can be
exploited. The necessary steps are then implemented with the goal of
loading a payload from the SD card.</p>

<p>However, the implementation of the necessary browser exploit does not
have to take place from scratch. The existing browser exploit with the
name <a href="https://github.com/WiiUTest/JsTypeHax">JSTypeHax</a>, which exploits the <a href="https://nvd.nist.gov/vuln/detail/CVE-2013-2857">CVE-2013-2857</a>
vulnerability, can be used as the basis. 
It is exploiting a heap-use-after-free
bug, that can be exploited via JavaScript code. It takes advantage
of the fact that the browser still uses a <strong>reference A</strong> to <strong>object A</strong> after
freeing it. If an <strong>object B</strong> is allocated directly afterwards, the data is
located at the point in the memory where <strong>object A</strong> previously was. A
manipulation of the memory to which the <strong>reference A</strong> points is
effectively possible via <strong>object B</strong>. The data is stored in the memory
where <strong>object A</strong> was previously located. The trick is that <strong>object B</strong> uses a
different data structure. This makes it possible to effectively
manipulate parts of <strong>object A</strong> to which no access is given via <strong>reference A</strong>.
The data structure of <strong>object B</strong> can be chosen freely by using a different data
structure. The use of <strong>reference A</strong> may cause unexpected values to be
used. By carefully choosing these values, a manipulation of the stack,
and thus a ROP chain execution, is possible. Subsequently, a payload is
written to the JIT area via the ROP chain and executed.</p>

<p>The problem with the existing implementation is the success rate. Only
in a few cases does the code execution succeed. This is to be improved.
In addition, the loading of <code class="language-plaintext highlighter-rouge">payload.elf</code> from the SD card must also be added.</p>

<h2 id="previous-implementation">Previous implementation</h2>

<p>In the existing implementation, code execution is achieved through the
following (simplified) steps.</p>

<ol>
  <li>Placing a ROP chain in memory by creating JavaScript objects
containing the ROP chain.</li>
  <li>Similarly, the payload to be executed is placed in memory.</li>
  <li>A security vulnerability in the browser is exploited to allow
manipulation of the stack.</li>
  <li>The manipulation of the stack executes the ROP chain placed in
memory.</li>
  <li>Via the ROP chain, the payload is copied to the JIT area and then
executed.</li>
</ol>

<p>For this to work, addresses must be predicted at which the ROP chain and
the target payload are located in memory. It is not possible to use
JavaScript to store data at specific addresses in Wii U memory. It is
therefore not possible to predict exactly in advance where the data will
end up in memory.</p>

<p>In order to increase the chances that the corresponding data is really
at the predicted address, it is stored several times in succession in
the memory. This is also known as “heap-spraying”. This increases the
probability that a predicted address will actually point to the target
data.</p>

<p>The problem here is that the target data is at the predicted address,
but not necessarily the beginning of the data. In order to avoid this, a
so-called <a href="https://en.wikipedia.org/wiki/NOP_slide">NOP-slide</a> is appended in front of the payload. This
corresponds to a series of instructions that are interpreted by the
processor as a null operation. If, for example, 1000 null operations are
appended to machine code before the payload, it is sufficient to predict
one of the addresses of the 1000 null operations. The intended code is
executed afterwards.</p>

<center><img src="/res/nop.png" width="400" align="middle" /></center>

<p>Starting at the predicted address, the memory is copied to the JIT area
and executed. This is shown schematically in the figure
above. The null operations at the beginning would
have no effect, but at some point the payload would be executed. In
general, the longer the NOP-slide, the higher the chance of success,
because the predicted address only has to hit a point in the NOP-slide.
However, the size of the NOP-slide is limited to 32 KiB, since the NOP
slide and payload must fit together in the JIT area.</p>

<p>Due to the preceding null-operations, the position of the code
potentially changes with each execution. This, however, creates the
problem that the payload cannot contain any position-dependent code. To
counteract this problem, another small payload is inserted between the
NOP slide and payload. This payload is position-independent and can
therefore be executed without problems. The task of this payload is to
determine the actual address of the payload to be executed.</p>

<p>For this reason, a special payload is created that consists of the
following parts:</p>

<ol>
  <li>A preceding NOP slide with which the maximum 32 KiB is filled.</li>
  <li>A small, position-independent payload to determine the address of
the payload to be executed.</li>
  <li>The size of the payload to be executed.</li>
  <li>The position-dependent payload to be executed.</li>
</ol>

<p>This special payload is spread across the heap.</p>

<p>Via the ROP chain, 32 KiB are copied to the JIT area and executed,
starting from the predicted address of the memory. If an address located
in the NOP slide is successfully predicted, these null operations and
then the small position-independent payload are executed. This is shown in the figure below.</p>

<center><img src="/res/old_nop1.png" width="400" align="middle" /></center>

<p>This payload knows its current execution position, the predicted
address, and its own size. This is sufficient to determine the correct
address of the payload to be executed. The payload to be executed is
then copied from the JIT area to the predicted address, this time
without the NOP slide and extra payload. This is shown in the figure below.</p>

<center><img src="/res/old_nop2.png" width="400" align="middle" /></center>

<p>The ROP chain can now again copy and execute the data from the now correctly predicted address into
the JIT area, whereby the position-dependent payload is executed
correctly. This is shown in the figure below.</p>

<center><img src="/res/old_nop3.png" width="400" align="middle" /></center>

<p>Detailed technical notes and annotated code of this implementation can be found <a href="https://gist.github.com/orboditilt/c4de45d284ba14bceef3d49b45312e52">here</a>.</p>

<p>The previous implementation currently has two critical points at which
predictions must be made. If one of the predictions is not precise
enough, the execution of the exploit fails and the console crashes. 
The new position of the stack (containing the ROP-Chain) and the position payload copied to the JIT-areas have to be predicted.
The prediction of the payload address is not always successful. 
Because the possible size of the NOP-slide is limited by the size of the JIT area, the success rate can’t be increased “infinitely” by extending the NOP-slide.
The NOP-slide plus payload can only be a maximum of 32KiB. As a result, the
probability of predicting an address in the middle of the payload and
not before (inside the NOP-Slide) increases, resulting in a crash.</p>

<h2 id="new-improved-implementation">New improved implementation</h2>

<p>After some tests it was clear that the ROP-Execution is stable, 
but executing the payload fails most of the time.
To increase the success rate of the browser exploit, the loading of the
payload must be optimized.</p>

<p>Up to now, attempts have been made to increase the required accuracy by
prefixing a NOP slide, which, however, can only have a limited length.
This length is limited by the size of the JIT area. If a payload is
written directly to the JIT area via the ROP chain, which helps to
determine the position of the payload to be executed, the restriction
can be circumvented.</p>

<p>This results in a new procedure:</p>

<ol>
  <li>Place a ROP chain in memory by creating corresponding JavaScript
objects.</li>
  <li>Similarly, the payload to be executed is placed in memory, preceded
by a unique value.</li>
  <li>A vulnerability in the browser is exploited to allow manipulation of
the stack.</li>
  <li>The manipulation of the stack is performed by the ROP chain placed
in memory.</li>
  <li>A small payload is written directly to memory to a specific address.</li>
  <li>This small payload is copied to the JIT area and then executed.</li>
  <li>Starting at a predefined address, this payload searches for the
real payload to be executed using the unique value. If it’s found,
the payload copies it to a pre-defined address in memory.</li>
  <li>The ROP-Chain will then copy it from pre-defined address to the 
JIT area, where it can be executed from.</li>
</ol>

<p>This new procedure simplifies the prediction of addresses. The value
that precedes the payload should be selected so that it probably does
not occur elsewhere in the memory. This ensures that as soon as the
value is found in the memory, the payload is behind it. For a successful
execution, it is only necessary that the unique value and payload are
behind the start address of the search. Crashes of the exploits are very
rare now.</p>

<h3 id="rop-chain-generation">ROP-Chain generation</h3>

<p>The previous implementation generates the ROP chain within the
JavaScript code. In the improved implementation the existing ROP chain generator
<a href="https://github.com/yellows8/wiiuhaxx_common">wiiuhaxx_common</a> will generate the ROP chain. This is implemented
in PHP and is already used in <a href="https://github.com/yellows8/wiiu_browserhax_fright">browser exploits for earlier
operating system versions</a>. The
wiiuhaxx_common ROP chain generator offers a dynamic generation, which
can be used by different exploits. It only uses gadgets in system
libraries, which are loaded at any time and at the same location in
memory. Thus, the ROP chains created by wiiuhaxx_common can be used system-wide, 
independent of the running application.</p>

<p>The generator already offers basic gadgets, which make it possible to
change data in the memory or to call functions. This makes it easy to
create or adapt ROP chains, which are also available in a readable
format. An exemplary creation of a very basic ROP chain can be seen in the following:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>// Creates a basic ROP Chain which copies data from $payload_srcaddr and executes it.
// The problem is finding the correct address for $payload_srcaddr
function generateropchain_type1(){
    global $payload_srcaddr;
    $payload_size = 0x20000;
    $codegen_addr = 0x01800000;
    // Switch to core 1.
    ropgen_switchto_core1();
    // Copy code to the JIT area
    ropgen_copycodebin_to_codegen($codegen_addr, $payload_srcaddr, $payload_size);
    ropchain_appendu32($codegen_addr); // Execute code in the jit area
}
</code></pre></div></div>

<p>This has to be extended by the part of finding/placing a valid copy of the payload in memory, so it can be copied to the JIT-area and executed.</p>

<p>For this purpose a function has been added which allows to write a payload (which will be embedded in the ROP-Chain) directly into memory. The corresponding function can be found in the listing below.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>function ropgen_writerop_toAddress($path, $dstaddr){
    $payload = wiiuhaxx_loadfilebinary($path);
    $len = strlen($payload);
    for($i = 0; $i &lt; $len; $i +=4) {
        ropgen_writeword_tomem(hexdec (bin2hex (substr($payload, $i, 4))),$dstaddr + $i);
    }
}
</code></pre></div></div>
<p>This payload length is limited by the maximum length of the ROP-Chain. The used payload is just 88 bytes and it’s used to find the “real” payload in memory and copy it to a pre-defined address. 
A existing gadget can be used to place arguments for the payload into the registers 24-31. After the payload is writting into memory, it will be copied to the JIT-Area, the registers will be set and the payload will be executed.
An excerpt of the ROP Chain can be found in the listing below.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>// Write our small search payload somewhere into mem
ropgen_writerop_toAddress($wiiuhaxxcfg_searchpayloadfilepath,$payload_tmp_address);

// Copy it to codegen/jit area
ropgen_copycodebin_to_codegen($codegen_addr, $payload_tmp_address, $search_payload_length);

// Set up some parameters
$regs = array();
$regs[24 - 24] = $ROP_OSFatal;//r24
$regs[25 - 24] = $ROP_Exit;//r25
$regs[26 - 24] = $payload_size;//r26 sizeToCopy
$regs[27 - 24] = $payload_search_for - 0x04;// r27 SearchFor. subtract 0x4 so we don't find THIS accidentally.
$regs[28 - 24] = $payload_start_search;  //r28 start of search
$regs[29 - 24] = $valid_payload_dst_address ; //r29 target address
$regs[30 - 24] = 0x8;//r30 The payload can do this at entry to determine the start address of the code-loading ROP-chain: r1+= r30. r1+4 after that is where the jump-addr should be loaded from. The above r29 is a ptr to the input data used for payload loading.
$regs[31 - 24] = $ROPHEAP;//r31    
ropgen_pop_r24_to_r31($regs);//Setup r24..r31 at the time of payload entry. Basically a "paramblk" in the form of registers, since this is the only available way to do this with the ROP-gadgets currently used by this codebase.

// And run it!
ropchain_appendu32($codegen_addr); //Jump to the codegen area where the payload was written.
</code></pre></div></div>

<p>The actual implementation can be found <a href="https://github.com/wiiu-env/wiiuhaxx_common/blob/master/wiiuhaxx_searcher.s">here</a>.
Afterwards the “real” payload can be copied from the pre-defined address to the JIT-Area, from where it can be executed. See:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>// On success, we should now have our actual payload @valid_payload_dst_address. Let's copy it to codegen.
ropgen_copycodebin_to_codegen($codegen_addr, $valid_payload_dst_address, $payload_size);
// and run it!
ropchain_appendu32($codegen_addr);
</code></pre></div></div>

<p>The full ROP-Chain used in this implementation can be found <a href="https://github.com/wiiu-env/wiiuhaxx_common/blob/master/wiiu_browserhax_common.php#L533">here</a>.</p>

<p>In addition, a new platform independent <a href="https://github.com/wiiu-env/RPXGadgetFinder">rop-gadget-finder</a> has been implemented in Java, which is used to find the address of gadgets in system libraries either by a binary pattern or function name. 
This new finder uses <a href="https://en.wikipedia.org/wiki/YAML">YAML</a> files to specify which gadgets should be searched. An example config for gadgets of the coreinit.rpl can be found <a href="https://github.com/wiiu-env/wiiuhaxx_common/blob/master/coreinit.yml">here</a>.</p>

<h1 id="browser-exploit-payload">Browser exploit payload</h1>

<p>The browser exploit can be used to execute any payloads that fit into
the JIT area (32 KiB). Now a new payload should be implemented that has the goal of being able to execute
another, larger payload from the SD card.</p>

<p>To be able to implement this, a kernel exploit is required, which is
explained in the next section. The kernel exploit is required to be able to remain code execution while switching to an application which has access to the SD Card.</p>

<h2 id="kernel-exploit">Kernel-Exploit</h2>

<p>The kernel exploit takes advantage of the fact that the GPU directly
accesses physical memory and also has access to parts of the kernel
area. Applications are normally not allowed access to the kernel area.</p>

<p>The kernel exploit is already publicly available and is compatible with
the current version of the OS (5.5.X). The implementation presented here is a
slight modification of the <a href="https://github.com/wiiudev/libwiiu/blob/master/kernel/gx2sploit/src/loader.c">existing implementation</a>. However, the
basic idea, the used values and the exploited bugs have been adopted.</p>

<p>The basic idea is to manipulate the kernel heap to allocate a memory
block that can be accessed by an application. To achieve this, some
information about the kernel heap is helpful. Information about the
kernel can be obtained from the open source emulator
<a href="https://github.com/decaf-emu/decaf-emu\">decaf</a>, in which the kernel was
reverse-engineered.</p>

<ul>
  <li>The heap implementation is a <a href="https://github.com/decaf-emu/decaf-emu/blob/002ee0cebfc8f5d724d02cb92e65bb4249e90b0a/src/libdecaf/src/cafe/cafe_tinyheap.cpp"><code class="language-plaintext highlighter-rouge">tiny heap</code></a>.</li>
  <li>If memory is being allocated, the blocks are iterated until there is
a free block. (<a href="https://github.com/decaf-emu/decaf-emu/blob/002ee0cebfc8f5d724d02cb92e65bb4249e90b0a/src/libdecaf/src/cafe/cafe_tinyheap.cpp#L375-L487">source</a>)</li>
  <li>This search starts with a block defined in a variable, which is
referred to in the following as <em>firstBlockIdx</em>.</li>
  <li>The position of the metadata of this memory block is calculated
using the variable <em>firstBlockIdx</em>.</li>
  <li>Due to the absence of checks, the manipulation of the variable
<em>firstBlockIdx</em> will allow the next memory block to be allocated in
a memory area that is accessible to applications.</li>
  <li>The memory address of the variable <em>firstBlockIdx</em> is known and does
not change.</li>
</ul>

<p>If it is possible to manipulate the variable <em>firstBlockIdx</em>, the meta
information of a memory block allocated can be manipulated. The data
structure of the meta information is called <a href="https://github.com/decaf-emu/decaf-emu/blob/002ee0cebfc8f5d724d02cb92e65bb4249e90b0a/src/libdecaf/src/cafe/cafe_tinyheap.cpp#L13-L34">TrackingBlockBase</a> in
decaf and is represented in the listing below. The field data refers to the address of the
block to be allocated. If it points to memory that can be modified by
applications, memory used in the kernel can be manipulated.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>struct TrackingBlockBase {   
   void * data; // Pointer to the allocated memory of the block   
   int32_t size; // Size of allocated memory, negative if not yet allocated
   int32_t prevBlockIdx; // Index of the previous block  
   int32_t nextBlockIdx; // Index of the following block
};
// TrackingBlockBase struct
</code></pre></div></div>

<p>A manipulation of the variable <em>firstBlockIdx</em> can be achieved via the
GPU. The function <code class="language-plaintext highlighter-rouge">SetSemaphore</code> allows to use a semaphore in a given
address in memory. It is possible to use an address in the kernel heap.
Effectively the variable <em>firstBlockIdx</em> can be manipulated by
incrementing the semaphore at the corresponding position in the memory.
The system library of the graphics card offers the possibility to use
the function. To bypass operating system checks, a corresponding PM450
package is generated directly and sent to the graphics card via the
system libraries.</p>

<p>A PM4 packet of the type <a href="http://developer.amd.com/
wordpress/media/2013/10/R6xx_R7xx_3D.pdf"><code class="language-plaintext highlighter-rouge">MEM_SEMAPHORE</code></a> is
created, which receives the physical address of the <em>firstBlockIdx</em>
variable as destination address. Each of these packets increases the
value of the variable and moves the position from which the
metainformation (TrackingBlockBase) of the next memory block is read.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>uint32_t* pm4 = (uint32_t*)MEMAllocFromDefaultHeapEx(0x20, 0x1000);
pm4[0] |= 0xC0013900; //PACKET3_MEM_SEMAPHORE
pm4[1] |= kpaddr;     //ADDR_LO = target
pm4[2] |= 0xC0000000; //SEL semaphore signal
pm4[3] |= 0x80000000; //nop
pm4[4] |= 0x80000000; //nop
pm4[5] |= 0x80000000; //nop
pm4[6] |= 0x80000000; //nop
pm4[7] |= 0x80000000; //nop

DCFlushRange(pm4, 0x20);

GX2DirectCallDisplayList((void*)pm4, 8 * sizeof(uint32_t)); // increment value of kpaddr by 0x01000000
GX2DirectCallDisplayList((void*)pm4, 8 * sizeof(uint32_t)); // increment value of kpaddr by 0x01000000

GX2Flush();
</code></pre></div></div>

<p>After enough packets, the meta information is read from a predictable
address that can be manipulated by applications. In this case, the metadata is read from 0xFF200014 instead of 0x1F200014.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/* Allocate memory accessible to applications that is stored in the kernel
   is to be used */
uint32_t *drvhax = OSAllocFromSystem(0x4c, 4);

/* Prepare kernel heap entry */
struct TrackingBlockBase *metadata = (struct TrackingBlockBase*) 0x1F200014;
metadata.data = drvhax;
metadata.size = -0x4c; // negative -&gt; is still available
metadata.prevBlockIdx = (uint32_t) -1;
metadata.nextBlockIdx = (uint32_t) -1;
</code></pre></div></div>

<p>The listing above shows the creation of the wrong
TrackingBlockBase entry at the position expected by the kernel heap from
manipulating the <em>firstBlockIdx</em> variable. Memory is allocated in line 3
and assigned to the entry in line 7. The negative size of the size field
in line 8 indicates to the kernel heap that this memory block is not yet
being used.</p>

<p>This makes it possible to manipulate objects used in the kernel using an
application. The next time something on the kernel heap is allocated, the memory
available to userspace is used, which can be controlled.
In <em>Cafe OS</em>, it’s possible to register as <code class="language-plaintext highlighter-rouge">OSDriver</code>. This <code class="language-plaintext highlighter-rouge">OSDriver</code> will be registered as hooks into system events.
Whenever a Driver gets (de-)initialized or the main application acquires/releases the foreground, a function of that Driver will be called.
However, the heap for userspace will be cleared whenever the application switches. 
To allow an <code class="language-plaintext highlighter-rouge">OSDriver</code> to store persistent data, a mechanism exists to store this data on the kernel heap.
This is the so-called <code class="language-plaintext highlighter-rouge">SaveArea</code> of a <code class="language-plaintext highlighter-rouge">OSDriver</code>. Before an application closes, the Driver can store data in the <code class="language-plaintext highlighter-rouge">SaveArea</code>, and load it back when a new application loads.</p>

<p>The data of the registered <code class="language-plaintext highlighter-rouge">OSDriver</code> is allocated on the kernel heap. 
Using the technique described above, it is possible to allocate the 
<code class="language-plaintext highlighter-rouge">OSDriver</code> data to an area accessible from userspace (<code class="language-plaintext highlighter-rouge">0x1F200014</code>) and then manipulate it.</p>

<p>The position of the <code class="language-plaintext highlighter-rouge">SaveArea</code> can be freely selected by manipulating the
<code class="language-plaintext highlighter-rouge">OSDriver</code> data. The data is written with kernel privileges, which makes
it possible to set the <code class="language-plaintext highlighter-rouge">SaveArea</code> to a position within the kernel. Afterwards
data can be written to the position via the function <code class="language-plaintext highlighter-rouge">CopyTo_SaveArea</code>.
The listing below shows how any memory area can be modified
using a registered driver.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/* Register driver. The driver data is stored by the
   manipulated kernel heap into the previously allocated memory.
   `drvhax`. */
char drvname[6] = {'D', 'R', 'V', 'H', 'A', 'X'};
Register(drvname, 6, NULL, NULL);

/* Via the driver data, the address of the _SaveArea_
   can be manipulated. */
drvhax[0x44/4] = ANY_ADDRESS;
/* SIZE bytes are copied from DATA to ANY_ADDRESS. */
CopyTo_SaveArea_(drvname, 6, DATA, SIZE);
</code></pre></div></div>

<p>From here, Syscalls can be registered for reading and writing with
kernel privileges. For this, parts of the existing kernel code are used.
Any writing and reading of data with kernel privileges is now possible.</p>

<p>The full used kernel exploit implementation can be found <a href="https://github.com/wiiu-env/gx2sploit">here</a>.</p>

<h3 id="payload-implementation">Payload implementation</h3>

<p>The payload, which is executed via the browser exploit, can be divided
into two parts. On the one hand the exploit specific part, which differs
depending on the entry point, on the other hand, common exploit
independent tasks can be abstracted into another payload. This applies
in particular to the part responsible for loading and copying
<code class="language-plaintext highlighter-rouge">payload.elf</code> from the SD card.</p>

<p>The initial payload for the browser is to run as follows and performs
the following actions:</p>

<ul>
  <li>A new thread is created and used.</li>
  <li>The processes of the browser are terminated so that the application
can be switched in the future.</li>
  <li>By executing the kernel exploit, syscalls can be registered for
reading and writing with kernel privileges. These syscalls use
existing code in memory and are therefore permanently available as
syscalls <code class="language-plaintext highlighter-rouge">kern_read</code> (0x34) and <code class="language-plaintext highlighter-rouge">kern_write</code> (0x35).</li>
  <li>The <code class="language-plaintext highlighter-rouge">kern_write</code> syscall can be used to register a custom Syscall
<code class="language-plaintext highlighter-rouge">KernelCopyData</code> that copies data independently of the MMU. Existing
access restrictions can thus be circumvented. The implementation can
be taken over from existing solutions.</li>
</ul>

<p>A list of already used syscalls can either be read from the kernel or
taken from the <a href="https://wiiubrew.org/wiki/Cafe_OS_Syscalls">WiiUbrew wiki</a>.</p>

<p>At this point, all requirements are met to switch to another application
while code execution remains intact. For this, the second,
exploit-independent, payload is copied with the help of the
<code class="language-plaintext highlighter-rouge">KernelCopyData</code> syscall to a free space in the memory that is executable.
Theoretically, you could already set and use your own memory areas at
this point, but as few changes as possible are deliberately made. The
goal is to make it possible to load a payload from the SD card with as
few changes to the system as possible, so that the payload can expect a
standardized, already known environment.</p>

<p>A generic payload is then copied via the <code class="language-plaintext highlighter-rouge">KernelCopyData</code> syscall to the
location in memory where it is statically linked. It is known from
existing solutions that the memory area between 0x011DD000 and
0x011E0000 is not used and can be executed as well. In order for code to
be executed after the application change, the system is modified so that
the call to the main function is overwritten by a jump to the payload.
In the following, this payload is called <code class="language-plaintext highlighter-rouge">main_hook.elf</code>. The address of
the actual main function can later be read from memory and the original
function, if necessary, executed.</p>

<p>At this point, a change to any application would execute the payload.
This is the case until the main hook is reverted.</p>

<p>The access to the JIT area, in which the code of the <code class="language-plaintext highlighter-rouge">KernelCopyData</code> 
syscall is located, is not longer given. This means that
it can no longer be used. At the same time there is the problem that the
free memory area from 0x011DD000 to 0x011E0000, in which the
<code class="language-plaintext highlighter-rouge">main_hook.elf</code> is located, code can be executed, but not with kernel
privileges. Thus it is not possible to use a syscall whose code is in
this range.</p>

<p>To work around this, the necessary permissions must be set and execution
with kernel privileges in this area must be allowed. These are
implemented by the MMU and managed for example by BAT
(Block Address Translation) registers. They can be used to map physical memory block by block to
virtual memory with corresponding permissions. There are two types of
BAT registers: Data BAT registers (DBAT), which map the memory in terms
of data, and Instruction BAT registers (IBAT), which map the memory in
terms of execution.</p>

<p>In order for the used memory area to be executed with kernel privileges
and thus registered as a function as syscall, a corresponding IBAT
register must be set. Therefore a function is placed in a free region of
the PowerPC kernel (at <code class="language-plaintext highlighter-rouge">0xFFF02344</code>) and registered as a Syscall (0x09). 
With this function the IBAT0 can be set. In this case a function is used to overwrite the
zeroth IBAT entry. Theoretically any other IBAT entry can be used. A
syscall to read out the previous value is possible, but not mandatory.
The <code class="language-plaintext highlighter-rouge">main_hook</code> can use the syscall 0x09 with the following function signature:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>extern void SC_0x09_SETIBAT0(uint32_t upper, uint32_t lower);
</code></pre></div></div>

<p>Now all preparations have been made to switch to the <em>Mii Maker</em>
application. At the start of the application the <code class="language-plaintext highlighter-rouge">main_hook.elf</code> payload
is executed.</p>

<p>The following guarantees can be given to the payload:</p>

<ul>
  <li>The payload is called every time an application is started.</li>
  <li>The payload has access to the SD card.</li>
  <li>A syscall 0x09 for setting IBAT0 is available.</li>
  <li>The <code class="language-plaintext highlighter-rouge">kern_read</code> (0x34) and <code class="language-plaintext highlighter-rouge">kern_write</code> (0x34) syscalls can be used to read or write
with kernel privileges.</li>
</ul>

<p>A similar procedure will be implemented for all further entry points in
the future. If the same guarantees are given, the <code class="language-plaintext highlighter-rouge">main_hook.elf</code> payload
can be used without any modifications. An example implementation for Browser
Exploit payload can be found <a href="https://github.com/wiiu-env/JsTypeHax_payload">here</a>.</p>

<h3 id="loading-a-gerneric-payload-main_hookelf">Loading a gerneric payload (<code class="language-plaintext highlighter-rouge">main_hook.elf</code>)</h3>

<p>In the <code class="language-plaintext highlighter-rouge">main_hook.elf</code> the loading of another payload, the <code class="language-plaintext highlighter-rouge">payload.elf</code>,
from the SD card shall be implemented. This requires that the
<code class="language-plaintext highlighter-rouge">main_hook.elf</code> payload has access to the SD card, the syscalls for
reading and writing with kernel privileges, and the syscall for setting
the IBAT register. These requirements are fulfilled using the presented browser exploit payload.</p>

<p>To be able to register the functions of the <code class="language-plaintext highlighter-rouge">main_hook.elf</code> as syscall,
the IBAT0 register must be set via the corresponding syscall. The
original mapping of the used memory area is retained and only execution
rights with kernel privileges are added. Then a syscall can be
registered, which defines an own, 8 MiB memory area, with full read,
write and execution permissions. The syscall is executed on every core
of the CPU where it should be available.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>// Call this on each CPU Core
static void SCSetupIBAT4DBAT5() {
    asm volatile("eieio; isync");

    // Give our and the kernel full execution rights.
    // 00800000-01000000 =&gt; 30800000-31000000 (read/write, user/supervisor)
    unsigned int ibat4u = 0x008000FF;
    unsigned int ibat4l = 0x30800012;
    asm volatile("mtspr 560, %0" : : "r" (ibat4u));
    asm volatile("mtspr 561, %0" : : "r" (ibat4l));

    // Give our and the kernel full data access rights.
    // 00800000-01000000 =&gt; 30800000-31000000 (read/write, user/supervisor)
    unsigned int dbat5u = ibat4u;
    unsigned int dbat5l = ibat4l;
    asm volatile("mtspr 570, %0" : : "r" (dbat5u));
    asm volatile("mtspr 571, %0" : : "r" (dbat5l));

    asm volatile("eieio; isync");
}
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">payload.elf</code> is then loaded into this newly defined memory area. The
loading of the ELF file can be done by using existing code from the <code class="language-plaintext highlighter-rouge">Homebrew Launcher</code>.
This allows you to load and execute ELF files that are located on the SD
card and have a maximum size of 8MiB. If the SD card cannot be accessed
or there is no <code class="language-plaintext highlighter-rouge">payload.elf</code> on the SD card, all previous changes are
reversed and the system menu is loaded.</p>

<p>Theoretically, the definition of the memory area could be overwritten by
the operating system at any time. In order to keep as little logic as
possible in the <code class="language-plaintext highlighter-rouge">main_hook.elf</code>, the responsibility to prevent this from
happening lies with the loaded <code class="language-plaintext highlighter-rouge">payload.elf</code>.</p>

<p>An example implementation of the <code class="language-plaintext highlighter-rouge">main_hook.elf</code> can be found <a href="https://github.com/wiiu-env/payload_loader">here</a>.</p>

<h1 id="backwards-compatiblity">Backwards compatiblity</h1>
<p>The<code class="language-plaintext highlighter-rouge">payload.elf</code> is an abstract payload and can be used for anything. In order to have backwards compatiblity to the old existing homebrew environment, 
I ported the homebrew launcher installer as a <code class="language-plaintext highlighter-rouge">payload.elf</code>, which can be found <a href="https://github.com/wiiu-env/homebrew_launcher_installer">here</a>.
With this it’s possible to have the stable browser exploit with abstract payload loading, but still using the old environment until the new one is finished.</p>]]></content><author><name></name></author><category term="homebrew" /><summary type="html"><![CDATA[This blog entry is intended to discuss the implementation some of the concepts developed in part 3. It will focus on getting stable code execution in form of loading a payload.elf from the sd card. The implementation discussed in this blog post has already been released back in january 2019.]]></summary></entry><entry><title type="html">Creating a homebrew environment on the Wii U - Part 3</title><link href="https://maschell.github.io/homebrew/2019/12/04/new-environment-part3.html" rel="alternate" type="text/html" title="Creating a homebrew environment on the Wii U - Part 3" /><published>2019-12-04T17:00:00+00:00</published><updated>2019-12-04T17:00:00+00:00</updated><id>https://maschell.github.io/homebrew/2019/12/04/new-environment-part3</id><content type="html" xml:base="https://maschell.github.io/homebrew/2019/12/04/new-environment-part3.html"><![CDATA[<p>In this post a homebrew environment is to be designed, which fulfills
all requirements from <a href="/homebrew/2019/11/27/new-environment-part2.html">part 2</a>. 
At the same time the knowledge about already existing solutions shall be considered. The
extent to which these solutions can be reused and which components need
to be revised or newly developed will be discussed in this post.</p>

<p>Existing solutions have so far been designed and developed independently 
of each other. On the one hand they have
been developed one by one, on the other hand the solutions come
from different, independent developers. No overall objective was followed. This leads
to some problems, whereby the defined requirements are not fulfilled.
These have already been explained in the <a href="/homebrew/2019/11/27/new-environment-part2.html">last blog entry</a>.</p>

<p>The following goals can be derived for the conception:</p>

<ul>
  <li>It should be possible to execute homebrew applications.</li>
  <li>At the same time it should be possible to use plugins that can
modify the Cafe OS and execute code in the background.</li>
  <li>IOSU modifications should be available in the homebrew environment
so that they can be expected from applications.</li>
  <li>Maintainability and easy updating should be possible (requirement
8), with as little effort as possible for the end user.</li>
  <li>The requirements already fully met by the existing solutions should
continue to be met.</li>
</ul>

<p>A concept that achieves these goals is developed in the following step.</p>

<h1 id="inital-code-execution">Inital code execution</h1>

<p>An initial code execution must be
enabled so that the setup of the execution environment and thus the
execution of homebrew applications is possible. Since a separate code
execution is not intended, it is necessary to exploit a bug in an
existing application. In general, applications in which data enters
the system or is modified by the user can be considered. This content
could, for example, be savegames, QR codes, websites or other media for a
media player.</p>

<p>On Wii U, it is unfortunately not possible to manipulate savegames in
order to take advantage of possible bugs when reading the savegames.
Wii U content can only be copied to an external medium (USB device) if it’s formatted in a <a href="https://github.com/koolkdev/wfslib">special file system</a>.
In addition, the medium is also encrypted.
The key used for encryption is unique for each console, which means that
no content can be transferred from an already modified console.
Therefore, it is not possible to use modified savegames on a console
without having the corresponding keys. To obtain this key other exploits would be needed. 
Because of this, savegames exploit are not feasible as primary entry exploits.</p>

<p>Another possible entry point would be the integrated web browser. The
following reasons speak for the use of the browser as an entry point:</p>

<ul>
  <li>The web browser is pre-installed on each console.</li>
  <li>The content of a website can be freely crafted.</li>
  <li>Webkit is a well-known browser engine.</li>
  <li>Through irregular updates, security vulnerabilities are fixed with
delay on the Wii U.</li>
  <li>An access to a memory area which is writable and executable at the
same time is given. (JIT-area, internally referred as codegen area)</li>
</ul>

<p>A website with arbitrary content can be created and viewed via the
browser, resulting in a huge attack vector. Due to the complexity of
today’s browsers, security vulnerabilities might occur. Because a known
browser engine is used, exploits are already known and can potentially
be used. In addition, consoles often do not receive regular browser
updates. The <a href="https://wiiubrew.org/wiki/Internet_Browser#Known_User_Agent_Strings">browser versions</a> used are often several years old. 
Information about fixed bugs <a href="https://www.cvedetails.com/product/10007/Apple-Webkit.html?vendor_id=49">can be found</a>
on the Internet. The probability that an already
existing browser exploit can be used is correspondingly high.</p>

<p>In addition, modern browsers use a JIT (just in time) compiler to efficiently execute
JavaScript. The executed JavaScript code is converted to native code at
runtime and then executed. This requires a part in memory that is
writable and executable at the same time. Typically, applications do not
have access to this area. In the case of the browser, however, this is
necessary for efficient execution. In the following, this area in memory
is referred to as the “JIT area”.</p>

<p>The memory available for the JIT compiler in the case of the Wii U
<a href="https://wiiubrew.org/wiki/Cafe_OS#Virtual_Memory_Map">is 32 KiB big</a>. By exploiting the browser with a
<a href="https://en.wikipedia.org/wiki/Return-oriented_programming">ROP</a> (<strong>R</strong>eturn <strong>O</strong>riented <strong>P</strong>rogramming) chain, you can use this memory for your own code. 
For a ROP chain a manipulation of the stack is required. The stack is modified in
such a way that the return addresses execute parts of the existing code
and thus achieve a desired behavior. Using the ROP chain it would be possible
to copy code into the JIT area, where it can be executed, resulting in a true
arbitrary code execution.</p>

<p>This execution is not only limited by the size of the JIT area. At the
same time, code execution is limited to the browser context. Any browser
restrictions apply equally to the own code.</p>

<p>It is therefore desirable to achieve a “better” code execution,
with which it is possible to execute more code in a cleaner context. 
With the exception of the JIT area, applications do not have areas in memory that can be
written and executed at the same time. This is implemented via the
MMU (<strong>M</strong>emory <strong>M</strong>apping <strong>Unit</strong>), which maps the physical memory to virtual memory with
corresponding permissions. This mapping as well as the permissions can
only be changed with (PPC) kernel privileges. This requires another exploit to
make the required modifications. In the following, this exploit is
referred to as the “kernel exploit”. Alternatively, it is also possible to
temporarily disable the MMU. Meanwhile, the memory can be accessed via
the physical addresses. This makes it possible to copy arbitrary code
into executable areas of the memory. The physical addresses can be
obtained for the respective virtual addresses via functions of the
system libraries (OSEffectiveToPhysical).</p>

<p>In order to increase maintainability, it makes sense to load potentially
changing code parts from an external source. This also has the advantage
that an abstraction takes place. Each potential entry point should only
contain as much code as is needed to allow a unified payload to be
loaded from external. In the case of an update, only this single payload
would have to be updated, not the actual exploits or entry points. 
With current solutions for example haxchi and the browser exploit needs to be updated independently.</p>

<p>Loading a secondary payload would to be possible to load from the SD card or via the network. 
When loading over the network, network access is required. In the case of a browser
exploit, this is required anyway; however, other exploits, such as
haxchi, work completely offline and independently. Therefore the payload should be stored
on the SD card. There it can be easily replaced by the user. This,
however, creates a dependency on the SD card.</p>

<p>In order to load the payload from the SD card, access to the SD card is
necessary. Like most applications on the Wii U, the browser does not
have access to the SD card. The pre-installed application <em>Mii Maker</em>
offers the option to store images on the SD card, so it has access to
the SD card. To access the SD card, you need to switch to the <em>Mii Maker</em> 
application. When the applications are switched, the memory
available for the application is cleared. At the same time, the change
also eliminates access to the JIT area and the possibility of code
execution. To ensure that code execution is still possible, a memory
area is required that can be written arbitrarily and can also be
executed. In addition, the content of this memory area must survive the
change of the currently running application in order to be able to store
a payload there.</p>

<p>Such a memory area can be set up using a kernel exploit. A payload must
then be placed in this memory area, which is executed in the context of
the <em>Mii Maker</em> application. It is then necessary to manipulate the Cafe
OS in such a way that the <em>Mii Maker</em> application executes this payload
when it is started. For example, the call of the “main” function of the
application can be replaced by the call of the payload. The necessary
parts of the Cafe OS can be modified thanks to the kernel exploit. In
the following this payload is called <em>“main hook”-payload</em>.</p>

<p>This <em>“main hook”-payload</em> will be executed in the context of the <em>Mii Maker</em>  as soon as the Mii Maker is opened.
It will be used to load another payload from the SD card.
This payload will be called <em>payload.elf</em> in the future.</p>

<center><img src="/res/payload_elf_chain.png" width="450" /></center>

<p>The figure
above shows the procedure for loading and
executing <em>payload.elf</em>, which can be summarized as follows:</p>

<ol>
  <li>Obtaining ROP chain execution using an exploit.</li>
  <li>Using the ROP chain, copy a payload to the JIT area and execute it.</li>
  <li>Use a PowerPC kernel exploit to copy another payload into an area
that survives a switch to the <em>Mii Maker</em> application.</li>
  <li>The Cafe OS must be manipulated so that this payload is executed
after a change of application.</li>
  <li>Switch to the <em>Mii Maker</em> application, which allows access to the SD
card.</li>
  <li>The payload now has access to the SD card and makes it possible to
load another payload from the SD card.</li>
</ol>

<p>On one hand the steps 1 and 2 would need to be created specifically for each application. 
On the other hand the steps 3-6 would be completely independent of the specific exploit and could be re-used without any changes.</p>

<h1 id="code-execution-is-possible">Code execution is possible</h1>

<p>At this point it is possible to load and execute a payload from the SD
card. Theoretically from this point on there is sufficient code
execution to execute any code. However, homebrew applications should
also be executable in the “.rpx” file format, which is not yet possible
at this time. It’s also not possible to run code in the background.</p>

<p>In general, it makes sense that future homebrew applications should only
use the “.rpx” file format. This is the native file format for
executable files on the console and offers the possibility to use the
system libraries directly. All homebrew applications that require a
deeper manipulation of the system (such as replacing system functions) can be implemented as plugins for the
Wii U Plugin System.</p>

<p>In the existing solutions, the “.rpx” files were executed by
manipulating the original <a href="http://wiiubrew.org/wiki/Loader">Cafe OS loader</a>. 
This was done because no control over the IOSU was possible yet. However, it is now possible to simplify this loading
via IOSU modifications. A <a href="https://github.com/QuarkTheAwesome/mocha/commit/8e56a1b2ce15f64fdb016a0dfe197c38be9b453e">proof of concept</a> from the developer
<a href="https://heyquark.com/aboutme/">“QuarkTheAwesome”</a> shows how file paths can be redirected to the SD card
when loading “.rpx” files. In addition, the
integrity checks of the “.rpx” files must be deactivated so that own
files can be loaded.</p>

<p>This approach has the advantage that, except for the manipulation of the
path, the loading is handled by the operating system. In addition,
it is no longer necessary to store the file in a separate memory area,
which may be limited in size.</p>

<p>So that homebrew applications can be executed from the SD
card, a homebrew launcher should be implemented analogous to the
existing one. Applications located on the SD card should be able to be
started via this launcher. The launcher will consist of a graphical user
interface which controls the redirection of the “.rpx” files. This
Homebrew Launcher can itself be implemented as a “.rpx” file and
executed via the redirections. To be able to start the Homebrew
Launcher, it should be opened when starting an application. This
requires a fixed rule in the “.rpx” redirection which exchanges the path
to this application with the path to the “Homebrew Launcher” which is
located on the SD card. Which application is exchanged is not relevant.
However, it is a good idea to select an application that is rarely used (for example the Health and Safety application).</p>

<p>In order to load “.rpx” files, an IOSU exploit is required to manipulate
the operating system to allow redirections. This IOSU exploit can be implemented in the form
of a <em>payload.elf</em>, which is loaded from the SD card from PPC userland exploits.</p>

<p>The IOSU exploit can either be used to load a modified fw.img from the SD
card, or to manipulate the IOSU in memory on-the-fly. After a restart, the
desired changes take effect. The problem with using a full custom fw.img is 
that it may contain copyrighted code and is not that easy to share.</p>

<p>In view of a possible future vulnerability in the bootrom, it would also be thinkable to create a own fw.img which does not have this problem.
An exploit of the bootroom would allow the execution of a fw.img directly at the start of the console.
If it is possible to boot directly into a own fw.img, this can serve as an early code execution and then modify and execute the original fw.img “on-the-fly”.</p>

<p>Such a fw.img could also be executed via usual IOSU exploits, but
without a corresponding vulnerability in the bootrom it does not bring
any advantages. For this reason, the IOSU modification should be done
via the <em>payload.elf</em> loaded from the SD card. All possibilities to
restart into the modified IOSU are shown in the following figure:</p>

<center><img src="/res/fw_img.png" width="550" /></center>

<p>After a restart into the modified IOSU, the corresponding IOSU
modifications, and thus also the “.rpx” redirection, are available. A
fixed redirection ensures that the start of a previously defined
application loads a “.rpx” file, in this case a Homebrew Launcher, from
the SD card. This Homebrew Launcher should enable the user to load any
homebrew application from the SD card. This requires a mechanism to
control the “.rpx” redirection. The IPC (<strong>I</strong>nter-<strong>p</strong>rocess <strong>c</strong>ommunication) interface for communication
between the Cafe OS and IOSU will be extended by a new IOCTL. The Homebrew
Launcher also needs access to the SD card in order to be able to show
the user a corresponding selection of possible homebrew applications. A
IOSU modification has to bypass the restriction that only
certain applications have access to the SD card.</p>

<p>Theoretically it would be possible to execute the IOSU exploit directly
in the browser exploit and restart the operating system with the desired
changes. Switching to the <em>Mii Maker</em> application and thus a kernel
exploit would no longer be necessary. A sufficient code execution is
given by the JIT area. However, the abstraction of the entry points and
thus the central payload on the SD card is lost. If the IOSU exploit is
modified or the desired IOSU modifications change, all entry points
would have to be updated (independently). Only a own fw.img, which
is used to start the original fw.img with on-the-fly modification, would benefit speed wise. 
A switch to the Mii Maker application wouldn’t be needed anymore. However,
this would lose the flexibility offered by a central payload from the SD
card. It would only be possible to execute a fw.img file, but no longer
generic code, from the SD card.</p>

<p>The following figure summarizes the current state starting from a
<em>payload.elf</em>. Homebrew applications can be loaded in the form of “.rpx”
files after a restart via a homebrew launcher. For this purpose, a
<em>payload.elf</em> is loaded from the SD card, which performs an IOSU exploit
and any necessary IOSU modifications. After a restart these
modifications take effect and the Homebrew Launcher can be started by
starting a previously defined application. The Homebrew Launcher can be
used to start the individual Homebrew applications.</p>

<center><img src="/res/hbl.png" width="450" /></center>

<p>At the same time it’s still possible to create a <em>payload.elf</em> implementation that 
recreates the old solution to provide backwards compatibility.</p>

<h1 id="code-execution-after-restart">Code execution after restart</h1>

<p>After rebooting into a modified IOSU, the Cafe OS will also be reloaded,
causing all temporary changes on the PPC side to be lost. Theoretically, it would be
possible to reboot into a modified Cafe OS, but this would add a
dependency on the IOSU exploit based on the implementation.</p>

<p>Instead, the privileges should be regained independently by using a
kernel exploit. Should only an IOSU exploit but no kernel exploit be
possible in a future operating system version, manipulation of the
PowerPC kernel from the IOSU would be an option.</p>

<p>The “.rpx” redirection can be used to get code execution after a
restart. After the restart, the system menu is loaded first. It is a
reasonable idea to redirect the loading of the corresponding “.rpx” file
to the SD card once so that code can be executed immediately after the
operating system has been restarted. In the following, this “.rpx” file
is referred to as <em>root.rpx</em>.</p>

<p>With the help of the code execution, the operating system can be set up
on the PowerPC processor. Full control over the PowerPC processor and
thus the Cafe OS can be obtained via a kernel exploit.</p>

<p>In order to keep code execution, the Cafe OS has to be modified. Again
the invocation of the “main” function is replaced by a jump to the own
code. For this payload, a separate memory area must be defined,
analogous to the original homebrew launcher in which the payload is
stored. The payload can be loaded from the SD card and is then called
each time the application is opened. This allows code execution parallel
to the actual homebrew applications. In the following this payload is
called <em>hook_payload.elf</em>. An overview is shown in the following figure:</p>

<center><img src="/res/root_rpx.png" width="350" align="middle" /></center>

<p>In addition, the homebrew environment on the PowerPC processor can be
further set up and configured.</p>

<h1 id="manipulation-of-the-cafe-os">Manipulation of the Cafe OS</h1>

<p>Each time an application is started, <em>hook_payload.elf</em> is executed,
which provides ongoing code execution. This is also the case if homebrew
applications are started via the Homebrew Launcher.</p>

<p>Among other things, it should be possible to manipulate the system
libraries of the Cafe OS. To do this, the Wii U plugin system can be
reused. This makes it possible to load plugins from the SD card which
can manipulate the functions of the system libraries.</p>

<p>For this the plugin system has to be updated. So far it was implemented
as an application for the Homebrew Launcher. Now the plugin system
should run independently from the Homebrew Launcher to allow
simultaneous use. For this purpose the plugin system must be executable
without the previous environment of the Homebrew Launcher. On the other
hand, the actual business logic and the graphical interface, which is
used to activate the plugins, must be separated. The business logic is
to be integrated into <em>hook_payload.elf</em> and a graphical user interface
is to be implemented as a homebrew application (.rpx).</p>

<p>With the help of the integrated plugin system in <em>hook_payload.elf</em> a
code execution in the background as well as the manipulation of the
functions of system libraries by plugins is possible. The functions can
be manipulated by directly replacing the first instruction of a function in memory in such a
way that own code is executed instead. If the overwritten instruction is
remembered, the original function can also be executed. System events
can be propagated to the plug-ins by specifically hooking into
certain functions of the system libraries. By creating threads, code can be executed in the
background for use. Due to the direct code execution after starting the
homebrew environment, it is also possible to execute plugins straight
away after booting into the homebrew environment.</p>

<p>A mechanism for communication with the business logic of the plugin
system is required so that a graphical interface in the form of a
homebrew application can control the plugins. For this reason it is
necessary to create a kind of IPC interface between <em>hook_payload.elf</em>
and homebrew applications.</p>

<p>It would be optimal if these background operations did not take away any
resources, such as memory, from the actually running application. If
enough unused memory is available, it can be mapped as virtual memory
using the kernel exploit. It may be possible that this memory can be
used as heap for plugins and other background processes that run
simultaneously to the normal system operations.</p>

<p>In summary, the homebrew environment can be seen in the follwing figure:</p>

<center><img src="/res/umgebung.png" width="550" align="middle" /></center>

<h1 id="full-control-over-the-system">Full control over the system</h1>

<p>So far, the IOSU exploit has been used to redirect the “.rpx” files.
However, other modifications can be implemented using the exploit.</p>

<p>Access to the file system is controlled by the IOSU. Each application
only has access to its own files, so system files are not accessible. In
order to gain access to the entire file system, the IOSU must be
modified accordingly.</p>

<p>Furthermore, (console-specific) cryptographic keys can be read. These
can be used, for example, to decrypt content or external media.</p>

<p>Similar to the communication between homebrew applications and the
<em>hook_payload.elf</em>, homebrew applications must be able to communicate
with the IOSU in order to benefit from these modifications. In this
case, the existing IPC interface can be used for communication between
the ARM and PowerPC processors. However, it is necessary to register a
separate endpoint with its own functions (wupserver).</p>

<p>In addition, the IOSU exploit can be used to access the full hardware.
Among other things, the internal storage could be accessed directly,
allowing a backup or recovery. These functionalities are not necessary
in the planned execution environment, but can be implemented in a
separate <em>payload.elf</em> if required. Alternatively a fw.img of the already existing
hexFW mentioned in previous blog posts can be used.</p>

<h1 id="persistent-code-execution">Persistent code execution</h1>

<p>All changes discussed so far are only temporary and disappear after
restarting or switching off the console. To be able to use the homebrew
environment again, it must be set up again via the browser (or any other entrypoint). The goal is
to achieve an (optional) persistent executon enrionment where the
browser exploit does not have to be executed manually.</p>

<p>The Wii U system files contain a configuration file that defines which
application should be executed after the console has been started (“system.xml”). It is
possible to manipulate this file using the IOSU exploit. If you select
an application that executes an exploit immediately, the console is
effectively started in the homebrew environment.</p>

<p>Unfortunately, the browser is not suitable for this because the web page
containing the exploit has to be called manually. In addition, this
would mean a dependency on a network connection, so an independent use
would not be possible.</p>

<p>Complete access to the file system increases the attack vector for
exploits. Manipulating files used by applications is now possible. In
addition to the savegames that can now be manipulated, it is now
possible to manipulate any files from applications, since their
integrity is only checked during installation, not at runtime (this is sometimes referred as “contenthax”).</p>

<p>It makes sense to use the haxchi exploit already introduced in the last blog entry.
This exploits a
security vulnerability in applications that have integrated a Nintendo
DS emulator. The ROM to be executed, i.e. the game, is located in the
“/content” folder, whose integrity is not checked at runtime. It is
therefore possible to exchange or modify this ROM. Due to a bug when
reading this ROM, a ROP chain execution is possible. Like the browser,
the Nintendo DS emulator also has access to the JIT area. The ROM is
read in directly after the application has been started and is therefore
suitable for persistent execution after the console has been started.
Similar to the browser exploit, the code execution can be used to load
the <em>payload.elf</em> from the SD card. The remaining procedure is identical
to the previous execution via the browser exploit, and thus starts the
homebrew environment. An update of the homebrew environment via
<em>payload.elf</em> has effects on a start via the browser exploit as well as
the haxchi exploit, resulting in a good maintainability.</p>

<p>It has to be considered that the original application, which executes
the haxchi exploit, can no longer be used. In addition, the memory of
the console is permanently changed and a compatible application must be
purchased, resulting in one-time costs.</p>

<p>Furthermore, it should be noted that a direct start in the haxchi
exploit, i.e. coldboot haxchi, also involves risks. The manipulation,
which application is executed when starting the console, is a deep
manipulation of the system. If the target application fails to start for
any reason, the entire console can no longer be used. This is also the
case if this application is accidentally deleted.</p>

<h1 id="fulfillment-of-the-goals">Fulfillment of the goals</h1>

<p>The goals defined at the beginning of the blog post can be achieved with
the presented concept.</p>

<p>With the help of “.rpx” redirections, which can be controlled via a
graphical user interface in the form of a new homebrew launcher, it is
possible to execute homebrew applications. The plugin system shall be
embedded in the <em>hook_payload.elf</em> and a control via a homebrew
application shall be possible. This decoupling of the Plugin System from
the Homebrew Launcher allows a simultaneous use. Homebrew applications
can only be executed after the execution environment has been started.
Thus the applications can now expect that corresponding IOSU
modifications have been performed. All relevant payloads that could
potentially change are loaded from the SD card. This makes it easy to
maintain and update the individual components of the homebrew
environment.</p>

<p>In summary, this last figure shows an overview of the concepts presented in
this blog entry.</p>

<center><img src="/res/gesamt.png" width="600" align="middle" /></center>]]></content><author><name></name></author><category term="homebrew" /><summary type="html"><![CDATA[In this post a homebrew environment is to be designed, which fulfills all requirements from part 2. At the same time the knowledge about already existing solutions shall be considered. The extent to which these solutions can be reused and which components need to be revised or newly developed will be discussed in this post.]]></summary></entry><entry><title type="html">Creating a homebrew environment on the Wii U - Part 2</title><link href="https://maschell.github.io/homebrew/2019/11/27/new-environment-part2.html" rel="alternate" type="text/html" title="Creating a homebrew environment on the Wii U - Part 2" /><published>2019-11-27T18:33:00+00:00</published><updated>2019-11-27T18:33:00+00:00</updated><id>https://maschell.github.io/homebrew/2019/11/27/new-environment-part2</id><content type="html" xml:base="https://maschell.github.io/homebrew/2019/11/27/new-environment-part2.html"><![CDATA[<p>The <a href="/homebrew/2019/11/20/new-environment-part1.html">last blog entry</a>
  brought an overview of the internal structure of the Wii U. 
So that a homebrew environment can be designed, some requirements will be specified in this entry.
Afterwards the existing solutions will be considered and compared with these requirements.</p>

<h2 id="requirements">Requirements</h2>

<ol>
  <li>
    <p><strong>The execution of own/unsigned software is possible:</strong><br />
The homebrew environment should make it possible to execute any
software written by the user. It should be possible to load and
execute own software from an SD card.</p>
  </li>
  <li>
    <p><strong>The existing operating system is still used:</strong><br />
The installed homebrew environment should use the existing operating
system as a basis instead of starting its own operating system. It
should still be possible to run official software. The applications
or the operating system should be able to be modified by the
homebrew environment.</p>
  </li>
  <li>
    <p><strong>The existing operating system can be manipulated:</strong><br />
It should be possible to manipulate and extend the existing
operating system if needed. For example, restricted access to the SD
card can be removed and functions of the system libraries can be
replaced.</p>
  </li>
  <li>
    <p><strong>Code execution in the background is possible</strong><br />
During runtime, for example during the execution of a game, it
should be possible to execute your own code in the background. This,
together with requirement 3, should allow the software to be
enhanced.</p>
  </li>
  <li>
    <p><strong>The homebrew environment is available after console start</strong><br />
After a one-time setup, the homebrew environment should (optionally)
immediately be usable. It should be possible to start in an homebrew
environment in which the operating system modifications are
available and own code execution is possible.</p>
  </li>
  <li>
    <p><strong>The homebrew environment can be implemented without hardware modifications</strong><br />
Only software solutions should be necessary to achieve this homebrew
environment. Physical modification of the hardware should not be
necessary.</p>
  </li>
  <li>
    <p><strong>The homebrew environment can be used on the latest version of the operating system</strong><br />
The homebrew environment should be executable on any <em>Wii U</em> that
has not yet been modified. No specific versions of the operating
system should be required, which cannot be reached via updates.</p>
  </li>
  <li>
    <p><strong>The homebrew environment should be easy to update and maintain</strong><br />
Simple usage and updating of the homebrew environment should be
achieved. Updates should be possible via a central point, such as
replacing files on the SD card.</p>
  </li>
</ol>

<h2 id="existing-solutions">Existing solutions</h2>

<p>At first, we will look at existing solutions that are publicly available
for the Wii U. Subsequently, it shall be considered where the weaknesses
of these solutions lie and which of these solutions can be adapted to
meet the requirements set.</p>

<h3 id="execution-of-own-applications">Execution of own applications</h3>

<p>Users can run homebrew applications on <em>Wii U</em> via the so-called
<em>Homebrew Launcher</em>. To use this, an initial entry point
into the system via an exploit is required. In addition, a kernel
exploit is required, which is integrated with the <em>Homebrew Launcher</em>.
While the <em>Homebrew Launcher</em> is executed via a browser exploit,
theoretically other entry points are also possible. The corresponding
homebrew applications are loaded from the SD card and then executed.</p>

<p>The <em>Homebrew Launcher</em> is divided into three components:</p>

<ul>
  <li>Installer</li>
  <li>sd-loader</li>
  <li>GUI</li>
</ul>

<p><strong>Installer</strong>: The installer is the part that is executed via a browser
exploit, for example. The installer performs various initial tasks to
prepare the system for loading additional code. The first task is to
obtain kernel privileges using a kernel exploit. This allows you to set
up your own memory area. This memory area has read, write, and execute
permissions. The Cafe OS does not use this memory area, so it can be
used as memory for the <em>Homebrew Launcher</em>. After setting up the memory
area, the sd-loader is copied to this area and remains there until the
console is turned off. The system is then manipulated so that the call
to an application first executes the sd-loader and then the actual
application.</p>

<p><strong>sd-loader</strong>: Before each application is started, the sd-loader is
executed. Its task is to execute either the graphical interface of the
<em>Homebrew Launcher</em>, the actual application, or a homebrew application.
In the sd-loader, it is implemented that the graphical user interface is
called as soon as the user starts the <em>Mii Maker</em> application. It is
necessary to use the <em>Mii Maker</em> application for this as it is the only
pre-installed application that has access to the SD card. This access is
defined per application and is enforced via the <em>IOSU</em>.</p>

<p><strong>GUI</strong>: The graphical user interface allows the user to select which
homebrew application is to be executed. If the user decides to execute
an application, it is loaded into the user’s own memory area. The
sd-loader recognizes the loaded application and executes it at the next
application start. After loading, the graphical user interface triggers
a restart of the <em>Mii Maker</em> application and thus initiates the
execution of the homebrew application. A reopening of the Mii Maker
application starts the graphical user interface of the <em>Homebrew
Launcher</em>.</p>

<p>Own homebrew applications can be created using the devkitPPC development
environment, which is part of the devkitPro development
environment. With the <em>Homebrew Launcher</em>, it is possible to execute
homebrew applications in the execution file format of <em>Wii U</em> (.rpx), as
well as statically linked ELF files.</p>

<p>The ELF files, statically linked, must use an address as the start address,
which is located in the own memory area. Since the memory is limited,
the applications must not be larger than 6.4 MiB. To be
able to use the official system libraries, the <em>Homebrew Launcher</em>
provides the necessary addresses of the functions “OSDynLoad_Acquire”
and “OSDynLoad_FindExport”. These can be read via fixed addresses in
the memory. With them, it is possible to load system libraries
(“OSDynLoad_Acquire”) and get the addresses of their functions
(“OSDynLoad_FindExport”). The homebrew application is copied directly
to the address it is linked to and can be executed from there. By
statically linking, it is not possible to run multiple homebrew
applications at the same time because they would overwrite each other.
Since the code is position-dependent, it cannot be loaded to another
address.</p>

<p>In addition, with the <em>Homebrew Launcher</em>, it is possible to run homebrew
applications in the “.rpx” file format. The “.rpx” files offer the
possibility to link directly dynamically against system libraries. In
general, the loader of the Cafe OS is responsible for loading and
linking “.rpx” and “.rpl” files. It receives the data from the <em>IOSU</em>
after the integrity has been checked there. The <em>Homebrew Launcher</em> also
uses the loader to load the “.rpx” files. Because the integrity of the
files has already been checked in the <em>IOSU</em>, the received data can be
manipulated. In concrete terms, the loader is manipulated in such a way
that the data is used from its own memory area and thus the homebrew
applications are loaded. The maximum size of the “.rpx” file depends on
the size of the own memory area. The development environment/SDK
<a href="https://github.com/decaf-emu/wut">wut</a> can be used to create your own applications in the “.rpx” file
format.</p>

<h3 id="persistent-code-execution">Persistent code execution</h3>

<p>In addition to the browser exploit as the entry point, further entry
points are possible. To achieve code execution, a vulnerability in the Nintendo DS
emulator is exploited when loading games. This exploit is known as
<a href="https://github.com/FIX94/haxchi">haxchi</a>.</p>

<p>In contrast to the browser exploit, which requires a connection to a
network to load a website, haxchi can be used completely offline after
installation and thus independently. However, control over the system is
already necessary for the installation, since the application files must
be modified. Therefore, haxchi cannot therefore be used as an initial entry point
into the system.</p>

<p>When the application is started, a game to be emulated is loaded from
the “/content” folder. The integrity of the files from this folder is
only checked at the time of installation, but not afterwards. If this
game is replaced with a modified version that uses an error in
interpreting the file, code execution is possible. From there, the
<em>Homebrew Launcher</em> can be temporarily installed and used, similar to
the browser exploit.</p>

<p>A system file (system.xml) defines which application is executed when the console is
started. If exploits can be used to control the <em>IOSU</em>, this file can be
modified to run an application with haxchi exploit instead of the system menu. 
This allows it to get code execution after starting the console with any manual user input. This
is also known as cold-boot haxchi or cbhc. This, however, comes with some risks. 
If the system can’t boot the set title, the console will refuse to start.</p>

<h3 id="manipulation-of-the-cafe-os">Manipulation of the Cafe OS</h3>

<p>With the help of a kernel exploit it is possible to manipulate the
entire memory over which the PowerPC processor has control. This can be
used to modify and extend the code of the loaded system libraries.</p>

<p>This is partly done by the homebrew applications themselves to
manipulate the behavior of the Cafe OS. For example, there are homebrew
applications that redirect file accesses from the internal memory to the
SD card (<a href="https://github.com/Maschell/SDCafiine">SD Cafiine</a>) or manipulate controller inputs (<a href="https://github.com/Maschell/hid_to_vpad">HID to VPAD</a>).</p>

<p>Alternatively, the <a href="https://github.com/Maschell/WiiUPluginSystem"><em>Wii U Plugin System</em></a> application can be used to
load plugins. This is an application in ELF file format that is executed
via the <em>Homebrew Launcher</em>. The <em>Wii U Plugin System</em> allows the
simultaneous use of multiple plugins loaded from the SD card. The
plugins are normal ELF files that contain additional information in
their own ELF sections.</p>

<p>Plugins can be used to overwrite the functions of the system libraries
to modify their implementation. The first command of the functions is
overwritten with a jump into its own implementation. In addition,
plugins can be used to execute code in the background parallel to the
actual operation of the system. Furthermore, plugins can define
functions that are called by the plugin system during certain events of
the operating system. This could be, for example, starting or stopping
an application.</p>

<h3 id="manipulation-of-the-iosu">Manipulation of the IOSU</h3>

<p>To manipulate the <em>IOSU</em>, appropriate exploits are necessary to
gain control over the <em>IOSU</em>. A customized IOSU makes it possible, among
other things, to read cryptographic keys from the console, gain full
control over the console’s file system, and temporarily disable digital
signature checks.</p>

<p>By disabling digital signature verification, it is possible to install
incorrectly signed content on the system. However, this content can only
be used as long as signature verification is disabled. As soon as the user 
restart the console, the titles can’t be started anymore until the user 
uses the customized IOSU again.
Furthermore, it is possible to manipulate the rights of the running application that are
managed and implemented in the <em>IOSU</em>. This means, for example, that
access to the SD card can be obtained in any application.</p>

<p>At the time of this blog post, several implementations of
<em>IOSU</em> exploits and similar <em>IOSU</em> modifications are publicly available.
This combination of <em>IOSU</em> exploits and <em>IOSU</em> modifications is
typically called custom firmware (cfw). The most common custom firmware
implementations are <a href="https://github.com/dimok789/mocha">mocha</a> and a custom firmware integrated in
haxchi.</p>

<p><em>IOSU</em> modifications are implemented by either restarting the system
with a previously modified fw.img or by modifying the existing fw.img at
runtime. In theory, it is also possible to use a completely separate
fw.img, for example, to start Linux as an independent operating system using 
<a href="https://gitlab.com/linux-wiiu/linux-loader">linux-wiiu</a>.</p>

<h3 id="current-use-of-the-solutions-at-a-glance">Current use of the solutions at a glance</h3>

<p>All existing solutions presented in this subsection can be used without
permanently modifying the console. The browser exploit can be used to
launch the <em>Homebrew Launcher</em> and the Homebrew application. To
get control over the <em>IOSU</em> and thus the whole system, a custom
firmware, for example in the form of mocha, has to be executed
additionally.</p>

<p>By modifying the internal memory of the console, an application
compatible with haxchi can be permanently used as an entry point. 
To be able to perform these modifications, however, control over
the <em>IOSU</em> is necessary, which is achieved via the browser exploit and
an <em>IOSU</em> exploit. The <em>Homebrew Launcher</em> can be started once via the
browser exploit and haxchi can be installed via its own installer. An
<em>IOSU</em> exploit is integrated directly in the installer. After powering
on the console, the <em>Homebrew Launcher</em> and/or the Custom Firmware
integrated into haxchi can be used via this application by starting 
the haxchi application.</p>

<p>By modifying the system.xml in the internal memory of the console the
start of the console can be redirected to an application with haxchi.
Then the Homebrew Launcher or a custom firmware can be used immediately
after switching on the console.</p>

<h2 id="meeting-the-requirements">Meeting the requirements</h2>

<p>With the existing solutions presented in this section, <strong>requirement 1</strong>
to run own software is fulfilled. Using the <em>Homebrew Launcher</em>, it is
possible to run homebrew applications in both ELF and “.rpx” file
formats. However, the size of the application is limited by the size
that can be defined as its own memory area. In addition, for loading the
“.rpx” files, the loader of the Cafe OS is modified to replace the data
received from the <em>IOSU</em> with its own. With <em>IOSU</em> control, the loading
of “.rpx” files can be modified on the <em>IOSU</em> side, eliminating the need
to modify the loader.</p>

<p><strong>Requirement 2</strong>, the use of the existing operating system, is also
fulfilled. The system can be used as usual. The manipulation of the
existing operating system requested in <strong>requirement 3</strong> is possible via
a custom firmware and the <em>Wii U</em> plugin system. <em>IOSU</em> changes are
possible with the Custom Firmware and Cafe OS changes with the <em>Wii U Plugin System</em>.
In general, code execution in the background by plug-ins
as required in <strong>requirement 4</strong> is possible, but not in combination
with homebrew applications. Because the <em>Wii U Plugin System</em> itself is
a homebrew application, plugins cannot be used simultaneously with other
homebrew applications.</p>

<p><strong>Requirement 5</strong> requires that the homebrew environment be available
after the console starts. By using cold boot haxchi it is possible to
run a custom firmware or the <em>Homebrew Launcher</em> directly after starting
the console. However, it is not possible to use the <em>Wii U Plugin System</em> 
directly, which means that the requirements are only fulfilled
to a limited extent by the currently existing solutions.</p>

<p><strong>Requirements 6 and 7</strong> are again met. It requires the homebrew
environment to be up to date with the latest version of the operating
system and without hardware modifications. The existing solutions only
use software exploits that can be used on the latest version of the
operating system.</p>

<p>One problem of existing solutions is maintainability. <strong>Requirement 8</strong>
requires that the homebrew environment be easy to maintain and update.
This is not always the case. The entry points use exploits with static
payloads. For example, the installer of the <em>Homebrew Launcher</em> is
integrated into the exploits that are used as entry points. Furthermore,
the installer is responsible for the complete setup of the homebrew
environment. To update the installer or sd-loader of the <em>Homebrew Launcher</em>,
all exploits that can start the <em>Homebrew Launcher</em> must be
updated. Exploits like haxchi would have to be completely reinstalled. A
centralized update is not possible.</p>

<p>There is no clear separation between the actual homebrew applications,
exploits and utility applications. The plugin system is implemented as a
homebrew application, although it is itself responsible for loading and
executing plugins. This prevents the simultaneous use of plugins and
homebrew applications. In addition, custom firmware is also
implemented as homebrew applications that are started by the user. An
application cannot rely on a custom firmware already running.
Applications that need control over the <em>IOSU</em> have partially integrated
the <em>IOSU</em> exploit or even a complete custom firmware into the existing
solutions. For example, an <em>IOSU</em> exploit is integrated with the haxchi
installer to allow access to the entire file system.</p>

<h1 id="next-blog-entry">Next blog entry</h1>
<p>The next blog entry will propose a concept for a homebrew environment that meets the specified requirements.</p>]]></content><author><name></name></author><category term="homebrew" /><summary type="html"><![CDATA[The last blog entry brought an overview of the internal structure of the Wii U. So that a homebrew environment can be designed, some requirements will be specified in this entry. Afterwards the existing solutions will be considered and compared with these requirements.]]></summary></entry><entry><title type="html">Creating a homebrew environment on the Wii U - Part 1</title><link href="https://maschell.github.io/homebrew/2019/11/20/new-environment-part1.html" rel="alternate" type="text/html" title="Creating a homebrew environment on the Wii U - Part 1" /><published>2019-11-20T17:05:00+00:00</published><updated>2019-11-20T17:05:00+00:00</updated><id>https://maschell.github.io/homebrew/2019/11/20/new-environment-part1</id><content type="html" xml:base="https://maschell.github.io/homebrew/2019/11/20/new-environment-part1.html"><![CDATA[<p>Some time ago, I went on a journey to create a new homebrew environment for the Wii U. 
An environment where homebrew applications can be run easily and on Wii U.
It’s been possible to run your own software on Wii U since 2015, but I wasn’t satisfied with the existing solutions. 
Some solutions, such as the Homebrew Launcher, date back to a time when no public IOSU exploit was known. 
In order to run Homebrew, some compromises had to be made.</p>

<p>Over time the whole thing became more and more confusing for the users:</p>

<ul>
  <li>There are different cfws (mocha vs haxchi) with different features</li>
  <li>Some apps require a special cfw (e.g. mocha with sd patches)</li>
  <li>There are two different formats for hombrews (rpx vs elf)</li>
  <li>Simultaneous use of plugins and homebrew application is not possible</li>
  <li>Updating any existing exploit is not quite user friendly</li>
  <li>and much more…</li>
</ul>

<p>In the following blog posts I want to give you an insight into how I tried to create my own homebrew environment and fix these existing problems.</p>

<p>This first post will be about giving a brief overview of the Wii U.</p>

<h1 id="the-wii-u">The Wii U</h1>

<p>Technical details about the exact hardware and software structure are
not available directly from <em>Nintendo</em>. Accordingly, the following
information comes from third parties and has been determined by reverse
engineering. A great source for internals of the system is <a href="https://fail0verflow.com/blog/2014/console-hacking-2013-omake/">this blogpost</a> 
by fail0verflow, <a href="https://wiiubrew.org/wiki/Main_Page">WiiUBrew Wiki</a> and the <a href="https://github.com/decaf-emu/decaf-emu">decaf-emu</a>.</p>

<h1 id="operating-system">Operating System</h1>

<p>The operating system of the <em>Wii U</em> is an own implementation of Nintendo
and is not based on an already existing operating system (like linux).
Exploits of similar systems cannot be taken over. On
the other hand, the probability of overlooking implementation errors
that can be exploited by third parties increases. Often there is a
cat-and-mouse game between the “hackers” and the manufacturers, in which
new exploits are found again and again and then fixed by Nintendo. 
Over time, this increases the security of the system.
It is only possible to run correctly digitally signed software. 
There is no possibility to officially run own code (“homebrew”).</p>

<p>The <em>Wii U</em> operating system is split between the PowerPC and ARM
processors. The so-called <em>Cafe OS</em> runs on the PowerPC processor,
while the <em>IOSU</em> runs on the ARM processor. These are described in
detail below:</p>

<p><strong>IOSU</strong>: The <em>IOSU</em> is based on a microkernel architecture and is
responsible for the boot process and all hardware accesses. It is a
continued development of the IOS, which runs on the ARM processor of the
Wii. In addition, it enforces the <em>Wii U</em> security guidelines. All
digital signatures are verified by the <em>IOSU</em>. The <em>Cafe OS</em> can
communicate with the <em>IOSU</em> via an IPC-interface.</p>

<p><strong>Cafe OS</strong>: The PowerPC processor runs the <em>Cafe OS</em> in which the
applications are executed. The <em>Cafe OS</em> itself consists of several
components. On the one hand there is the kernel, which manages the
processor. The kernel runs in “supervisor mode” and manages the running
application, the mapping of the physical memory to the virtual memory
and is responsable for the process isolation. In addition, communication with
the <em>IOSU</em> is handled by the kernel. On the other hand, there is the
loader, which is responsible for loading and dynamically linking the
executable files. In addition to the actual application, the loader also
loads software libraries that are themselves part of the <em>Cafe OS</em>. The
execution files “.rpx” and software libraries “.rpl” on the <em>Wii U</em> 
based on the ELF fileformat with some additions. The individual ELF 
sections are compressed and the imports and exports are defined in separate sections.</p>

<p>Applications run on the PowerPC processor with user privileges and thus
with restrictions - including limited access to memory. For example, it
is implemented that regions in memory cannot be written to and executed
by the application at the same time. Among other things, this concept
prevents trivial code execution, which becomes possible if the stack of
a thread can be manipulated via a buffer overflow.</p>

<p>This division of tasks between the processors has the side effect that
control over the PowerPC processor where the games are running 
does not allow control over the entire
system. If an error in an application is exploited and the ability to
execute code is obtained, it is still not possible to read sensitive
information from the <em>IOSU</em>, such as cryptographic keys used to decrypt
critical parts of the system. A separate MPU ensures that the memory of the <em>IOSU</em> cannot be read despite
control over the PowerPC.</p>

<p>Applications are executed either from the internal memory or from an
optical medium. The files of an application are divided into three
subdirectories, “/code”, “/content” and “/meta”, which are described in
more detail below.</p>

<p><strong>/code</strong>: The “/code” folder contains execution files, additional
libraries and configuration files that configure the memory or the
permissions of the application, for example. The executable files are
loaded by the loader, i.e. directly on the PowerPC processor, and linked
dynamically, with the data coming from the <em>IOSU</em>. The remaining files
are processed directly by the <em>IOSU</em>. The integrity of these files is
ensured by the <em>IOSU</em> each time the application is started.</p>

<p><strong>/meta</strong>: The “/meta” folder contains the meta information of the
application, such as the electronic manual, graphics displayed at
startup, and another configuration file. The “meta.xml” file stores,
for example, the title of the application in the various
languages.</p>

<p><strong>/content</strong>: The actual data used by the application is stored in the
“/content” folder.</p>

<p>As soon as the user opens the “Home Menu” via the controller, the
current application will then only be running in the background. From
there, the application can be closed or additional applications such as
the browser or the friends list can be launched. While a application is running
in background it’s limited to use only one of the CPU-Cores.</p>

<h1 id="boot-process--chain-of-trust">Boot process / Chain of Trust</h1>

<p>With the <em>Wii U</em> the boot process takes place in several stages. 
The <em>Wii U</em> implements the
concept of the <em>chain of trust</em>. If the integrity of one stage is
guaranteed, the integrity of the next stage can be guaranteed. If the
Chain of Trust is broken at one point, the integrity remains intact up
to the previous stage.</p>

<p>The boot process of the <em>Wii U</em> starts with the first stage of the
bootloader <strong>boot0</strong>. Boot0 is located in a ROM within the ARM
processor, embedded in hardware. This means that it can only be read,
but not changed, and thus provides the basis for the <em>chain of trust</em>,
i.e. the so-called “Trust Anchor”. The manufacturer must ensure that
this level does not contain any vulnerabilities, as these cannot be
patched by software. The task of this stage is to read the next stage of
the bootloader boot1 from the internal memory, decrypt it and then
verify its digital signature. On success, the boot1 stage is executed. A
pseudo code of this step can be found <a href="https://wiiubrew.org/wiki/Boot0">here</a>.</p>

<p>The <strong>boot1</strong> stage is not implemented in hardware, so it can be updated by
the manufacturer, but it is digitally signed. The digital signature
ensures the authenticity and integrity of the level. A suitable digital
signature from a third party cannot be created without the private key.
This concept is consistently implemented for all further stages. At this
stage, the hardware is initialized and then a further stage in the form
of a fw.img file is loaded from the internal memory, decrypted and its
digital signature verified. The fw.img file contains the <em>IOSU</em>, the
operating system running on the ARM processor. It consists of a simple
ELF loader and the actual <em>IOSU</em> modules. This ELF loader is executed at
the end of the boot1 stage. A pseudo code of level boot1 can be found
under <a href="https://wiiubrew.org/wiki/Boot1">here</a>.</p>

<p>The <strong>ELF loader of the <em>IOSU</em></strong> is responsible for loading the <em>IOSU</em>
kernel. This is responsible for loading the remaining <em>IOSU</em> (user)
modules. It also loads the kernel for the PowerPC processor, which is
part of the <em>Cafe OS</em>. This is loaded from the internal memory of the
kernel.img file. The ELF loader decrypts the kernel and verifies its
digital signature.</p>

<p>The <strong>PowerPC kernel</strong> is responsible for initializing the PowerPC processor
and loads the loader from internal memory. This is also decrypted and
the integrity and authenticity is checked using the digital signature.
System libraries and applications can then be loaded via the loader.</p>

<p>A <em>chain of trust</em> is given. Each stage checks the next one, while the
initial stage is unchangeable and trustworthy. This extends all the way
to the application that the user sees at the end. The execution of an
own firmware is basically not possible at startup, even if the
corresponding files are exchanged. As a result, <em>Nintendo</em> can be the
only company that releases firmware. In order to gain control over the
system, the <em>chain of trust</em> must be broken at any point.</p>

<h1 id="how-to-gain-control-over-the-system">How to gain control over the system</h1>

<p>The sooner the <em>chain of trust</em> can be broken, the sooner control over
the system can be gained. Earlier control also provides more control
over the system because less code was running that cannot be controlled.
The integrity of all potentially subsequent stages is no longer assured.
If the <em>chain of trust</em> is broken at a later point in time, the
integrity of all previous levels remains intact. In order to be able to
manipulate the preceding levels, vulnerabilities in them must be
exploited.</p>

<p>It is desirable to gain control over the system already in the first
stages. This is possible on some consoles like the <a href="https://wiibrew.org/wiki/BootMii"><em>Nintendo Wii</em></a>
, the <a href="https://www.3dbrew.org/wiki/3DS_System_Flaws#Boot_ROM"><em>Nintendo 3DS</em></a> or
the <a href="https://switchbrew.org/wiki/Switch_System_Flaws#Hardware"><em>Nintendo Switch</em></a>. On the <em>Wii
U</em>, at bootime this was only possible with a <a href="http://wiiubrew.org/wiki/Wii_U_System_Flaws#boot0">“glitching”-setup</a>.
In fact, there is also an exploit that
allows <a href="http://hexkyz.blogspot.com/2018/01/anatomy-of-wii-u-end.html">code execution in the boot1 stage</a>, but the console must have been
completely started and taken over. When the console is started, the
<em>boot0</em> level stores a data structure in the main memory. If a restart
is initiated while the console is running, the boot process starts at
the boot1 stage in which the existing data structure is read. Thus it
can be used that the main memory is not emptied during a restart of the
console, whereby a manipulation of the data structure is possible. An
error when verifying the values can be used to gain control over the
boot1 stage. A solution that allows control during
the boot process without modification of the hardware and immediately
after power-on does not yet exist.</p>

<p>Instead, it is necessary to gain control of the operating system in
another way. Vulnerabilities in applications can be exploited to execute
custom code. If you succeed in gaining additional control over the
kernel of the PowerPC processor, you have complete control over the
processor and the <em>Cafe OS</em> running on it. For control over the <em>IOSU</em>
and thus the ARM processor, an <em>IOSU</em> module and ultimately the <em>IOSU</em>
kernel would have to be taken over via the IPC interface by exploiting
security vulnerabilities. It is necessary that the described steps are
performed each time the console is switched off. Persistent changes to
the operating system would violate the integrity of the data, which
would prevent the console from being started.</p>

<p>All cryptographic keys on the console are known publicly and can be read
with publicly available applications such as <a href="https://github.com/hexkyz/hexFW">hexFW</a>. This makes it
possible to decrypt all console contents and analyze them for bugs. In
order to be able to digitally sign and use your own content, however,
the appropriate private key is required. This key is not known and will
probably never reach the public. A large part of the system has already
been analyzed, however, and corresponding information can be found on
the Internet (for example in <a href="http://wiiubrew.org/">WiiUBrew-Wiki</a>). Exploits are also
publicly available, and already allow full control of the system
(for example using the <a href="https://github.com/dimok789/homebrew_launcher">homberew launcher</a> in combination with <a href="https://github.com/Maschell/mocha/">mocha</a> or by running <a href="https://github.com/hexkyz/hexFW">hexFW</a>). Information
about the initial obtaining of full control and the reading out of
corresponding keys via the <em>Wii U</em> can be found for example <a href="https://www.youtube.com/watch?v=oss_dwj-IkE">here</a>.</p>

<h1 id="next-blog-entry">Next blog entry</h1>
<p>The next entry will discuss the requirements that will be used for creating the environment. 
It will also discuss which parts of the existing solutions are bad and need to be improved, and which parts can be reused.</p>]]></content><author><name></name></author><category term="homebrew" /><summary type="html"><![CDATA[Some time ago, I went on a journey to create a new homebrew environment for the Wii U. An environment where homebrew applications can be run easily and on Wii U. It’s been possible to run your own software on Wii U since 2015, but I wasn’t satisfied with the existing solutions. Some solutions, such as the Homebrew Launcher, date back to a time when no public IOSU exploit was known. In order to run Homebrew, some compromises had to be made.]]></summary></entry></feed>