Exploiting USB Attacks on Microcontroller Firmware

1

Who Hacks Video Game Consoles?

Manufacturing of counterfeit and unauthorized products is very common in the world of video game consoles. This is a multi-billion dollar industry where demand creates supply. You can now find devices for almost every existing console that allow you to play copies of licensed video game “backups” from flash drives, counterfeit game controllers and accessories, various adapters, some of which also work for other players, and cheating in online and offline video games. There are even services that let you buy achievements in video games directly without spending hours to complete them. Of course, all of these are sold without the consent of the video game console manufacturers.

Just like 20 years ago, modern video game consoles are proprietary systems whose rules are set by hardware manufacturers rather than by the millions of gamers who use these devices. They are designed with various protections to ensure that these consoles only run authorized code, meaning they only play licensed and legally obtained video games, and all players have equal rights to only play with officially authorized accessories. In some countries, attempting to hack your own video game console is even illegal.

But at the same time, such strict protection schemes make these consoles an attractive target for attacks and a significant crack for hobbyists interested in information security and reverse engineering. Because for them, the harder the puzzle is, the more challenging and interesting it becomes. Especially for those players who have been obsessed with video games since childhood.

2

DualShock 4’s Protection Scheme

Readers who follow my Twitter account may know that I am a long-time fan of reverse engineering video game consoles and their related content, including unofficial gaming devices. In the early days of the PlayStation 4, a well-known vulnerability in the FreeBSD kernel (on which the PlayStation 4 is based) allowed me and many other researchers to understand the architecture and inner workings of Sony’s new console. I have conducted various research, some of which includes understanding how USB authentication works in the PlayStation 4 and how it distinguishes between licensed devices and prevents unauthorized devices. This research is interesting because I have previously done similar studies on other game consoles. The authentication scheme of the PlayStation 4 is much simpler than that used in the Xbox 360, but equally effective.

Exploiting USB Attacks on Microcontroller FirmwareFigure:Authorization scheme for PlayStation 4 USB accessories

PS4 sends 0x100 random bytes as a response, the game controller creates an RSASSA-PSS SHA-256 signature and sends it back with the necessary cryptographic constants N and E (public key). These constants are unique for all manufactured DualShock 4 game controllers. The game controller also sends the signature required to verify N and E. It uses the same RSASSA-PSS SHA-256 algorithm, but the cryptographic constants are the same for all PlayStation 4 consoles and are stored in the kernel.

This means that if you want to verify your own USB device, attacking the PlayStation 4 kernel is not enough, you also need to have the private key stored in the game controller. Even if someone manages to hack the game controller and obtain the private key, Sony can still blacklist the key with a firmware update. If the game console does not receive a verification response after eight minutes, it will stop communicating with the game controller, and you need to remove the controller from the USB port and plug it back in to make it work. This is why early counterfeit game controllers needed to simulate the USB port removal/insertion process every 8 minutes to work, which was very annoying for those who bought them.

3

Rumors About Super Counterfeit DualShock 4

For a while, I hadn’t heard any incidents of cracking this authentication scheme until I heard rumors that new counterfeit game controllers that look like the originals were being sold on the market, which made me really want to investigate them, so I ordered some from a Chinese store.

While waiting for the package to arrive, I decided to try to collect more information about the counterfeit game controllers. After quite a bit of searching, I found a game controller called Gator Claw.

Exploiting USB Attacks on Microcontroller FirmwareUnauthorizedGator Clawgame controller

On Reddit, there was an interesting discussion where people said it worked like other unauthorized game controllers—only 8 minutes, but developers managed to solve this issue through firmware updates. The stores selling it included links to firmware updates and manuals.

Exploiting USB Attacks on Microcontroller FirmwareGatorClawfirmware update manual

4

Basics of Embedded Firmware Analysis

The first thing I did was look at the resource section of the firmware update executable.

Exploiting USB Attacks on Microcontroller FirmwareFirmware found in Gator Claw’s firmware update resource

