Major update

Changed titlekey dump methodology to no longer need reboot.
Added SD seed dumping.
Reorganized and clarified UI text.
Swapped C++-style I/O for C-style.
Tightened up dependencies.
This commit is contained in:
shchmue 2018-12-28 16:06:18 -05:00
parent 41c2604d9a
commit 922cf3f4c4
25 changed files with 23552 additions and 372 deletions

View File

@ -32,12 +32,12 @@ include $(DEVKITPRO)/libnx/switch_rules
#---------------------------------------------------------------------------------
APP_TITLE := Lockpick
APP_AUTHOR := shchmue
APP_VERSION := 1.0
APP_VERSION := 1.1
TARGET := $(subst $e ,_,$(notdir $(APP_TITLE)))
BUILD := build
OUTDIR := out
SOURCES := source
SOURCES := source source/fatfs source/nx
DATA := data
INCLUDES := include
EXEFS_SRC := exefs_src

View File

@ -1,11 +1,11 @@
Lockpick
=
This is a ground-up C++17 rewrite of homebrew key derivation software, namely [kezplez-nx](https://github.com/tesnos/kezplez-nx). It also dumps titlekeys. This will dump all keys through `*_key_05` on firmwares below `6.2.0` and through `*_key_06` on `6.2.0` and above.
Lockpick is a ground-up C++17 rewrite of homebrew key derivation software, namely [kezplez-nx](https://github.com/tesnos/kezplez-nx). It also dumps titlekeys. This will dump all keys through `*_key_05` on firmwares below `6.2.0` and through `*_key_06` on `6.2.0`.
What this software does differently
=
* Dumps `titlekeys`
* Dumps `6.2.0` keys
* Dumps `titlekeys` and SD seed
* Dumps all keys through `6.2.0`
* Uses the superfast `xxHash` instead of `sha256` when searching exefs for keys for a ~5x speed improvement
* Gets all possible keys from running process memory - this means no need to decrypt `Package2` at all, let alone decompress `KIP`s
* Gets `header_key` without `tsec`, `sbk`, `master_key_00` or `aes` sources - which may or may not be the same way `ChoiDujourNX` does it :eyes: (and I'm gonna issue a challenge to homebrew title installers to implement similar code so you don't need your users to use separate software like this :stuck_out_tongue_winking_eye: it's up to you to figure out if the same can be done for `key_area_keys` if needed)
@ -15,16 +15,16 @@ Usage
1. Use [Hekate v4.5+](https://github.com/CTCaer/hekate/releases) to dump TSEC and fuses:
1. Push hekate payload bin using [TegraRCMSmash](https://github.com/rajkosto/TegraRcmSmash)/[TegraRCMGUI](https://github.com/eliboa/TegraRcmGUI)/modchip/injector
2. Using the `VOL` and `Power` buttons to navigate, select `Console info...`
3. Select `Print fuse info`
3. Select `Print fuse info` (_not_ `kfuse info`)
4. Press `Power` to save fuse info to SD card
5. Select `Print TSEC keys`
6. Press `Power` to save TSEC keys to SD card
2. Launch CFW of choice
3. Open `Homebrew Menu`
4. Run `Lockpick`
5. Use the resulting `prod.keys` file as needed and rename if required
5. Use the resulting `/switch/prod.keys` file as needed and rename if required by any software you're using
You may instead use [biskeydump](https://github.com/rajkosto/biskeydump) and dump to SD to get all keys prior to the 6.2.0 generation - all keys up to those ending in 05. This will dump all keys up to that point regardless which firmware it's run on.
You may instead use [biskeydump](https://github.com/rajkosto/biskeydump) and dump to SD to get all keys prior to the 6.2.0 generation - all keys up to those ending in 05. Lockpick will dump all keys up to that point regardless which firmware it's run on.
Notes
=
@ -62,7 +62,9 @@ Special Thanks
Licenses
=
* `AES` functions are from [mbedtls](https://tls.mbed.org/) licensed under [GPLv2](https://www.gnu.org/licenses/old-licenses/gpl-2.0.html))
* `creport_debug_types` and fast `sha256` implementation are from [Atmosphère](https://github.com/atmosphere-NX/Atmosphere) licensed under [GPLv2](https://github.com/Atmosphere-NX/Atmosphere/blob/master/LICENSE)
* `AES` functions are from [mbedtls 2.13.0](https://tls.mbed.org/) licensed under [GPLv2](source/mbedtls/gpl-2.0.txt)
* Aarch64 assembly `sha256` is from [Atmosphère](https://github.com/atmosphere-NX/Atmosphere) licensed under [GPLv2](https://github.com/Atmosphere-NX/Atmosphere/blob/master/LICENSE)
* `es` ipc code is from [Tinfoil](https://github.com/Adubbz/Tinfoil) licensed under [MIT](https://github.com/Adubbz/Tinfoil/blob/master/LICENSE)
* `FatFs R0.13c` is located [here](http://elm-chan.org/fsw/ff/00index_e.html) and is licensed under its own [BSD-style license](source/fatfs/LICENSE.txt)
* Simple `xxHash` implementation is from [stbrumme](https://github.com/stbrumme/xxhash) licensed under [MIT](https://github.com/stbrumme/xxhash/blob/master/LICENSE)
* Padlock icon is from [Icons8](https://icons8.com/) licensed under [Creative Commons Attribution-NoDerivs 3.0 Unported](https://creativecommons.org/licenses/by-nd/3.0/)

11
changelog.md Normal file
View File

@ -0,0 +1,11 @@
# Changelog
## Version 1.1
* Changed titlekey dump methodology
* No longer crashes sysmodule, reboot no longer needed
* Queries ES to verify ticket list is accurate
* May take slightly longer than before on systems with hundreds of tickets
* Now dumps SD seed
* Reorganized and clarified UI text
* Now indicates if no titles are installed to dump titlekeys from
* Swapped C++ stream functions for C I/O to reclaim some speed and binary size
* Tightened up dependencies

View File

@ -20,14 +20,17 @@
*/
#include "Common.hpp"
#include "Key.hpp"
#include <machine/endian.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <filesystem>
#include <fstream>
#include <string>
extern "C" {
#include <machine/endian.h>
}
#include <switch.h>
#include "sha256.h"
@ -116,18 +119,18 @@ namespace Common {
FT_New_Memory_Face(library, static_cast<FT_Byte *>(font.address), font.size, 0, &face);
FT_Set_Char_Size(face, 0, 6*64, 300, 300);
gfxSetMode(GfxMode_LinearDouble);
gfxSetMode(GfxMode_LinearDouble); // todo: update for nwindow/framebuffer
framebuf = (u32 *)gfxGetFramebuffer(&framebuf_width, NULL);
memset(framebuf, 0, gfxGetFramebufferSize());
draw_text(0x10, 0x020, YELLOW, "Lockpick! by shchmue");
draw_set_rect(814, 452 + 42 * 0, 450, 42, RGBA8_MAXALPHA(0xe7, 0x00, 0x00));
draw_set_rect(814, 452 + 42 * 1, 450, 42, RGBA8_MAXALPHA(0xff, 0x8c, 0x00));
draw_set_rect(814, 452 + 42 * 2, 450, 42, RGBA8_MAXALPHA(0xff, 0xef, 0x00));
draw_set_rect(814, 452 + 42 * 3, 450, 42, RGBA8_MAXALPHA(0x00, 0x81, 0x1f));
draw_set_rect(814, 452 + 42 * 4, 450, 42, RGBA8_MAXALPHA(0x00, 0x44, 0xff));
draw_set_rect(814, 452 + 42 * 5, 450, 42, RGBA8_MAXALPHA(0x76, 0x00, 0x89));
draw_set_rect(814, 452 + 42 * 0, 450, 42, FLAG_RED);
draw_set_rect(814, 452 + 42 * 1, 450, 42, FLAG_ORANGE);
draw_set_rect(814, 452 + 42 * 2, 450, 42, FLAG_YELLOW);
draw_set_rect(814, 452 + 42 * 3, 450, 42, FLAG_GREEN);
draw_set_rect(814, 452 + 42 * 4, 450, 42, FLAG_BLUE);
draw_set_rect(814, 452 + 42 * 5, 450, 42, FLAG_VIOLET);
if ( !(envIsSyscallHinted(0x60) && // svcDebugActiveProcess
envIsSyscallHinted(0x63) && // svcGetDebugEvent
@ -135,76 +138,70 @@ namespace Common {
envIsSyscallHinted(0x69) && // svcQueryDebugProcessMemory
envIsSyscallHinted(0x6a))) { // svcReadDebugProcessMemory
draw_text(0x190, 0x20, RED, "Error: Please run with debug svc permissions!");
wait_to_exit(Status_fail);
wait_to_exit();
}
draw_text(0x10, 0x080, CYAN, "Get Tegra keys...");
draw_text(0x10, 0x0a0, CYAN, "Get keys from memory...");
draw_text(0x10, 0x0c0, CYAN, "Get master keys...");
draw_text(0x10, 0x0e0, CYAN, "Derive remaining keys...");
draw_text(0x10, 0x100, CYAN, "Saving keys to keyfile...");
draw_text(0x10, 0x130, CYAN, "Total time elapsed:");
draw_text(0x10, 0x060, CYAN, "Get Tegra keys...");
draw_text(0x10, 0x080, CYAN, "Get keys from memory...");
draw_text(0x10, 0x0a0, CYAN, "Get master keys...");
draw_text(0x10, 0x0c0, CYAN, "Derive remaining keys...");
draw_text(0x10, 0x0e0, CYAN, "Saving keys to keyfile...");
draw_text(0x10, 0x110, CYAN, "Total time elapsed:");
consoleUpdate(NULL);
}
void get_tegra_keys(Key &sbk, Key &tsec, Key &tsec_root) {
// support hekate dump
if (!std::filesystem::exists("/backup"))
return;
for (auto &p : std::filesystem::recursive_directory_iterator("/backup")) {
if (sbk.found() && tsec.found())
return;
if (p.is_regular_file()) {
if (!sbk.found() && (p.file_size() == 0x2fc) &&
(std::string("fuse").compare(std::string(p.path().filename()).substr(0, 4)) == 0))
{
std::ifstream fuse_file(p.path(), std::ios::binary);
byte_vector temp_key(0x10);
fuse_file.seekg(0xa4);
fuse_file.read(reinterpret_cast<char *>(temp_key.data()), 0x10);
sbk = Key("secure_boot_key", 0x10, temp_key);
}
else if (!tsec.found() && (p.file_size() == 0x30) &&
(std::string("tsec").compare(std::string(p.path().filename()).substr(0, 4)) == 0))
{
std::ifstream tsec_file(p.path(), std::ios::binary);
byte_vector temp_key(0x10);
tsec_file.read(reinterpret_cast<char *>(temp_key.data()), 0x10);
tsec = Key("tsec_key", 0x10, temp_key);
tsec_file.read(reinterpret_cast<char *>(temp_key.data()), 0x10);
tsec_root.find_key(temp_key);
// support Hekate dump
if (std::filesystem::exists("/backup")) {
for (auto &p : std::filesystem::recursive_directory_iterator("/backup")) {
if (p.is_regular_file()) {
if (!sbk.found() && (p.file_size() == 0x2fc) &&
(std::string("fuse").compare(std::string(p.path().filename()).substr(0, 4)) == 0))
{
FILE *fuse_file = fopen(p.path().c_str(), "rb");
if (!fuse_file) continue;
byte_vector temp_key(0x10);
fseek(fuse_file, 0xa4, SEEK_SET);
fread(temp_key.data(), 0x10, 1, fuse_file);
sbk = Key("secure_boot_key", 0x10, temp_key);
fclose(fuse_file);
}
else if (!tsec.found() && (p.file_size() == 0x30) &&
(std::string("tsec").compare(std::string(p.path().filename()).substr(0, 4)) == 0))
{
FILE *tsec_file = fopen(p.path().c_str(), "rb");
if (!tsec_file) continue;
byte_vector temp_key(0x10);
fread(temp_key.data(), 0x10, 1, tsec_file);
tsec = Key("tsec_key", 0x10, temp_key);
fread(temp_key.data(), 0x10, 1, tsec_file);
tsec_root.find_key(temp_key);
fclose(tsec_file);
}
}
if (sbk.found() && tsec.found())
return;
}
}
// support biskeydump v7 dump
if (std::filesystem::exists("/device.keys")) {
std::ifstream key_file("/device.keys");
for (std::string line; std::getline(key_file, line); !sbk.found() && !tsec.found()) {
line.erase(std::remove_if(
line.begin(), line.end(),
[l = std::locale{}](auto ch) { return std::isspace(ch, l); }
), line.end());
if (line.substr(0, 15).compare("secure_boot_key") == 0)
FILE *key_file = fopen("/device.keys", "r");
char line[0x100];
while (fgets(line, sizeof(line), key_file) && !(sbk.found() && tsec.found())) {
if (strncmp("secure_boot_key", line, 15) == 0)
sbk = Key("secure_boot_key", 0x10, key_string_to_byte_vector(line));
else if (line.substr(0, 8).compare("tsec_key") == 0)
else if (strncmp("tsec_key", line, 8) == 0)
tsec = Key("tsec_key", 0x10, key_string_to_byte_vector(line));
}
fclose(key_file);
}
}
void wait_to_exit(int status) {
if (status == Status_fail)
draw_text(0x1f4, 0x080, RED, ">> Press + to exit <<");
else if (status == Status_success_no_titlekeys)
draw_text(0x1f4, 0x1a0, GREEN, ">> Press + to exit <<");
else if (status == Status_success_titlekeys)
draw_text(0x1f4, 0x1f0, GREEN, ">> Press + to exit <<");
else if (status == Status_success_titlekeys_failed)
draw_text(0x1f4, 0x1f0, RED, ">> Press + to exit <<");
void wait_to_exit() {
draw_text(0x10b, 0x24b, YELLOW, ">> Press + to exit <<");
while(appletMainLoop() & (status != Status_success_no_titlekeys)) {
while(appletMainLoop()) {
hidScanInput();
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
if (kDown & KEY_PLUS) break;
@ -229,9 +226,9 @@ namespace Common {
}
byte_vector key_string_to_byte_vector(std::string key_string) {
key_string = key_string.substr(key_string.find('=') + 1);
byte_vector temp_key(key_string.size() / 2);
for (size_t i = 0; i < temp_key.size(); i += 8)
key_string = key_string.substr(key_string.find('=') + 2);
byte_vector temp_key((key_string.size() - 1) / 2);
for (size_t i = 0; i < temp_key.size() - 1; i += 8)
*reinterpret_cast<u64 *>(temp_key.data() + i) = __bswap64(strtoul(key_string.substr(i * 2, 0x10).c_str(), NULL, 16));
return temp_key;
}

View File

@ -16,26 +16,30 @@
#pragma once
#include "Key.hpp"
#include <string>
#include <vector>
#include <ft2build.h>
#include <switch.h>
#include FT_FREETYPE_H
#include <switch/types.h>
#define GREEN RGBA8_MAXALPHA(0, 0xff, 0)
#define RED RGBA8_MAXALPHA(0xff, 0, 0)
#define CYAN RGBA8_MAXALPHA(0, 0xff, 0xff)
#define YELLOW RGBA8_MAXALPHA(0xff, 0xff, 0)
enum {
Status_fail = 0,
Status_success_no_titlekeys,
Status_success_titlekeys,
Status_success_titlekeys_failed
};
#define FLAG_RED RGBA8_MAXALPHA(0xe7, 0x00, 0x00)
#define FLAG_ORANGE RGBA8_MAXALPHA(0xff, 0x8c, 0x00)
#define FLAG_YELLOW RGBA8_MAXALPHA(0xff, 0xef, 0x00)
#define FLAG_GREEN RGBA8_MAXALPHA(0x00, 0x81, 0x1f)
#define FLAG_BLUE RGBA8_MAXALPHA(0x00, 0x44, 0xff)
#define FLAG_VIOLET RGBA8_MAXALPHA(0x76, 0x00, 0x89)
class Key;
typedef std::vector<u8> byte_vector;
namespace Common {
// draw letter, called by draw_text
void draw_glyph(FT_Bitmap *bitmap, u32 x, u32 y, u32 color);
@ -54,10 +58,10 @@ namespace Common {
void intro();
// get tegra keys from payload dump
void get_tegra_keys(Key &sbk, Key &tsec, Key &tsec_root);
// print exit in color green or red (fail==true)
void wait_to_exit(int status);
// print exit
void wait_to_exit();
void sha256(const u8 *data, u8 *hash, size_t length);
// reads "<keyname> = <hexkey>" and returns byte vector
std::vector<u8> key_string_to_byte_vector(std::string key_string);
byte_vector key_string_to_byte_vector(std::string key_string);
}

View File

@ -17,12 +17,12 @@
#include "Key.hpp"
#include <algorithm>
#include <iomanip>
#include <vector>
#include <mbedtls/aes.h>
#include <mbedtls/cmac.h>
#include "Common.hpp"
#include "xxhash64.h"
size_t Key::saved_key_count = 0;
@ -68,19 +68,15 @@ Key::Key() :
{
}
void Key::save_key(std::ofstream &file) {
void Key::save_key(FILE *file) {
if (!found())
return;
// format: <keyname> = <hex key> for hactool and similar tools
char key_chars[3] = "00";
file.write(name.c_str(), name.size());
file.write(" = ", 3);
for (u8 c : key) {
sprintf(key_chars, "%02x", c);
file.write(key_chars, 2);
}
file.write("\n", 1);
fprintf(file, "%s = ", name.c_str());
for (auto n : key)
fprintf(file, "%02x", n);
fprintf(file, "\n");
saved_key_count++;
}

View File

@ -16,13 +16,12 @@
#pragma once
#include <fstream>
#include <string>
#include <vector>
#include <switch.h>
#include <switch/types.h>
#include "Common.hpp"
#include <stdio.h>
typedef std::vector<u8> byte_vector;
@ -44,7 +43,7 @@ public:
void set_found() { is_found = true; }
// write key to file
void save_key(std::ofstream &file);
void save_key(FILE *file);
static const size_t get_saved_key_count() { return saved_key_count; }

View File

@ -17,29 +17,40 @@
#include "KeyCollection.hpp"
#include "Common.hpp"
#include "creport_debug_types.hpp"
#include "Stopwatch.hpp"
#include <algorithm>
#include <chrono>
#include <filesystem>
#include <fstream>
#include <functional>
#include <iomanip>
#include <set>
#include <string>
#include <unordered_map>
#include <stdio.h>
#include <switch.h>
#include "fatfs/ff.h"
extern "C" {
#include "set_ext.h"
#include "nx/es.h"
#include "nx/set_ext.h"
}
const u8 KeyCollection::null_hash[0x20] = { // hash of empty string
#define TITLEKEY_BUFFER_SIZE 0x40000
// hash of empty string
const u8 KeyCollection::null_hash[0x20] = {
0xE3, 0xB0, 0xC4, 0x42, 0x98, 0xFC, 0x1C, 0x14, 0x9A, 0xFB, 0xF4, 0xC8, 0x99, 0x6F, 0xB9, 0x24,
0x27, 0xAE, 0x41, 0xE4, 0x64, 0x9B, 0x93, 0x4C, 0xA4, 0x95, 0x99, 0x1B, 0x78, 0x52, 0xB8, 0x55};
FsStorage storage;
// function timer
template<typename Duration = std::chrono::microseconds, typename FT, typename ... Args>
typename Duration::rep profile(FT&& fun, Args&&... args) {
const auto beg = std::chrono::high_resolution_clock::now();
std::invoke(fun, std::forward<Args>(args)...);//std::forward<FT>(fun)(std::forward<Args>(args)...);
std::invoke(fun, std::forward<Args>(args)...);
const auto end = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<Duration>(end - beg).count();
}
@ -226,67 +237,51 @@ KeyCollection::KeyCollection() {
};
};
int KeyCollection::get_keys() {
void KeyCollection::get_keys() {
Stopwatch total_time;
total_time.start();
int64_t profiler_time = profile(Common::get_tegra_keys, sbk, tsec, tsec_root_key);
if ((sbk.found() && tsec.found()) || tsec_root_key.found()) {
Common::draw_text_with_time(0x10, 0x80, GREEN, "Get Tegra keys...", profiler_time);
Common::draw_text_with_time(0x10, 0x60, GREEN, "Get Tegra keys...", profiler_time);
} else {
Common::draw_text(0x010, 0x80, RED, "Get Tegra keys...");
Common::draw_text(0x190, 0x80, RED, "Failed");
Common::draw_text(0x010, 0x60, RED, "Get Tegra keys...");
Common::draw_text(0x190, 0x60, RED, "Failed");
Common::draw_text(0x190, 0x20, RED, "Warning: Saving limited keyset.");
Common::draw_text(0x190, 0x40, RED, "Dump Tegra keys with payload and run again to get all keys.");
}
profiler_time = profile(&KeyCollection::get_memory_keys, *this);
Common::draw_text_with_time(0x10, 0x0a0, GREEN, "Get keys from memory...", profiler_time);
Common::draw_text_with_time(0x10, 0x080, GREEN, "Get keys from memory...", profiler_time);
profiler_time = profile(&KeyCollection::get_master_keys, *this);
Common::draw_text_with_time(0x10, 0x0c0, GREEN, "Get master keys...", profiler_time);
Common::draw_text_with_time(0x10, 0x0a0, GREEN, "Get master keys...", profiler_time);
profiler_time = profile(&KeyCollection::derive_keys, *this);
Common::draw_text_with_time(0x10, 0x0e0, GREEN, "Derive remaining keys...", profiler_time);
Common::draw_text_with_time(0x10, 0x0c0, GREEN, "Derive remaining keys...", profiler_time);
profiler_time = profile(&KeyCollection::save_keys, *this);
Common::draw_text_with_time(0x10, 0x100, GREEN, "Saving keys to keyfile...", profiler_time);
Common::draw_text_with_time(0x10, 0x0e0, GREEN, "Saving keys to keyfile...", profiler_time);
total_time.stop();
Common::draw_line(0x8, 0x110, 0x280, GREEN);
Common::draw_text_with_time(0x10, 0x130, GREEN, "Total time elapsed:", total_time.get_elapsed());
Common::draw_line(0x8, 0xf0, 0x280, GREEN);
Common::draw_text_with_time(0x10, 0x110, GREEN, "Total time elapsed:", total_time.get_elapsed());
char keys_str[32]; // todo: get sd seed
char keys_str[32];
sprintf(keys_str, "Total keys found: %lu", Key::get_saved_key_count());
Common::draw_text(0x2a0, 0x130, CYAN, keys_str);
Common::draw_text(0x2a0, 0x110, CYAN, keys_str);
Common::draw_text(0x80, 0x140, GREEN, "Keys saved to \"/switch/prod.keys\"!");
Common::draw_text(0x30, 0x160, YELLOW, "WARNING: dumping titlekeys may crash homebrew or games UNLESS you reboot afterwards");
Common::draw_text(0x160, 0x180, CYAN, ">> Press A to dump titlekeys or + to exit <<");
while(appletMainLoop()) {
hidScanInput();
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
if (kDown & KEY_PLUS)
return Status_success_no_titlekeys;
else if (kDown & KEY_A)
break;
consoleUpdate(NULL);
}
Common::draw_text(0x10, 0x1b0, CYAN, "Dumping titlekeys...");
Common::draw_text(0x10, 0x170, CYAN, "Dumping titlekeys...");
consoleUpdate(NULL);
profiler_time = profile(&KeyCollection::get_titlekeys, *this);
if (titlekeys_dumped > 0) {
Common::draw_text_with_time(0x10, 0x1b0, GREEN, "Dumping titlekeys...", profiler_time);
sprintf(keys_str, "Titlekeys found: %lu", titlekeys_dumped);
Common::draw_text(0x2a0, 0x1b0, CYAN, keys_str);
return Status_success_titlekeys;
} else {
Common::draw_text(0x010, 0x1b0, RED, "Dumping titlekeys...");
Common::draw_text(0x190, 0x1b0, RED, "Failed. Reboot and try again!"); // todo: detect if no titles installed
return Status_success_titlekeys_failed;
}
Common::draw_text_with_time(0x10, 0x170, GREEN, "Dumping titlekeys...", profiler_time);
sprintf(keys_str, "Titlekeys found: %lu", titlekeys_dumped);
Common::draw_text(0x2a0, 0x170, CYAN, keys_str);
if (titlekeys_dumped > 0)
Common::draw_text(0x80, 0x1a0, GREEN, "Titlekeys saved to \"/switch/title.keys\"!");
else
Common::draw_text(0x80, 0x1a0, GREEN, "No titlekeys found. Either you've never played or installed a game or dump failed.");
}
void KeyCollection::get_master_keys() {
@ -435,10 +430,42 @@ void KeyCollection::derive_keys() {
if (ssl_rsa_kek_source_x.found() && ssl_rsa_kek_source_y.found() && !master_key.empty())
ssl_rsa_kek = Key {"ssl_rsa_kek", 0x10,
ssl_rsa_kek_source_x.generate_kek(master_key[0], rsa_private_kek_generation_source, ssl_rsa_kek_source_y)};
char seed_vector[0x10], seed[0x10], buffer[0x10];
u32 bytes_read, file_pos = 0;
// dump sd seed
FILE *sd_private = fopen("/Nintendo/Contents/private", "rb");
if (!sd_private) return;
fread(seed_vector, 0x10, 1, sd_private);
fclose(sd_private);
FATFS fs;
FRESULT fr;
FIL save_file;
fsOpenBisStorage(&storage, 31);
if (f_mount(&fs, "", 1) || f_chdir("/save")) return;
if (f_open(&save_file, "8000000000000043", FA_READ | FA_OPEN_EXISTING)) return;
for (;;) {
fr = f_read(&save_file, buffer, 0x10, &bytes_read);
if (fr || (bytes_read == 0)) break;
if (std::equal(seed_vector, seed_vector + 0x10, buffer)) {
f_read(&save_file, seed, 0x10, &bytes_read);
sd_seed = Key {"sd_seed", 0x10, byte_vector(seed, seed + 0x10)};
break;
}
file_pos += 0x4000;
if (f_lseek(&save_file, file_pos)) break;
}
f_close(&save_file);
fsStorageClose(&storage);
}
void KeyCollection::save_keys() {
std::ofstream key_file("/switch/prod.keys");
FILE *key_file = fopen("/switch/prod.keys", "w");
if (!key_file) return;
aes_kek_generation_source.save_key(key_file);
aes_key_generation_source.save_key(key_file);
@ -496,6 +523,7 @@ void KeyCollection::save_keys() {
sd_card_kek_source.save_key(key_file);
sd_card_nca_key_source.save_key(key_file);
sd_card_save_key_source.save_key(key_file);
sd_seed.save_key(key_file);
ssl_rsa_kek.save_key(key_file);
for (auto k : ssl_keys)
k->save_key(key_file);
@ -504,12 +532,46 @@ void KeyCollection::save_keys() {
titlekek_source.save_key(key_file);
tsec.save_key(key_file);
tsec_root_key.save_key(key_file);
fclose(key_file);
}
void KeyCollection::get_titlekeys() {
if (!kernelAbove200() || !eticket_rsa_kek.found())
return;
u32 common_count, personalized_count, bytes_read, ids_written;
esInitialize();
esCountCommonTicket(&common_count);
esCountPersonalizedTicket(&personalized_count);
NcmRightsId common_rights_ids[common_count], personalized_rights_ids[personalized_count];
esListCommonTicket(&ids_written, common_rights_ids, sizeof(common_rights_ids));
esListPersonalizedTicket(&ids_written, personalized_rights_ids, sizeof(personalized_rights_ids));
esExit();
if ((common_count == 0) && (personalized_count == 0))
return;
/*
catalog all currently installed rights ids
since we are crawling the whole save file, we might accidentally find previously deleted tickets
this would be fine, except we have to match the exact list so we don't stop too early
*/
char titlekey_block[0x100], buffer[TITLEKEY_BUFFER_SIZE], rights_id_string[0x21], titlekey_string[0x21];
std::set<std::string> rights_ids;
for (size_t i = 0; i < common_count; i++) {
for (size_t j = 0; j < 0x10; j++) {
sprintf(&rights_id_string[j*2], "%02x", common_rights_ids[i].c[j]);
}
rights_ids.insert(rights_id_string);
}
for (size_t i = 0; i < personalized_count; i++) {
for (size_t j = 0; j < 0x10; j++) {
sprintf(&rights_id_string[j*2], "%02x", personalized_rights_ids[i].c[j]);
}
rights_ids.insert(rights_id_string);
}
// get extended eticket RSA key from PRODINFO
u8 eticket_data[0x244] = {};
@ -522,8 +584,8 @@ void KeyCollection::get_titlekeys() {
byte_vector(eticket_data + 4, eticket_data + 0x14)
);
// public exponent must be 65537 == 0x10001
if (!(dec_keypair[0x201] == 1) || !(dec_keypair[0x203] == 1))
// public exponent must be 65537 == 0x10001 (big endian)
if (!(dec_keypair[0x200] == 0) || !(dec_keypair[0x201] == 1) || !(dec_keypair[0x202] == 0) || !(dec_keypair[0x203] == 1))
return;
u8 *D = &dec_keypair[0], *N = &dec_keypair[0x100], *E = &dec_keypair[0x200];
@ -531,92 +593,101 @@ void KeyCollection::get_titlekeys() {
if (!test_key_pair(E, D, N))
return;
FsFileSystem save_fs;
Result rc;
FATFS fs;
FRESULT fr;
FIL save_file;
// map of all found rights ids and corresponding titlekeys
std::unordered_map<std::string, std::string> titlekeys;
// todo: try reading as block device to not have to crash ES!
for(size_t attempts = 0; attempts < 100; attempts++) {
pmshellTerminateProcessByTitleId(ES_TID);
fsOpenBisStorage(&storage, 31);
if (f_mount(&fs, "", 1) || f_chdir("/save")) return;
if (f_open(&save_file, "80000000000000e1", FA_READ | FA_OPEN_EXISTING)) return;
while ((common_count != 0) && (titlekeys_dumped < common_count)) {
fr = f_read(&save_file, buffer, TITLEKEY_BUFFER_SIZE, &bytes_read);
if (fr || (bytes_read == 0)) break;
for (size_t i = 0; i < bytes_read; i += 0x4000) {
for (size_t j = i; j < i + 0x4000; j += 0x400) {
if (*reinterpret_cast<u32 *>(&buffer[j]) == 0x10004) {
for (size_t k = 0; k < 0x10; k++)
sprintf(&rights_id_string[k*2], "%02x", buffer[j + 0x2a0 + k]);
if (R_SUCCEEDED(rc = fsMount_SystemSaveData(&save_fs, ES_COMMON_SAVE_ID)))
break;
// skip if rights id found but not reported by es
if (rights_ids.find(rights_id_string) == rights_ids.end())
continue;
// skip if rights id already in map
if (titlekeys.find(rights_id_string) != titlekeys.end())
continue;
for (size_t k = 0; k < 0x10; k++)
sprintf(&titlekey_string[k*2], "%02x", buffer[j + 0x180 + k]);
titlekeys[rights_id_string] = titlekey_string;
titlekeys_dumped++;
} else {
break;
}
}
}
}
if (R_FAILED(rc))
return;
if (fsdevMountDevice("save", save_fs) == -1)
return;
char ca_issuer[4], titlekey_block[0x100], rights_id[0x10], write_string[0x20];
std::ofstream titlekey_file("/switch/title.keys");
std::ifstream common_ticket_bin("save:/ticket.bin", std::ios::binary);
for (size_t i = 0; ; i += 0x400) {
common_ticket_bin.seekg(i + 0x140);
common_ticket_bin.read(ca_issuer, 4);
if (!std::equal(ca_issuer, ca_issuer + 4, "Root"))
break;
common_ticket_bin.seekg(i + 0x180);
common_ticket_bin.read(titlekey_block, 0x10);
common_ticket_bin.seekg(i + 0x2a0);
common_ticket_bin.read(rights_id, 0x10);
for (size_t j = 0; j < 0x10; j++)
sprintf(&write_string[j*2], "%02x", rights_id[j]);
titlekey_file.write(write_string, 0x20);
titlekey_file.write(" = ", 3);
for (size_t j = 0; j < 0x10; j++)
sprintf(&write_string[j*2], "%02x", titlekey_block[j]);
titlekey_file.write(write_string, 0x20);
titlekey_file.write("\n", 1);
titlekeys_dumped++;
}
fsdevUnmountDevice("save");
if (R_FAILED(fsMount_SystemSaveData(&save_fs, ES_PERSONALIZED_SAVE_ID)) ||
(fsdevMountDevice("save", save_fs) == -1))
return;
std::ifstream personalized_ticket_bin("save:/ticket.bin", std::ios::binary);
f_close(&save_file);
u8 M[0x100];
for (size_t i = 0; ; i += 0x400) {
personalized_ticket_bin.seekg(i + 0x140);
personalized_ticket_bin.read(ca_issuer, 4);
if (!std::equal(ca_issuer, ca_issuer + 4, "Root"))
break;
personalized_ticket_bin.seekg(i + 0x180);
personalized_ticket_bin.read(titlekey_block, 0x100);
splUserExpMod(titlekey_block, N, D, 0x100, M);
// decrypts the titlekey from personalized ticket
u8 salt[0x20], db[0xdf];
mgf1(M + 0x21, 0xdf, salt, 0x20);
for (size_t j = 0; j < 0x20; j++)
salt[j] ^= M[j + 1];
if (f_open(&save_file, "80000000000000e2", FA_READ | FA_OPEN_EXISTING)) return;
while ((personalized_count != 0) && (titlekeys_dumped < common_count + personalized_count)) {
fr = f_read(&save_file, buffer, TITLEKEY_BUFFER_SIZE, &bytes_read);
if (fr || (bytes_read == 0)) break;
for (size_t i = 0; i < bytes_read; i += 0x4000) {
for (size_t j = i; j < i + 0x4000; j += 0x400) {
if (*reinterpret_cast<u32 *>(&buffer[j]) == 0x10004) {
std::copy(buffer + j + 0x180, buffer + j + 0x280, titlekey_block);
splUserExpMod(titlekey_block, N, D, 0x100, M);
mgf1(salt, 0x20, db, 0xdf);
for (size_t j = 0; j < 0xdf; j++)
db[j] ^= M[j + 0x21];
// decrypts the titlekey from personalized ticket
u8 salt[0x20], db[0xdf];
mgf1(M + 0x21, 0xdf, salt, 0x20);
for (size_t k = 0; k < 0x20; k++)
salt[k] ^= M[k + 1];
// verify it starts with hash of null string
if (!std::equal(db, db + 0x20, null_hash))
continue;
mgf1(salt, 0x20, db, 0xdf);
for (size_t k = 0; k < 0xdf; k++)
db[k] ^= M[k + 0x21];
personalized_ticket_bin.seekg(i + 0x2a0);
personalized_ticket_bin.read(rights_id, 0x10);
for (size_t j = 0; j < 0x10; j++)
sprintf(&write_string[j*2], "%02x", rights_id[j]);
titlekey_file.write(write_string, 0x20);
titlekey_file.write(" = ", 3);
for (size_t j = 0; j < 0x10; j++)
sprintf(&write_string[j*2], "%02x", db[j + 0xcf]);
titlekey_file.write(write_string, 0x20);
titlekey_file.write("\n", 1);
titlekeys_dumped++;
// verify it starts with hash of null string
if (!std::equal(db, db + 0x20, null_hash))
continue;
for (size_t k = 0; k < 0x10; k++)
sprintf(&rights_id_string[k*2], "%02x", buffer[j + 0x2a0 + k]);
// skip if rights id found but not reported by es
if (rights_ids.find(rights_id_string) == rights_ids.end())
continue;
// skip if rights id already in map
if (titlekeys.find(rights_id_string) != titlekeys.end())
continue;
for (size_t k = 0; k < 0x10; k++)
sprintf(&titlekey_string[k*2], "%02x", db[k + 0xcf]);
titlekeys[rights_id_string] = titlekey_string;
titlekeys_dumped++;
} else {
break;
}
}
}
}
fsdevUnmountDevice("save");
f_close(&save_file);
fsStorageClose(&storage);
if (titlekeys.empty())
return;
FILE *titlekey_file = fopen("/switch/title.keys", "wb");
if (!titlekey_file) return;
for (auto k : titlekeys)
fprintf(titlekey_file, "%s = %s\n", k.first.c_str(), k.second.c_str());
fclose(titlekey_file);
}
void KeyCollection::mgf1(const u8 *data, size_t data_length, u8 *mask, size_t mask_length) {

View File

@ -19,12 +19,14 @@
#include "Key.hpp"
#include "KeyLocation.hpp"
#include <switch/types.h>
class KeyCollection {
public:
KeyCollection();
// get KeyLocations and find keys in them
int get_keys();
void get_keys();
private:
// utility functions called by get_keys
@ -87,7 +89,9 @@ private:
rsa_oaep_kek_generation_source,
rsa_private_kek_generation_source,
save_mac_key,
ssl_rsa_kek;
ssl_rsa_kek,
// other
sd_seed;
// key families
std::vector<Key>

View File

@ -16,14 +16,11 @@
#include "KeyLocation.hpp"
#include <filesystem>
#include <fstream>
#include "creport_debug_types.hpp"
#include <switch.h>
void KeyLocation::get_from_memory(u64 tid, u8 segMask) {
Handle debug_handle = INVALID_HANDLE;
DebugEventInfo d;
u64 d[8];
// if not a kernel process, get pid from pm:dmnt
if ((tid > 0x0100000000000005) && (tid != 0x0100000000000028)) {
@ -44,7 +41,7 @@ void KeyLocation::get_from_memory(u64 tid, u8 segMask) {
for (i = 0; i < num_processes - 1; i++) {
if (R_SUCCEEDED(svcDebugActiveProcess(&debug_handle, pids[i])) &&
R_SUCCEEDED(svcGetDebugEvent(reinterpret_cast<u8 *>(&d), debug_handle)) &&
(d.info.attach_process.title_id == tid))
(d[2] == tid))
{
break;
}

View File

@ -18,9 +18,7 @@
#include <vector>
#include <switch.h>
#include "Common.hpp"
#include <switch/types.h>
#define FS_TID 0x0100000000000000
#define SSL_TID 0x0100000000000024
@ -41,6 +39,8 @@
#define KEYBLOB_OFFSET 0x180000
typedef std::vector<u8> byte_vector;
class KeyLocation {
public:
// get memory in requested segments from running title

View File

@ -16,8 +16,6 @@
#include "Stopwatch.hpp"
#include "Common.hpp"
void Stopwatch::start() {
clock_gettime(CLOCK_REALTIME, &start_time);
}

View File

@ -1,116 +0,0 @@
/*
* Copyright (c) 2018 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/////////////////////////////////////
// modified 13 nov 2018 by shchmue // -> deleted everything that isn't the struct defines
/////////////////////////////////////
#pragma once
#include <switch.h>
struct StackFrame {
u64 fp;
u64 lr;
};
struct AttachProcessInfo {
u64 title_id;
u64 process_id;
char name[0xC];
u32 flags;
u64 user_exception_context_address; /* 5.0.0+ */
};
struct AttachThreadInfo {
u64 thread_id;
u64 tls_address;
u64 entrypoint;
};
enum class DebugExceptionType : u32 {
UndefinedInstruction = 0,
InstructionAbort = 1,
DataAbort = 2,
AlignmentFault = 3,
DebuggerAttached = 4,
BreakPoint = 5,
UserBreak = 6,
DebuggerBreak = 7,
BadSvc = 8,
UnknownNine = 9,
};
struct UndefinedInstructionInfo {
u32 insn;
};
struct DataAbortInfo {
u64 address;
};
struct AlignmentFaultInfo {
u64 address;
};
struct UserBreakInfo {
u64 break_reason;
u64 address;
u64 size;
};
struct BadSvcInfo {
u32 id;
};
union SpecificExceptionInfo {
UndefinedInstructionInfo undefined_instruction;
DataAbortInfo data_abort;
AlignmentFaultInfo alignment_fault;
UserBreakInfo user_break;
BadSvcInfo bad_svc;
u64 raw;
};
struct ExceptionInfo {
DebugExceptionType type;
u64 address;
SpecificExceptionInfo specific;
};
enum class DebugEventType : u32 {
AttachProcess = 0,
AttachThread = 1,
ExitProcess = 2,
ExitThread = 3,
Exception = 4
};
union DebugInfo {
AttachProcessInfo attach_process;
AttachThreadInfo attach_thread;
ExceptionInfo exception;
};
struct DebugEventInfo {
DebugEventType type;
u32 flags;
u64 thread_id;
union {
DebugInfo info;
u64 _[0x40/sizeof(u64)];
};
};

24
source/fatfs/LICENSE.txt Normal file
View File

@ -0,0 +1,24 @@
FatFs License
FatFs has being developped as a personal project of the author, ChaN. It is free from the code anyone else wrote at current release. Following code block shows a copy of the FatFs license document that heading the source files.
/*----------------------------------------------------------------------------/
/ FatFs - Generic FAT Filesystem Module Rx.xx /
/-----------------------------------------------------------------------------/
/
/ Copyright (C) 20xx, ChaN, all right reserved.
/
/ FatFs module is an open source software. Redistribution and use of FatFs in
/ source and binary forms, with or without modification, are permitted provided
/ that the following condition is met:
/
/ 1. Redistributions of source code must retain the above copyright notice,
/ this condition and the following disclaimer.
/
/ This software is provided by the copyright holder and contributors "AS IS"
/ and any warranties related to this software are DISCLAIMED.
/ The copyright owner or contributors be NOT LIABLE for any damages caused
/ by use of this software.
/----------------------------------------------------------------------------*/
Therefore FatFs license is one of the BSD-style licenses but there is a significant feature. FatFs is mainly intended for embedded systems. In order to extend the usability for commercial products, the redistributions of FatFs in binary form, such as embedded code, binary library and any forms without source code, does not need to include about FatFs in the documentations. This is equivalent to the 1-clause BSD license. Of course FatFs is compatible with the most of open source software licenses including GNU GPL. When you redistribute the FatFs source code with any changes or create a fork, the license can also be changed to GNU GPL, BSD-style license or any open source software license that not conflict with FatFs license.

92
source/fatfs/diskio.c Normal file
View File

@ -0,0 +1,92 @@
/*-----------------------------------------------------------------------*/
/* Low level disk I/O module skeleton for FatFs (C)ChaN, 2016 */
/*-----------------------------------------------------------------------*/
/* If a working storage control module is available, it should be */
/* attached to the FatFs via a glue function rather than modifying it. */
/* This is an example of glue functions to attach various exsisting */
/* storage control modules to the FatFs module with a defined API. */
/*-----------------------------------------------------------------------*/
#include "ff.h" /* Obtains integer types */
#include "diskio.h" /* Declarations of disk functions */
#include <switch.h>
extern FsStorage storage;
/*-----------------------------------------------------------------------*/
/* Get Drive Status */
/*-----------------------------------------------------------------------*/
DSTATUS disk_status (
BYTE pdrv /* Physical drive nmuber to identify the drive */
)
{
return 0;
}
/*-----------------------------------------------------------------------*/
/* Inidialize a Drive */
/*-----------------------------------------------------------------------*/
DSTATUS disk_initialize (
BYTE pdrv /* Physical drive nmuber to identify the drive */
)
{
return 0;
}
/*-----------------------------------------------------------------------*/
/* Read Sector(s) */
/*-----------------------------------------------------------------------*/
DRESULT disk_read (
BYTE pdrv, /* Physical drive nmuber to identify the drive */
BYTE *buff, /* Data buffer to store read data */
DWORD sector, /* Start sector in LBA */
UINT count /* Number of sectors to read */
)
{
if (R_SUCCEEDED(fsStorageRead(&storage, FF_MAX_SS * sector, buff, FF_MAX_SS * count)))
return RES_OK;
return RES_ERROR;
}
/*-----------------------------------------------------------------------*/
/* Write Sector(s) */
/*-----------------------------------------------------------------------*/
#if FF_FS_READONLY == 0
DRESULT disk_write (
BYTE pdrv, /* Physical drive nmuber to identify the drive */
const BYTE *buff, /* Data to be written */
DWORD sector, /* Start sector in LBA */
UINT count /* Number of sectors to write */
)
{
return RES_PARERR;
}
#endif
/*-----------------------------------------------------------------------*/
/* Miscellaneous Functions */
/*-----------------------------------------------------------------------*/
DRESULT disk_ioctl (
BYTE pdrv, /* Physical drive nmuber (0..) */
BYTE cmd, /* Control code */
void *buff /* Buffer to send/receive control data */
)
{
return RES_OK;
}

77
source/fatfs/diskio.h Normal file
View File

@ -0,0 +1,77 @@
/*-----------------------------------------------------------------------/
/ Low level disk interface modlue include file (C)ChaN, 2014 /
/-----------------------------------------------------------------------*/
#ifndef _DISKIO_DEFINED
#define _DISKIO_DEFINED
#ifdef __cplusplus
extern "C" {
#endif
/* Status of Disk Functions */
typedef BYTE DSTATUS;
/* Results of Disk Functions */
typedef enum {
RES_OK = 0, /* 0: Successful */
RES_ERROR, /* 1: R/W Error */
RES_WRPRT, /* 2: Write Protected */
RES_NOTRDY, /* 3: Not Ready */
RES_PARERR /* 4: Invalid Parameter */
} DRESULT;
/*---------------------------------------*/
/* Prototypes for disk control functions */
DSTATUS disk_initialize (BYTE pdrv);
DSTATUS disk_status (BYTE pdrv);
DRESULT disk_read (BYTE pdrv, BYTE* buff, DWORD sector, UINT count);
DRESULT disk_write (BYTE pdrv, const BYTE* buff, DWORD sector, UINT count);
DRESULT disk_ioctl (BYTE pdrv, BYTE cmd, void* buff);
/* Disk Status Bits (DSTATUS) */
#define STA_NOINIT 0x01 /* Drive not initialized */
#define STA_NODISK 0x02 /* No medium in the drive */
#define STA_PROTECT 0x04 /* Write protected */
/* Command code for disk_ioctrl fucntion */
/* Generic command (Used by FatFs) */
#define CTRL_SYNC 0 /* Complete pending write process (needed at FF_FS_READONLY == 0) */
#define GET_SECTOR_COUNT 1 /* Get media size (needed at FF_USE_MKFS == 1) */
#define GET_SECTOR_SIZE 2 /* Get sector size (needed at FF_MAX_SS != FF_MIN_SS) */
#define GET_BLOCK_SIZE 3 /* Get erase block size (needed at FF_USE_MKFS == 1) */
#define CTRL_TRIM 4 /* Inform device that the data on the block of sectors is no longer used (needed at FF_USE_TRIM == 1) */
/* Generic command (Not used by FatFs) */
#define CTRL_POWER 5 /* Get/Set power status */
#define CTRL_LOCK 6 /* Lock/Unlock media removal */
#define CTRL_EJECT 7 /* Eject media */
#define CTRL_FORMAT 8 /* Create physical format on the media */
/* MMC/SDC specific ioctl command */
#define MMC_GET_TYPE 10 /* Get card type */
#define MMC_GET_CSD 11 /* Get CSD */
#define MMC_GET_CID 12 /* Get CID */
#define MMC_GET_OCR 13 /* Get OCR */
#define MMC_GET_SDSTAT 14 /* Get SD status */
#define ISDIO_READ 55 /* Read data form SD iSDIO register */
#define ISDIO_WRITE 56 /* Write data to SD iSDIO register */
#define ISDIO_MRITE 57 /* Masked write data to SD iSDIO register */
/* ATA/CF specific ioctl command */
#define ATA_GET_REV 20 /* Get F/W revision */
#define ATA_GET_MODEL 21 /* Get model name */
#define ATA_GET_SN 22 /* Get serial number */
#ifdef __cplusplus
}
#endif
#endif

6554
source/fatfs/ff.c Normal file

File diff suppressed because it is too large Load Diff

405
source/fatfs/ff.h Normal file
View File

@ -0,0 +1,405 @@
/*----------------------------------------------------------------------------/
/ FatFs - Generic FAT Filesystem module R0.13c /
/-----------------------------------------------------------------------------/
/
/ Copyright (C) 2018, ChaN, all right reserved.
/
/ FatFs module is an open source software. Redistribution and use of FatFs in
/ source and binary forms, with or without modification, are permitted provided
/ that the following condition is met:
/ 1. Redistributions of source code must retain the above copyright notice,
/ this condition and the following disclaimer.
/
/ This software is provided by the copyright holder and contributors "AS IS"
/ and any warranties related to this software are DISCLAIMED.
/ The copyright owner or contributors be NOT LIABLE for any damages caused
/ by use of this software.
/
/----------------------------------------------------------------------------*/
#ifndef FF_DEFINED
#define FF_DEFINED 86604 /* Revision ID */
#ifdef __cplusplus
extern "C" {
#endif
#include "ffconf.h" /* FatFs configuration options */
#if FF_DEFINED != FFCONF_DEF
#error Wrong configuration file (ffconf.h).
#endif
/* Integer types used for FatFs API */
#if defined(_WIN32) /* Main development platform */
#define FF_INTDEF 2
#include <windows.h>
typedef unsigned __int64 QWORD;
#elif (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__cplusplus) /* C99 or later */
#define FF_INTDEF 2
#include <stdint.h>
typedef unsigned int UINT; /* int must be 16-bit or 32-bit */
typedef unsigned char BYTE; /* char must be 8-bit */
typedef uint16_t WORD; /* 16-bit unsigned integer */
typedef uint16_t WCHAR; /* 16-bit unsigned integer */
typedef uint32_t DWORD; /* 32-bit unsigned integer */
typedef uint64_t QWORD; /* 64-bit unsigned integer */
#else /* Earlier than C99 */
#define FF_INTDEF 1
typedef unsigned int UINT; /* int must be 16-bit or 32-bit */
typedef unsigned char BYTE; /* char must be 8-bit */
typedef unsigned short WORD; /* 16-bit unsigned integer */
typedef unsigned short WCHAR; /* 16-bit unsigned integer */
typedef unsigned long DWORD; /* 32-bit unsigned integer */
#endif
/* Definitions of volume management */
#if FF_MULTI_PARTITION /* Multiple partition configuration */
typedef struct {
BYTE pd; /* Physical drive number */
BYTE pt; /* Partition: 0:Auto detect, 1-4:Forced partition) */
} PARTITION;
extern PARTITION VolToPart[]; /* Volume - Partition resolution table */
#endif
#if FF_STR_VOLUME_ID
#ifndef FF_VOLUME_STRS
extern const char* VolumeStr[FF_VOLUMES]; /* User defied volume ID */
#endif
#endif
/* Type of path name strings on FatFs API */
#ifndef _INC_TCHAR
#define _INC_TCHAR
#if FF_USE_LFN && FF_LFN_UNICODE == 1 /* Unicode in UTF-16 encoding */
typedef WCHAR TCHAR;
#define _T(x) L ## x
#define _TEXT(x) L ## x
#elif FF_USE_LFN && FF_LFN_UNICODE == 2 /* Unicode in UTF-8 encoding */
typedef char TCHAR;
#define _T(x) u8 ## x
#define _TEXT(x) u8 ## x
#elif FF_USE_LFN && FF_LFN_UNICODE == 3 /* Unicode in UTF-32 encoding */
typedef DWORD TCHAR;
#define _T(x) U ## x
#define _TEXT(x) U ## x
#elif FF_USE_LFN && (FF_LFN_UNICODE < 0 || FF_LFN_UNICODE > 3)
#error Wrong FF_LFN_UNICODE setting
#else /* ANSI/OEM code in SBCS/DBCS */
typedef char TCHAR;
#define _T(x) x
#define _TEXT(x) x
#endif
#endif
/* Type of file size variables */
#if FF_FS_EXFAT
#if FF_INTDEF != 2
#error exFAT feature wants C99 or later
#endif
typedef QWORD FSIZE_t;
#else
typedef DWORD FSIZE_t;
#endif
/* Filesystem object structure (FATFS) */
typedef struct {
BYTE fs_type; /* Filesystem type (0:not mounted) */
BYTE pdrv; /* Associated physical drive */
BYTE n_fats; /* Number of FATs (1 or 2) */
BYTE wflag; /* win[] flag (b0:dirty) */
BYTE fsi_flag; /* FSINFO flags (b7:disabled, b0:dirty) */
WORD id; /* Volume mount ID */
WORD n_rootdir; /* Number of root directory entries (FAT12/16) */
WORD csize; /* Cluster size [sectors] */
#if FF_MAX_SS != FF_MIN_SS
WORD ssize; /* Sector size (512, 1024, 2048 or 4096) */
#endif
#if FF_USE_LFN
WCHAR* lfnbuf; /* LFN working buffer */
#endif
#if FF_FS_EXFAT
BYTE* dirbuf; /* Directory entry block scratchpad buffer for exFAT */
#endif
#if FF_FS_REENTRANT
FF_SYNC_t sobj; /* Identifier of sync object */
#endif
#if !FF_FS_READONLY
DWORD last_clst; /* Last allocated cluster */
DWORD free_clst; /* Number of free clusters */
#endif
#if FF_FS_RPATH
DWORD cdir; /* Current directory start cluster (0:root) */
#if FF_FS_EXFAT
DWORD cdc_scl; /* Containing directory start cluster (invalid when cdir is 0) */
DWORD cdc_size; /* b31-b8:Size of containing directory, b7-b0: Chain status */
DWORD cdc_ofs; /* Offset in the containing directory (invalid when cdir is 0) */
#endif
#endif
DWORD n_fatent; /* Number of FAT entries (number of clusters + 2) */
DWORD fsize; /* Size of an FAT [sectors] */
DWORD volbase; /* Volume base sector */
DWORD fatbase; /* FAT base sector */
DWORD dirbase; /* Root directory base sector/cluster */
DWORD database; /* Data base sector */
#if FF_FS_EXFAT
DWORD bitbase; /* Allocation bitmap base sector */
#endif
DWORD winsect; /* Current sector appearing in the win[] */
BYTE win[FF_MAX_SS]; /* Disk access window for Directory, FAT (and file data at tiny cfg) */
} FATFS;
/* Object ID and allocation information (FFOBJID) */
typedef struct {
FATFS* fs; /* Pointer to the hosting volume of this object */
WORD id; /* Hosting volume mount ID */
BYTE attr; /* Object attribute */
BYTE stat; /* Object chain status (b1-0: =0:not contiguous, =2:contiguous, =3:fragmented in this session, b2:sub-directory stretched) */
DWORD sclust; /* Object data start cluster (0:no cluster or root directory) */
FSIZE_t objsize; /* Object size (valid when sclust != 0) */
#if FF_FS_EXFAT
DWORD n_cont; /* Size of first fragment - 1 (valid when stat == 3) */
DWORD n_frag; /* Size of last fragment needs to be written to FAT (valid when not zero) */
DWORD c_scl; /* Containing directory start cluster (valid when sclust != 0) */
DWORD c_size; /* b31-b8:Size of containing directory, b7-b0: Chain status (valid when c_scl != 0) */
DWORD c_ofs; /* Offset in the containing directory (valid when file object and sclust != 0) */
#endif
#if FF_FS_LOCK
UINT lockid; /* File lock ID origin from 1 (index of file semaphore table Files[]) */
#endif
} FFOBJID;
/* File object structure (FIL) */
typedef struct {
FFOBJID obj; /* Object identifier (must be the 1st member to detect invalid object pointer) */
BYTE flag; /* File status flags */
BYTE err; /* Abort flag (error code) */
FSIZE_t fptr; /* File read/write pointer (Zeroed on file open) */
DWORD clust; /* Current cluster of fpter (invalid when fptr is 0) */
DWORD sect; /* Sector number appearing in buf[] (0:invalid) */
#if !FF_FS_READONLY
DWORD dir_sect; /* Sector number containing the directory entry (not used at exFAT) */
BYTE* dir_ptr; /* Pointer to the directory entry in the win[] (not used at exFAT) */
#endif
#if FF_USE_FASTSEEK
DWORD* cltbl; /* Pointer to the cluster link map table (nulled on open, set by application) */
#endif
#if !FF_FS_TINY
BYTE buf[FF_MAX_SS]; /* File private data read/write window */
#endif
} FIL;
/* Directory object structure (DIR) */
typedef struct {
FFOBJID obj; /* Object identifier */
DWORD dptr; /* Current read/write offset */
DWORD clust; /* Current cluster */
DWORD sect; /* Current sector (0:Read operation has terminated) */
BYTE* dir; /* Pointer to the directory item in the win[] */
BYTE fn[12]; /* SFN (in/out) {body[8],ext[3],status[1]} */
#if FF_USE_LFN
DWORD blk_ofs; /* Offset of current entry block being processed (0xFFFFFFFF:Invalid) */
#endif
#if FF_USE_FIND
const TCHAR* pat; /* Pointer to the name matching pattern */
#endif
} DIR;
/* File information structure (FILINFO) */
typedef struct {
FSIZE_t fsize; /* File size */
WORD fdate; /* Modified date */
WORD ftime; /* Modified time */
BYTE fattrib; /* File attribute */
#if FF_USE_LFN
TCHAR altname[FF_SFN_BUF + 1];/* Altenative file name */
TCHAR fname[FF_LFN_BUF + 1]; /* Primary file name */
#else
TCHAR fname[12 + 1]; /* File name */
#endif
} FILINFO;
/* File function return code (FRESULT) */
typedef enum {
FR_OK = 0, /* (0) Succeeded */
FR_DISK_ERR, /* (1) A hard error occurred in the low level disk I/O layer */
FR_INT_ERR, /* (2) Assertion failed */
FR_NOT_READY, /* (3) The physical drive cannot work */
FR_NO_FILE, /* (4) Could not find the file */
FR_NO_PATH, /* (5) Could not find the path */
FR_INVALID_NAME, /* (6) The path name format is invalid */
FR_DENIED, /* (7) Access denied due to prohibited access or directory full */
FR_EXIST, /* (8) Access denied due to prohibited access */
FR_INVALID_OBJECT, /* (9) The file/directory object is invalid */
FR_WRITE_PROTECTED, /* (10) The physical drive is write protected */
FR_INVALID_DRIVE, /* (11) The logical drive number is invalid */
FR_NOT_ENABLED, /* (12) The volume has no work area */
FR_NO_FILESYSTEM, /* (13) There is no valid FAT volume */
FR_MKFS_ABORTED, /* (14) The f_mkfs() aborted due to any problem */
FR_TIMEOUT, /* (15) Could not get a grant to access the volume within defined period */
FR_LOCKED, /* (16) The operation is rejected according to the file sharing policy */
FR_NOT_ENOUGH_CORE, /* (17) LFN working buffer could not be allocated */
FR_TOO_MANY_OPEN_FILES, /* (18) Number of open files > FF_FS_LOCK */
FR_INVALID_PARAMETER /* (19) Given parameter is invalid */
} FRESULT;
/*--------------------------------------------------------------*/
/* FatFs module application interface */
FRESULT f_open (FIL* fp, const TCHAR* path, BYTE mode); /* Open or create a file */
FRESULT f_close (FIL* fp); /* Close an open file object */
FRESULT f_read (FIL* fp, void* buff, UINT btr, UINT* br); /* Read data from the file */
FRESULT f_write (FIL* fp, const void* buff, UINT btw, UINT* bw); /* Write data to the file */
FRESULT f_lseek (FIL* fp, FSIZE_t ofs); /* Move file pointer of the file object */
FRESULT f_truncate (FIL* fp); /* Truncate the file */
FRESULT f_sync (FIL* fp); /* Flush cached data of the writing file */
FRESULT f_opendir (DIR* dp, const TCHAR* path); /* Open a directory */
FRESULT f_closedir (DIR* dp); /* Close an open directory */
FRESULT f_readdir (DIR* dp, FILINFO* fno); /* Read a directory item */
FRESULT f_findfirst (DIR* dp, FILINFO* fno, const TCHAR* path, const TCHAR* pattern); /* Find first file */
FRESULT f_findnext (DIR* dp, FILINFO* fno); /* Find next file */
FRESULT f_mkdir (const TCHAR* path); /* Create a sub directory */
FRESULT f_unlink (const TCHAR* path); /* Delete an existing file or directory */
FRESULT f_rename (const TCHAR* path_old, const TCHAR* path_new); /* Rename/Move a file or directory */
FRESULT f_stat (const TCHAR* path, FILINFO* fno); /* Get file status */
FRESULT f_chmod (const TCHAR* path, BYTE attr, BYTE mask); /* Change attribute of a file/dir */
FRESULT f_utime (const TCHAR* path, const FILINFO* fno); /* Change timestamp of a file/dir */
FRESULT f_chdir (const TCHAR* path); /* Change current directory */
FRESULT f_chdrive (const TCHAR* path); /* Change current drive */
FRESULT f_getcwd (TCHAR* buff, UINT len); /* Get current directory */
FRESULT f_getfree (const TCHAR* path, DWORD* nclst, FATFS** fatfs); /* Get number of free clusters on the drive */
FRESULT f_getlabel (const TCHAR* path, TCHAR* label, DWORD* vsn); /* Get volume label */
FRESULT f_setlabel (const TCHAR* label); /* Set volume label */
FRESULT f_forward (FIL* fp, UINT(*func)(const BYTE*,UINT), UINT btf, UINT* bf); /* Forward data to the stream */
FRESULT f_expand (FIL* fp, FSIZE_t szf, BYTE opt); /* Allocate a contiguous block to the file */
FRESULT f_mount (FATFS* fs, const TCHAR* path, BYTE opt); /* Mount/Unmount a logical drive */
FRESULT f_mkfs (const TCHAR* path, BYTE opt, DWORD au, void* work, UINT len); /* Create a FAT volume */
FRESULT f_fdisk (BYTE pdrv, const DWORD* szt, void* work); /* Divide a physical drive into some partitions */
FRESULT f_setcp (WORD cp); /* Set current code page */
int f_putc (TCHAR c, FIL* fp); /* Put a character to the file */
int f_puts (const TCHAR* str, FIL* cp); /* Put a string to the file */
int f_printf (FIL* fp, const TCHAR* str, ...); /* Put a formatted string to the file */
TCHAR* f_gets (TCHAR* buff, int len, FIL* fp); /* Get a string from the file */
#define f_eof(fp) ((int)((fp)->fptr == (fp)->obj.objsize))
#define f_error(fp) ((fp)->err)
#define f_tell(fp) ((fp)->fptr)
#define f_size(fp) ((fp)->obj.objsize)
#define f_rewind(fp) f_lseek((fp), 0)
#define f_rewinddir(dp) f_readdir((dp), 0)
#define f_rmdir(path) f_unlink(path)
#define f_unmount(path) f_mount(0, path, 0)
#ifndef EOF
#define EOF (-1)
#endif
/*--------------------------------------------------------------*/
/* Additional user defined functions */
/* RTC function */
#if !FF_FS_READONLY && !FF_FS_NORTC
DWORD get_fattime (void);
#endif
/* LFN support functions */
#if FF_USE_LFN >= 1 /* Code conversion (defined in unicode.c) */
WCHAR ff_oem2uni (WCHAR oem, WORD cp); /* OEM code to Unicode conversion */
WCHAR ff_uni2oem (DWORD uni, WORD cp); /* Unicode to OEM code conversion */
DWORD ff_wtoupper (DWORD uni); /* Unicode upper-case conversion */
#endif
#if FF_USE_LFN == 3 /* Dynamic memory allocation */
void* ff_memalloc (UINT msize); /* Allocate memory block */
void ff_memfree (void* mblock); /* Free memory block */
#endif
/* Sync functions */
#if FF_FS_REENTRANT
int ff_cre_syncobj (BYTE vol, FF_SYNC_t* sobj); /* Create a sync object */
int ff_req_grant (FF_SYNC_t sobj); /* Lock sync object */
void ff_rel_grant (FF_SYNC_t sobj); /* Unlock sync object */
int ff_del_syncobj (FF_SYNC_t sobj); /* Delete a sync object */
#endif
/*--------------------------------------------------------------*/
/* Flags and offset address */
/* File access mode and open method flags (3rd argument of f_open) */
#define FA_READ 0x01
#define FA_WRITE 0x02
#define FA_OPEN_EXISTING 0x00
#define FA_CREATE_NEW 0x04
#define FA_CREATE_ALWAYS 0x08
#define FA_OPEN_ALWAYS 0x10
#define FA_OPEN_APPEND 0x30
/* Fast seek controls (2nd argument of f_lseek) */
#define CREATE_LINKMAP ((FSIZE_t)0 - 1)
/* Format options (2nd argument of f_mkfs) */
#define FM_FAT 0x01
#define FM_FAT32 0x02
#define FM_EXFAT 0x04
#define FM_ANY 0x07
#define FM_SFD 0x08
/* Filesystem type (FATFS.fs_type) */
#define FS_FAT12 1
#define FS_FAT16 2
#define FS_FAT32 3
#define FS_EXFAT 4
/* File attribute bits for directory entry (FILINFO.fattrib) */
#define AM_RDO 0x01 /* Read only */
#define AM_HID 0x02 /* Hidden */
#define AM_SYS 0x04 /* System */
#define AM_DIR 0x10 /* Directory */
#define AM_ARC 0x20 /* Archive */
#ifdef __cplusplus
}
#endif
#endif /* FF_DEFINED */

288
source/fatfs/ffconf.h Normal file
View File

@ -0,0 +1,288 @@
/*---------------------------------------------------------------------------/
/ FatFs Functional Configurations
/---------------------------------------------------------------------------*/
#define FFCONF_DEF 86604 /* Revision ID */
/*---------------------------------------------------------------------------/
/ Function Configurations
/---------------------------------------------------------------------------*/
#define FF_FS_READONLY 1
/* This option switches read-only configuration. (0:Read/Write or 1:Read-only)
/ Read-only configuration removes writing API functions, f_write(), f_sync(),
/ f_unlink(), f_mkdir(), f_chmod(), f_rename(), f_truncate(), f_getfree()
/ and optional writing functions as well. */
#define FF_FS_MINIMIZE 2
/* This option defines minimization level to remove some basic API functions.
/
/ 0: Basic functions are fully enabled.
/ 1: f_stat(), f_getfree(), f_unlink(), f_mkdir(), f_truncate() and f_rename()
/ are removed.
/ 2: f_opendir(), f_readdir() and f_closedir() are removed in addition to 1.
/ 3: f_lseek() function is removed in addition to 2. */
#define FF_USE_STRFUNC 0
/* This option switches string functions, f_gets(), f_putc(), f_puts() and f_printf().
/
/ 0: Disable string functions.
/ 1: Enable without LF-CRLF conversion.
/ 2: Enable with LF-CRLF conversion. */
#define FF_USE_FIND 2
/* This option switches filtered directory read functions, f_findfirst() and
/ f_findnext(). (0:Disable, 1:Enable 2:Enable with matching altname[] too) */
#define FF_USE_MKFS 0
/* This option switches f_mkfs() function. (0:Disable or 1:Enable) */
#define FF_USE_FASTSEEK 0
/* This option switches fast seek function. (0:Disable or 1:Enable) */
#define FF_USE_EXPAND 0
/* This option switches f_expand function. (0:Disable or 1:Enable) */
#define FF_USE_CHMOD 0
/* This option switches attribute manipulation functions, f_chmod() and f_utime().
/ (0:Disable or 1:Enable) Also FF_FS_READONLY needs to be 0 to enable this option. */
#define FF_USE_LABEL 0
/* This option switches volume label functions, f_getlabel() and f_setlabel().
/ (0:Disable or 1:Enable) */
#define FF_USE_FORWARD 0
/* This option switches f_forward() function. (0:Disable or 1:Enable) */
/*---------------------------------------------------------------------------/
/ Locale and Namespace Configurations
/---------------------------------------------------------------------------*/
#define FF_CODE_PAGE 932
/* This option specifies the OEM code page to be used on the target system.
/ Incorrect code page setting can cause a file open failure.
/
/ 437 - U.S.
/ 720 - Arabic
/ 737 - Greek
/ 771 - KBL
/ 775 - Baltic
/ 850 - Latin 1
/ 852 - Latin 2
/ 855 - Cyrillic
/ 857 - Turkish
/ 860 - Portuguese
/ 861 - Icelandic
/ 862 - Hebrew
/ 863 - Canadian French
/ 864 - Arabic
/ 865 - Nordic
/ 866 - Russian
/ 869 - Greek 2
/ 932 - Japanese (DBCS)
/ 936 - Simplified Chinese (DBCS)
/ 949 - Korean (DBCS)
/ 950 - Traditional Chinese (DBCS)
/ 0 - Include all code pages above and configured by f_setcp()
*/
#define FF_USE_LFN 1
#define FF_MAX_LFN 255
/* The FF_USE_LFN switches the support for LFN (long file name).
/
/ 0: Disable LFN. FF_MAX_LFN has no effect.
/ 1: Enable LFN with static working buffer on the BSS. Always NOT thread-safe.
/ 2: Enable LFN with dynamic working buffer on the STACK.
/ 3: Enable LFN with dynamic working buffer on the HEAP.
/
/ To enable the LFN, ffunicode.c needs to be added to the project. The LFN function
/ requiers certain internal working buffer occupies (FF_MAX_LFN + 1) * 2 bytes and
/ additional (FF_MAX_LFN + 44) / 15 * 32 bytes when exFAT is enabled.
/ The FF_MAX_LFN defines size of the working buffer in UTF-16 code unit and it can
/ be in range of 12 to 255. It is recommended to be set 255 to fully support LFN
/ specification.
/ When use stack for the working buffer, take care on stack overflow. When use heap
/ memory for the working buffer, memory management functions, ff_memalloc() and
/ ff_memfree() in ffsystem.c, need to be added to the project. */
#define FF_LFN_UNICODE 0
/* This option switches the character encoding on the API when LFN is enabled.
/
/ 0: ANSI/OEM in current CP (TCHAR = char)
/ 1: Unicode in UTF-16 (TCHAR = WCHAR)
/ 2: Unicode in UTF-8 (TCHAR = char)
/ 3: Unicode in UTF-32 (TCHAR = DWORD)
/
/ Also behavior of string I/O functions will be affected by this option.
/ When LFN is not enabled, this option has no effect. */
#define FF_LFN_BUF 255
#define FF_SFN_BUF 12
/* This set of options defines size of file name members in the FILINFO structure
/ which is used to read out directory items. These values should be suffcient for
/ the file names to read. The maximum possible length of the read file name depends
/ on character encoding. When LFN is not enabled, these options have no effect. */
#define FF_STRF_ENCODE 3
/* When FF_LFN_UNICODE >= 1 with LFN enabled, string I/O functions, f_gets(),
/ f_putc(), f_puts and f_printf() convert the character encoding in it.
/ This option selects assumption of character encoding ON THE FILE to be
/ read/written via those functions.
/
/ 0: ANSI/OEM in current CP
/ 1: Unicode in UTF-16LE
/ 2: Unicode in UTF-16BE
/ 3: Unicode in UTF-8
*/
#define FF_FS_RPATH 1
/* This option configures support for relative path.
/
/ 0: Disable relative path and remove related functions.
/ 1: Enable relative path. f_chdir() and f_chdrive() are available.
/ 2: f_getcwd() function is available in addition to 1.
*/
/*---------------------------------------------------------------------------/
/ Drive/Volume Configurations
/---------------------------------------------------------------------------*/
#define FF_VOLUMES 1
/* Number of volumes (logical drives) to be used. (1-10) */
#define FF_STR_VOLUME_ID 0
#define FF_VOLUME_STRS "RAM","NAND","CF","SD","SD2","USB","USB2","USB3"
/* FF_STR_VOLUME_ID switches support for volume ID in arbitrary strings.
/ When FF_STR_VOLUME_ID is set to 1 or 2, arbitrary strings can be used as drive
/ number in the path name. FF_VOLUME_STRS defines the volume ID strings for each
/ logical drives. Number of items must not be less than FF_VOLUMES. Valid
/ characters for the volume ID strings are A-Z, a-z and 0-9, however, they are
/ compared in case-insensitive. If FF_STR_VOLUME_ID >= 1 and FF_VOLUME_STRS is
/ not defined, a user defined volume string table needs to be defined as:
/
/ const char* VolumeStr[FF_VOLUMES] = {"ram","flash","sd","usb",...
*/
#define FF_MULTI_PARTITION 0
/* This option switches support for multiple volumes on the physical drive.
/ By default (0), each logical drive number is bound to the same physical drive
/ number and only an FAT volume found on the physical drive will be mounted.
/ When this function is enabled (1), each logical drive number can be bound to
/ arbitrary physical drive and partition listed in the VolToPart[]. Also f_fdisk()
/ funciton will be available. */
#define FF_MIN_SS 512
#define FF_MAX_SS 512
/* This set of options configures the range of sector size to be supported. (512,
/ 1024, 2048 or 4096) Always set both 512 for most systems, generic memory card and
/ harddisk. But a larger value may be required for on-board flash memory and some
/ type of optical media. When FF_MAX_SS is larger than FF_MIN_SS, FatFs is configured
/ for variable sector size mode and disk_ioctl() function needs to implement
/ GET_SECTOR_SIZE command. */
#define FF_USE_TRIM 0
/* This option switches support for ATA-TRIM. (0:Disable or 1:Enable)
/ To enable Trim function, also CTRL_TRIM command should be implemented to the
/ disk_ioctl() function. */
#define FF_FS_NOFSINFO 0
/* If you need to know correct free space on the FAT32 volume, set bit 0 of this
/ option, and f_getfree() function at first time after volume mount will force
/ a full FAT scan. Bit 1 controls the use of last allocated cluster number.
/
/ bit0=0: Use free cluster count in the FSINFO if available.
/ bit0=1: Do not trust free cluster count in the FSINFO.
/ bit1=0: Use last allocated cluster number in the FSINFO if available.
/ bit1=1: Do not trust last allocated cluster number in the FSINFO.
*/
/*---------------------------------------------------------------------------/
/ System Configurations
/---------------------------------------------------------------------------*/
#define FF_FS_TINY 0
/* This option switches tiny buffer configuration. (0:Normal or 1:Tiny)
/ At the tiny configuration, size of file object (FIL) is shrinked FF_MAX_SS bytes.
/ Instead of private sector buffer eliminated from the file object, common sector
/ buffer in the filesystem object (FATFS) is used for the file data transfer. */
#define FF_FS_EXFAT 0
/* This option switches support for exFAT filesystem. (0:Disable or 1:Enable)
/ To enable exFAT, also LFN needs to be enabled. (FF_USE_LFN >= 1)
/ Note that enabling exFAT discards ANSI C (C89) compatibility. */
#define FF_FS_NORTC 0
#define FF_NORTC_MON 1
#define FF_NORTC_MDAY 1
#define FF_NORTC_YEAR 2018
/* The option FF_FS_NORTC switches timestamp functiton. If the system does not have
/ any RTC function or valid timestamp is not needed, set FF_FS_NORTC = 1 to disable
/ the timestamp function. Every object modified by FatFs will have a fixed timestamp
/ defined by FF_NORTC_MON, FF_NORTC_MDAY and FF_NORTC_YEAR in local time.
/ To enable timestamp function (FF_FS_NORTC = 0), get_fattime() function need to be
/ added to the project to read current time form real-time clock. FF_NORTC_MON,
/ FF_NORTC_MDAY and FF_NORTC_YEAR have no effect.
/ These options have no effect at read-only configuration (FF_FS_READONLY = 1). */
#define FF_FS_LOCK 0
/* The option FF_FS_LOCK switches file lock function to control duplicated file open
/ and illegal operation to open objects. This option must be 0 when FF_FS_READONLY
/ is 1.
/
/ 0: Disable file lock function. To avoid volume corruption, application program
/ should avoid illegal open, remove and rename to the open objects.
/ >0: Enable file lock function. The value defines how many files/sub-directories
/ can be opened simultaneously under file lock control. Note that the file
/ lock control is independent of re-entrancy. */
/* #include <somertos.h> // O/S definitions */
#define FF_FS_REENTRANT 0
#define FF_FS_TIMEOUT 1000
#define FF_SYNC_t HANDLE
/* The option FF_FS_REENTRANT switches the re-entrancy (thread safe) of the FatFs
/ module itself. Note that regardless of this option, file access to different
/ volume is always re-entrant and volume control functions, f_mount(), f_mkfs()
/ and f_fdisk() function, are always not re-entrant. Only file/directory access
/ to the same volume is under control of this function.
/
/ 0: Disable re-entrancy. FF_FS_TIMEOUT and FF_SYNC_t have no effect.
/ 1: Enable re-entrancy. Also user provided synchronization handlers,
/ ff_req_grant(), ff_rel_grant(), ff_del_syncobj() and ff_cre_syncobj()
/ function, must be added to the project. Samples are available in
/ option/syscall.c.
/
/ The FF_FS_TIMEOUT defines timeout period in unit of time tick.
/ The FF_SYNC_t defines O/S dependent sync object type. e.g. HANDLE, ID, OS_EVENT*,
/ SemaphoreHandle_t and etc. A header file for O/S definitions needs to be
/ included somewhere in the scope of ff.h. */
/*--- End of configuration options ---*/

15597
source/fatfs/ffunicode.c Normal file

File diff suppressed because it is too large Load Diff

View File

@ -23,7 +23,6 @@ extern "C" void userAppInit()
{
plInitialize();
pmdmntInitialize();
pmshellInitialize();
splCryptoInitialize();
splInitialize();
}
@ -32,7 +31,6 @@ extern "C" void userAppExit()
{
plExit();
pmdmntExit();
pmshellExit();
splCryptoExit();
splExit();
}
@ -41,7 +39,8 @@ int main(int argc, char **argv) {
Common::intro();
KeyCollection Keys;
Common::wait_to_exit(Keys.get_keys());
Keys.get_keys();
Common::wait_to_exit();
return 0;
}

170
source/nx/es.c Normal file
View File

@ -0,0 +1,170 @@
#include "es.h"
#include <switch/arm/atomics.h>
#include <switch/kernel/ipc.h>
#include <switch/services/sm.h>
static Service g_esSrv;
static u64 g_esRefCnt;
Result esInitialize() {
atomicIncrement64(&g_esRefCnt);
if (serviceIsActive(&g_esSrv))
return 0;
return smGetService(&g_esSrv, "es");
}
void esExit()
{
if (atomicDecrement64(&g_esRefCnt) == 0) {
serviceClose(&g_esSrv);
}
}
Result esCountCommonTicket(u32 *num_tickets)
{
IpcCommand c;
ipcInitialize(&c);
struct {
u64 magic;
u64 cmd_id;
} *raw;
raw = ipcPrepareHeader(&c, sizeof(*raw));
raw->magic = SFCI_MAGIC;
raw->cmd_id = 9;
Result rc = serviceIpcDispatch(&g_esSrv);
if (R_SUCCEEDED(rc)) {
IpcParsedCommand r;
ipcParse(&r);
struct {
u64 magic;
u64 result;
u32 num_tickets;
} *resp = r.Raw;
rc = resp->result;
if (R_SUCCEEDED(rc)) {
*num_tickets = resp->num_tickets;
}
}
return rc;
}
Result esCountPersonalizedTicket(u32 *num_tickets)
{
IpcCommand c;
ipcInitialize(&c);
struct {
u64 magic;
u64 cmd_id;
} *raw;
raw = ipcPrepareHeader(&c, sizeof(*raw));
raw->magic = SFCI_MAGIC;
raw->cmd_id = 10;
Result rc = serviceIpcDispatch(&g_esSrv);
if (R_SUCCEEDED(rc)) {
IpcParsedCommand r;
ipcParse(&r);
struct {
u64 magic;
u64 result;
u32 num_tickets;
} *resp = r.Raw;
rc = resp->result;
if (R_SUCCEEDED(rc)) {
*num_tickets = resp->num_tickets;
}
}
return rc;
}
Result esListCommonTicket(u32 *numRightsIdsWritten, NcmRightsId *outBuf, size_t bufSize) {
IpcCommand c;
ipcInitialize(&c);
ipcAddRecvBuffer(&c, outBuf, bufSize, BufferType_Normal);
struct {
u64 magic;
u64 cmd_id;
} *raw;
raw = ipcPrepareHeader(&c, sizeof(*raw));
raw->magic = SFCI_MAGIC;
raw->cmd_id = 11;
Result rc = serviceIpcDispatch(&g_esSrv);
if (R_SUCCEEDED(rc)) {
IpcParsedCommand r;
ipcParse(&r);
struct {
u64 magic;
u64 result;
u32 num_rights_ids_written;
} *resp = r.Raw;
rc = resp->result;
if (R_SUCCEEDED(rc)) {
if (numRightsIdsWritten) *numRightsIdsWritten = resp->num_rights_ids_written;
}
}
return rc;
}
Result esListPersonalizedTicket(u32 *numRightsIdsWritten, NcmRightsId *outBuf, size_t bufSize) {
IpcCommand c;
ipcInitialize(&c);
ipcAddRecvBuffer(&c, outBuf, bufSize, BufferType_Normal);
struct {
u64 magic;
u64 cmd_id;
} *raw;
raw = ipcPrepareHeader(&c, sizeof(*raw));
raw->magic = SFCI_MAGIC;
raw->cmd_id = 12;
Result rc = serviceIpcDispatch(&g_esSrv);
if (R_SUCCEEDED(rc)) {
IpcParsedCommand r;
ipcParse(&r);
struct {
u64 magic;
u64 result;
u32 num_rights_ids_written;
} *resp = r.Raw;
rc = resp->result;
if (R_SUCCEEDED(rc)) {
if (numRightsIdsWritten) *numRightsIdsWritten = resp->num_rights_ids_written;
}
}
return rc;
}

12
source/nx/es.h Normal file
View File

@ -0,0 +1,12 @@
#pragma once
#include <switch/types.h>
#include <switch/services/ncm.h>
Result esInitialize();
void esExit();
Result esCountCommonTicket(u32 *num_tickets); //9
Result esCountPersonalizedTicket(u32 *num_tickets); // 10
Result esListCommonTicket(u32 *numRightsIdsWritten, NcmRightsId *outBuf, size_t bufSize);
Result esListPersonalizedTicket(u32 *numRightsIdsWritten, NcmRightsId *outBuf, size_t bufSize);

View File

@ -1,9 +1,8 @@
#include "set_ext.h"
#include <string.h>
#include <switch.h>
#include <switch/arm/atomics.h>
#include <switch/services/sm.h>
#include <switch/types.h>
static Service g_setcalSrv;
static u64 g_refCntCal;
@ -23,7 +22,7 @@ void setcalExit(void) {
}
}
Result setcalGetEticketDeviceKey(u8 *key) {
Result setcalGetEticketDeviceKey(void *key) {
IpcCommand c;
ipcInitialize(&c);
ipcAddRecvBuffer(&c, key, 0x244, 0);

View File

@ -1,12 +1,12 @@
#pragma once
#include <switch.h>
Result setcalInitialize(void);
void setcalExit(void);
/**
* @brief Gets the extended ETicket RSA-2048 Key from CAL0
* @param key Pointer to 0x244-byte output buffer.
*/
Result setcalGetEticketDeviceKey(u8 *key);
#pragma once
#include <switch/result.h>
Result setcalInitialize(void);
void setcalExit(void);
/**
* @brief Gets the extended ETicket RSA-2048 Key from CAL0
* @param key Pointer to 0x244-byte output buffer.
*/
Result setcalGetEticketDeviceKey(void *key);