Changes

14,404 bytes added ,  13:56, 30 December 2011
Created page with "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 jueg..."
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 [[Games/es|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.
* New games saves can be backed-up and restored (same key is used from one save to another).
*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).

=== Wear leveling ===

The 3DS employs a wear leveling scheme on the savegame FLASH chips. This is done through the usage of blockmaps and a journal. The blockmap is located at offset 0 of the flash chip, and is immediately followed by the journal. The initial state is dictated by the blockmap, and the journal is then applied to that.

First, there are 8 bytes whose purposes are currently unknown. Then comes the actual blockmap.
The blockmap structure is simple:
<pre>
struct header_entry {
uint8_t phys_sec; // when bit7 is set, block has checksums, otherwise checksums are all zero
uint8_t alloc_cnt;
uint8_t chksums[8];
} __attribute__((__packed__));
</pre>

There's one entry per sector, counting from physical sector 1 (sector 0 contains the blockmap/journal).

The 2 bytes that follow the blockmap are the CRC16 (with starting value 0xFFFF (like modbus)) of the first 8 bytes and the blockmap.

Then comes the journal.
The journal structure is as follows:
<pre>
struct sector_entry {
uint8_t virt_sec; // Mapped to sector
uint8_t prev_virt_sec; // Physical sector previously mapped to
uint8_t phys_sec; // Mapped from sector
uint8_t prev_phys_sec; // Virtual sector previously mapped to
uint8_t phys_realloc_cnt; // Amount of times physical sector has been remapped
uint8_t virt_realloc_cnt; // Amount of times virtual sector has been remapped
uint8_t chksums[8];
} __attribute__((__packed__));

struct long_sector_entry{
struct sector_entry sector;
struct sector_entry dupe;
uint32_t magic;
}__attribute__((__packed__));
</pre>

With magic being a constant 0x080d6ce0.

The checksums in the blockmap/journal entries work as follows:
* each byte is the checksum of an encrypted 0x200 bytes large block
* to calculate the checksum, a CRC16 of the block (with starting value 0xFFFF) is calculated, and the two bytes of the CRC16 are XORed together to produce the 8bit checksum

=== Partitions ===

There can be multiple partitions on the chip.
The partitions are represented by tables of DIFI blobs inside a DISA structure.
The order of the DIFI blobs is the order of the partitions in the 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).

{| class="wikitable"
|-
! Start
! Length
! Description
|-
| 0x00
| 4
| Magic ("DISA")
|-
| 0x04
| 4
| Unknown (maybe magic, the same in all the save files so far)
|-
| 0x08
| 8
| Partition table size
|-
| 0x10
| 8
| Offset to primary partition table in DISA
|-
| 0x18
| 8
| Offset to secondary partition table in DISA
|-
| 0x20
| 8
| Partition table's length
|-
| 0x28
| 8
| SAVE Partition entry offset in the partition table
|-
| 0x30
| 8
| SAVE Partition entry length in the partition table
|-
| 0x38
| 8
| DATA Partition entry offset in the partition table
|-
| 0x40
| 8
| DATA Partition entry length in the partition table
|-
| 0x48
| 8
| SAVE Partition offset
|-
| 0x50
| 8
| SAVE Partition length
|-
| 0x58
| 8
| DATA Partition offset
|-
| 0x60
| 8
| DATA Partition length
|-
| 0x68
| 4
| Active table (and the offset to the filebase)
|-
| 0x6C
| 0x20
| Hash from active table
|-
| 0x8C
| 4*29
| Unknown
|}

* 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).

{| class="wikitable"
|-
! 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'''

{| class="wikitable"
|-
! 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'''

{| class="wikitable"
|-
! 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'''

[[File: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 --[[User:Elisherer|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:
<pre>
struct folder_entry {
u32 parent_folder_index;
u8 filename[0x10];
u32 folder_index;
u32 unk1;
u32 last_file_index;
u32 unk3;
u32 unk4;
}
</pre>

File's entry structure:
<pre>
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;
}
</pre>

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:
<pre>
//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 Ü...............
</pre>

{| class="wikitable"
|-
! 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'''

[[File:Sfsave_drawing.png]]

=== Initialization ===

When a save EEPROM contains all xFFFF blocks it's assumed uninitialized by the game cartridges and it initializes default data in place, without prompting the user.

I got a new game SplinterCell3D-Pal and I downloaded the save and it was 128KB of 0xFF, except the first 0x10 bytes which were the letter 'Z' (uppercase) --[[User:Elisherer|Elisherer]] 22:41, 15 October 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.. --[[User:Elisherer|Elisherer]] 22:41, 15 October 2011 (CEST)
85

edits