Readers familiar with writing code for embedded devices are likely to recognize this file format. This is the Intel HEX file format, commonly used for encoding microcontrollers, and many compilers (such as GNU Compiler) can output compiled code in this format. Additionally, we can see that the information entropy at the beginning of the firmware is not very high, and the byte sequences are easily recognizable. This means the firmware is neither encrypted nor compressed. After decoding this firmware from Intel HEX format and loading it into a hex editor (010 editor can directly open files in that format), we can check what architecture it was compiled for. Since ARM Cortex-M is widely adopted, I immediately recognized it.

Exploiting USB Attacks on Microcontroller FirmwareGatorClaw’s firmware (left) and the vector table of ARM Cortex-M (right)

According to the specification, the first double word is the initial stack pointer, followed by the exception vector table. The first double word in that table is the reset vector (Reset Vector), which serves as the firmware entry point. Other high addresses of exception handlers provide information on the firmware’s base address.

In addition to the firmware, the resource section of the firmware updater also contains a configuration file that describes different microcontrollers. The developer of the firmware updater likely used publicly available source code from the microcontroller manufacturer, which may explain why this configuration file comes with the source code.

Exploiting USB Attacks on Microcontroller FirmwareConfiguration file containing descriptions of different microcontrollers

After searching for microcontroller identifiers in the configuration file, we found the manufacturer’s website— Nuvoton. Technical documents and product information in the SDK are available for free download without any licensing agreements.

Exploiting USB Attacks on Microcontroller FirmwareNuvoton microcontroller manufacturer’s website

At this point, we have the firmware, we know its architecture and the microcontroller manufacturer, and we have information about the base address, initial stack pointer, and entry point. Therefore, we have a lot of information, more than what is needed to load the firmware in IDA Pro and start analyzing it.

The ARM processor has two different instruction sets: ARM (32-bit instructions) and Thumb (using Thumb-2 32-bit instruction extensions of 16-bit instructions). Cortex-M0 only supports Thumb mode, so when we load the firmware into IDA Pro, we will switch the radio button in the “Processor Options” – “Edit” – “ARM Architecture Options” – “Set ARM Instructions” to “NO“.

After that, we can see the firmware has been loaded at the base address 0, and automatic analysis can recognize almost every function. Now the question is how to advance the reverse engineering of the firmware?

Exploiting USB Attacks on Microcontroller Firmware

Example of one of the multi-firmware functionalities

If we analyze the firmware, we will see that it performs read and write operations on the memory mapped I/O (MMIO) registers at the base address of 0x40000000. These MMIO registers allow you to access and control all peripheral components of the microcontroller. Everything the firmware does is achieved by accessing them.

Exploiting USB Attacks on Microcontroller FirmwareMemory mapping of peripheral controllers

By searching the technical documentation for the address 0x40000000, we find that this microcontroller belongs to the M451 series. Now that we understand the microcontroller series, we can download the SDK and code examples for that platform. In the SDK, we find a header file that contains definitions for all MMIO addresses, bit fields, and structures. We can also compile code examples using all libraries and compare them with functions in IDB, or we can look up the names of the MMIO addresses in the source code and compare them with our disassembly. This makes the reverse engineering process much simpler. That is because we know the architecture and model of the microcontroller, and we have definitions for all MMIO registers. If we didn’t have that information, the analysis would be much more complicated.

Exploiting USB Attacks on Microcontroller FirmwareFinding library functions in the firmware

5

In the Shadow of Giants

