key_manager.h 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project & 2024 suyu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #pragma once
  4. #include <array>
  5. #include <filesystem>
  6. #include <map>
  7. #include <optional>
  8. #include <span>
  9. #include <string>
  10. #include <variant>
  11. #include <fmt/format.h>
  12. #include "common/common_funcs.h"
  13. #include "common/common_types.h"
  14. #include "core/crypto/partition_data_manager.h"
  15. namespace Common::FS {
  16. class IOFile;
  17. }
  18. namespace FileSys {
  19. class ContentProvider;
  20. }
  21. namespace Loader {
  22. enum class ResultStatus : u16;
  23. }
  24. namespace Core::Crypto {
  25. using Key128 = std::array<u8, 0x10>;
  26. using Key256 = std::array<u8, 0x20>;
  27. using SHA256Hash = std::array<u8, 0x20>;
  28. enum class SignatureType {
  29. RSA_4096_SHA1 = 0x10000,
  30. RSA_2048_SHA1 = 0x10001,
  31. ECDSA_SHA1 = 0x10002,
  32. RSA_4096_SHA256 = 0x10003,
  33. RSA_2048_SHA256 = 0x10004,
  34. ECDSA_SHA256 = 0x10005,
  35. };
  36. u64 GetSignatureTypeDataSize(SignatureType type);
  37. u64 GetSignatureTypePaddingSize(SignatureType type);
  38. enum class TitleKeyType : u8 {
  39. Common = 0,
  40. Personalized = 1,
  41. };
  42. struct TicketData {
  43. std::array<u8, 0x40> issuer;
  44. union {
  45. std::array<u8, 0x100> title_key_block;
  46. struct {
  47. Key128 title_key_common;
  48. std::array<u8, 0xF0> title_key_common_pad;
  49. };
  50. };
  51. INSERT_PADDING_BYTES(0x1);
  52. TitleKeyType type;
  53. INSERT_PADDING_BYTES(0x3);
  54. u8 revision;
  55. INSERT_PADDING_BYTES(0xA);
  56. u64 ticket_id;
  57. u64 device_id;
  58. std::array<u8, 0x10> rights_id;
  59. u32 account_id;
  60. INSERT_PADDING_BYTES(0x14C);
  61. };
  62. static_assert(sizeof(TicketData) == 0x2C0, "TicketData has incorrect size.");
  63. struct RSA4096Ticket {
  64. SignatureType sig_type;
  65. std::array<u8, 0x200> sig_data;
  66. INSERT_PADDING_BYTES(0x3C);
  67. TicketData data;
  68. };
  69. static_assert(sizeof(RSA4096Ticket) == 0x500, "RSA4096Ticket has incorrect size.");
  70. struct RSA2048Ticket {
  71. SignatureType sig_type;
  72. std::array<u8, 0x100> sig_data;
  73. INSERT_PADDING_BYTES(0x3C);
  74. TicketData data;
  75. };
  76. static_assert(sizeof(RSA2048Ticket) == 0x400, "RSA2048Ticket has incorrect size.");
  77. struct ECDSATicket {
  78. SignatureType sig_type;
  79. std::array<u8, 0x3C> sig_data;
  80. INSERT_PADDING_BYTES(0x40);
  81. TicketData data;
  82. };
  83. static_assert(sizeof(ECDSATicket) == 0x340, "ECDSATicket has incorrect size.");
  84. struct Ticket {
  85. std::variant<std::monostate, RSA4096Ticket, RSA2048Ticket, ECDSATicket> data;
  86. [[nodiscard]] bool IsValid() const;
  87. [[nodiscard]] SignatureType GetSignatureType() const;
  88. [[nodiscard]] TicketData& GetData();
  89. [[nodiscard]] const TicketData& GetData() const;
  90. [[nodiscard]] u64 GetSize() const;
  91. /**
  92. * Synthesizes a common ticket given a title key and rights ID.
  93. *
  94. * @param title_key Title key to store in the ticket.
  95. * @param rights_id Rights ID the ticket is for.
  96. * @return The synthesized common ticket.
  97. */
  98. static Ticket SynthesizeCommon(Key128 title_key, const std::array<u8, 0x10>& rights_id);
  99. /**
  100. * Reads a ticket from a file.
  101. *
  102. * @param file File to read the ticket from.
  103. * @return The read ticket. If the ticket data is invalid, Ticket::IsValid() will be false.
  104. */
  105. static Ticket Read(const FileSys::VirtualFile& file);
  106. /**
  107. * Reads a ticket from a memory buffer.
  108. *
  109. * @param raw_data Buffer to read the ticket from.
  110. * @return The read ticket. If the ticket data is invalid, Ticket::IsValid() will be false.
  111. */
  112. static Ticket Read(std::span<const u8> raw_data);
  113. };
  114. static_assert(sizeof(Key128) == 16, "Key128 must be 128 bytes big.");
  115. static_assert(sizeof(Key256) == 32, "Key256 must be 256 bytes big.");
  116. template <size_t bit_size, size_t byte_size = (bit_size >> 3)>
  117. struct RSAKeyPair {
  118. std::array<u8, byte_size> encryption_key;
  119. std::array<u8, byte_size> decryption_key;
  120. std::array<u8, byte_size> modulus;
  121. std::array<u8, 4> exponent;
  122. };
  123. template <size_t bit_size, size_t byte_size>
  124. bool operator==(const RSAKeyPair<bit_size, byte_size>& lhs,
  125. const RSAKeyPair<bit_size, byte_size>& rhs) {
  126. return std::tie(lhs.encryption_key, lhs.decryption_key, lhs.modulus, lhs.exponent) ==
  127. std::tie(rhs.encryption_key, rhs.decryption_key, rhs.modulus, rhs.exponent);
  128. }
  129. template <size_t bit_size, size_t byte_size>
  130. bool operator!=(const RSAKeyPair<bit_size, byte_size>& lhs,
  131. const RSAKeyPair<bit_size, byte_size>& rhs) {
  132. return !(lhs == rhs);
  133. }
  134. enum class KeyCategory : u8 {
  135. Standard,
  136. Title,
  137. Console,
  138. };
  139. enum class S256KeyType : u64 {
  140. SDKey, // f1=SDKeyType
  141. Header, //
  142. SDKeySource, // f1=SDKeyType
  143. HeaderSource, //
  144. };
  145. enum class S128KeyType : u64 {
  146. Master, // f1=crypto revision
  147. Package1, // f1=crypto revision
  148. Package2, // f1=crypto revision
  149. Titlekek, // f1=crypto revision
  150. ETicketRSAKek, //
  151. KeyArea, // f1=crypto revision f2=type {app, ocean, system}
  152. SDSeed, //
  153. Titlekey, // f1=rights id LSB f2=rights id MSB
  154. Source, // f1=source type, f2= sub id
  155. Keyblob, // f1=crypto revision
  156. KeyblobMAC, // f1=crypto revision
  157. TSEC, //
  158. SecureBoot, //
  159. BIS, // f1=partition (0-3), f2=type {crypt, tweak}
  160. HeaderKek, //
  161. SDKek, //
  162. RSAKek, //
  163. };
  164. enum class KeyAreaKeyType : u8 {
  165. Application,
  166. Ocean,
  167. System,
  168. };
  169. enum class SourceKeyType : u8 {
  170. SDKek, //
  171. AESKekGeneration, //
  172. AESKeyGeneration, //
  173. RSAOaepKekGeneration, //
  174. Master, //
  175. Keyblob, // f2=crypto revision
  176. KeyAreaKey, // f2=KeyAreaKeyType
  177. Titlekek, //
  178. Package2, //
  179. HeaderKek, //
  180. KeyblobMAC, //
  181. ETicketKek, //
  182. ETicketKekek, //
  183. };
  184. enum class SDKeyType : u8 {
  185. Save,
  186. NCA,
  187. };
  188. enum class BISKeyType : u8 {
  189. Crypto,
  190. Tweak,
  191. };
  192. enum class RSAKekType : u8 {
  193. Mask0,
  194. Seed3,
  195. };
  196. template <typename KeyType>
  197. struct KeyIndex {
  198. KeyType type;
  199. u64 field1;
  200. u64 field2;
  201. std::string DebugInfo() const {
  202. u8 key_size = 16;
  203. if constexpr (std::is_same_v<KeyType, S256KeyType>)
  204. key_size = 32;
  205. return fmt::format("key_size={:02X}, key={:02X}, field1={:016X}, field2={:016X}", key_size,
  206. static_cast<u8>(type), field1, field2);
  207. }
  208. };
  209. // boost flat_map requires operator< for O(log(n)) lookups.
  210. template <typename KeyType>
  211. bool operator<(const KeyIndex<KeyType>& lhs, const KeyIndex<KeyType>& rhs) {
  212. return std::tie(lhs.type, lhs.field1, lhs.field2) < std::tie(rhs.type, rhs.field1, rhs.field2);
  213. }
  214. class KeyManager {
  215. public:
  216. static KeyManager& Instance() {
  217. static KeyManager instance;
  218. return instance;
  219. }
  220. KeyManager(const KeyManager&) = delete;
  221. KeyManager& operator=(const KeyManager&) = delete;
  222. KeyManager(KeyManager&&) = delete;
  223. KeyManager& operator=(KeyManager&&) = delete;
  224. bool HasKey(S128KeyType id, u64 field1 = 0, u64 field2 = 0) const;
  225. bool HasKey(S256KeyType id, u64 field1 = 0, u64 field2 = 0) const;
  226. Key128 GetKey(S128KeyType id, u64 field1 = 0, u64 field2 = 0) const;
  227. Key256 GetKey(S256KeyType id, u64 field1 = 0, u64 field2 = 0) const;
  228. Key256 GetBISKey(u8 partition_id) const;
  229. void SetKey(S128KeyType id, Key128 key, u64 field1 = 0, u64 field2 = 0);
  230. void SetKey(S256KeyType id, Key256 key, u64 field1 = 0, u64 field2 = 0);
  231. static bool KeyFileExists(bool title);
  232. // Call before using the sd seed to attempt to derive it if it doesn't exist. Needs system
  233. // save 8*43 and the private file to exist.
  234. void DeriveSDSeedLazy();
  235. bool BaseDeriveNecessary() const;
  236. void DeriveBase();
  237. void DeriveETicket(PartitionDataManager& data, const FileSys::ContentProvider& provider);
  238. void PopulateTickets();
  239. void SynthesizeTickets();
  240. void PopulateFromPartitionData(PartitionDataManager& data);
  241. const std::map<u128, Ticket>& GetCommonTickets() const;
  242. const std::map<u128, Ticket>& GetPersonalizedTickets() const;
  243. bool AddTicket(const Ticket& ticket);
  244. void ReloadKeys();
  245. bool AreKeysLoaded() const;
  246. private:
  247. KeyManager();
  248. std::map<KeyIndex<S128KeyType>, Key128> s128_keys;
  249. std::map<KeyIndex<S256KeyType>, Key256> s256_keys;
  250. // Map from rights ID to ticket
  251. std::map<u128, Ticket> common_tickets;
  252. std::map<u128, Ticket> personal_tickets;
  253. bool ticket_databases_loaded = false;
  254. std::array<std::array<u8, 0xB0>, 0x20> encrypted_keyblobs{};
  255. std::array<std::array<u8, 0x90>, 0x20> keyblobs{};
  256. std::array<u8, 576> eticket_extended_kek{};
  257. RSAKeyPair<2048> eticket_rsa_keypair{};
  258. bool dev_mode;
  259. void LoadFromFile(const std::filesystem::path& file_path, bool is_title_keys);
  260. template <size_t Size>
  261. void DeriveGeneralPurposeKeys(std::size_t crypto_revision);
  262. void DeriveETicketRSAKey();
  263. void SetKeyWrapped(S128KeyType id, Key128 key, u64 field1 = 0, u64 field2 = 0);
  264. void SetKeyWrapped(S256KeyType id, Key256 key, u64 field1 = 0, u64 field2 = 0);
  265. /// Parses the title key section of a ticket.
  266. std::optional<Key128> ParseTicketTitleKey(const Ticket& ticket);
  267. };
  268. Key128 GenerateKeyEncryptionKey(Key128 source, Key128 master, Key128 kek_seed, Key128 key_seed);
  269. Key128 DeriveKeyblobKey(const Key128& sbk, const Key128& tsec, Key128 source);
  270. Key128 DeriveKeyblobMACKey(const Key128& keyblob_key, const Key128& mac_source);
  271. Key128 DeriveMasterKey(const std::array<u8, 0x90>& keyblob, const Key128& master_source);
  272. std::array<u8, 0x90> DecryptKeyblob(const std::array<u8, 0xB0>& encrypted_keyblob,
  273. const Key128& key);
  274. std::optional<Key128> DeriveSDSeed();
  275. Loader::ResultStatus DeriveSDKeys(std::array<Key256, 2>& sd_keys, KeyManager& keys);
  276. std::vector<Ticket> GetTicketblob(const Common::FS::IOFile& ticket_save);
  277. } // namespace Core::Crypto