Savegames/es

From 3dbrew
Jump to navigation Jump to search

Esta página describe el formato, la des/encriptación, etc de las partidas guardadas de los cartuchos de los juegos de la 3DS. Puedes encontrar partidas guardadas de varios juegos de la 3DS en la página de Juegos.


Encriptación

En la 3DS las partidas se almacenan de una forma similar a la DS, en un chip FLASH en el cartucho del juego. En la DS estas partidas están en formato de texto plano pero en la 3DS se añade una capa de encriptación. Esto se parece mucho a un flujo de cifrado, donde los contenidos de algunas partidas tienen un comportamiento extraño cuando se XORean algunas partes juntas de la partida y da como resultado un archivo de texto plano.

La razón por la que esto funciona es porque el cifrado usado tiene un tamaño de 512 bytes. Que es lo mismo, se va repitiendo la misma clave cada 512 bytes. La forma de encriptar con un cifrado es la producida por una clave XOR. Por desgracia, si se repite la clave y estás encriptando un texto plano conocido (en nuestro caso, ceros) básicamente estás “regalando” tu clave.

Entonces, ¿cómo puedo utilizar esto para desencriptar una partida guardada en una 3DS? En primer lugar, tienes que dividir la partida en chunks (trozos) de 512 bytes. Entonces, debes seleccionar los chunks por su contenido, descartando los que solo contengan FF. Ahora debes buscar el chunk más común. Esta es la clave. Ahora XORea con la clave que acabas de encontrar la partida original y deberías obtener la partida completamente desencriptada. Si vuelves a XORear con la clave a la partida desencriptada volverás a obtener la partida completamente encriptada.

Actualización:

Desde el firmware 2.0.0-4 Nintendo ha introducido una nueva forma de encriptación (podría ser una solución para la exploit de más arriba). El xorpad parece repetirse en el archivo pero no cada 0x200 bytes. Así que por ahora no se sabe cómo descifrar las nuevas partidas.

Juegos que usan la nueva encriptación:

  • Super Mario 3D Land
  • Mario Kart 7
  • Need for Speed - The Run

Más información:

  • Los juegos viejos aún usan el antiguo xorpad de 0x200 bytes.
  • Los juegos nuevos puedes ser copiados y restaurados (se usa la misma clava tanto una partida como para otra)
  • El wearleveling sigue siendo el mismo.
  • XOReando dos archivos juntos puede producir algo de texto claro.
  • Se ha observado que el xorpad se repite cada 0x1000 bytes (podría ser la longitud máxima pero aún no se ha probado).

Nivel de desgaste

La 3DS utiliza un esquema para prevenir el nivel de desgaste de los chips FLASH de las partidas. Eso lo consigue utilizando blockmaps i un journal. El blockmap se encuentra en el offset 0 del chip, y es seguido inmediatamente por el journal. El estado inicial es dictado por el blockmap, y el journal es entonces aplicado.

Primero hay 8 bytes cuyos fines se desconocen aún. Luego viene el blockmap. La estructura del blockmap es simple:

struct header_entry {
        uint8_t phys_sec; // cuando se establece el sépitmo bit, el bloque tiene  checksums,  de lo contrario los checksums  son cero
        uint8_t alloc_cnt;
        uint8_t chksums[8];
} __attribute__((__packed__));

Hay un journal por sector, contando desde el sector físico 1(el sector 0 contiene el blockmap/journal). Los siguientes dos bytes que siguen al blockmap son el CRC16 (con 0xFFFF como valor inicial (como el modbus)) de los primeros 8 bytes del blockmap.

Entonces hay el journal. La estructura del journal es:

struct sector_entry {
        uint8_t virt_sec;       // Asignado al sector
        uint8_t prev_virt_sec;  // Sector físico previamente asignado
        uint8_t phys_sec;       // Asignado desde el sector
        uint8_t prev_phys_sec;  // Sector virtual previamente asignado
        uint8_t phys_realloc_cnt;       // Cantidas de veces que el sector físico ha sido reasignado
        uint8_t virt_realloc_cnt;       // Cantidas de veces que el sector virtual ha sido reasignado
        uint8_t chksums[8];
} __attribute__((__packed__));

struct long_sector_entry{
        struct sector_entry sector;
        struct sector_entry dupe;
        uint32_t magic;
}__attribute__((__packed__));

Con la constante mágica 0x080d6ce0.

Los checksums de las entradas del blockmap/journal trabajan de la siguiente forma:

  • cada byte es el checksum de un bloque de tamaño 0x200 bytes encriptado
  • para calcular el checksum, el CRC16 del bloque ( con el valor iniciar 0xFFFF) es calculado, y los dos bytes del CRC16 son XOReados juntos para producir un checksum de 8 bits.

Particiones