While waiting for my counterfeit game controller to arrive, I studied the firmware of Gator Claw, which had little of interest internally—the authentication data was sent to another microcontroller accessible via I2C, and the response was sent back to the console. The developers of this unauthorized game controller knew that this firmware could be reverse engineered, and the existence of more counterfeit game controllers might harm their business. To prevent this, the only purpose of using another microcontroller is security. This is a common practice. Hackers put a lot of effort into their products and do not want to be hacked. What really caught my attention in this firmware was the presence of some seemingly unused strings. It is likely part of the USB device descriptor, but that particular descriptor was not used. Was this string left intentionally? Is it some sort of signature? Most likely, because this string is the name of a major hardware manufacturer known for logic analyzers. But it turns out they also have a gaming division aimed at being an original equipment manufacturer (OEM) and even hold many patents related to the production of gaming accessories. Besides, they also have subsidiaries with websites that offer a variety of gaming accessories. Among the products on sale are dozens of adapters that allow a console’s game controller to work with another console. For example, one product allows you to connect an Xbox 360 controller to a PlayStation 4, and another product allows you to connect a PlayStation 3 controller to an Xbox One, and so on, including universal “all-in-one” devices. The product list also includes adapters that allow you to connect a PC mouse and keyboard to PS4, Xbox One, and Nintendo Switch video game consoles, various game controllers, and printed circuit boards to create your own arcade controller for game consoles. All products come with firmware updaters similar to those provided for Gator Claw, but with a significant difference—all firmware is encrypted.

Exploiting USB Attacks on Microcontroller FirmwareExample of a manual and encrypted firmware for one of the products

The printed circuit board for creating your own arcade controller allows you to view the PCB design without having to purchase the device and take it apart, and their designs are likely very close to that of Gator Claw. We can see two microcontrollers: one should be the Nuvoton M451, and the other is an additional microcontroller that stores secrets. All traces enter the microcontroller under black epoxy, so the main microcontroller should be, while the microcontroller with four yellow pins seems to have the functionality needed to work via I2C.

Exploiting USB Attacks on Microcontroller FirmwareExample of a product’s PCB design

6

Revelations

At this point, I finally received the package from Shenzhen, and this is what I found inside. I think you will agree that the counterfeit game controller looks just like the original DualShock 4 and feels like an authentic controller. It is a wireless game controller made of high-quality materials, with a working touchpad, speaker, and headphone port.

Exploiting USB Attacks on Microcontroller FirmwareCounterfeitDualShock 4(external view)

I pressed one of the combinations in the update instructions and turned on the power. The game controller booted into DFU mode! When connected to a PC in this mode, it was recognized as another device with different identifiers and characteristics. I already knew what I would see inside…

Exploiting USB Attacks on Microcontroller FirmwareCounterfeitDualShock 4(main PCB view)

I soldered some wires to what looked like JTAG points and connected them to a JTAG programmer, which could recognize the microcontroller but had the security lock enabled.

Exploiting USB Attacks on Microcontroller FirmwareProgramming tool recognizes the microcontroller but has the security lock enabled

7

Exploiting USB Attacks on Microcontroller Firmware

After this rather lengthy introduction, it is now time to return to the subject of this article.USB (Universal Serial Bus) is the industry standard for peripheral devices. It is designed to be very flexible and widely applicable.USB protocol defines two entities, a host and other devices connected to it.USB devices are categorized into hubs, human interfaces, printers, imaging, mass storage devices, etc.

Exploiting USB Attacks on Microcontroller FirmwareConnection scheme for USB devices

The exchange of data and control between devices and hosts occurs through a set of unidirectional or bidirectional pipes. Through the pipes, we consider data transfer between the host software and specific endpoints on the USB device. A device can have many different endpoints to exchange different types of data.

Exploiting USB Attacks on Microcontroller FirmwareData transfer types

There are four different types of data transfers:

1. Control transfers (for configuring devices)

2. Bulk data transfers (generated or used in relatively large and burst quantities)

3. Interrupt data transfers (for timely but reliable transmission of data)

4. Isochronous data transfers (occupying a pre-negotiated amount of USB bandwidth with pre-negotiated transmission delays)

All USB devices must support a special designated pipe at endpoint zero, and the control pipe of the USB device will connect to that pipe.These types of data transfers are implemented using packets provided according to the following scheme.Exploiting USB Attacks on Microcontroller FirmwarePackets used in the USB protocol

In fact, the USB protocol is a state machine, and we will not check all these packets in this article. You can see below an example of a packet used in control transfers.

Exploiting USB Attacks on Microcontroller FirmwareControl transfer

