diff options
Diffstat (limited to '')
-rw-r--r-- | src/core/crypto/aes_util.cpp | 112 | ||||
-rw-r--r-- | src/core/crypto/aes_util.h | 62 | ||||
-rw-r--r-- | src/core/crypto/ctr_encryption_layer.cpp | 56 | ||||
-rw-r--r-- | src/core/crypto/ctr_encryption_layer.h | 33 | ||||
-rw-r--r-- | src/core/crypto/encryption_layer.cpp | 42 | ||||
-rw-r--r-- | src/core/crypto/encryption_layer.h | 32 | ||||
-rw-r--r-- | src/core/crypto/key_manager.cpp | 215 | ||||
-rw-r--r-- | src/core/crypto/key_manager.h | 119 | ||||
-rw-r--r-- | src/core/crypto/sha_util.cpp | 5 | ||||
-rw-r--r-- | src/core/crypto/sha_util.h | 20 |
10 files changed, 696 insertions, 0 deletions
diff --git a/src/core/crypto/aes_util.cpp b/src/core/crypto/aes_util.cpp new file mode 100644 index 000000000..4690af5f8 --- /dev/null +++ b/src/core/crypto/aes_util.cpp @@ -0,0 +1,112 @@ +// Copyright 2018 yuzu emulator team +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include <mbedtls/cipher.h> +#include "core/crypto/aes_util.h" +#include "core/crypto/key_manager.h" + +namespace Core::Crypto { + +static_assert(static_cast<size_t>(Mode::CTR) == static_cast<size_t>(MBEDTLS_CIPHER_AES_128_CTR), + "CTR has incorrect value."); +static_assert(static_cast<size_t>(Mode::ECB) == static_cast<size_t>(MBEDTLS_CIPHER_AES_128_ECB), + "ECB has incorrect value."); +static_assert(static_cast<size_t>(Mode::XTS) == static_cast<size_t>(MBEDTLS_CIPHER_AES_128_XTS), + "XTS has incorrect value."); + +// Structure to hide mbedtls types from header file +struct CipherContext { + mbedtls_cipher_context_t encryption_context; + mbedtls_cipher_context_t decryption_context; +}; + +template <typename Key, size_t KeySize> +Crypto::AESCipher<Key, KeySize>::AESCipher(Key key, Mode mode) + : ctx(std::make_unique<CipherContext>()) { + mbedtls_cipher_init(&ctx->encryption_context); + mbedtls_cipher_init(&ctx->decryption_context); + + ASSERT_MSG((mbedtls_cipher_setup( + &ctx->encryption_context, + mbedtls_cipher_info_from_type(static_cast<mbedtls_cipher_type_t>(mode))) || + mbedtls_cipher_setup( + &ctx->decryption_context, + mbedtls_cipher_info_from_type(static_cast<mbedtls_cipher_type_t>(mode)))) == 0, + "Failed to initialize mbedtls ciphers."); + + ASSERT( + !mbedtls_cipher_setkey(&ctx->encryption_context, key.data(), KeySize * 8, MBEDTLS_ENCRYPT)); + ASSERT( + !mbedtls_cipher_setkey(&ctx->decryption_context, key.data(), KeySize * 8, MBEDTLS_DECRYPT)); + //"Failed to set key on mbedtls ciphers."); +} + +template <typename Key, size_t KeySize> +AESCipher<Key, KeySize>::~AESCipher() { + mbedtls_cipher_free(&ctx->encryption_context); + mbedtls_cipher_free(&ctx->decryption_context); +} + +template <typename Key, size_t KeySize> +void AESCipher<Key, KeySize>::SetIV(std::vector<u8> iv) { + ASSERT_MSG((mbedtls_cipher_set_iv(&ctx->encryption_context, iv.data(), iv.size()) || + mbedtls_cipher_set_iv(&ctx->decryption_context, iv.data(), iv.size())) == 0, + "Failed to set IV on mbedtls ciphers."); +} + +template <typename Key, size_t KeySize> +void AESCipher<Key, KeySize>::Transcode(const u8* src, size_t size, u8* dest, Op op) { + size_t written = 0; + + const auto context = op == Op::Encrypt ? &ctx->encryption_context : &ctx->decryption_context; + + mbedtls_cipher_reset(context); + + if (mbedtls_cipher_get_cipher_mode(context) == MBEDTLS_MODE_XTS) { + mbedtls_cipher_update(context, src, size, dest, &written); + if (written != size) + LOG_WARNING(Crypto, "Not all data was decrypted requested={:016X}, actual={:016X}.", + size, written); + } else { + const auto block_size = mbedtls_cipher_get_block_size(context); + + for (size_t offset = 0; offset < size; offset += block_size) { + auto length = std::min<size_t>(block_size, size - offset); + mbedtls_cipher_update(context, src + offset, length, dest + offset, &written); + if (written != length) + LOG_WARNING(Crypto, "Not all data was decrypted requested={:016X}, actual={:016X}.", + length, written); + } + } + + mbedtls_cipher_finish(context, nullptr, nullptr); +} + +template <typename Key, size_t KeySize> +void AESCipher<Key, KeySize>::XTSTranscode(const u8* src, size_t size, u8* dest, size_t sector_id, + size_t sector_size, Op op) { + if (size % sector_size > 0) { + LOG_CRITICAL(Crypto, "Data size must be a multiple of sector size."); + return; + } + + for (size_t i = 0; i < size; i += sector_size) { + SetIV(CalculateNintendoTweak(sector_id++)); + Transcode<u8, u8>(src + i, sector_size, dest + i, op); + } +} + +template <typename Key, size_t KeySize> +std::vector<u8> AESCipher<Key, KeySize>::CalculateNintendoTweak(size_t sector_id) { + std::vector<u8> out(0x10); + for (size_t i = 0xF; i <= 0xF; --i) { + out[i] = sector_id & 0xFF; + sector_id >>= 8; + } + return out; +} + +template class AESCipher<Key128>; +template class AESCipher<Key256>; +} // namespace Core::Crypto
\ No newline at end of file diff --git a/src/core/crypto/aes_util.h b/src/core/crypto/aes_util.h new file mode 100644 index 000000000..5b0b02738 --- /dev/null +++ b/src/core/crypto/aes_util.h @@ -0,0 +1,62 @@ +// Copyright 2018 yuzu emulator team +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include <memory> +#include <type_traits> +#include <vector> +#include "common/assert.h" +#include "core/file_sys/vfs.h" + +namespace Core::Crypto { + +struct CipherContext; + +enum class Mode { + CTR = 11, + ECB = 2, + XTS = 70, +}; + +enum class Op { + Encrypt, + Decrypt, +}; + +template <typename Key, size_t KeySize = sizeof(Key)> +class AESCipher { + static_assert(std::is_same_v<Key, std::array<u8, KeySize>>, "Key must be std::array of u8."); + static_assert(KeySize == 0x10 || KeySize == 0x20, "KeySize must be 128 or 256."); + +public: + AESCipher(Key key, Mode mode); + + ~AESCipher(); + + void SetIV(std::vector<u8> iv); + + template <typename Source, typename Dest> + void Transcode(const Source* src, size_t size, Dest* dest, Op op) { + Transcode(reinterpret_cast<const u8*>(src), size, reinterpret_cast<u8*>(dest), op); + } + + void Transcode(const u8* src, size_t size, u8* dest, Op op); + + template <typename Source, typename Dest> + void XTSTranscode(const Source* src, size_t size, Dest* dest, size_t sector_id, + size_t sector_size, Op op) { + XTSTranscode(reinterpret_cast<const u8*>(src), size, reinterpret_cast<u8*>(dest), sector_id, + sector_size, op); + } + + void XTSTranscode(const u8* src, size_t size, u8* dest, size_t sector_id, size_t sector_size, + Op op); + +private: + std::unique_ptr<CipherContext> ctx; + + static std::vector<u8> CalculateNintendoTweak(size_t sector_id); +}; +} // namespace Core::Crypto diff --git a/src/core/crypto/ctr_encryption_layer.cpp b/src/core/crypto/ctr_encryption_layer.cpp new file mode 100644 index 000000000..106db02b3 --- /dev/null +++ b/src/core/crypto/ctr_encryption_layer.cpp @@ -0,0 +1,56 @@ +// Copyright 2018 yuzu emulator team +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include <cstring> +#include "common/assert.h" +#include "core/crypto/ctr_encryption_layer.h" + +namespace Core::Crypto { + +CTREncryptionLayer::CTREncryptionLayer(FileSys::VirtualFile base_, Key128 key_, size_t base_offset) + : EncryptionLayer(std::move(base_)), base_offset(base_offset), cipher(key_, Mode::CTR), + iv(16, 0) {} + +size_t CTREncryptionLayer::Read(u8* data, size_t length, size_t offset) const { + if (length == 0) + return 0; + + const auto sector_offset = offset & 0xF; + if (sector_offset == 0) { + UpdateIV(base_offset + offset); + std::vector<u8> raw = base->ReadBytes(length, offset); + if (raw.size() != length) + return Read(data, raw.size(), offset); + cipher.Transcode(raw.data(), length, data, Op::Decrypt); + return length; + } + + // offset does not fall on block boundary (0x10) + std::vector<u8> block = base->ReadBytes(0x10, offset - sector_offset); + UpdateIV(base_offset + offset - sector_offset); + cipher.Transcode(block.data(), block.size(), block.data(), Op::Decrypt); + size_t read = 0x10 - sector_offset; + + if (length + sector_offset < 0x10) { + std::memcpy(data, block.data() + sector_offset, std::min<u64>(length, read)); + return read; + } + std::memcpy(data, block.data() + sector_offset, read); + return read + Read(data + read, length - read, offset + read); +} + +void CTREncryptionLayer::SetIV(const std::vector<u8>& iv_) { + const auto length = std::min(iv_.size(), iv.size()); + iv.assign(iv_.cbegin(), iv_.cbegin() + length); +} + +void CTREncryptionLayer::UpdateIV(size_t offset) const { + offset >>= 4; + for (size_t i = 0; i < 8; ++i) { + iv[16 - i - 1] = offset & 0xFF; + offset >>= 8; + } + cipher.SetIV(iv); +} +} // namespace Core::Crypto diff --git a/src/core/crypto/ctr_encryption_layer.h b/src/core/crypto/ctr_encryption_layer.h new file mode 100644 index 000000000..11b8683c7 --- /dev/null +++ b/src/core/crypto/ctr_encryption_layer.h @@ -0,0 +1,33 @@ +// Copyright 2018 yuzu emulator team +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include <vector> +#include "core/crypto/aes_util.h" +#include "core/crypto/encryption_layer.h" +#include "core/crypto/key_manager.h" + +namespace Core::Crypto { + +// Sits on top of a VirtualFile and provides CTR-mode AES decription. +class CTREncryptionLayer : public EncryptionLayer { +public: + CTREncryptionLayer(FileSys::VirtualFile base, Key128 key, size_t base_offset); + + size_t Read(u8* data, size_t length, size_t offset) const override; + + void SetIV(const std::vector<u8>& iv); + +private: + size_t base_offset; + + // Must be mutable as operations modify cipher contexts. + mutable AESCipher<Key128> cipher; + mutable std::vector<u8> iv; + + void UpdateIV(size_t offset) const; +}; + +} // namespace Core::Crypto diff --git a/src/core/crypto/encryption_layer.cpp b/src/core/crypto/encryption_layer.cpp new file mode 100644 index 000000000..4204527e3 --- /dev/null +++ b/src/core/crypto/encryption_layer.cpp @@ -0,0 +1,42 @@ +// Copyright 2018 yuzu emulator team +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include "core/crypto/encryption_layer.h" + +namespace Core::Crypto { + +EncryptionLayer::EncryptionLayer(FileSys::VirtualFile base_) : base(std::move(base_)) {} + +std::string EncryptionLayer::GetName() const { + return base->GetName(); +} + +size_t EncryptionLayer::GetSize() const { + return base->GetSize(); +} + +bool EncryptionLayer::Resize(size_t new_size) { + return false; +} + +std::shared_ptr<FileSys::VfsDirectory> EncryptionLayer::GetContainingDirectory() const { + return base->GetContainingDirectory(); +} + +bool EncryptionLayer::IsWritable() const { + return false; +} + +bool EncryptionLayer::IsReadable() const { + return true; +} + +size_t EncryptionLayer::Write(const u8* data, size_t length, size_t offset) { + return 0; +} + +bool EncryptionLayer::Rename(std::string_view name) { + return base->Rename(name); +} +} // namespace Core::Crypto diff --git a/src/core/crypto/encryption_layer.h b/src/core/crypto/encryption_layer.h new file mode 100644 index 000000000..71bca1f23 --- /dev/null +++ b/src/core/crypto/encryption_layer.h @@ -0,0 +1,32 @@ +// Copyright 2018 yuzu emulator team +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include "core/file_sys/vfs.h" + +namespace Core::Crypto { + +// Basically non-functional class that implements all of the methods that are irrelevant to an +// EncryptionLayer. Reduces duplicate code. +class EncryptionLayer : public FileSys::VfsFile { +public: + explicit EncryptionLayer(FileSys::VirtualFile base); + + size_t Read(u8* data, size_t length, size_t offset) const override = 0; + + std::string GetName() const override; + size_t GetSize() const override; + bool Resize(size_t new_size) override; + std::shared_ptr<FileSys::VfsDirectory> GetContainingDirectory() const override; + bool IsWritable() const override; + bool IsReadable() const override; + size_t Write(const u8* data, size_t length, size_t offset) override; + bool Rename(std::string_view name) override; + +protected: + FileSys::VirtualFile base; +}; + +} // namespace Core::Crypto diff --git a/src/core/crypto/key_manager.cpp b/src/core/crypto/key_manager.cpp new file mode 100644 index 000000000..678ac5752 --- /dev/null +++ b/src/core/crypto/key_manager.cpp @@ -0,0 +1,215 @@ +// Copyright 2018 yuzu emulator team +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include <array> +#include <fstream> +#include <locale> +#include <sstream> +#include <string_view> +#include <mbedtls/sha256.h> +#include "common/assert.h" +#include "common/common_paths.h" +#include "common/file_util.h" +#include "common/logging/log.h" +#include "core/crypto/key_manager.h" +#include "core/settings.h" +#include "key_manager.h" + +namespace Core::Crypto { + +static u8 ToHexNibble(char c1) { + if (c1 >= 65 && c1 <= 70) + return c1 - 55; + if (c1 >= 97 && c1 <= 102) + return c1 - 87; + if (c1 >= 48 && c1 <= 57) + return c1 - 48; + throw std::logic_error("Invalid hex digit"); +} + +template <size_t Size> +static std::array<u8, Size> HexStringToArray(std::string_view str) { + std::array<u8, Size> out{}; + for (size_t i = 0; i < 2 * Size; i += 2) { + auto d1 = str[i]; + auto d2 = str[i + 1]; + out[i / 2] = (ToHexNibble(d1) << 4) | ToHexNibble(d2); + } + return out; +} + +std::array<u8, 16> operator""_array16(const char* str, size_t len) { + if (len != 32) + throw std::logic_error("Not of correct size."); + return HexStringToArray<16>(str); +} + +std::array<u8, 32> operator""_array32(const char* str, size_t len) { + if (len != 64) + throw std::logic_error("Not of correct size."); + return HexStringToArray<32>(str); +} + +KeyManager::KeyManager() { + // Initialize keys + const std::string hactool_keys_dir = FileUtil::GetHactoolConfigurationPath(); + const std::string yuzu_keys_dir = FileUtil::GetUserPath(FileUtil::UserPath::KeysDir); + if (Settings::values.use_dev_keys) { + dev_mode = true; + AttemptLoadKeyFile(yuzu_keys_dir, hactool_keys_dir, "dev.keys", false); + } else { + dev_mode = false; + AttemptLoadKeyFile(yuzu_keys_dir, hactool_keys_dir, "prod.keys", false); + } + + AttemptLoadKeyFile(yuzu_keys_dir, hactool_keys_dir, "title.keys", true); +} + +void KeyManager::LoadFromFile(std::string_view filename_, bool is_title_keys) { + const auto filename = std::string(filename_); + std::ifstream file(filename); + if (!file.is_open()) + return; + + std::string line; + while (std::getline(file, line)) { + std::vector<std::string> out; + std::stringstream stream(line); + std::string item; + while (std::getline(stream, item, '=')) + out.push_back(std::move(item)); + + if (out.size() != 2) + continue; + + out[0].erase(std::remove(out[0].begin(), out[0].end(), ' '), out[0].end()); + out[1].erase(std::remove(out[1].begin(), out[1].end(), ' '), out[1].end()); + + if (is_title_keys) { + auto rights_id_raw = HexStringToArray<16>(out[0]); + u128 rights_id{}; + std::memcpy(rights_id.data(), rights_id_raw.data(), rights_id_raw.size()); + Key128 key = HexStringToArray<16>(out[1]); + SetKey(S128KeyType::Titlekey, key, rights_id[1], rights_id[0]); + } else { + std::transform(out[0].begin(), out[0].end(), out[0].begin(), ::tolower); + if (s128_file_id.find(out[0]) != s128_file_id.end()) { + const auto index = s128_file_id.at(out[0]); + Key128 key = HexStringToArray<16>(out[1]); + SetKey(index.type, key, index.field1, index.field2); + } else if (s256_file_id.find(out[0]) != s256_file_id.end()) { + const auto index = s256_file_id.at(out[0]); + Key256 key = HexStringToArray<32>(out[1]); + SetKey(index.type, key, index.field1, index.field2); + } + } + } +} + +void KeyManager::AttemptLoadKeyFile(std::string_view dir1_, std::string_view dir2_, + std::string_view filename_, bool title) { + const std::string dir1(dir1_); + const std::string dir2(dir2_); + const std::string filename(filename_); + if (FileUtil::Exists(dir1 + DIR_SEP + filename)) + LoadFromFile(dir1 + DIR_SEP + filename, title); + else if (FileUtil::Exists(dir2 + DIR_SEP + filename)) + LoadFromFile(dir2 + DIR_SEP + filename, title); +} + +bool KeyManager::HasKey(S128KeyType id, u64 field1, u64 field2) const { + return s128_keys.find({id, field1, field2}) != s128_keys.end(); +} + +bool KeyManager::HasKey(S256KeyType id, u64 field1, u64 field2) const { + return s256_keys.find({id, field1, field2}) != s256_keys.end(); +} + +Key128 KeyManager::GetKey(S128KeyType id, u64 field1, u64 field2) const { + if (!HasKey(id, field1, field2)) + return {}; + return s128_keys.at({id, field1, field2}); +} + +Key256 KeyManager::GetKey(S256KeyType id, u64 field1, u64 field2) const { + if (!HasKey(id, field1, field2)) + return {}; + return s256_keys.at({id, field1, field2}); +} + +void KeyManager::SetKey(S128KeyType id, Key128 key, u64 field1, u64 field2) { + s128_keys[{id, field1, field2}] = key; +} + +void KeyManager::SetKey(S256KeyType id, Key256 key, u64 field1, u64 field2) { + s256_keys[{id, field1, field2}] = key; +} + +bool KeyManager::KeyFileExists(bool title) { + const std::string hactool_keys_dir = FileUtil::GetHactoolConfigurationPath(); + const std::string yuzu_keys_dir = FileUtil::GetUserPath(FileUtil::UserPath::KeysDir); + if (title) { + return FileUtil::Exists(hactool_keys_dir + DIR_SEP + "title.keys") || + FileUtil::Exists(yuzu_keys_dir + DIR_SEP + "title.keys"); + } + + if (Settings::values.use_dev_keys) { + return FileUtil::Exists(hactool_keys_dir + DIR_SEP + "dev.keys") || + FileUtil::Exists(yuzu_keys_dir + DIR_SEP + "dev.keys"); + } + + return FileUtil::Exists(hactool_keys_dir + DIR_SEP + "prod.keys") || + FileUtil::Exists(yuzu_keys_dir + DIR_SEP + "prod.keys"); +} + +const std::unordered_map<std::string, KeyIndex<S128KeyType>> KeyManager::s128_file_id = { + {"master_key_00", {S128KeyType::Master, 0, 0}}, + {"master_key_01", {S128KeyType::Master, 1, 0}}, + {"master_key_02", {S128KeyType::Master, 2, 0}}, + {"master_key_03", {S128KeyType::Master, 3, 0}}, + {"master_key_04", {S128KeyType::Master, 4, 0}}, + {"package1_key_00", {S128KeyType::Package1, 0, 0}}, + {"package1_key_01", {S128KeyType::Package1, 1, 0}}, + {"package1_key_02", {S128KeyType::Package1, 2, 0}}, + {"package1_key_03", {S128KeyType::Package1, 3, 0}}, + {"package1_key_04", {S128KeyType::Package1, 4, 0}}, + {"package2_key_00", {S128KeyType::Package2, 0, 0}}, + {"package2_key_01", {S128KeyType::Package2, 1, 0}}, + {"package2_key_02", {S128KeyType::Package2, 2, 0}}, + {"package2_key_03", {S128KeyType::Package2, 3, 0}}, + {"package2_key_04", {S128KeyType::Package2, 4, 0}}, + {"titlekek_00", {S128KeyType::Titlekek, 0, 0}}, + {"titlekek_01", {S128KeyType::Titlekek, 1, 0}}, + {"titlekek_02", {S128KeyType::Titlekek, 2, 0}}, + {"titlekek_03", {S128KeyType::Titlekek, 3, 0}}, + {"titlekek_04", {S128KeyType::Titlekek, 4, 0}}, + {"eticket_rsa_kek", {S128KeyType::ETicketRSAKek, 0, 0}}, + {"key_area_key_application_00", + {S128KeyType::KeyArea, 0, static_cast<u64>(KeyAreaKeyType::Application)}}, + {"key_area_key_application_01", + {S128KeyType::KeyArea, 1, static_cast<u64>(KeyAreaKeyType::Application)}}, + {"key_area_key_application_02", + {S128KeyType::KeyArea, 2, static_cast<u64>(KeyAreaKeyType::Application)}}, + {"key_area_key_application_03", + {S128KeyType::KeyArea, 3, static_cast<u64>(KeyAreaKeyType::Application)}}, + {"key_area_key_application_04", + {S128KeyType::KeyArea, 4, static_cast<u64>(KeyAreaKeyType::Application)}}, + {"key_area_key_ocean_00", {S128KeyType::KeyArea, 0, static_cast<u64>(KeyAreaKeyType::Ocean)}}, + {"key_area_key_ocean_01", {S128KeyType::KeyArea, 1, static_cast<u64>(KeyAreaKeyType::Ocean)}}, + {"key_area_key_ocean_02", {S128KeyType::KeyArea, 2, static_cast<u64>(KeyAreaKeyType::Ocean)}}, + {"key_area_key_ocean_03", {S128KeyType::KeyArea, 3, static_cast<u64>(KeyAreaKeyType::Ocean)}}, + {"key_area_key_ocean_04", {S128KeyType::KeyArea, 4, static_cast<u64>(KeyAreaKeyType::Ocean)}}, + {"key_area_key_system_00", {S128KeyType::KeyArea, 0, static_cast<u64>(KeyAreaKeyType::System)}}, + {"key_area_key_system_01", {S128KeyType::KeyArea, 1, static_cast<u64>(KeyAreaKeyType::System)}}, + {"key_area_key_system_02", {S128KeyType::KeyArea, 2, static_cast<u64>(KeyAreaKeyType::System)}}, + {"key_area_key_system_03", {S128KeyType::KeyArea, 3, static_cast<u64>(KeyAreaKeyType::System)}}, + {"key_area_key_system_04", {S128KeyType::KeyArea, 4, static_cast<u64>(KeyAreaKeyType::System)}}, +}; + +const std::unordered_map<std::string, KeyIndex<S256KeyType>> KeyManager::s256_file_id = { + {"header_key", {S256KeyType::Header, 0, 0}}, + {"sd_card_save_key", {S256KeyType::SDSave, 0, 0}}, + {"sd_card_nca_key", {S256KeyType::SDNCA, 0, 0}}, +}; +} // namespace Core::Crypto diff --git a/src/core/crypto/key_manager.h b/src/core/crypto/key_manager.h new file mode 100644 index 000000000..03152a12c --- /dev/null +++ b/src/core/crypto/key_manager.h @@ -0,0 +1,119 @@ +// Copyright 2018 yuzu emulator team +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include <array> +#include <type_traits> +#include <unordered_map> +#include <vector> +#include <fmt/format.h> +#include "common/common_types.h" + +namespace Core::Crypto { + +using Key128 = std::array<u8, 0x10>; +using Key256 = std::array<u8, 0x20>; +using SHA256Hash = std::array<u8, 0x20>; + +static_assert(sizeof(Key128) == 16, "Key128 must be 128 bytes big."); +static_assert(sizeof(Key256) == 32, "Key128 must be 128 bytes big."); + +enum class S256KeyType : u64 { + Header, // + SDSave, // + SDNCA, // +}; + +enum class S128KeyType : u64 { + Master, // f1=crypto revision + Package1, // f1=crypto revision + Package2, // f1=crypto revision + Titlekek, // f1=crypto revision + ETicketRSAKek, // + KeyArea, // f1=crypto revision f2=type {app, ocean, system} + SDSeed, // + Titlekey, // f1=rights id LSB f2=rights id MSB +}; + +enum class KeyAreaKeyType : u8 { + Application, + Ocean, + System, +}; + +template <typename KeyType> +struct KeyIndex { + KeyType type; + u64 field1; + u64 field2; + + std::string DebugInfo() const { + u8 key_size = 16; + if constexpr (std::is_same_v<KeyType, S256KeyType>) + key_size = 32; + return fmt::format("key_size={:02X}, key={:02X}, field1={:016X}, field2={:016X}", key_size, + static_cast<u8>(type), field1, field2); + } +}; + +// The following two (== and hash) are so KeyIndex can be a key in unordered_map + +template <typename KeyType> +bool operator==(const KeyIndex<KeyType>& lhs, const KeyIndex<KeyType>& rhs) { + return std::tie(lhs.type, lhs.field1, lhs.field2) == std::tie(rhs.type, rhs.field1, rhs.field2); +} + +template <typename KeyType> +bool operator!=(const KeyIndex<KeyType>& lhs, const KeyIndex<KeyType>& rhs) { + return !operator==(lhs, rhs); +} + +} // namespace Core::Crypto + +namespace std { +template <typename KeyType> +struct hash<Core::Crypto::KeyIndex<KeyType>> { + size_t operator()(const Core::Crypto::KeyIndex<KeyType>& k) const { + using std::hash; + + return ((hash<u64>()(static_cast<u64>(k.type)) ^ (hash<u64>()(k.field1) << 1)) >> 1) ^ + (hash<u64>()(k.field2) << 1); + } +}; +} // namespace std + +namespace Core::Crypto { + +std::array<u8, 0x10> operator"" _array16(const char* str, size_t len); +std::array<u8, 0x20> operator"" _array32(const char* str, size_t len); + +class KeyManager { +public: + KeyManager(); + + bool HasKey(S128KeyType id, u64 field1 = 0, u64 field2 = 0) const; + bool HasKey(S256KeyType id, u64 field1 = 0, u64 field2 = 0) const; + + Key128 GetKey(S128KeyType id, u64 field1 = 0, u64 field2 = 0) const; + Key256 GetKey(S256KeyType id, u64 field1 = 0, u64 field2 = 0) const; + + void SetKey(S128KeyType id, Key128 key, u64 field1 = 0, u64 field2 = 0); + void SetKey(S256KeyType id, Key256 key, u64 field1 = 0, u64 field2 = 0); + + static bool KeyFileExists(bool title); + +private: + std::unordered_map<KeyIndex<S128KeyType>, Key128> s128_keys; + std::unordered_map<KeyIndex<S256KeyType>, Key256> s256_keys; + + bool dev_mode; + void LoadFromFile(std::string_view filename, bool is_title_keys); + void AttemptLoadKeyFile(std::string_view dir1, std::string_view dir2, std::string_view filename, + bool title); + + static const std::unordered_map<std::string, KeyIndex<S128KeyType>> s128_file_id; + static const std::unordered_map<std::string, KeyIndex<S256KeyType>> s256_file_id; +}; +} // namespace Core::Crypto diff --git a/src/core/crypto/sha_util.cpp b/src/core/crypto/sha_util.cpp new file mode 100644 index 000000000..180008a85 --- /dev/null +++ b/src/core/crypto/sha_util.cpp @@ -0,0 +1,5 @@ +// Copyright 2018 yuzu emulator team +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +namespace Crypto {} // namespace Crypto diff --git a/src/core/crypto/sha_util.h b/src/core/crypto/sha_util.h new file mode 100644 index 000000000..fa3fa9d33 --- /dev/null +++ b/src/core/crypto/sha_util.h @@ -0,0 +1,20 @@ +// Copyright 2018 yuzu emulator team +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include "common/assert.h" +#include "core/file_sys/vfs.h" +#include "key_manager.h" +#include "mbedtls/cipher.h" + +namespace Crypto { +typedef std::array<u8, 0x20> SHA256Hash; + +inline SHA256Hash operator"" _HASH(const char* data, size_t len) { + if (len != 0x40) + return {}; +} + +} // namespace Crypto |