Wednesday, January 4, 2017

Apologetic shenanigans

This is going to be a short post.

In my previous blog entry I shared my views on the 33C3 Nintendo Hacking talk. After chatting with derrek (one of the speakers) I have to admit how unfair I was.
There's a lot going on at events like these and speaking for a broad and curious audience is never an easy task.

I was very eager to learn more about the Wii U's boot1 that I ended up misunderstanding something very important: there is no XML parsing bug.
What derrek was saying is that there might be a bug in boot1, but it turned out to be too much of a boring task to look into it. Whatever the bug might be, it's not in the XML parsing code.
Taking that into account, it's quite possible that the nature of the bug itself (if proven to exist) may just translate into a complicated, or even pointless, exploit.
Also, I wasn't fully aware of how uninterested hackers and developers are in the Wii U. Now I see that the inclusion of the Wii U portion was more of a projection of what the team had achieved before moving on to different things.
It makes sense to detail attacks that interest people and such happened during the 3DS part. If the team decided to go into further detail on the Wii U, their audience would be fairly disappointed.

Apologies to derrek, naehrwert and nedwill for my caustic comments and misinformation.

Sunday, January 1, 2017

New year, same challenges...

WARNING: The following blog post is filled with the author's own opinions. Reader discretion is advised!

New year, new blog post.

I would like to start off by issuing a public apology to Wii U's homebrew developer dimok. I've given my opinion publicly about the "Mocha CFW" project and I'm afraid I may have expressed myself poorly.
I do think Mocha CFW's code base is weak. It lacks structure and has plenty of poorly optimized solutions for certain features. That doesn't mean it won't change in the future or that my work is any better.
I appreciate, like many others, dimok's contributions to the Wii U scene and I think him and other developers have been doing great work under the public eyes.
I clarified my opinions on IRC with MaschellDev, but I haven't been able to contact dimok directly yet. Meanwhile, MaschellDev brought to my attention that a Reddit user made a negative comment on dimok's work using arguments very similar to mine.
My suspicion is that some user in IRC saw my arguments and attempted to bash dimok's work with them without having a clear idea on what they meant.
I'm not going to play the drama game that has turned many developers against each other, so I'm taking this chance to publicly address dimok and apologize for my comment on Twitter and also to report that I have nothing to do with whoever made negative remarks on Reddit or whatever.

Anyway, on to more interesting things!

33C3... Unfortunately, I was unable to attend the event, but I spent the past days watching talk after talk on multiple ingenious exploitation methods and achievements.
If you have been following this blog for a while, you know I've been recently researching and developing tools for the Wii U. Therefore, I was particularly excited to know that derrek and naehrwert were going to talk about the Wii U and it's vulnerabilities.
I was glued to the live stream and watched the whole talk, but I ended up feeling very disappointed.

I'm aware that the 3DS is a much more popular console and I was already expecting it to be the main focus of the talk, with just a brief overview of the Wii U exploitation path.
On that note, Ned Williamson was certainly the star of the talk for me. While the bugs presented were nothing particularly new (UAFs, overflows), he presented novel ways to exploit them ("soundhax" and "fasthax") and was very assertive in detailing the attacks.
Hacker naehrwert only talked during the Wii U portion and detailed two distinct exploits: "ioctlvhax" and "mqhax". The "ioctlvhax" exploit was already publicly disclosed by naehrwert himself, but it's understandable why it was brought to the talk. This flaw exposes a large attack surface, both on the PPC and ARM sides.
IOSU userspace flaws were not presented during the talk, which is a bummer, but I can also understand their reasons specially due to time constraints.
A new IOSU kernel exploit was present though, "mqhax". Interesting, but nothing really groundbreaking.
It's also worth noting that IOSU userspace and kernel exploits were already available publicly and had been implemented by several people (myself included).
There was also a brief mention to "contenthax", "haxchi" and "coldboothax" which, despite the names, are not exactly exploits but design choices (a.k.a. flaws) instead.

Up to this point, nothing new was presented since fail0verflow had achieved this level of access years ago. Then came the part I was really excited for: boot1.
This was something that fail0verflow didn't manage to crack and remained the last mystery of the Wii U.
Now, I had high expectations for this so I guess it was my fault I was let down. Hacker derrek had published, quite some time ago, a tweet with boot1 key's hash were you could read "BOOT1_FAIL":
I naively assumed he had found a flaw in boot1 itself (whence boot1 + fail) and managed to blindly exploit boot1's execution and stumbled upon some silly mistake from Nintendo (like leaving a duplicate boot1's key inside boot1's binary :P).