USB devices may contain vulnerabilities when implementing bulk transfers, interrupt transfers, and isochronous transfers, but these types of data transfers are optional, and their presence and usage will vary based on the target. However, all USB devices support control transfers. Their format is common, making this type of data transfer the most attractive for vulnerability analysis.

The scheme below shows the format of the SETUP packet used to perform control transfers.

Exploiting USB Attacks on Microcontroller FirmwareFormat of the SETUP packet

The SETUP packet occupies 8 bytes and can be used to obtain different types of data based on the request type. Some requests are universal for all devices (e.g., GET DESCRIPTOR); other requests depend on device class and manufacturer licensing. The length of data to be sent or received is provided in the SETUP packet as a 16-bit word.

Exploiting USB Attacks on Microcontroller FirmwareExamples of standard and class-specific requests

In summary: “Control Transfers” use a very simple protocol supported by all USB devices, which can have many additional requests, allowing us to control the size of the data. All of this makes Control Transfers a perfect target for fuzzing and exploitation.

8

Development

To hack my counterfeit game controller, I did not have to fuzz it because I found vulnerabilities while looking at the Gator Claw code.

Exploiting USB Attacks on Microcontroller FirmwareWeak code in the HID class request handler

The function HID_ClassRequest( is used to simulate the original DualShock 4 game controller’s operation and implements the minimum required requests to make it work with the PlayStation 4. USBD_GetSetupPacket( retrieves the SETUP packet, and depending on the report type, it will send data with the function USBD_PrepareCntrlIn( or receive it using the function USBD_PrepareCntrlOut(. This function does not check the length of the requested data, which should allow us to read a part of the firmware located in internal flash memory and also read and write the beginning of SRAM memory.

Exploiting USB Attacks on Microcontroller FirmwareBuffer overflow during control transfer

The size of the DATA packet is defined in the USB device descriptor (also received via control transfer), but it seems that it was not noticed that this size defines the length of a single data packet, and many packets may rely on the length set in the SETUP packet.

It is worth noting that the code examples provided on the Nuvoton website also lack length checks, and this could lead to the spread of similar errors in all products using this code as a reference.

Exploiting USB Attacks on Microcontroller FirmwareExploiting buffer overflow in SRAM memory

SRAM (Static Random Access Memory) is a type of memory that includes memory occupied by the stack. SRAM is typically also executable memory (this is configurable). This is usually done to improve performance by copying frequently called code snippets (such as real-time operating systems) into SRAM. It cannot be guaranteed that the top of the stack can be accessed through buffer overflow, but the possibility is still quite high.

Surprisingly, the main obstacle to exploiting USB firmware is the operating system. I observed the following while using Windows, but I think most of it also applies to Linux without special patches.

First, the operating system does not allow you to read more than 4 kb of data during control transfers. Second, based on my experience, the operating system does not allow you to write multiple DATA packets during control transfers. Third, USB devices may have hidden requests, and the OS will block all attempts to use them.

This can easily be demonstrated with Human Interface Devices (HID), including game controllers. HID comes with additional descriptors (HID descriptor, report descriptor, physical descriptor). The report descriptor is completely different from other descriptors, consisting of different items that describe the supported reports. If a report is missing in the report descriptor, the operating system will refuse to complete the report even if it has been processed in the device. This essentially diminishes the discovery and exploitation of vulnerabilities in USB device firmware, and these nuances are most likely to prevent the discovery of vulnerabilities.

To address this issue without having to read and recompile the source code of the Linux kernel, I simply used low-end instruments I had on hand: Arduino Mega board and USB Host Shield (totaling <$ 30).

Exploiting USB Attacks on Microcontroller FirmwareConnection scheme

After connecting the devices using the scheme above, I used the Arduino board to perform control transfers without any interference from the operating system.

Exploiting USB Attacks on Microcontroller FirmwareArduino Mega and USB Host Shield

The counterfeit game controller had the same vulnerabilities as Gator Claw, and the first thing I did was dump part of the firmware.

Exploiting USB Attacks on Microcontroller FirmwarePartial firmware dump

The easiest way to find the base address of the firmware dump is to look for structures containing pointers to known data. After that, we can calculate the address offset and load the partial firmware dump into IDA Pro.

Exploiting USB Attacks on Microcontroller FirmwareStructure with pointers to known data

The firmware dump allows us to find the address of the printf( function, which outputs factory quality assurance required UART information. More importantly, I was able to find the hexdump( function in the dump, which means I didn’t even need to write shellcode.

Exploiting USB Attacks on Microcontroller FirmwareFinding functions that help development

After finding the UART points on the printed circuit board of the game controller, soldering wires, and connecting them to a TTL2USB adapter, we could see the output in the serial terminal.

Exploiting USB Attacks on Microcontroller FirmwareStandard UART output during game controller boot

The standard library for the Nuvoton microcontroller comes with a very handy hard fault exception handler that outputs a register dump. This greatly facilitates development and allows for debugging vulnerabilities.

Exploiting USB Attacks on Microcontroller FirmwareUART output after stack overflow leading to hard fault exception

The final vulnerability of the dumped firmware can be seen in the screenshot below.

Exploiting USB Attacks on Microcontroller FirmwareExploiting shellcode and shellcode through UART to dump firmware

However, this way of dumping firmware is not perfect because the Nuvoton M451 series microcontroller may have two types of firmware, main firmware (APROM) and mini firmware (LDROM) for device firmware updates.

Exploiting USB Attacks on Microcontroller FirmwareMemory mapping for flash and system memory in different modes

APROM and LDROM map to the same memory addresses, so only one can be dumped. To obtain the LDROM firmware dump, we need to disable the security lock and use the programming tool to read the flash memory.

Exploiting USB Attacks on Microcontroller FirmwareShellcode to disable the security lock

9

Decryption Failure

Analysis of the firmware responsible for updates (LDROM) shows that it is primarily standard code from Nuvoton, with added code to decrypt firmware updates.

Exploiting USB Attacks on Microcontroller FirmwareEncryption algorithm scheme used to decrypt firmware updates

The encryption algorithm used to decrypt firmware updates is a custom block cipher. It executes in cipher block chaining mode, but the block size is only 32 bits. The algorithm takes the key as the product’s text (ascii) identifier and an array of instructions to define the transformations to be performed on the current block. When the end of the key and the array is encountered, their current position is set to the initial position. The transformation list includes six operations: xor (exclusive or), subtraction, reverse subtraction, and the same operations but with swapped bytes. Since the firmware contains large areas filled with zeros, it is easy to compute the secret part of this algorithm.

Exploiting USB Attacks on Microcontroller FirmwareDisplay of the firmware update encryption key

Applying the algorithm extracted from the firmware of the counterfeit game controller to the firmware produced by the main OEM manufacturer can reveal that all these firmwares are encrypted with this encryption algorithm. The weakness of this algorithm allows us to compute an encryption key applicable to all devices and decrypt their firmware updates. In other words, the algorithm used in counterfeit products compromises the security of all products developed by that manufacturer.

Conclusion

This blog content is extensive, and I really want the audience to understand this principle. I have analyzed embedded firmware analysis, found vulnerabilities, and exploited them to obtain firmware dumps and execute code on USB devices.

The topic of fault attacks is not included in this article’s scope, but such attacks are also very effective against USB devices. For those who want to learn more about related information, I recommend watching this video. For those who want to know how piracy managed to obtain algorithms and keys from DualShock 4 to create their own devices, I suggest reading this article.

As for the mystery of the auxiliary microcontroller used for confidentiality, I found that it is not applied in all devices; it was only added to increase complexity. This microcontroller does not retain any secrets and is only used for SHA1 and SHA256. This research also helps enthusiasts create their own open-source projects for game consoles.

As for the buyers of counterfeit game controllers, they are not in an enviable position, as the manufacturers block the keys used for illegal usage, and these buyers ultimately end up with non-working game controllers without hints on where to obtain firmware updates.

Translation: He Yueying, Sun Zhonghao

Exploiting USB Attacks on Microcontroller Firmware

Leave a Comment