From e59dd9c8f053702fac157012ec2aa1f9058c1714 Mon Sep 17 00:00:00 2001 From: Michael Scire Date: Mon, 20 Apr 2020 16:57:25 -0700 Subject: [PATCH] ams.mitm: completely revamp prodinfo backup mechanism --- exosphere/src/exocfg.c | 2 +- .../stratosphere/ams/ams_exosphere_api.hpp | 5 + .../include/stratosphere/settings.hpp | 18 +- .../factory/settings_device_certificate.hpp | 39 ++ .../factory/settings_serial_number.hpp | 27 + .../include/stratosphere/spl/spl_api.hpp | 3 + .../include/stratosphere/spl/spl_types.hpp | 32 + .../source/ams/ams_exosphere_api.cpp | 29 +- .../libstratosphere/source/spl/spl_api.cpp | 11 + .../source/amsmitm_initialization.cpp | 63 +- .../source/amsmitm_prodinfo_utils.cpp | 579 ++++++++++++++++++ .../source/amsmitm_prodinfo_utils.hpp | 25 + stratosphere/spl/source/spl_main.cpp | 2 +- 13 files changed, 761 insertions(+), 74 deletions(-) create mode 100644 libraries/libstratosphere/include/stratosphere/settings/factory/settings_device_certificate.hpp create mode 100644 libraries/libstratosphere/include/stratosphere/settings/factory/settings_serial_number.hpp create mode 100644 stratosphere/ams_mitm/source/amsmitm_prodinfo_utils.cpp create mode 100644 stratosphere/ams_mitm/source/amsmitm_prodinfo_utils.hpp diff --git a/exosphere/src/exocfg.c b/exosphere/src/exocfg.c index 7fb8c4e9d..fd23d214a 100644 --- a/exosphere/src/exocfg.c +++ b/exosphere/src/exocfg.c @@ -115,7 +115,7 @@ unsigned int exosphere_should_allow_writing_to_cal(void) { if (exosphere_is_emummc()) { return 1; } else { - return 0; + return EXOSPHERE_CHECK_FLAG(EXOSPHERE_FLAG_ALLOW_WRITING_TO_CAL_SYSMMC); } } diff --git a/libraries/libstratosphere/include/stratosphere/ams/ams_exosphere_api.hpp b/libraries/libstratosphere/include/stratosphere/ams/ams_exosphere_api.hpp index eb80efef4..bc0efd139 100644 --- a/libraries/libstratosphere/include/stratosphere/ams/ams_exosphere_api.hpp +++ b/libraries/libstratosphere/include/stratosphere/ams/ams_exosphere_api.hpp @@ -27,6 +27,11 @@ namespace ams::exosphere { bool IsRcmBugPatched(); + bool ShouldBlankProdInfo(); + bool ShouldAllowWritesToProdInfo(); + + u64 GetDeviceId(); + void CopyToIram(uintptr_t iram_dst, const void *dram_src, size_t size); void CopyFromIram(void *dram_dst, uintptr_t iram_src, size_t size); diff --git a/libraries/libstratosphere/include/stratosphere/settings.hpp b/libraries/libstratosphere/include/stratosphere/settings.hpp index a509fe93a..d78e42bef 100644 --- a/libraries/libstratosphere/include/stratosphere/settings.hpp +++ b/libraries/libstratosphere/include/stratosphere/settings.hpp @@ -16,11 +16,13 @@ #pragma once -#include "settings/settings_types.hpp" -#include "settings/settings_fwdbg_types.hpp" -#include "settings/settings_fwdbg_api.hpp" -#include "settings/system/settings_error_report.hpp" -#include "settings/system/settings_firmware_version.hpp" -#include "settings/system/settings_product_model.hpp" -#include "settings/system/settings_region.hpp" -#include "settings/system/settings_serial_number.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include diff --git a/libraries/libstratosphere/include/stratosphere/settings/factory/settings_device_certificate.hpp b/libraries/libstratosphere/include/stratosphere/settings/factory/settings_device_certificate.hpp new file mode 100644 index 000000000..b9be05258 --- /dev/null +++ b/libraries/libstratosphere/include/stratosphere/settings/factory/settings_device_certificate.hpp @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2018-2020 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 . + */ +#pragma once +#include + +namespace ams::settings::factory { + + struct EccP256DeviceCertificate { + u8 data[0x180]; + }; + static_assert(sizeof(EccP256DeviceCertificate) == 0x180); + static_assert(std::is_pod::value); + + struct EccB233DeviceCertificate { + u8 data[0x180]; + }; + static_assert(sizeof(EccB233DeviceCertificate) == 0x180); + static_assert(std::is_pod::value); + + struct Rsa2048DeviceCertificate { + u8 data[0x240]; + }; + static_assert(sizeof(Rsa2048DeviceCertificate) == 0x240); + static_assert(std::is_pod::value); + +} diff --git a/libraries/libstratosphere/include/stratosphere/settings/factory/settings_serial_number.hpp b/libraries/libstratosphere/include/stratosphere/settings/factory/settings_serial_number.hpp new file mode 100644 index 000000000..068d7d655 --- /dev/null +++ b/libraries/libstratosphere/include/stratosphere/settings/factory/settings_serial_number.hpp @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2018-2020 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 . + */ +#pragma once +#include + +namespace ams::settings::factory { + + struct SerialNumber { + char str[0x18]; + }; + static_assert(sizeof(SerialNumber) == 0x18); + static_assert(std::is_pod::value); + +} diff --git a/libraries/libstratosphere/include/stratosphere/spl/spl_api.hpp b/libraries/libstratosphere/include/stratosphere/spl/spl_api.hpp index b2ce4a56e..3b9639f82 100644 --- a/libraries/libstratosphere/include/stratosphere/spl/spl_api.hpp +++ b/libraries/libstratosphere/include/stratosphere/spl/spl_api.hpp @@ -27,4 +27,7 @@ namespace ams::spl { bool IsMariko(); bool IsRecoveryBoot(); + Result GenerateAesKek(AccessKey *access_key, const void *key_source, size_t key_source_size, u32 generation, u32 option); + Result GenerateAesKey(void *dst, size_t dst_size, const AccessKey &access_key, const void *key_source, size_t key_source_size); + } diff --git a/libraries/libstratosphere/include/stratosphere/spl/spl_types.hpp b/libraries/libstratosphere/include/stratosphere/spl/spl_types.hpp index e73e66713..43dbb54ed 100644 --- a/libraries/libstratosphere/include/stratosphere/spl/spl_types.hpp +++ b/libraries/libstratosphere/include/stratosphere/spl/spl_types.hpp @@ -183,6 +183,36 @@ namespace ams::spl { static_assert(alignof(AccessKey) == alignof(u8), "KeySource definition!"); #pragma pack(pop) + enum class ConfigItem : u32 { + /* Standard config items. */ + DisableProgramVerification = 1, + DramId = 2, + SecurityEngineIrqNumber = 3, + Version = 4, + HardwareType = 5, + IsRetail = 6, + IsRecoveryBoot = 7, + DeviceId = 8, + BootReason = 9, + MemoryMode = 10, + IsDebugMode = 11, + KernelConfiguration = 12, + IsChargerHiZModeEnabled = 13, + IsQuest = 14, + RegulatorType = 15, + DeviceUniqueKeyGeneration = 16, + Package2Hash = 17, + + /* Extension config items for exosphere. */ + ExosphereApiVersion = 65000, + ExosphereNeedsReboot = 65001, + ExosphereNeedsShutdown = 65002, + ExosphereGitCommitHash = 65003, + ExosphereHasRcmBugPatch = 65004, + ExosphereBlankProdInfo = 65005, + ExosphereAllowCalWrites = 65006, + }; + } /* Extensions to libnx spl config item enum. */ @@ -191,3 +221,5 @@ constexpr inline SplConfigItem SplConfigItem_ExosphereNeedsReboot = static_ca constexpr inline SplConfigItem SplConfigItem_ExosphereNeedsShutdown = static_cast(65002); constexpr inline SplConfigItem SplConfigItem_ExosphereGitCommitHash = static_cast(65003); constexpr inline SplConfigItem SplConfigItem_ExosphereHasRcmBugPatch = static_cast(65004); +constexpr inline SplConfigItem SplConfigItem_ExosphereBlankProdInfo = static_cast(65005); +constexpr inline SplConfigItem SplConfigItem_ExosphereAllowCalWrites = static_cast(65006); diff --git a/libraries/libstratosphere/source/ams/ams_exosphere_api.cpp b/libraries/libstratosphere/source/ams/ams_exosphere_api.cpp index 915166445..63243d66a 100644 --- a/libraries/libstratosphere/source/ams/ams_exosphere_api.cpp +++ b/libraries/libstratosphere/source/ams/ams_exosphere_api.cpp @@ -51,19 +51,32 @@ namespace ams::exosphere { namespace { - inline Result GetRcmBugPatched(bool *out) { - u64 tmp = 0; - R_TRY(spl::smc::ConvertResult(spl::smc::GetConfig(&tmp, 1, SplConfigItem_ExosphereHasRcmBugPatch))); - *out = (tmp != 0); - return ResultSuccess(); + inline u64 GetU64ConfigItem(spl::ConfigItem cfg) { + u64 tmp; + R_ABORT_UNLESS(spl::smc::ConvertResult(spl::smc::GetConfig(std::addressof(tmp), 1, static_cast<::SplConfigItem>(cfg)))); + return tmp; + } + + inline bool GetBooleanConfigItem(spl::ConfigItem cfg) { + return GetU64ConfigItem(cfg) != 0; } } bool IsRcmBugPatched() { - bool rcm_bug_patched; - R_ABORT_UNLESS(GetRcmBugPatched(&rcm_bug_patched)); - return rcm_bug_patched; + return GetBooleanConfigItem(spl::ConfigItem::ExosphereHasRcmBugPatch); + } + + bool ShouldBlankProdInfo() { + return GetBooleanConfigItem(spl::ConfigItem::ExosphereBlankProdInfo); + } + + bool ShouldAllowWritesToProdInfo() { + return GetBooleanConfigItem(spl::ConfigItem::ExosphereAllowCalWrites); + } + + u64 GetDeviceId() { + return GetU64ConfigItem(spl::ConfigItem::DeviceId); } } diff --git a/libraries/libstratosphere/source/spl/spl_api.cpp b/libraries/libstratosphere/source/spl/spl_api.cpp index 032ac52ac..7ffa4c333 100644 --- a/libraries/libstratosphere/source/spl/spl_api.cpp +++ b/libraries/libstratosphere/source/spl/spl_api.cpp @@ -78,4 +78,15 @@ namespace ams::spl { } } + Result GenerateAesKek(AccessKey *access_key, const void *key_source, size_t key_source_size, u32 generation, u32 option) { + AMS_ASSERT(key_source_size == sizeof(KeySource)); + return splCryptoGenerateAesKek(key_source, generation, option, static_cast(access_key)); + } + + Result GenerateAesKey(void *dst, size_t dst_size, const AccessKey &access_key, const void *key_source, size_t key_source_size) { + AMS_ASSERT(dst_size == crypto::AesEncryptor128::KeySize); + AMS_ASSERT(key_source_size == sizeof(KeySource)); + return splCryptoGenerateAesKey(std::addressof(access_key), key_source, dst); + } + } diff --git a/stratosphere/ams_mitm/source/amsmitm_initialization.cpp b/stratosphere/ams_mitm/source/amsmitm_initialization.cpp index ee4abd888..0ba71cb3a 100644 --- a/stratosphere/ams_mitm/source/amsmitm_initialization.cpp +++ b/stratosphere/ams_mitm/source/amsmitm_initialization.cpp @@ -16,6 +16,7 @@ #include #include "amsmitm_initialization.hpp" #include "amsmitm_fs_utils.hpp" +#include "amsmitm_prodinfo_utils.hpp" #include "bpc_mitm/bpc_ams_power_utils.hpp" #include "set_mitm/settings_sd_kvs.hpp" @@ -58,10 +59,6 @@ namespace ams::mitm { alignas(os::ThreadStackAlignment) u8 g_initialize_thread_stack[InitializeThreadStackSize]; /* Console-unique data backup and protection. */ - constexpr size_t CalibrationBinarySize = 0x8000; - u8 g_calibration_binary_storage_backup[CalibrationBinarySize]; - u8 g_calibration_binary_file_backup[CalibrationBinarySize]; - FsFile g_calibration_binary_file; FsFile g_bis_key_file; /* Emummc file protection. */ @@ -90,57 +87,10 @@ namespace ams::mitm { /* Create a backup directory, if one doesn't exist. */ mitm::fs::CreateAtmosphereSdDirectory("/automatic_backups"); - /* Read the calibration binary. */ - { - FsStorage calibration_binary_storage; - R_ABORT_UNLESS(fsOpenBisStorage(&calibration_binary_storage, FsBisPartitionId_CalibrationBinary)); - ON_SCOPE_EXIT { fsStorageClose(&calibration_binary_storage); }; - - R_ABORT_UNLESS(fsStorageRead(&calibration_binary_storage, 0, g_calibration_binary_storage_backup, CalibrationBinarySize)); - } - - /* Copy serial number from partition. */ - /* TODO: Define the magic numbers? Structs? */ - char serial_number[0x40] = {}; - std::memcpy(serial_number, g_calibration_binary_storage_backup + 0x250, 0x18); - - /* Backup the calibration binary. */ - { - char calibration_binary_backup_name[ams::fs::EntryNameLengthMax + 1]; - GetBackupFileName(calibration_binary_backup_name, sizeof(calibration_binary_backup_name), serial_number, "PRODINFO.bin"); - - mitm::fs::CreateAtmosphereSdFile(calibration_binary_backup_name, CalibrationBinarySize, ams::fs::CreateOption_None); - R_ABORT_UNLESS(mitm::fs::OpenAtmosphereSdFile(&g_calibration_binary_file, calibration_binary_backup_name, ams::fs::OpenMode_ReadWrite)); - - s64 file_size = 0; - R_ABORT_UNLESS(fsFileGetSize(&g_calibration_binary_file, &file_size)); - - bool is_file_backup_valid = file_size == CalibrationBinarySize; - if (is_file_backup_valid) { - u64 read_size = 0; - R_ABORT_UNLESS(fsFileRead(&g_calibration_binary_file, 0, g_calibration_binary_file_backup, CalibrationBinarySize, FsReadOption_None, &read_size)); - AMS_ABORT_UNLESS(read_size == CalibrationBinarySize); - is_file_backup_valid &= std::memcmp(g_calibration_binary_file_backup, "CAL0", 4) == 0; - is_file_backup_valid &= std::memcmp(g_calibration_binary_file_backup + 0x250, serial_number, 0x18) == 0; - const u32 cal_bin_size = *reinterpret_cast(g_calibration_binary_file_backup + 0x8); - is_file_backup_valid &= cal_bin_size + 0x40 <= CalibrationBinarySize; - if (is_file_backup_valid) { - u8 calc_hash[SHA256_HASH_SIZE]; - /* TODO: ams::crypto? */ - sha256CalculateHash(calc_hash, g_calibration_binary_file_backup + 0x40, cal_bin_size); - is_file_backup_valid &= std::memcmp(calc_hash, g_calibration_binary_file_backup + 0x20, sizeof(calc_hash)) == 0; - } - } - - if (!is_file_backup_valid) { - R_ABORT_UNLESS(fsFileSetSize(&g_calibration_binary_file, CalibrationBinarySize)); - R_ABORT_UNLESS(fsFileWrite(&g_calibration_binary_file, 0, g_calibration_binary_storage_backup, CalibrationBinarySize, FsWriteOption_Flush)); - } - - /* Note: g_calibration_binary_file is intentionally not closed here. This prevents any other process from opening it. */ - std::memset(g_calibration_binary_file_backup, 0, CalibrationBinarySize); - std::memset(g_calibration_binary_storage_backup, 0, CalibrationBinarySize); - } + /* Initialize PRODINFO and get a reference for the device. */ + char device_reference[0x40] = {}; + ON_SCOPE_EXIT { std::memset(device_reference, 0, sizeof(device_reference)); }; + mitm::InitializeProdInfoManagement(device_reference, sizeof(device_reference)); /* Backup BIS keys. */ { @@ -151,6 +101,7 @@ namespace ams::mitm { u8 bis_keys[4][2][0x10]; std::memset(bis_keys, 0xCC, sizeof(bis_keys)); + ON_SCOPE_EXIT { std::memset(bis_keys, 0xCC, sizeof(bis_keys)); }; /* TODO: Clean this up. */ for (size_t partition = 0; partition < 4; partition++) { @@ -170,7 +121,7 @@ namespace ams::mitm { } char bis_keys_backup_name[ams::fs::EntryNameLengthMax + 1]; - GetBackupFileName(bis_keys_backup_name, sizeof(bis_keys_backup_name), serial_number, "BISKEYS.bin"); + GetBackupFileName(bis_keys_backup_name, sizeof(bis_keys_backup_name), device_reference, "BISKEYS.bin"); mitm::fs::CreateAtmosphereSdFile(bis_keys_backup_name, sizeof(bis_keys), ams::fs::CreateOption_None); R_ABORT_UNLESS(mitm::fs::OpenAtmosphereSdFile(&g_bis_key_file, bis_keys_backup_name, ams::fs::OpenMode_ReadWrite)); diff --git a/stratosphere/ams_mitm/source/amsmitm_prodinfo_utils.cpp b/stratosphere/ams_mitm/source/amsmitm_prodinfo_utils.cpp new file mode 100644 index 000000000..86f629605 --- /dev/null +++ b/stratosphere/ams_mitm/source/amsmitm_prodinfo_utils.cpp @@ -0,0 +1,579 @@ +/* + * Copyright (c) 2018-2020 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 . + */ +#include +#include "amsmitm_fs_utils.hpp" +#include "amsmitm_prodinfo_utils.hpp" + +namespace ams::mitm { + + namespace { + + constexpr inline u16 Crc16InitialValue = 0x55AA; + + constexpr inline u16 Crc16Table[] = { + 0x0000, 0xCC01, 0xD801, 0x1400, + 0xF001, 0x3C00, 0x2800, 0xE401, + 0xA001, 0x6C00, 0x7800, 0xB401, + 0x5000, 0x9C01, 0x8801, 0x4400, + }; + + u16 GetCrc16(const void *data, size_t size) { + AMS_ASSERT(data != nullptr); + AMS_ASSERT(size > 0); + + const u8 *src = static_cast(data); + + u16 crc = Crc16InitialValue; + + u16 tmp = 0; + while ((size--) > 0) { + tmp = Crc16Table[crc & 0xF]; + crc = ((crc >> 4) & 0x0FFF) ^ tmp ^ Crc16Table[*src & 0xF]; + tmp = Crc16Table[crc & 0xF]; + crc = ((crc >> 4) & 0x0FFF) ^ tmp ^ Crc16Table[(*(src++) >> 4) & 0xF]; + } + return crc; + } + + bool IsBlank(const void *data, size_t size) { + AMS_ASSERT(data != nullptr); + AMS_ASSERT(size > 0); + + const u8 *src = static_cast(data); + while ((size--) > 0) { + if (*(src++) != 0) { + return false; + } + } + return true; + } + + constexpr inline u32 CalibrationMagic = util::FourCC<'C','A','L','0'>::Code; + + struct Sha256Hash { + u8 data[crypto::Sha256Generator::HashSize]; + }; + + struct CalibrationInfoHeader { + u32 magic; + u32 version; + u32 body_size; + u16 model; + u16 update_count; + u8 pad[0xE]; + u16 crc; + Sha256Hash body_hash; + }; + static_assert(sizeof(CalibrationInfoHeader) == 0x40); + + constexpr inline size_t CalibrationInfoBodySizeMax = 0x8000 - sizeof(CalibrationInfoHeader); + + struct CalibrationInfo { + CalibrationInfoHeader header; + u8 body[CalibrationInfoBodySizeMax]; /* TODO: CalibrationInfoBody body; */ + + template + Block &GetBlock() { + static_assert(Block::Offset >= sizeof(CalibrationInfoHeader)); + static_assert(Block::Offset < sizeof(CalibrationInfo)); + static_assert(Block::Offset + Block::Size <= sizeof(CalibrationInfo)); + return *static_cast(static_cast(std::addressof(this->body[Block::Offset - sizeof(this->header)]))); + } + + template + const Block &GetBlock() const { + static_assert(Block::Offset >= sizeof(CalibrationInfoHeader)); + static_assert(Block::Offset < sizeof(CalibrationInfo)); + static_assert(Block::Offset + Block::Size <= sizeof(CalibrationInfo)); + return *static_cast(static_cast(std::addressof(this->body[Block::Offset - sizeof(this->header)]))); + } + }; + static_assert(sizeof(CalibrationInfo) == 0x8000); + + struct SecureCalibrationInfoBackup { + CalibrationInfo info; + Sha256Hash hash; + u8 pad[0xC000 - sizeof(info) - sizeof(hash)]; + }; + static_assert(sizeof(SecureCalibrationInfoBackup) == 0xC000); + + bool IsValidSha256Hash(const Sha256Hash &hash, const void *data, size_t data_size) { + Sha256Hash calc_hash; + ON_SCOPE_EXIT { ::ams::crypto::ClearMemory(std::addressof(calc_hash), sizeof(calc_hash)); }; + + ::ams::crypto::GenerateSha256Hash(std::addressof(calc_hash), sizeof(calc_hash), data, data_size); + return ::ams::crypto::IsSameBytes(std::addressof(calc_hash), std::addressof(hash), sizeof(Sha256Hash)); + } + + bool IsValid(const CalibrationInfoHeader &header) { + return header.magic == CalibrationMagic && GetCrc16(std::addressof(header), OFFSETOF(CalibrationInfoHeader, crc)) == header.crc; + } + + bool IsValid(const CalibrationInfoHeader &header, const void *body) { + return IsValid(header) && IsValidSha256Hash(header.body_hash, body, header.body_size); + } + + #define DEFINE_CALIBRATION_CRC_BLOCK(_TypeName, _Offset, _Size, _Decl, _MemberName) \ + struct _TypeName { \ + static constexpr size_t Offset = _Offset; \ + static constexpr size_t Size = _Size; \ + static constexpr bool IsCrcBlock = true; \ + static constexpr bool IsShaBlock = false; \ + _Decl; \ + static_assert(Size >= sizeof(_MemberName) + sizeof(u16)); \ + u8 pad[Size - sizeof(_MemberName) - sizeof(u16)]; \ + u16 crc; \ + }; \ + static_assert(sizeof(_TypeName) == _TypeName::Size) + + #define DEFINE_CALIBRATION_SHA_BLOCK(_TypeName, _Offset, _Size, _Decl, _MemberName) \ + struct _TypeName { \ + static constexpr size_t Offset = _Offset; \ + static constexpr size_t Size = _Size; \ + static constexpr bool IsCrcBlock = false; \ + static constexpr bool IsShaBlock = true; \ + _Decl; \ + static_assert(Size == sizeof(_MemberName) + sizeof(Sha256Hash)); \ + Sha256Hash sha256_hash; \ + }; \ + static_assert(sizeof(_TypeName) == _TypeName::Size) + + DEFINE_CALIBRATION_CRC_BLOCK(SerialNumberBlock, 0x0250, 0x020, ::ams::settings::factory::SerialNumber serial_number, serial_number); + DEFINE_CALIBRATION_CRC_BLOCK(EccB233DeviceCertificateBlock, 0x0480, 0x190, ::ams::settings::factory::EccB233DeviceCertificate device_certificate, device_certificate); + DEFINE_CALIBRATION_CRC_BLOCK(SslKeyBlock, 0x09B0, 0x120, u8 ssl_key[0x110], ssl_key); + DEFINE_CALIBRATION_CRC_BLOCK(SslCertificateSizeBlock, 0x0AD0, 0x010, u64 ssl_certificate_size, ssl_certificate_size); + DEFINE_CALIBRATION_SHA_BLOCK(SslCertificateBlock, 0x0AE0, 0x820, u8 ssl_certificate[0x800], ssl_certificate); + DEFINE_CALIBRATION_CRC_BLOCK(EcqvEcdsaAmiiboRootCertificateBlock, 0x35A0, 0x080, u8 data[0x70], data); + DEFINE_CALIBRATION_CRC_BLOCK(EcqvBlsAmiiboRootCertificateBlock, 0x36A0, 0x0A0, u8 data[0x90], data); + DEFINE_CALIBRATION_CRC_BLOCK(ExtendedSslKeyBlock, 0x3AE0, 0x140, u8 ssl_key[0x134], ssl_key); + DEFINE_CALIBRATION_CRC_BLOCK(Rsa2048DeviceKeyBlock, 0x3D70, 0x250, u8 device_key[0x240], device_key); + DEFINE_CALIBRATION_CRC_BLOCK(Rsa2048DeviceCertificateBlock, 0x3FC0, 0x250, ::ams::settings::factory::Rsa2048DeviceCertificate device_certificate, device_certificate); + + #undef DEFINE_CALIBRATION_CRC_BLOCK + #undef DEFINE_CALIBRATION_SHA_BLOCK + + constexpr inline const char BlankSerialNumberString[] = "XAW00000000000"; + + template + void Blank(Block &block) { + if constexpr (std::is_same::value) { + static_assert(sizeof(BlankSerialNumberString) <= sizeof(SerialNumberBlock::serial_number)); + std::memset(std::addressof(block), 0, Block::Size - sizeof(block.crc)); + std::memcpy(block.serial_number.str, BlankSerialNumberString, sizeof(BlankSerialNumberString)); + block.crc = GetCrc16(std::addressof(block), Block::Size - sizeof(block.crc)); + } else if constexpr (std::is_same::value) { + std::memset(std::addressof(block), 0, Block::Size); + } else if constexpr (Block::IsCrcBlock) { + std::memset(std::addressof(block), 0, Block::Size - sizeof(block.crc)); + block.crc = GetCrc16(std::addressof(block), Block::Size - sizeof(block.crc)); + } else { + static_assert(Block::IsShaBlock); + std::memset(std::addressof(block), 0, Block::Size); + ::ams::crypto::GenerateSha256Hash(std::addressof(block.sha256_hash), sizeof(block.sha256_hash), std::addressof(block), Block::Size - sizeof(block.sha256_hash)); + } + } + + void Blank(CalibrationInfo &info) { + /* Set header. */ + info.header.magic = CalibrationMagic; + info.header.body_size = sizeof(info.body); + info.header.crc = GetCrc16(std::addressof(info.header), OFFSETOF(CalibrationInfoHeader, crc)); + + /* Set blocks. */ + Blank(info.GetBlock()); + Blank(info.GetBlock()); + Blank(info.GetBlock()); + Blank(info.GetBlock()); + Blank(info.GetBlock()); + Blank(info.GetBlock()); + Blank(info.GetBlock()); + Blank(info.GetBlock()); + Blank(info.GetBlock()); + + /* Set header hash. */ + crypto::GenerateSha256Hash(std::addressof(info.header.body_hash), sizeof(info.header.body_hash), std::addressof(info.body), sizeof(info.body)); + } + + template + bool IsBlank(const Block &block) { + if constexpr (std::is_same::value) { + static_assert(sizeof(BlankSerialNumberString) <= sizeof(SerialNumberBlock::serial_number)); + return std::memcmp(block.serial_number.str, BlankSerialNumberString, sizeof(BlankSerialNumberString) - 1) == 0 || IsBlank(std::addressof(block), Block::Size - sizeof(block.crc)); + } else if constexpr (Block::IsCrcBlock) { + return IsBlank(std::addressof(block), Block::Size - sizeof(block.crc)); + } else { + return IsBlank(std::addressof(block), Block::Size - sizeof(block.sha256_hash)); + } + } + + template + bool IsValid(const Block &block, size_t size = 0) { + if constexpr (Block::IsCrcBlock) { + return GetCrc16(std::addressof(block), Block::Size - sizeof(block.crc)) == block.crc; + } else { + static_assert(Block::IsShaBlock); + return IsValidSha256Hash(block.sha256_hash, std::addressof(block), size != 0 ? size : Block::Size - sizeof(block.sha256_hash)); + } + } + + bool IsValidHeader(const CalibrationInfo &cal) { + return IsValid(cal.header) && cal.header.body_size <= CalibrationInfoBodySizeMax && IsValid(cal.header, cal.body); + } + + bool IsValidSerialNumber(const char *sn) { + for (size_t i = 0; i < std::strlen(sn); i++) { + if (!std::isalnum(static_cast(sn[i]))) { + return false; + } + } + return true; + } + + void GetSerialNumber(char *dst, const CalibrationInfo &info) { + std::memcpy(dst, std::addressof(info.GetBlock()), sizeof(info.GetBlock().serial_number)); + dst[sizeof(info.GetBlock().serial_number) + 1] = '\x00'; + } + + bool IsValidSerialNumber(const CalibrationInfo &cal) { + char sn[0x20] = {}; + ON_SCOPE_EXIT { std::memset(sn, 0, sizeof(sn)); }; + + GetSerialNumber(sn, cal); + return IsValidSerialNumber(sn); + } + + bool IsValid(const CalibrationInfo &cal) { + return IsValidHeader(cal) && + IsValid(cal.GetBlock()) && + IsValid(cal.GetBlock()) && + IsValid(cal.GetBlock()) && + IsValid(cal.GetBlock()) && + IsValid(cal.GetBlock()) && + IsValid(cal.GetBlock()) && + IsValid(cal.GetBlock()) && + IsValid(cal.GetBlock()) && + IsValidSerialNumber(cal); + } + + bool ContainsCorrectDeviceId(const EccB233DeviceCertificateBlock &block, u64 device_id) { + static constexpr size_t DeviceIdOffset = 0xB4; + char expected_device_id[sizeof("NX0011223344556677")] = {}; + ON_SCOPE_EXIT { std::memset(expected_device_id, 0, sizeof(expected_device_id)); }; + + std::snprintf(expected_device_id, sizeof(expected_device_id), "NX%016lX", device_id); + return std::memcmp(expected_device_id, std::addressof(block.device_certificate.data[DeviceIdOffset]), sizeof(expected_device_id) - 1) == 0; + } + + bool ContainsCorrectDeviceId(const CalibrationInfo &cal) { + return ContainsCorrectDeviceId(cal.GetBlock(), exosphere::GetDeviceId()); + } + + bool IsValidForSecureBackup(const CalibrationInfo &cal) { + return IsValid(cal) && ContainsCorrectDeviceId(cal); + } + + bool IsBlank(const CalibrationInfo &cal) { + return IsBlank(cal.GetBlock()) || + IsBlank(cal.GetBlock()) || + IsBlank(cal.GetBlock()) || + IsBlank(cal.GetBlock()) || + IsBlank(cal.GetBlock()) || + IsBlank(cal.GetBlock()) || + IsBlank(cal.GetBlock()) || + IsBlank(cal.GetBlock()); + } + + void ReadStorageCalibrationBinary(CalibrationInfo *out) { + FsStorage calibration_binary_storage; + R_ABORT_UNLESS(fsOpenBisStorage(&calibration_binary_storage, FsBisPartitionId_CalibrationBinary)); + ON_SCOPE_EXIT { fsStorageClose(&calibration_binary_storage); }; + + R_ABORT_UNLESS(fsStorageRead(&calibration_binary_storage, 0, out, sizeof(*out))); + } + + constexpr inline s64 SecureCalibrationInfoBackupOffset = 3_MB; + + constexpr inline const u8 SecureCalibrationBinaryBackupIv[crypto::Aes128CtrDecryptor::IvSize] = {}; + + void ReadStorageEncryptedSecureCalibrationBinaryBackupUnsafe(SecureCalibrationInfoBackup *out) { + FsStorage calibration_binary_storage; + R_ABORT_UNLESS(fsOpenBisStorage(&calibration_binary_storage, FsBisPartitionId_CalibrationBinary)); + ON_SCOPE_EXIT { fsStorageClose(&calibration_binary_storage); }; + + R_ABORT_UNLESS(fsStorageRead(&calibration_binary_storage, SecureCalibrationInfoBackupOffset, out, sizeof(*out))); + } + + void WriteStorageEncryptedSecureCalibrationBinaryBackupUnsafe(const SecureCalibrationInfoBackup *src) { + FsStorage calibration_binary_storage; + R_ABORT_UNLESS(fsOpenBisStorage(&calibration_binary_storage, FsBisPartitionId_CalibrationBinary)); + ON_SCOPE_EXIT { fsStorageClose(&calibration_binary_storage); }; + + R_ABORT_UNLESS(fsStorageWrite(&calibration_binary_storage, SecureCalibrationInfoBackupOffset, src, sizeof(*src))); + } + + void GenerateSecureCalibrationBinaryBackupKey(void *dst, size_t dst_size) { + static constexpr const u8 SecureCalibrationBinaryBackupKeySource[crypto::Aes128CtrDecryptor::KeySize] = { '|', '-', 'A', 'M', 'S', '-', 'C', 'A', 'L', '0', '-', 'K', 'E', 'Y', '-', '|' }; + spl::AccessKey access_key; + ON_SCOPE_EXIT { crypto::ClearMemory(std::addressof(access_key), sizeof(access_key)); }; + + /* Generate a personalized kek. */ + R_ABORT_UNLESS(spl::GenerateAesKek(std::addressof(access_key), SecureCalibrationBinaryBackupKeySource, sizeof(SecureCalibrationBinaryBackupKeySource), 0, 1)); + + /* Generate a personalized key. */ + R_ABORT_UNLESS(spl::GenerateAesKey(dst, dst_size, access_key, SecureCalibrationBinaryBackupKeySource, sizeof(SecureCalibrationBinaryBackupKeySource))); + } + + bool ReadStorageSecureCalibrationBinaryBackup(SecureCalibrationInfoBackup *out) { + /* Read the data. */ + ReadStorageEncryptedSecureCalibrationBinaryBackupUnsafe(out); + + /* Don't leak any data unless we validate. */ + auto clear_guard = SCOPE_GUARD { std::memset(out, 0, sizeof(*out)); }; + + { + /* Create a buffer to hold our key. */ + u8 key[crypto::Aes128CtrDecryptor::KeySize]; + ON_SCOPE_EXIT { crypto::ClearMemory(key, sizeof(key)); }; + + /* Generate the key. */ + GenerateSecureCalibrationBinaryBackupKey(key, sizeof(key)); + + /* Decrypt the data in place. */ + crypto::DecryptAes128Ctr(out, sizeof(*out), key, sizeof(key), SecureCalibrationBinaryBackupIv, sizeof(SecureCalibrationBinaryBackupIv), out, sizeof(*out)); + } + + /* Generate a hash for the data. */ + if (!IsValidSha256Hash(out->hash, std::addressof(out->info), sizeof(out->info))) { + return false; + } + + /* Validate the backup. */ + if (!IsValidForSecureBackup(out->info)) { + return false; + } + + /* Our backup is valid. */ + clear_guard.Cancel(); + return true; + } + + void WriteStorageSecureCalibrationBinaryBackup(SecureCalibrationInfoBackup *src) { + /* Clear the input once we've written it. */ + ON_SCOPE_EXIT { std::memset(src, 0, sizeof(*src)); }; + + /* Ensure that the input is valid. */ + AMS_ABORT_UNLESS(IsValidForSecureBackup(src->info)); + + /* Set the Sha256 hash. */ + crypto::GenerateSha256Hash(std::addressof(src->hash), sizeof(src->hash), std::addressof(src->info), sizeof(src->info)); + + /* Validate the hash. */ + AMS_ABORT_UNLESS(IsValidSha256Hash(src->hash, std::addressof(src->info), sizeof(src->info))); + + /* Encrypt the data. */ + { + /* Create a buffer to hold our key. */ + u8 key[crypto::Aes128CtrDecryptor::KeySize]; + ON_SCOPE_EXIT { crypto::ClearMemory(key, sizeof(key)); }; + + /* Generate the key. */ + GenerateSecureCalibrationBinaryBackupKey(key, sizeof(key)); + + /* Encrypt the data in place. */ + crypto::EncryptAes128Ctr(src, sizeof(*src), key, sizeof(key), SecureCalibrationBinaryBackupIv, sizeof(SecureCalibrationBinaryBackupIv), src, sizeof(*src)); + } + + /* Write the encrypted data. */ + WriteStorageEncryptedSecureCalibrationBinaryBackupUnsafe(src); + } + + void GetBackupFileName(char *dst, size_t dst_size, const CalibrationInfo &info) { + char sn[0x20] = {}; + ON_SCOPE_EXIT { std::memset(sn, 0, sizeof(sn)); }; + + + if (IsValidForSecureBackup(info)) { + GetSerialNumber(sn, info); + std::snprintf(dst, dst_size, "automatic_backups/%s_PRODINFO.bin", sn); + } else { + Sha256Hash hash; + crypto::GenerateSha256Hash(std::addressof(hash), sizeof(hash), std::addressof(info), sizeof(info)); + ON_SCOPE_EXIT { crypto::ClearMemory(std::addressof(hash), sizeof(hash)); }; + + if (IsValid(info)) { + if (IsBlank(info)) { + std::snprintf(dst, dst_size, "automatic_backups/BLANK_PRODINFO_%02X%02X%02X%02X.bin", hash.data[0], hash.data[1], hash.data[2], hash.data[3]); + } else { + GetSerialNumber(sn, info); + std::snprintf(dst, dst_size, "automatic_backups/%s_PRODINFO_%02X%02X%02X%02X.bin", sn, hash.data[0], hash.data[1], hash.data[2], hash.data[3]); + } + } else { + std::snprintf(dst, dst_size, "automatic_backups/INVALID_PRODINFO_%02X%02X%02X%02X.bin", hash.data[0], hash.data[1], hash.data[2], hash.data[3]); + } + } + } + + void SafeRead(ams::fs::fsa::IFile *file, s64 offset, void *dst, size_t size) { + size_t read_size = 0; + R_ABORT_UNLESS(file->Read(std::addressof(read_size), offset, dst, size)); + AMS_ABORT_UNLESS(read_size == size); + } + + alignas(os::MemoryPageSize) CalibrationInfo g_temp_calibration_info = {}; + + void SaveProdInfoBackup(std::optional *dst, const CalibrationInfo &info) { + char backup_fn[0x100]; + GetBackupFileName(backup_fn, sizeof(backup_fn), info); + + /* Create the file, in case it does not exist. */ + mitm::fs::CreateAtmosphereSdFile(backup_fn, sizeof(CalibrationInfo), ams::fs::CreateOption_None); + + /* Open the file. */ + FsFile libnx_file; + R_ABORT_UNLESS(mitm::fs::OpenAtmosphereSdFile(std::addressof(libnx_file), backup_fn, ams::fs::OpenMode_ReadWrite)); + + /* Create our accessor. */ + std::unique_ptr file = std::make_unique(libnx_file); + AMS_ABORT_UNLESS(file != nullptr); + + /* Check if we're valid already. */ + bool valid = false; + s64 size; + R_ABORT_UNLESS(file->GetSize(std::addressof(size))); + if (size == sizeof(CalibrationInfo)) { + SafeRead(file.get(), 0, std::addressof(g_temp_calibration_info), sizeof(g_temp_calibration_info)); + ON_SCOPE_EXIT { std::memset(std::addressof(g_temp_calibration_info), 0, sizeof(g_temp_calibration_info)); }; + + if (std::memcmp(std::addressof(info), std::addressof(g_temp_calibration_info), sizeof(CalibrationInfo)) == 0) { + valid = true; + } + } + + /* If we're not valid, we need to save. */ + if (!valid) { + R_ABORT_UNLESS(file->Write(0, std::addressof(info), sizeof(info), ams::fs::WriteOption::Flush)); + } + + /* Save our storage to output. */ + if (dst != nullptr) { + dst->emplace(std::move(file)); + } + } + + void GetRandomEntropy(Sha256Hash *dst) { + AMS_ASSERT(dst != nullptr); + + u64 data_buffer[3] = {}; + ON_SCOPE_EXIT { crypto::ClearMemory(data_buffer, sizeof(data_buffer)); }; + + data_buffer[0] = os::GetSystemTick().GetInt64Value(); + R_ABORT_UNLESS(svc::GetInfo(data_buffer + 1, svc::InfoType_AliasRegionAddress, svc::PseudoHandle::CurrentProcess, 0)); + if (hos::GetVersion() >= hos::Version_2_0_0) { + R_ABORT_UNLESS(svc::GetInfo(data_buffer + 2, svc::InfoType_RandomEntropy, svc::InvalidHandle, (data_buffer[0] ^ (data_buffer[1] >> 24)) & 3)); + } else { + data_buffer[2] = os::GetSystemTick().GetInt64Value(); + } + + return crypto::GenerateSha256Hash(dst, sizeof(*dst), data_buffer, sizeof(data_buffer)); + } + + void FillWithGarbage(void *dst, size_t dst_size) { + /* Get random entropy. */ + Sha256Hash entropy; + ON_SCOPE_EXIT { crypto::ClearMemory(std::addressof(entropy), sizeof(entropy)); }; + GetRandomEntropy(std::addressof(entropy)); + + /* Clear dst. */ + std::memset(dst, 0xCC, dst_size); + + /* Encrypt dst. */ + static_assert(sizeof(entropy) == crypto::Aes128CtrEncryptor::KeySize + crypto::Aes128CtrEncryptor::IvSize); + crypto::EncryptAes128Ctr(dst, dst_size, entropy.data, crypto::Aes128CtrEncryptor::KeySize, entropy.data + crypto::Aes128CtrEncryptor::KeySize, crypto::Aes128CtrEncryptor::IvSize, dst, dst_size); + } + + alignas(os::MemoryPageSize) CalibrationInfo g_calibration_info = {}; + alignas(os::MemoryPageSize) SecureCalibrationInfoBackup g_secure_calibration_info_backup = {}; + + std::optional g_blank_prodinfo_file; + std::optional g_prodinfo_backup_file; + std::optional g_fake_secure_backup_storage; + + } + + void InitializeProdInfoManagement(char *out_name, size_t out_name_size) { + /* First, get our options. */ + const bool should_blank = exosphere::ShouldBlankProdInfo(); + bool allow_writes = exosphere::ShouldAllowWritesToProdInfo(); + + /* Next, read our prodinfo. */ + ReadStorageCalibrationBinary(std::addressof(g_calibration_info)); + ON_SCOPE_EXIT { FillWithGarbage(std::addressof(g_calibration_info), sizeof(g_calibration_info)); }; + + /* Next, check if we have a secure backup. */ + bool has_secure_backup = ReadStorageSecureCalibrationBinaryBackup(std::addressof(g_secure_calibration_info_backup)); + ON_SCOPE_EXIT { FillWithGarbage(std::addressof(g_secure_calibration_info_backup), sizeof(g_secure_calibration_info_backup)); }; + + /* Only allow writes if we have a secure backup. */ + if (allow_writes && !has_secure_backup) { + /* If we can make a secure backup, great. */ + if (IsValidForSecureBackup(g_calibration_info)) { + g_secure_calibration_info_backup.info = g_calibration_info; + WriteStorageSecureCalibrationBinaryBackup(std::addressof(g_secure_calibration_info_backup)); + g_secure_calibration_info_backup.info = g_calibration_info; + has_secure_backup = true; + } else { + /* Don't allow writes if we can't make a secure backup. */ + allow_writes = false; + } + } + + /* Ensure our preconditions are met. */ + AMS_ABORT_UNLESS(!allow_writes || has_secure_backup); + + /* Save our backup. We always prefer to save a secure copy of data over a non-secure one. */ + if (has_secure_backup) { + GetSerialNumber(out_name, g_secure_calibration_info_backup.info); + SaveProdInfoBackup(std::addressof(g_prodinfo_backup_file), g_secure_calibration_info_backup.info); + } else { + if (IsValid(g_calibration_info) && !IsBlank(g_calibration_info)) { + GetSerialNumber(out_name, g_calibration_info); + } else { + Sha256Hash hash; + ON_SCOPE_EXIT { crypto::ClearMemory(std::addressof(hash), sizeof(hash)); }; + crypto::GenerateSha256Hash(std::addressof(hash), sizeof(hash), std::addressof(g_calibration_info), sizeof(g_calibration_info)); + + std::snprintf(out_name, out_name_size, "%02X%02X%02X%02X", hash.data[0], hash.data[1], hash.data[2], hash.data[3]); + } + SaveProdInfoBackup(std::addressof(g_prodinfo_backup_file), g_calibration_info); + } + + /* Ensure we made our backup. */ + AMS_ABORT_UNLESS(g_prodinfo_backup_file); + + /* If we should blank our prodinfo, do so. */ + if (should_blank) { + Blank(g_calibration_info); + SaveProdInfoBackup(std::addressof(g_blank_prodinfo_file), g_calibration_info); + } + + /* Ensure that we have a blank file if we need one. */ + AMS_ABORT_UNLESS(!should_blank || g_blank_prodinfo_file); + + /* Setup our memory storage. */ + g_fake_secure_backup_storage.emplace(std::addressof(g_secure_calibration_info_backup), sizeof(g_secure_calibration_info_backup)); + } + +} diff --git a/stratosphere/ams_mitm/source/amsmitm_prodinfo_utils.hpp b/stratosphere/ams_mitm/source/amsmitm_prodinfo_utils.hpp new file mode 100644 index 000000000..d37290601 --- /dev/null +++ b/stratosphere/ams_mitm/source/amsmitm_prodinfo_utils.hpp @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2018-2020 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 . + */ +#pragma once +#include + +namespace ams::mitm { + + void InitializeProdInfoManagement(char *out_name, size_t out_name_size); + + + +} diff --git a/stratosphere/spl/source/spl_main.cpp b/stratosphere/spl/source/spl_main.cpp index 3b26e7893..fe0df90b2 100644 --- a/stratosphere/spl/source/spl_main.cpp +++ b/stratosphere/spl/source/spl_main.cpp @@ -104,7 +104,7 @@ namespace { constexpr size_t GeneralMaxSessions = 7; constexpr sm::ServiceName CryptoServiceName = sm::ServiceName::Encode("spl:mig"); - constexpr size_t CryptoMaxSessions = 6; + constexpr size_t CryptoMaxSessions = 7; constexpr sm::ServiceName SslServiceName = sm::ServiceName::Encode("spl:ssl"); constexpr size_t SslMaxSessions = 2;