Euskal Encounter 16, BEC (Barakaldo), Julyio de 2008
Introduction
Our goals:
- Figure out how the Wii's hardware and software works
- Enable and sustain the ability to run homebrew code on the Wii
- Use the console for all sorts of our own purposes
Manufacturers try to make it difficult for us...
In this conference we'll cover:
- The Wii's hardware
- The Wii's software
- The security system
- Attacks and exploits
- Future attacks
- Homebrew: development environment, tools, apps
¿What's a Wii?
After the GameCube's underwhelming sales, Nintendo decided to reinvent the console:
- Let's start with the GameCube's hardware (pretty decent)
- PowerPC CPU @ 485Mhz ("Gekko")
- 24MB main RAM (1T-SRAM), 16MB audio and DVD RAM (DRAM)
- "Flipper" GPU @ 162Mhz (developed by ArtX, now ATI)
- Optical disc unit (modified DVDs)
- Expansion ports, controllers, memory cards, etc.
- Let's upgrade stuff: CPU now runs at 729Mhz and GPU now at 243Mhz
- And throw in new stuff:
- 64MB of extra GDDR3 memory (replaces the old 16MB DRAM)
- SD card reader
- USB ports
- Bluetooth (and wireless controllers - I could give an entire talk about those)
- WiFi
Things get messy...
On the GameCube, running homebrew was easy
- Software on discs is completely unsigned
- The BIOS, although encrypted, is unsigned and the encryption is a joke (with a terrible bug)
- You can use modchips to replace the BIOS or run code from DVDs
Nintendo seems to have learned the lesson with the Wii
- All software is signed
- All software is encrypted
- The crypto used is standard, modern, and secure
- There's a chain of trust started during the boot process, via hardware
- Game data is also encrypted - even game saves
- The FLASH memory is also encrypted and signed
- There's an entirely separate CPU dedicated to security
Or that's the theory anyway...
The Wii's software
There are a bunch of independent software modules:
- The boot process stages: boot0, boot1, and boot2
- The software that normally runs on Starlet, IOS
- The GameCube compatibility subsystem, MIOS and BC
- The system menu
- Games loaded from DVD
- Wii Menu channels (apps and games)
- Internal "Channels" (e.g. the EULA)
Except for the boot stages, they are all titles and share a common installation, signing, and execution subsystem
Titltes
A title is a software package, composed of:
- A TitleID, which is a code (or number, depending on how you look at it) that identifies it
- It's a 64-bit number, where the first 32 bits identify the title class and the last 32 bits are usually four ASCII letters
- Some Title IDs are special
- A TMD (Title Meta-Data) that descriptes a particular version of the software and its contents
- An eTicket (aka ticket o tik), your "license" to run the software
- A series of data files, the contents, which can be shared among different titles to save space
- One of the contents, the boot content, is the main executable
- A certificate chain which is used to validate the digital signatures
The TMD
The TMD is the base file that is used to sign the contents, and contains:
- The TitleID
- The title version
- Which IOS to use, if applicable
- A content descriptor per content:
- Content index
- Content ID
- Size
- SHA-1 hash of the data
TMDs are signed using 2048-bit RSA
The eTicket
The eTicket gives us access to a specific title, possibly with restrictions. Contains:
- The TitleID
- A 128-bit key to decrypt the title
- This key is itself encrypted
- Zero or more limits, such as a usage time limit
eTickets are also signed using 2048-bit RSA
There are two variants:
- Common eTickets, for free (as in beer) software, system software, or DVD games
- Their key is encrypted with a common master key that all Wiis share
- Per-console eTickets, for Wii Shop software
- Their key is supposedly encrypted with a key generated by an algorithm over the Wii's private key and a random number. Except it's not - they use the common key. WTF. **figure this out**
Keys, keys, keys (too lazy to translate this)
En la Wii se utilizan varias claves criptográficas. Algunas son comunes a todas las consolas:
- La Clave común (AES), que sirve para encriptar las claves de los títulos comunes
- ebe42a225e8593e448d9c5457381aaf7
- La Clave SD (AES), que sirve para ofuscar los datos de las tarjetas SD
- ab01b9d8e1622b08afbad84dbfc2a55d, IV: 216712e6aa1f689f95c5a22324dc6a98
- Blanqueador MD5: 0e65378199be4517ab06ec22451a5793
- El Certificado raíz (su clave pública RSA) que verifica a todo lo demás
Y otras son privadas y cambian de consola a consola:
- La Clave NAND (AES), que encripta el contenido de la memoria NAND FLASH de nuestra consola
- La Clave NAND HMAC, que firma la NAND FLASH
- La Clave privada NG (ECC), que es la clave que usa nuestra consola para firmar datos de SD y para obtener acceso a títulos protegidos, y la clave pública NG (ECC), que va certificada por Nintendo
IOS
IOS is the operating system that runs on the Starlet during normal operation of the Wii:
- It is responsible for booting the main CPU and loading its boot code
- Contains drivers for all new devices in the Wii, including the NAND FLASH
- Talks with the main CPU over an IPC interface
- Performs all of the low-level crypto, and is responsible for system security
- Steals the upper 12MB of GDDR3 RAM (this RAM is protected from access by the main CPU)
There are several versions of IOS installed on the console, since each title always uses the same version. Each version is a different title, and we call them IOS21, IOS30, IOS37, etc.
- However, these titles have their own software version number, so they can be updated individually while maintaining their Title ID and IOS number.
IOS (continued)
Some important parts of IOS:
- IOSP, the kernel, is an operating system (microkernel type) on top of which run the rest of the drivers.
- FFS, Flash FileSystem, is the NAND FLASH driver and filesystem implementation. It transparently encrypts and decrypts data and checks the signatures.
- ES, ETicket Services, is responsible for administrating titles and, in particular, installing them on flash. It also handles title security.
- DI is the DVD interface driver, and in Wii mode it handles transparent disc decryption.
The boot process
The boot process is designed to guarantee that any software running on the console is officially signed by Nintendo:
- First, Starlet boots from an internal ROM called boot0. This ROM is part of the Hollywood die, and therefore fixed. boot0 reads boot1 from the first few NAND blocks and checks it against a SHA-1 hash stored in a one-time-programmable memory (this is written at the factory).
- boot1 contains the necessary code to load boot2 from NAND and verify it as if it were a title (boot2 is a slightly strange title). It includes checks for the eTicket, TMD, signatures, etc.
- boot2 lives in a reserved area of NAND, and it is basically a cut-down IOS. It only contains the NAND driver and ES. Its job is to load the real IOS that will be used to boot the system menu
This interesting system lets Nintendo change boot1 in new consoles whenever they want, without having to trash already manufactured Hollywood chips.
boot2 can be updated via software (this is the first part of the boot process that can be upgraded or modified after the factory)
So now what?
So far, it looks like a pretty secure system
- Most of the Wii's security system is designed pretty well
- However, it suffers from implementation problems and bugs
There are several kinds of exploits that have been used to break the system's security:
- Twiizer Attack
- Fakesigning, also known as truchasigning
- Twilight Hack
Twiizer Attack (blah blah you know this part)
En el modo de GameCube, pronto se pudo usar homebrew gracias a los chips
- Los juegos de GameCube no van firmados, así que es fácil insertar código casero
- Nos limita al modo de compatibilidad de GameCube, y no podemos hacer nada interesante
Podemos atacar el hardware para conseguir información interesante
- En el modo de GameCube, se usa la parte baja de la memoria GDDR3 para emular la ARAM de la GameCube
- A la vez, los 12MB altos se reservan para MIOS, pero MIOS apenas usa unos kilobytes
- Antes de cargar MIOS, el IOS ha usado parte de esos 12MB para guardar... ¡claves!
- No podemos acceder a esos 12MB directamente...
- ... pero podemos puentear una conexión en el chip de GDDR3 para leerlos como si fueran parte de la zona de ARAM
Nace el Twiizer Attack, que nos permitió extraer todas las claves importantes, incluyendo la clave común, gracias a la cual podemos:
- Desencriptar cualquier juego de Wii
- Desencriptar cualquier IOS u otro título común
Fakesigning (ninty fails at hash comparisons)
Ahora que podemos ver un IOS en claro, podemos desensamblarlo y analizarlo
Se encontró un curioso problema en la comprobación de firmas de IOS:
- Las firmas digitales RSA de la Wii se crean generando un hash SHA-1 del contenido a firmar, y luego cifrándolo con RSA
- Al comprobar las firmas, se extrae este hash de la firma y se compara con el hash calculado
- Los hash SHA-1 son 20 bytes binarios...
Una grave metedura de pata: se comprueba dicho hash ¡como si fuera texto! Entonces:
- Las comparaciones de texto terminan en cuanto se encuentra un byte a cero
- Hacemos fuerza bruta al hash para que empiece por cero
- Y reemplazamos la firma RSA por ceros
- Debido a las propiedades matemáticas de RSA, cuando la firma es cero al comprobar salen ceros
Con este fallo podemos generar firmas que la Wii considerará válidas. Se conocen como firmas trucha ya que el primer programa en hacer uso de ellas fue Trucha Signer.
Twilight Hack (we've got the save keys so we can exploit games)
Nos queda el problema de conseguir meter nuestro código en algún sitio para que la Wii lo ejecute
- Podemos crear discos caseros, pero para esto hace falta un modchip
- No podemos atacar la red ya que se usa SSL (y no es vulnerable al fallo)
- No hay forma de instalar un canal desde SD, ya que las copias a SD no incluyen el eTicket
Sin embargo, gracias al Twiizer Attack tenemos las claves privadas de nuestra consola
- Estas claves nos permiten generar saves válidos para otras consolas
- Podemos explotar fallos que tengan los juegos
- Estos fallos son muy comunes
Gracias a un fallo en el conocido juego The Legend of Zelda: Twilight Princess, podemos ejecutar código en el PowerPC
- Y desde ahí, hablar con IOS y decirle que instale canales, IOSes, o lo que sea
Con esto nace el Twilight Hack: un save del juego que, explotando el bug, carga un ejecutable desde la tarjeta SD.
- Actualmente es la única forma de empezar a ejecutar software casero en una Wii sin modchip
Counterattacks
Nintendo ha ido solucionando algunos de los problemas:
- Las claves ya no se guardan en la GDDR3, sino en una memoria interna de Starlet
- Esto da igual, ya que ya tenemos las claves comunes y siempre podemos obtener las privadas usando otros métodos por software
- En una actualización, Nintendo empezó a arreglar el bug de las firmas
- Esto nos imposibilita usar discos que usen el bug en el menú del sistema, pero sigue funcionando Twilight Hack y podemos usar IOSes que aún son vulnerables
- Recientemente, han intentado detectar y eliminar el Twilight Hack
- Lo hicieron tan mal que a las 6 horas teníamos una solución
Es muy dificil que consigan cerrar todo en actualizaciones futuras:
- Los exploits de los juegos son tan comunes que son prácticamente desechables
- Incluso si arreglan los fallos públicos de IOS, conocemos unos cuantos bugs que se momento no son públicos
- Nintendo tarda meses en producir y probar una actualización de Wii, mientras que nosotros podemos contestar en horas
Current homebrew state
Tenemos un control casi total sobre la consola:
- Podemos ejecutar código en el PowerPC, instalarlo como canales, modificar juegos, etc
- Podemos crear código para Starlet nuevo o parchear el IOS
Sin embargo, todavía dependemos mucho del software de Nintendo:
- Estamos limitados por las restricciones del IOS oficial, a no ser que desarrollemos parches para eliminarlas
- Siempre tenemos que usar el IOS de Nintendo para hacer todo, ya que no existe una alternativa homebrew viable
- Dependemos de una serie de software durante el arranque. Si cualquier elemento del arranque falla (boot2, menú, IOS), la Wii quedará inservible (brickeada)
- Cualquier actualización de Nintendo puede cambiar la situación
Project: recovery firmware
La idea: un código personalizado delante de boot2 que implemente un sistema de recuperación
- Si se pulsa un botón al arrancar, el sistema carga un menú desde la tarjeta SD y lo ejecuta (desde el cual se podría restaurar o hacer una copia de seguridad de la NAND)
- Si no se pulsa nada, el arranque es normal
Nos daría inmunidad contra cualquier actualización, siempre y cuando no se toque boot2
Estamos desarrollando una alternativa básica a IOS que de acceso directo a todo el hardware de la Wii, sin restricciones, para usarse en programas tales como:
- El firmware de recuperación
- Un extractor de claves
- Wii Linux
Future: intelligent IOS patcher
Un parcheador que dinámicamente parchee IOS desde boot2
- Un parche eliminaría la posibilidad de cambiar boot2
- Otro parche se usaría para mantener esta habilidad cuando se vayan cargando otros IOS
- Se puede integrar con el sistema de recuperación
- Podemos arrancar en limpio, sin parches, si fuera necesario
- Más flexible que ir instalando IOS parcheados
Con esto ya tendríamos un control prácticamente total sobre la consola y sus actualizaciones
Homebrew
Tenemos librerías para acceder a casi todo el hardware de Wii
- Gráficos, mandos, pads, red WiFi y ethernet, SD, USB, y mucho más
- El adaptador USBGecko crea un puerto serie virtual en la Wii y se comunica con el PC via USB
Herramientas de desarrollo:
- devkitPPC, la suite de compiladores para el PowerPC de la Wii
- libOGC, la libería que nos da acceso a casi todo el hardware de Wii (y de la GameCube)
- libFAT, para acceder al sistema de archivos FAT en SD y USB
- devkitARM, para compilar para Starlet
Cargadores:
- El Canal Homebrew (The Homebrew Channel), un cargador gráfico de aplicaciones desde SD
- También carga binarios por WiFi o por USBGecko