Puede haber múltiples particiones en el chip. Las particiones están representadas por tablas de manchas del DIFI dentro de la estructura DISA. El orden de las manchas del DIFI es el orden de las particiones del chip.

DISA

  • If the uint32 @ 0x168 into the image in the DISA is a %1=1, then first table is is hashed, otherwise the second DIFI table is hashed.
  • If the table has more then 1 DIFI then the uint32 @ 0x168 is the offset from the DATA partition to the file base (masked with 0xFFFFFFFE).
Principio Longitud Descripción
0x00 4 Magic ("DISA")
0x04 4 Desconocido (puede ser mágico, puede ser el mismo que todas las partidas)
0x08 8 Tamaño de la tabla de particiones
0x10 8 Offset a la partición primaria de la tabla del DISA
0x18 8 Offset a la partición secundaria de la tabla del DISA
0x20 8 Longitud de la tabla de particiones
0x28 8 Offset de la entrada de guardado en la tabla de particiones
0x30 8 Longitud de la entrada de guardado en la tabla de particiones
0x38 8 Offset de la entrada de datos en la tabla de particiones
0x40 8 Longitud de la entrada de datos en la tabla de particiones
0x48 8 Offset de la partición de guardado
0x50 8 Longitud de la partición de guardado
0x58 8 Offset de la partición de datos
0x60 8 Longitud de la partición de datos
0x68 4 Tabla activa (y el offset hacia la filebase)
0x6C 0x20 Hash desde la partición activa
0x8C 4*29 Desconocido
  • The hash in the DISA hashes the Active Table (starting from tables's offset to tables's offset + table length) with SHA256.
  • The partitions offsets points to a 0x1000 long block which isn't understood yet. The actual information starts after that block.