Unfortunately, they simply confirmed something I had found and documented days before: boot0 has no useful bugs.
I had reversed and fully documented boot0 ( and even left a small note regarding the dangerous size check done on the boot1's ancast image (see "
Stages 0x15, 0x16 and 0x17").
If that size check was flawed, it would be trivial to overflow boot1's memory region into boot0's region and hijack the next instruction. I wasted a lot of time looking into this but all I could do was verify that all checks were in place.
Nonetheless, a fault injection is an attack and a lot of hackers resort to that when nothing else works. I was expecting that derrek would go into detail on his setup and the specifics of the attack, but that didn't happen. This confused me.
Why bother to include the Wii U in this talk when your most important achievement (and, actually, the only new thing to present) was going to be left out?
That made no sense to me, but that was still not the worst. Apparently, when analyzing boot1, the team found a potential bug in XML parsing. Interesting, right?
However, they got bored and didn't bother to look into it... Seriously? I get that the Wii U is not exactly popular but, again, why bring this up at all just to end with "we didn't care"?

At this point I was a bit revolted with their attitude. This talk started to sound more like a bragfest than anything useful.
Watching Ned Williamson's part caught my interest again, but then derrek proceeded to unveil how they cracked the 3DS bootROMs. Again, nothing groundbreaking, but still an incredible achievement. The bootROM was the last line of defense for the 3DS and no one had manage to break it.
I was very eager to see what kind of setup they used, since they had to resort to fault injection again, but, once more, they preferred to keep that in secret.
The last exploit presented was "sighax". Very interesting finding and somewhat hilarious to see that Nintendo had messed up RSA again.

The parting note about the Switch was completely unnecessary in my opinion and so was the remark about them being "nice" by not presenting this earlier considering they had achieved this back in the summer of 2015.

Also, after the talk was over, hacker plutoo released the group's notes on the Wii U:
Unfortunately, aside from a few tidbits, most of the documentation is very incomplete in comparison to the public documentation available at

It's great to achieve something against all odds, to break a system it's designer deemed "perfect" and learn from that experience. Unfortunately, I feel that this talk pushed things a bit too far and focused a lot on rubbing on Nintendo's face how much they suck.
I don't feel comfortable with this attitude at all. I believe there's room for healthy mockery, I mean come on, talented guys breaking a product that had millions of dollars invested in it (and in it's security) deserves some bragging.
However, we must not forget that hackers are not winning anything. Hacking consumer electronics IS illegal and it's up to these multimillionaire companies to decide the fate of perpetrators.
With that said, I really felt that this talk pushed the limits in an unhealthy way. By all means, that doesn't mean it was the only one doing that throughout the history, but after seeing something like HENkaku happening, I believe we hackers must drop the attitude a bit and start being more serious and professional in our activities.

Anyway, end of rant. I have nothing against these talented hackers and regardless of the means, they still achieved what others were unable to, so, congratulations to them all!

Moving on, I have a couple things I wish to achieve this year and I'm very happy with the results so far.
On the Wii U, I'm still going to work on hexFW, but right now my main focus is to attempt dumping boot1's key. While exploiting the Vita, I ended developing a XML fuzzing framework to look for bugs in the updatelist's parsing and I'm very eager to put it to good use in looking for that potential XML parsing bug in boot1.
For this task, I plan on attempting standard hardware fault injection techniques to replicate what derrek did. Unfortunately, while this kind of attacks aren't particularly difficult to deploy, they are very, very dangerous to the console.
What was presented during the talk relied on NAND readings to figure out the necessary timing for the attack. This requires the attacker to purposefully corrupt the Wii U's boot1 image in the NAND.
However, there might be another venue that was not explored by the group. The same size check is performed when reading a boot1 image from the SD card. This could potentially be a safer way of developing the attack, but I have yet to find out how to tell boot0 to load boot1 from the SD card (a specific event combo is needed).

As for the Vita, I have a bunch of tools I'll be releasing as necessary and tons of documentation that I'll be pushing to the HENkaku wiki. I have also recently managed to break TrustZone, but, unfortunately, the bug I've exploited was patched long ago. I suspect I stumbled upon the same bug Team molecule may have used in the past, but I plan on doing a proper write-up later on if they agree.

My next blog post will be a complete write-up on how I implemented the two public Wii U exploits to bring hexFW to life (IOS_CreateThread memset bug and uhshax). I was waiting for 33C3 just in case any of the hackers would present the IOS_CreateThread exploit, but since they decided to present "mqhax" instead and hykem is nowhere to be found, I'll just go ahead and detail my own experiences.
I believe these two exploits deserve a proper write-up and it would be a nice tribute to ex-hacker hykem who documented extensively and publicly the internals of the Wii U.

As always, stay tuned!

Monday, November 7, 2016

Anatomy of a Wii U: hexFW

As I mentioned in my last post, in parallel to researching the Vita's kernel I decided to research the Wii U and see what I could come up with.

For all this to make any sense, we must go back to the beginning and waste a couple minutes looking into the Wii U hacking scene's history.
It all began back in 2013 when team fail0verflow made a presentation at 30C3 describing their journey in hacking the Wii U.
For quite some time they became the reference in terms of research and documentation for the Wii U's internals and even set up a wiki for this purpose:
However, they had no intention to release their exploits or talk about any vulnerabilities. This led to a community-driven effort to recreate their steps and hack this system.

Attempts to exploit the vWii date from late 2013, but it wasn't until mid 2014 that Wii U userspace code execution was achieved. This was done originally by what would become the libwiiu team.
One year later, the same team achieved the first PowerPC kernel exploit (a TOCTOU involving the OSDriver structures) and opened the doors for homebrew (with some restrictions).
The libwiiu project became a very valuable framework to write, compile and execute code from within the Wii U's Web Browser and it kept being used across firmware changes.
Other projects were developed during this time frame and eventually branched away from libwiiu (e.g.: Loadiine, homebrew_launcher).

Later that year, the first reports of someone being able to break into the Wii U's secure processor (IOP, running a custom operating system called IOS and dubbed IOSU by the community) showed up. The hacker and developer hykem claimed that had defeated IOSU around December of 2015.
This was shortly followed by another team claiming the same feat. This time it came from smealum, plutoo, naehrwert, derrek and yellows8, all very well known video game console hackers from the 3DS (and PS3 in naehrwert's case) scene.
The 3DS group wasn't planning a release while hykem, on the other hand, revealed that was working on a CFW-like setup for a public release.
During the following weeks, hykem massively documented his findings on the wiiubrew wiki, but ended up disappearing before releasing his announced project.
Then came an awkward period of drama and mystery that marked the Wii U hacking scene for good.
Eventually, smealum announced he had no plans on developing further for the Wii U and released "iosuhax", a collection of patches for the IOSU that would, in theory, create a CFW-like environment (privileged memory access and direct communication with the IOSU in a RPC setup). However, no one released an actual exploit to take over the system and allow for firmware patching.
Earlier this year, someone documented two vulnerabilities found by hykem, naehrwert and plutoo in the wiiubrew wiki and yet again, a community-driven effort began to build an exploit based on these bugs.

This led us to today. The current state of the Wii U hacking scene is a fragmented playground with two dominant groups using this now public information to build an exploit chain and achieve the goal of building a CFW for the Wii U:
- Team SALT: a collective of hackers/developers mainly active on the 3DS scene that began working on a CFW solution quite early this year. They are developing everything in private and share a few details occasionally on their progress.
- Team wiiubru: formed under the public eye by early contributors and developers of the PowerPC homebrew scene that sparked after libwiiu. They develop everything in public and have achieved popularity among the community.

After learning about all this, I still felt motivated to research and work by myself for quite a few reasons:
 - The Wii U's security scheme is nowhere near the Vita's and is much easier to take down;
 - Public vulnerabilities already exist and there's plenty of documentation out there as well;
 - My vision conflicts with team SALT's and team wiiubru's.

That last point is crucial. Team SALT chose to work privately, which is understandable when dealing with something that can potentially brick your console, but it's not possible to evaluate what they have accomplished thus far. Also, one of their members was allegedly responsible for leaking team libwiiu's OSDriver exploit which doesn't inspire much trust in the group.
On the other hand, team wiiubru is doing everything in public, but using low standards in terms of code quality and organization, which is to be expected when working in large groups.

Not satisfied with either groups' approaches, I decided to come up with my own: hexFW.
The name may not be very original, but to be honest, I didn't put much effort into making it up.

So, in order to build a CFW of my own, I made two important decisions: use smealum's iosuhax as the base for IOSU patching and implement my own exploit chain.
In my opinion, iosuhax does the job fairly well. It's a set of patches and a script that replaces sections of a firmware image and re-encrypts it back to be run on the Wii U. The idea is to start with smealum's code base and evolve from there.

But that only covers the process of creating a CFW image, the hard part is to exploit the system and make it load this image.
I looked into wiiubru's public implementation of the two publicly disclosed bugs, but found many issues with it.
By far, what seemed to make less sense in their implementation was the fact that the exploit is launched using the "homebrew_launcher" (or HBL). This felt like an overkill: why exploit the PPC kernel and run userspace code to exploit the IOSU when the disclosed bugs can be used without kernel privileges?
After playing around with the bugs for a while I finally understood their point: it's really hard to pull this off solely from the browser.

Hacker yellows8 released a stagefright exploit compatible with the Wii U a long time ago which became the standard for userspace code execution under the most recent firmware versions (the bugs libwiiu had used in the past have all been patched). It's code is quite clean and does the job perfectly, so I decided to use it as the main entry point to achieve userspace code execution.
For compiling the code I resorted to libwiiu for it's simplicity and began writing the exploit chain from scratch. Soon enough I came across an issue that might have been why wiiubru decided to ditch direct code execution and resort to HBL and ELF loading: the userspace payload's size is limited due to the nature of the stagefright exploit.

Nonetheless, I came up with some creative ways of squeezing all the necessary steps into a single payload and managed to get it working.
This means hexFW is launched solely from the browser without the need for installing or using HBL!
Of course, this came with a small cost: it's very likely that running the exploit will crash once. This is due to how I'm locating a target thread inside the IOSU to modify it's stack pointer. However, if you reset the console it is guaranteed to launch the second time. After the launcher runs, the actual CFW will be booted into the system from the SD card.

I have released a preview version of hexFW on Github:
It contains my own exploit chain ("fwboot") and a copy of smealum's original iosuhax minus the filesystem patches (IOS-FS). This is merely to demonstrate it's usage, but the overall structure is very likely to stay the same. The following commits will consist in the actual firmware patches that make hexFW a CFW (SLC/MLC/OTP/SEEPROM dumping with/without compression, redNAND, USB read/write/install, coldboot, etc.).
If you're familiar with iosuhax, you can setup hexFW and it will generate a patched firmware image that contains smealum's wupserver. You can then communicate with it using the script and play around with it.

In the next days I'll be pushing several components of hexFW I've been working on. My next post will be a detailed write-up on the two vulnerabilities exploited and how I constructed the exploit chain from scratch.

Stay tuned!

Friday, November 4, 2016

The aftermath: What's next?

Even though HENkaku's KOTH challenge has ended, this is far from being the end!

First and foremost, I want to personally congratulate Team molecule for their achievements and show my appreciation for what they have done.
In the past few days we've got a full fledged CFW framework (taiHEN), an upgraded HENkaku payload (taiHENkaku), a SDK with plugin and kernel module support and a handful of valuable documentation on the Vita's internals.
I've taken the time to analyze everything and I simply stared at my laptop's screen in awe. The level of dedication that has been put into this project is mind blowing.
Their talent is unquestionable, sure, but the professional and meticulous way they handled everything is unparalleled.
Many successful companies (which actually profit from their work) don't have this level of coordination and dedication. I can easily tell this is a labor of pure love. Love for knowledge, curiosity and overall fun.
I can't thank you enough for what you have done here. I hope this will help cement how much hackers' love their work and promote an healthy coexistence between companies and individuals.
Four talented individuals brought interest back to a forsaken video game console and did it in the most respectful and professional way I've ever seen.
I can't stress this enough, everything was orchestred in such a way that the intentions of Team molecule became fully transparent and resulted in something that opens many doors without hurting the (almost non-existent anyway) market.

History has been made. Yes, we are talking about hacking video game consoles, but the principles behind this go way past that. We are actually seeing talented people doing something good and showing the world we have the right to explore, research and reverse-engineer in the name of knowledge.
Actions like this help building and supporting those who defend our rights and I eager for the day we have the freedom to explore without being afraid.
Thank you Yifan Lu, Davee, Proxima and xyz. Your work will never be forgotten.

So, what's next?
As you've probably noticed, the challenge's prize was the access to the now public Vita Wiki. Me and st4rk (the other winner of the challenge) were granted write access to this collaborative Wiki and I plan to put that privilege to good use.
I've been spending a lot of time researching the Vita's kernel and planning TrustZone attacks. All the information I'm acquiring in the process will be gradually added to the Wiki not only to fill in the gaps but also to continue Team molecule's work for as long as I can.
Even though we are running code inside the Vita's kernel by now, there's still a lot to do. Team molecule themselves have already defeated the secure kernel (a.k.a. TrustZone) and learned about it's true purpose: communicate with the security processor (dubbed F00D due to ELF headers).
I plan on following their steps and, hopefully, defeat the secure kernel next. After that comes the massive challenge of defeating the obscure F00D processor.
Considering how little is known about it and how small it's attack surface is, we may never even be able to take it down. Still, the process is guaranteed to provide critical information just like Team molecule has proven.

Parallel to all this, I've been introduced to a whole different "scene" recently. Earlier this week, a friend of mine came to me complaining about how disappointed he was with his latest purchase: a Wii U.
Apparently he hated the console and watching the new Switch's trailer was enough for him to get rid of it. Believe it or not, he wanted to toss it in the trash (yeah, money is not a problem there) but asked me first if I wanted it.
The last Nintendo console I ever had was a SNES so, why not?
Naturally, I began looking into hacking it and learned a looooong story about it in the process. Popular video game console hackers fail0verflow were the first to crack this device back in 2012, but only recently people have managed to defeat it's most critical security components.
Unfortunately, it appears that hacking efforts for this device are heavily fragmented with a large group of people working on it publicly and a smaller one working in private. Useful vulnerabilities are already public and a few shaky implementations are out in the wild as well.
After researching the console and analyzing what's been documented already I've decided to take a shot at it and over the last few days I've spent plenty of time digging into it and working on cool stuff for it (emuNAND, USB read/write, boot-time launching, to name a few).
I'll be publishing a few articles about this along with a crude CFW and some tools. I'm working on top of other hackers' work, so I'll be sure to cover and credit their work as well.

Stay tuned!

Wednesday, October 19, 2016

HENkaku - Exploit teardown - Stage 3

Here it is, Stage 3, the last stage of HENkaku.
This was by far the toughest to crack, so, let's dive in!

HENkaku - Stage 3

In Stage 2, we analyzed how HENkaku exploits two distinct kernel bugs to achieve code execution: a memory leak bug (in the sceIoDevctl function) to defeat KASLR and a use-after-free (in the sceNetIoctl function) to break into the kernel and do ROP.
However, since the execution flow switches over to a ROP chain planted into the kernel, we still couldn't figure out what was happening next.

Like I mentioned in the previous write-up's ending note, dumping the kernel (more specifically, the SceSysmem module) was now necessary. Team molecule did not provide any additional vulnerability that we could use for this purpose, so, it was up to the participants to figure it out themselves.

I had already found a potential memory leak vulnerability while playing around with Stage 2 but, unfortunately, due to it's nature (out-of-bounds read) it wasn't enough to reach the SceSysmem module.
Frustrated, I began looking for other plausible entry-points. It took me several attempts and required analyzing several key components of the Vita's system:
- Network:
    The SceNet module was the origin of the use-after-free and I had already an OOB read there, so, what else could be in there?
- Filesystem:
    The SceDriverUser module exposes a decent amount of unique system calls for the filesystem. Some of them crash. Can I leak memory here?
- Audio:
    Developers don't pay much attention to security when it comes to implement media handling. Some specific audio handling features are taken care by the kernel itself. Can I compromise it?
- Graphics:
    Just like with audio, graphics are a common source of flaws. The Vita has plenty of libraries with unique system calls for this (SceGpuEs4User, SceGxm, ScePaf). Will this help?
- Application:
    User applications are managed by modules that heavily communicate with the kernel (SceAppUtil and SceDriverUser via SceAppMgr calls). Perhaps this can be taken down?
Eventually, one of those gave me what I wanted and I was able to dump the entire Vita's kernel memory. After locating the SceSysmem module among the dumped binaries I became able to solve the rest of the challenge.
On a side note, I did attempt blind ROP at first by relocating a few gadgets and taking wild guesses, but team molecule made sure it wouldn't be that easy. The gadgets' placement makes it very difficult to predict what each one will do.

Anyway, here is the result:

So, random comments and mistakes aside, this gives us a clear view of what the kernel ROP chain is doing:

If you recall, the kernel loader was an encrypted chunk of 0x100 bytes that was appended to the bottom of the ROP chain we copy into a kernel stack using sceIoDevctl:
  • // NULLs for padding at the bottom of the chain
    0x00(x_stack + 0x00008D7C) = 0x00000000;
    0x00(x_stack + 0x00008D80) = 0x00000000;
    0x00(x_stack + 0x00008D84) = 0x00000000;

    // Code starts here
    0x00(x_stack + 0x00008D88) = ...;

The kernel ROP decrypts this chunk using AES-256-ECB and the key is a piece of code from SceSysmem itself.
This is what the kernel loader looks like (note that base offset is set to 0x00000000):

In sum, the loader allocates two memory blocks, one for data and another for code. Then it fetches the HENkaku's payload from user memory (using copy_from_user) and decrypts it in place using a static key (stored inside the kernel loader binary data). Finally, it copies the decrypted payload into an executable memory block, set's PC and SP and jumps to it.

Now we have HENkaku running on our system!
As proof, here are the SHA-1 hashes of the two crucial keys for the entire process:
Kernel loader key (AES-256-ECB): f1a8e9415bf3551377a36a1a5b25ba64f2d96494
Kernel payload key (AES-128-ECB): eacac4a780065c8c106349e412696aabd1b1b8d1

And that's it! This concludes the final stage of the HENkaku's KOTH challenge.
I don't plan on dwelving much into how I leaked the kernel's memory and I don't plan on releasing the keys themselves out of respect for other groups attempting to complete the challenge and for the developers themselves.
I believe the goal of this challenge was not to simply crown the first person to crack HENkaku, but to get the whole community engaged and bringing new ideas to the table.
By not releasing the decrypted binaries or the method I used to leak memory, others still have the chance to solve the challenge themselves.
I may publish a few more posts detailing some interesting features of the HENkaku's payload, but I will leave the full source code reveal to the developers themselves.

Until next time!

HENkaku - Exploit teardown - Stage 2

HENkaku - Stage 2


Stage 2's payload is composed by another ROP chain and data.
It creates two userland threads (each one with it's own ROP chain), that take care of leaking kernel pointers (by issuing devctl commands to "sdstor0:") and breaking the userland sandbox (by exploiting sceNet functions).
Stage 2 leverages a bug in sceIoDevctl in order to leak 2 distinct kernel pointers. These 2 pointers refer, respectively, to SceSysmem module's base address and SceIoFilemgr(?) thread's stack address:
  •     // Store leaked kernel pointer 1
        // Comes from devctl_outbuf + 0x3D4
        scesysmem_base = 0x00(x_stack + 0x00007308) + 0xFFFFA8B9
        // Store leaked kernel pointer 2
        // Comes from devctl_outbuf + 0x3C4
        sceiofilemgr_stack_base = 0x00(x_stack + 0x000072F8) + 0xFFFFF544
When preparing to write the kernel ROP chain, we can see a few pointers being set. These translate to:
  •     // Kernel ROP inside sceiofilemgr
        // This is where our ROP chain gets copied to inside the SceIoFilemgr module
        kern_rop = sceiofilemgr_stack_base + 0x000006F8
        // Encrypted kernel code
        kern_code = kern_rop + 0x300
Now we write down our kernel ROP chain in the stack, but we can see that some values only get written afterwards.
This is because these values are directly related to the decryption of the next kernel level stage! Team molecule likely only writes them into the ROP chain later so they can easily update the encrypted stage without having to change the kernel ROP chain directly.
  •     // Overwrite specific NULLs in the ROP chain
        0x00(x_stack + 0x00008C04) = 0x00(x_stack + 0x00008EAC)     // kern_code
        0x00(x_stack + 0x00008B48) = 0x00000090
        0x00(x_stack + 0x00008CC0) = 0x00000240
        0x00(x_stack + 0x00008D58) = 0x00000200
        0x00(x_stack + 0x00008D14) = 0x00008FC0                     // kern_next_payload
And our final ROP chain should look like this:
Now we copy the chain from the stack into the buffer that's being sent through sceIoDevctl:
  •     // Copy kernel ROP chain
        memcpy(x_stack + 0x00007448, x_stack + 0x00008A8C, 0x300);
        // Copy the first 0x400 bytes of "obfuscated" data
        // and append them at the bottom of the ROP chain
        memcpy(x_stack + 0x00007744, x_stack + 0x00008EB8, 0x400);
And so, the final input buffer will look like this:
  •     // SceSysmem address
        // Unknown pointer written right on top of the input buffer
        0x00(x_stack + 0x00007444) = scesysmem_base + 0x0001E460
        // Kernel ROP chain
        0x00(x_stack + 0x00007448) = 0xXXXXXXXX;
        0x00(x_stack + 0x00007734) = 0xXXXXXXXX;
        // A few NULLs for padding
        0x00(x_stack + 0x00007738) = 0x00000000;
        0x00(x_stack + 0x0000773C) = 0x00000000;
        0x00(x_stack + 0x00007740) = 0x00000000;
        // Encrypted kernel code
        // Only the first 0x100 bytes will fit in the buffer
        0x00(x_stack + 0x00007744) = 0xXXXXXXXX;
        0x00(x_stack + 0x00007B44) = 0xXXXXXXXX;
Finally, we must craft a buffer that will have our ROP chain's SP and PC. This is the buffer we feed the SceNet exploit with:
  •     // Set kernel thread SP, PC, UNK
        0x00(x_stack + 0x0000884C) = sceiofilemgr_stack_base + 0x000006F8 + 0x00000004      // SP
        0x00(x_stack + 0x00008850) = scesysmem_base + 0x00000347                            // PC
        0x00(x_stack + 0x00008858) = sceiofilemgr_stack_base + 0x000006DC                   // UNK
When the SceNet exploit finishes, we should have hijacked a kernel thread inside the SceNetPs module and overwritten it's stack contents with our own.
This results in the kernel jumping to scesysmem_base + 0x00000347 (which is very likely a POP {PC} gadget) and executing our ROP chain at sceiofilemgr_stack_base + 0x000006F8 + 0x00000004 (which translates to kern_rop + 0x04).
To further reverse the exploit, one must dump the target kernel modules, rebuild the kernel ROP and deobfuscate/decrypt the rest of HENkaku's code.

Next up, stage 3!

HENkaku - Exploit teardown - Stage 1

This post aggregates my previously published write-ups that detail the first stage of HENkaku's exploit chain.
Information has been reorganized to reflect the original developers' naming scheme.

HENkaku - Stage 1

Visiting and pressing the "Install" button results in a server side useragent check.
If the browser's useragent matches the one of a PS Vita/PSTV on the latest firmware version (3.60), the user is redirected to and an exploit is deployed.
This exploit re-uses elements from the older public exploits (heap spraying method, sort() bug, scrollLeft attribute manipulation) and pairs them with a new heap corruption technique.
Team molecule renamed variables and methods to provide a simple obfuscation layer on the HTML code.

Partially reversed HTML:

Similarly to older exploits, this allows to corrupt an object's vtable and achieve ROP inside the SceWebkit module.
Offsets for libraries and relevant ROP gadgets are fetched from a javascript file ( during the last stage of the exploit.
Team molecule implemented a dynamic method to relocate gadgets and functions' offsets for each module after their base addresses' are found (by looking at SceWebkit's import stubs).
The payload.js file contains two arrays, one containing the payload's binary data and another containing the relocation type for each word.
By crossing this information the exploit reads the payload and relocates all code offsets to their target module's address space by adding the module's base address to them:
    Relocation type 0 -> Plain data stored inside the ROP space itself. No relocation needed.
    Relocation type 1 -> Offset inside the ROP payload's stack.
    Relocation type 2 -> Offset inside the SceWebkit module.
    Relocation type 3 -> Offset inside the SceLibKernel module.
    Relocation type 4 -> Offset inside the SceLibc module.
    Relocation type 5 -> Offset inside the SceLibHttp module.
    Relocation type 6 -> Offset inside the SceNet module.
    Relocation type 7 -> Offset inside the SceAppMgr module.

Payload's generated binary data:

This payload is responsible for taking care of a few things like:

After the payload is done, an HTTP request is sent to the server using the following template:
The "x" script on the server side collects the base addresses for each module and generates a second payload to be run on the Vita.

This second payload is composed by another ROP chain and obfuscated ARM code.
A preliminary analysis of this payload reveals a few interesting things:

Next up, stage 2!