amiibo_crypto.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. // SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-3.0-or-later
  3. // SPDX-FileCopyrightText: Copyright 2017 socram8888/amiitool
  4. // SPDX-License-Identifier: MIT
  5. #include <array>
  6. #include <mbedtls/aes.h>
  7. #include <mbedtls/hmac_drbg.h>
  8. #include "common/fs/file.h"
  9. #include "common/fs/path_util.h"
  10. #include "common/logging/log.h"
  11. #include "core/hle/service/mii/mii_manager.h"
  12. #include "core/hle/service/nfp/amiibo_crypto.h"
  13. namespace Service::NFP::AmiiboCrypto {
  14. bool IsAmiiboValid(const EncryptedNTAG215File& ntag_file) {
  15. const auto& amiibo_data = ntag_file.user_memory;
  16. LOG_DEBUG(Service_NFP, "uuid_lock=0x{0:x}", ntag_file.static_lock);
  17. LOG_DEBUG(Service_NFP, "compability_container=0x{0:x}", ntag_file.compability_container);
  18. LOG_INFO(Service_NFP, "write_count={}", amiibo_data.write_counter);
  19. LOG_INFO(Service_NFP, "character_id=0x{0:x}", amiibo_data.model_info.character_id);
  20. LOG_INFO(Service_NFP, "character_variant={}", amiibo_data.model_info.character_variant);
  21. LOG_INFO(Service_NFP, "amiibo_type={}", amiibo_data.model_info.amiibo_type);
  22. LOG_INFO(Service_NFP, "model_number=0x{0:x}", amiibo_data.model_info.model_number);
  23. LOG_INFO(Service_NFP, "series={}", amiibo_data.model_info.series);
  24. LOG_DEBUG(Service_NFP, "fixed_value=0x{0:x}", amiibo_data.model_info.constant_value);
  25. LOG_DEBUG(Service_NFP, "tag_dynamic_lock=0x{0:x}", ntag_file.dynamic_lock);
  26. LOG_DEBUG(Service_NFP, "tag_CFG0=0x{0:x}", ntag_file.CFG0);
  27. LOG_DEBUG(Service_NFP, "tag_CFG1=0x{0:x}", ntag_file.CFG1);
  28. // Validate UUID
  29. constexpr u8 CT = 0x88; // As defined in `ISO / IEC 14443 - 3`
  30. if ((CT ^ ntag_file.uuid[0] ^ ntag_file.uuid[1] ^ ntag_file.uuid[2]) != ntag_file.uuid[3]) {
  31. return false;
  32. }
  33. if ((ntag_file.uuid[4] ^ ntag_file.uuid[5] ^ ntag_file.uuid[6] ^ ntag_file.uuid[7]) !=
  34. ntag_file.uuid[8]) {
  35. return false;
  36. }
  37. // Check against all know constants on an amiibo binary
  38. if (ntag_file.static_lock != 0xE00F) {
  39. return false;
  40. }
  41. if (ntag_file.compability_container != 0xEEFF10F1U) {
  42. return false;
  43. }
  44. if (amiibo_data.constant_value != 0xA5) {
  45. return false;
  46. }
  47. if (amiibo_data.model_info.constant_value != 0x02) {
  48. return false;
  49. }
  50. // dynamic_lock value apparently is not constant
  51. // ntag_file.dynamic_lock == 0x0F0001
  52. if (ntag_file.CFG0 != 0x04000000U) {
  53. return false;
  54. }
  55. if (ntag_file.CFG1 != 0x5F) {
  56. return false;
  57. }
  58. return true;
  59. }
  60. NTAG215File NfcDataToEncodedData(const EncryptedNTAG215File& nfc_data) {
  61. NTAG215File encoded_data{};
  62. memcpy(encoded_data.uuid2.data(), nfc_data.uuid.data() + 0x8, sizeof(encoded_data.uuid2));
  63. encoded_data.static_lock = nfc_data.static_lock;
  64. encoded_data.compability_container = nfc_data.compability_container;
  65. encoded_data.hmac_data = nfc_data.user_memory.hmac_data;
  66. encoded_data.constant_value = nfc_data.user_memory.constant_value;
  67. encoded_data.write_counter = nfc_data.user_memory.write_counter;
  68. encoded_data.settings = nfc_data.user_memory.settings;
  69. encoded_data.owner_mii = nfc_data.user_memory.owner_mii;
  70. encoded_data.title_id = nfc_data.user_memory.title_id;
  71. encoded_data.applicaton_write_counter = nfc_data.user_memory.applicaton_write_counter;
  72. encoded_data.application_area_id = nfc_data.user_memory.application_area_id;
  73. encoded_data.unknown = nfc_data.user_memory.unknown;
  74. encoded_data.hash = nfc_data.user_memory.hash;
  75. encoded_data.application_area = nfc_data.user_memory.application_area;
  76. encoded_data.hmac_tag = nfc_data.user_memory.hmac_tag;
  77. memcpy(encoded_data.uuid.data(), nfc_data.uuid.data(), sizeof(encoded_data.uuid));
  78. encoded_data.model_info = nfc_data.user_memory.model_info;
  79. encoded_data.keygen_salt = nfc_data.user_memory.keygen_salt;
  80. encoded_data.dynamic_lock = nfc_data.dynamic_lock;
  81. encoded_data.CFG0 = nfc_data.CFG0;
  82. encoded_data.CFG1 = nfc_data.CFG1;
  83. encoded_data.password = nfc_data.password;
  84. return encoded_data;
  85. }
  86. EncryptedNTAG215File EncodedDataToNfcData(const NTAG215File& encoded_data) {
  87. EncryptedNTAG215File nfc_data{};
  88. memcpy(nfc_data.uuid.data() + 0x8, encoded_data.uuid2.data(), sizeof(encoded_data.uuid2));
  89. memcpy(nfc_data.uuid.data(), encoded_data.uuid.data(), sizeof(encoded_data.uuid));
  90. nfc_data.static_lock = encoded_data.static_lock;
  91. nfc_data.compability_container = encoded_data.compability_container;
  92. nfc_data.user_memory.hmac_data = encoded_data.hmac_data;
  93. nfc_data.user_memory.constant_value = encoded_data.constant_value;
  94. nfc_data.user_memory.write_counter = encoded_data.write_counter;
  95. nfc_data.user_memory.settings = encoded_data.settings;
  96. nfc_data.user_memory.owner_mii = encoded_data.owner_mii;
  97. nfc_data.user_memory.title_id = encoded_data.title_id;
  98. nfc_data.user_memory.applicaton_write_counter = encoded_data.applicaton_write_counter;
  99. nfc_data.user_memory.application_area_id = encoded_data.application_area_id;
  100. nfc_data.user_memory.unknown = encoded_data.unknown;
  101. nfc_data.user_memory.hash = encoded_data.hash;
  102. nfc_data.user_memory.application_area = encoded_data.application_area;
  103. nfc_data.user_memory.hmac_tag = encoded_data.hmac_tag;
  104. nfc_data.user_memory.model_info = encoded_data.model_info;
  105. nfc_data.user_memory.keygen_salt = encoded_data.keygen_salt;
  106. nfc_data.dynamic_lock = encoded_data.dynamic_lock;
  107. nfc_data.CFG0 = encoded_data.CFG0;
  108. nfc_data.CFG1 = encoded_data.CFG1;
  109. nfc_data.password = encoded_data.password;
  110. return nfc_data;
  111. }
  112. u32 GetTagPassword(const TagUuid& uuid) {
  113. // Verifiy that the generated password is correct
  114. u32 password = 0xAA ^ (uuid[1] ^ uuid[3]);
  115. password &= (0x55 ^ (uuid[2] ^ uuid[4])) << 8;
  116. password &= (0xAA ^ (uuid[3] ^ uuid[5])) << 16;
  117. password &= (0x55 ^ (uuid[4] ^ uuid[6])) << 24;
  118. return password;
  119. }
  120. HashSeed GetSeed(const NTAG215File& data) {
  121. HashSeed seed{
  122. .magic = data.write_counter,
  123. .padding = {},
  124. .uuid1 = {},
  125. .uuid2 = {},
  126. .keygen_salt = data.keygen_salt,
  127. };
  128. // Copy the first 8 bytes of uuid
  129. memcpy(seed.uuid1.data(), data.uuid.data(), sizeof(seed.uuid1));
  130. memcpy(seed.uuid2.data(), data.uuid.data(), sizeof(seed.uuid2));
  131. return seed;
  132. }
  133. std::vector<u8> GenerateInternalKey(const InternalKey& key, const HashSeed& seed) {
  134. const std::size_t seedPart1Len = sizeof(key.magic_bytes) - key.magic_length;
  135. const std::size_t string_size = key.type_string.size();
  136. std::vector<u8> output(string_size + seedPart1Len);
  137. // Copy whole type string
  138. memccpy(output.data(), key.type_string.data(), '\0', string_size);
  139. // Append (16 - magic_length) from the input seed
  140. memcpy(output.data() + string_size, &seed, seedPart1Len);
  141. // Append all bytes from magicBytes
  142. output.insert(output.end(), key.magic_bytes.begin(),
  143. key.magic_bytes.begin() + key.magic_length);
  144. output.insert(output.end(), seed.uuid1.begin(), seed.uuid1.end());
  145. output.insert(output.end(), seed.uuid2.begin(), seed.uuid2.end());
  146. for (std::size_t i = 0; i < sizeof(seed.keygen_salt); i++) {
  147. output.emplace_back(static_cast<u8>(seed.keygen_salt[i] ^ key.xor_pad[i]));
  148. }
  149. return output;
  150. }
  151. void CryptoInit(CryptoCtx& ctx, mbedtls_md_context_t& hmac_ctx, const HmacKey& hmac_key,
  152. const std::vector<u8>& seed) {
  153. // Initialize context
  154. ctx.used = false;
  155. ctx.counter = 0;
  156. ctx.buffer_size = sizeof(ctx.counter) + seed.size();
  157. memcpy(ctx.buffer.data() + sizeof(u16), seed.data(), seed.size());
  158. // Initialize HMAC context
  159. mbedtls_md_init(&hmac_ctx);
  160. mbedtls_md_setup(&hmac_ctx, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 1);
  161. mbedtls_md_hmac_starts(&hmac_ctx, hmac_key.data(), hmac_key.size());
  162. }
  163. void CryptoStep(CryptoCtx& ctx, mbedtls_md_context_t& hmac_ctx, DrgbOutput& output) {
  164. // If used at least once, reinitialize the HMAC
  165. if (ctx.used) {
  166. mbedtls_md_hmac_reset(&hmac_ctx);
  167. }
  168. ctx.used = true;
  169. // Store counter in big endian, and increment it
  170. ctx.buffer[0] = static_cast<u8>(ctx.counter >> 8);
  171. ctx.buffer[1] = static_cast<u8>(ctx.counter >> 0);
  172. ctx.counter++;
  173. // Do HMAC magic
  174. mbedtls_md_hmac_update(&hmac_ctx, reinterpret_cast<const unsigned char*>(ctx.buffer.data()),
  175. ctx.buffer_size);
  176. mbedtls_md_hmac_finish(&hmac_ctx, output.data());
  177. }
  178. DerivedKeys GenerateKey(const InternalKey& key, const NTAG215File& data) {
  179. const auto seed = GetSeed(data);
  180. // Generate internal seed
  181. const std::vector<u8> internal_key = GenerateInternalKey(key, seed);
  182. // Initialize context
  183. CryptoCtx ctx{};
  184. mbedtls_md_context_t hmac_ctx;
  185. CryptoInit(ctx, hmac_ctx, key.hmac_key, internal_key);
  186. // Generate derived keys
  187. DerivedKeys derived_keys{};
  188. std::array<DrgbOutput, 2> temp{};
  189. CryptoStep(ctx, hmac_ctx, temp[0]);
  190. CryptoStep(ctx, hmac_ctx, temp[1]);
  191. memcpy(&derived_keys, temp.data(), sizeof(DerivedKeys));
  192. // Cleanup context
  193. mbedtls_md_free(&hmac_ctx);
  194. return derived_keys;
  195. }
  196. void Cipher(const DerivedKeys& keys, const NTAG215File& in_data, NTAG215File& out_data) {
  197. mbedtls_aes_context aes;
  198. std::size_t nc_off = 0;
  199. std::array<u8, sizeof(keys.aes_iv)> nonce_counter{};
  200. std::array<u8, sizeof(keys.aes_iv)> stream_block{};
  201. const auto aes_key_size = static_cast<u32>(keys.aes_key.size() * 8);
  202. mbedtls_aes_setkey_enc(&aes, keys.aes_key.data(), aes_key_size);
  203. memcpy(nonce_counter.data(), keys.aes_iv.data(), sizeof(keys.aes_iv));
  204. constexpr std::size_t encrypted_data_size = HMAC_TAG_START - SETTINGS_START;
  205. mbedtls_aes_crypt_ctr(&aes, encrypted_data_size, &nc_off, nonce_counter.data(),
  206. stream_block.data(),
  207. reinterpret_cast<const unsigned char*>(&in_data.settings),
  208. reinterpret_cast<unsigned char*>(&out_data.settings));
  209. // Copy the rest of the data directly
  210. out_data.uuid2 = in_data.uuid2;
  211. out_data.static_lock = in_data.static_lock;
  212. out_data.compability_container = in_data.compability_container;
  213. out_data.constant_value = in_data.constant_value;
  214. out_data.write_counter = in_data.write_counter;
  215. out_data.uuid = in_data.uuid;
  216. out_data.model_info = in_data.model_info;
  217. out_data.keygen_salt = in_data.keygen_salt;
  218. out_data.dynamic_lock = in_data.dynamic_lock;
  219. out_data.CFG0 = in_data.CFG0;
  220. out_data.CFG1 = in_data.CFG1;
  221. out_data.password = in_data.password;
  222. }
  223. bool LoadKeys(InternalKey& locked_secret, InternalKey& unfixed_info) {
  224. const auto yuzu_keys_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::KeysDir);
  225. const Common::FS::IOFile keys_file{yuzu_keys_dir / "key_retail.bin",
  226. Common::FS::FileAccessMode::Read,
  227. Common::FS::FileType::BinaryFile};
  228. if (!keys_file.IsOpen()) {
  229. LOG_ERROR(Service_NFP, "No keys detected");
  230. return false;
  231. }
  232. if (keys_file.Read(unfixed_info) != 1) {
  233. LOG_ERROR(Service_NFP, "Failed to read unfixed_info");
  234. return false;
  235. }
  236. if (keys_file.Read(locked_secret) != 1) {
  237. LOG_ERROR(Service_NFP, "Failed to read locked-secret");
  238. return false;
  239. }
  240. return true;
  241. }
  242. bool DecodeAmiibo(const EncryptedNTAG215File& encrypted_tag_data, NTAG215File& tag_data) {
  243. InternalKey locked_secret{};
  244. InternalKey unfixed_info{};
  245. if (!LoadKeys(locked_secret, unfixed_info)) {
  246. return false;
  247. }
  248. // Generate keys
  249. NTAG215File encoded_data = NfcDataToEncodedData(encrypted_tag_data);
  250. const auto data_keys = GenerateKey(unfixed_info, encoded_data);
  251. const auto tag_keys = GenerateKey(locked_secret, encoded_data);
  252. // Decrypt
  253. Cipher(data_keys, encoded_data, tag_data);
  254. // Regenerate tag HMAC. Note: order matters, data HMAC depends on tag HMAC!
  255. constexpr std::size_t input_length = DYNAMIC_LOCK_START - UUID_START;
  256. mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), tag_keys.hmac_key.data(),
  257. sizeof(HmacKey), reinterpret_cast<const unsigned char*>(&tag_data.uuid),
  258. input_length, reinterpret_cast<unsigned char*>(&tag_data.hmac_tag));
  259. // Regenerate data HMAC
  260. constexpr std::size_t input_length2 = DYNAMIC_LOCK_START - WRITE_COUNTER_START;
  261. mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), data_keys.hmac_key.data(),
  262. sizeof(HmacKey),
  263. reinterpret_cast<const unsigned char*>(&tag_data.write_counter), input_length2,
  264. reinterpret_cast<unsigned char*>(&tag_data.hmac_data));
  265. if (tag_data.hmac_data != encrypted_tag_data.user_memory.hmac_data) {
  266. LOG_ERROR(Service_NFP, "hmac_data doesn't match");
  267. return false;
  268. }
  269. if (tag_data.hmac_tag != encrypted_tag_data.user_memory.hmac_tag) {
  270. LOG_ERROR(Service_NFP, "hmac_tag doesn't match");
  271. return false;
  272. }
  273. return true;
  274. }
  275. bool EncodeAmiibo(const NTAG215File& tag_data, EncryptedNTAG215File& encrypted_tag_data) {
  276. InternalKey locked_secret{};
  277. InternalKey unfixed_info{};
  278. if (!LoadKeys(locked_secret, unfixed_info)) {
  279. return false;
  280. }
  281. // Generate keys
  282. const auto data_keys = GenerateKey(unfixed_info, tag_data);
  283. const auto tag_keys = GenerateKey(locked_secret, tag_data);
  284. NTAG215File encoded_tag_data{};
  285. // Generate tag HMAC
  286. constexpr std::size_t input_length = DYNAMIC_LOCK_START - UUID_START;
  287. constexpr std::size_t input_length2 = HMAC_TAG_START - WRITE_COUNTER_START;
  288. mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), tag_keys.hmac_key.data(),
  289. sizeof(HmacKey), reinterpret_cast<const unsigned char*>(&tag_data.uuid),
  290. input_length, reinterpret_cast<unsigned char*>(&encoded_tag_data.hmac_tag));
  291. // Init mbedtls HMAC context
  292. mbedtls_md_context_t ctx;
  293. mbedtls_md_init(&ctx);
  294. mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 1);
  295. // Generate data HMAC
  296. mbedtls_md_hmac_starts(&ctx, data_keys.hmac_key.data(), sizeof(HmacKey));
  297. mbedtls_md_hmac_update(&ctx, reinterpret_cast<const unsigned char*>(&tag_data.write_counter),
  298. input_length2); // Data
  299. mbedtls_md_hmac_update(&ctx, reinterpret_cast<unsigned char*>(&encoded_tag_data.hmac_tag),
  300. sizeof(HashData)); // Tag HMAC
  301. mbedtls_md_hmac_update(&ctx, reinterpret_cast<const unsigned char*>(&tag_data.uuid),
  302. input_length);
  303. mbedtls_md_hmac_finish(&ctx, reinterpret_cast<unsigned char*>(&encoded_tag_data.hmac_data));
  304. // HMAC cleanup
  305. mbedtls_md_free(&ctx);
  306. // Encrypt
  307. Cipher(data_keys, tag_data, encoded_tag_data);
  308. // Convert back to hardware
  309. encrypted_tag_data = EncodedDataToNfcData(encoded_tag_data);
  310. return true;
  311. }
  312. } // namespace Service::NFP::AmiiboCrypto