The DIFIs table @ 0x200 (into the image) is written twice, (Meaning, if there's 4 DIFI blobs then the table is 2 DIFIs long).

The second table is for backup. The active table is mentioned at 0x13C into the image (1=First table, other=Second Table)

DIFI

These 0x130 large blobs describe the partitions. Every DIFI blob describes a partition. Partitions are catted together, so after the end of one partition is the beginning of the next.

Actually DIFI blobs are 0x12C large because the last 4 are not used and appear 0xFFFFFFFF at the encrypted image.

For most games there's only 1 partition (The SAVE partition) and some (like Asphalt 3D, Steel Diver & Lego Star Wars III) has 2 partitions.

  • 2 Partitions means that the files inside the SAVE partition is on the other partition (we would call it DATA partition).
  • No more than 2 partitions have been seen yet (and can't be becuase of the DISA known structure).
Start Length Description
0x00 4 Magic ("DIFI")
0x04 4 Magic Number (0x10000)
0x08 8 Offset to "IVFC" blob in DIFI (usually 0x44)
0x10 8 Size of "IVFC" blob
0x18 8 Offset to "DPFS" blob in DIFI (usually 0xBC)
0x20 8 Size of "DPFS" blob
0x28 8 Offset to the hash in DIFI (usually 0x010C)
0x30 8 Size of this hash
0x38 4 Flags (1 means DATA partition)
0x3C 8 File base offset (for DATA partitions)

IVFC

Start Length Description
0x00 4 Magic ("IVFC")
0x04 4 Magic Number (0x20000)
0x08 8 Unknown (0x20?)
0x10 8 First Hash Offset
0x18 8 First Hash Length
0x20 8 First Hash Block Size (1<<value)
0x28 8 Second Hash Offset
0x30 8 Second Hash Length
0x38 8 Second Hash Block Size (1<<value)
0x40 8 HashTable Offset
0x48 8 HashTable Length
0x50 8 HashTable Block Size (1<<value)
0x58 8 FileSystem Offset
0x60 8 FileSystem Length
0x68 8 FileSystem Block Size (1<<value)
0x70 8 Unknown (usually 0x78=120)
  • First & Second hash are not understood yet.

DPFS

Start Length Description
0x00 4 Magic ("DPFS")
0x04 4 Magic Number (0x10000)
0x08 8 Offset To First table
0x10 8 First table length
0x18 8 First table block size (1<<value)
0x20 8 Offset To Second table
0x28 8 Second table length
0x30 8 Second table block size (1<<value)
0x38 8 Offset to Data
0x40 8 Data Length
0x48 8 Data block size (1<<value)
  • Every block this table point to is written twice (concatenated). You can see that the offset to the next block is twice the length (except the data which always begin after 0x1000).

The first partition's data starts at 0x2000. First comes the hashtable (usually start @ 0x40 into the partition) and then the filesystem.

The hashtable entries' size is 2^x where x is the 'Hashed block size' from the IVFC block.

Hash

After the DIFI,IVFC & DPFS comes a 0x20 long hash, it is unknown what it's hashing.

Summary Drawing

Sfimg drawing.png

The SAVE partition

  • The SAVE filesystem works with a backup. There are two SAVE blocks inside the partition concatenated. Which SAVE block is the updated one is unknown yet.. (I'm guessing from experience that (image[0x100B] & 0x20) == 0x20 --> 1st SAVE --Elisherer 01:30, 18 October 2011 (CEST))

Finding the folders table:

  • If DATA partition exists: At folder table exact offset from the SAVE struct (from the beginning of the struct).
  • Otherwise: The 'folder table offset' * 'folder table media' (=0x200) from the 'filestore offset'. (usually 0 from filebase)

Finding the files table:

  • If DATA partition exists: At file table exact offset from the SAVE struct (from the beginning of the struct).
  • Otherwise: The 'file table offset' * 'file table media' (=0x200) from the 'filestore offset'.

Detemining the filestore base:

  • If DATA partition exists: At file base from the DATA's DIFI struct into the DATA partition.
  • Otherwise: At the 'filestore offset' from the beginning of the SAVE struct.

Folder's entry structure:

 struct folder_entry {
     u32 parent_folder_index;
     u8  filename[0x10];
     u32 folder_index;
     u32 unk1; 
     u32 last_file_index;
     u32 unk3; 
     u32 unk4;
 }

File's entry structure:

 struct file_entry {
     u32 parent_folder_index;
     u8  filename[0x10];
     u32 index;
     u32 unk1; // magic?
     u32 block_offset;
     u64 file_size;
     u32 unk2; // flags?
     u32 unk3;
 }

The first entry in both tables is the count of the table, the parent directory index will be the amount of table rows. The root includes itself, so there are the amount - 1 (minus one) folders in the root directory (or files). The entries that follow after the root are the actual folders/files.

Reading the files out is as simple as taking the file base offset and adding (block_offset * 0x200) to it.

Here's a follow-up example from the Legend of Zelda: Ocarina of Time 3D:

//FST entry = SAVE base + File base + (FST offset * 0x200) + (FST entry # * 0x30)
//0x2600    = 0x2000    + 0x400     + (0x1        * 0x200) + (0x0         * 0x30)

00002600: 03000000 09000000 00000000 00000000  ................
00002610: 00000000 00000000 00000000 00000000  ................
00002620: 00000000 00000000 00000000 00000000  ................
00002630: 01000000 73797374 656D2E64 61740000  ....system.dat..
00002640: 00000000 00000000 D57B1100 02000000  ........Õ{......
00002650: 22000000 00000000 E8121500 00000000  ".......è.......
00002660: 01000000 73617665 30302E62 696E0000  ....save00.bin..
00002670: 00000000 01000000 69921100 03000000  ........i’......
00002680: DC140000 00000000 04000000 00000000  Ü...............
Start Length Description
0x00 4 Magic ("SAVE")
0x04 4 Magic padding
0x08 8 Unknown
0x10 8 Partition Size [medias]
0x18 4 Partition Media Size
0x1C 8 Unknown
0x24 4 Unknown
0x28 8 FolderMap Offset
0x30 4 FolderMap Size
0x34 4 FolderMap Media Size
0x38 8 FileMap Offset
0x40 4 FileMap Size
0x44 4 FileMap Media Size
0x48 8 BlockMap Offset
0x50 4 BlockMap Size
0x54 4 BlockMap Media Size
0x58 8 File store offset (from SAVE)
0x60 4 File store length [medias]
0x64 4 File store media size
0x68 4/8 Folders Table offset (8 bytes in DATA)
0x6C 4 Folders Table Length (medias) (Only in no DATA)
0x70 4 Folders Table unknown
0x74 4 Folders Table Media size
0x78 4/8 Files Table offset (8 bytes in DATA)
0x7C 4 Files Table Length (medias) (Only in no DATA)
0x80 4 Files Table unknown
0x84 4 Files Table Media size
  • The FolderMap and FileMap still unknown. They are tables of uint32.
  • The BlockMap is a map of the blocks in the filestore. An entry in the BlockMap is 2 uint32: {uint32 start_block; uint32 end_block; }. This is still being researched. (You can use 3DSExplorer to see those maps.

Summary Drawing

Sfsave drawing.png

La Inicialización

Cuando un EEPROM save contiene todos los bloques xFFFF se asume sin inicializar los cartuchos y lo inicializa los datos por defecto en su lugar, sin preguntar al usuario.

Tengo un juego nuevo SplinterCell3D-Pal y he descargado la partida guardada y era 128KB de 0xFF, excepto los primeros bytes 0x10, que fueron 'Z' (en mayúsculas) --Elisherer 22:41, 15 de octubre de 2011 (CEST)

Fun Facts

If you have facts that you found out by looking at the binary files please share them here:

  • From one save to another the game backups the last files that were in the partition and the entire image header in "random" locations.. --Elisherer 22:41, 15 October 2011 (CEST)