amiibo_crypto.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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, 2);
  63. encoded_data.static_lock = nfc_data.static_lock;
  64. encoded_data.compability_container = nfc_data.compability_container;
  65. encoded_data.unfixed_hash = nfc_data.user_memory.unfixed_hash;
  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.locked_hash = nfc_data.user_memory.locked_hash;
  77. memcpy(encoded_data.uuid.data(), nfc_data.uuid.data(), 8);
  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(), 2);
  89. memcpy(nfc_data.uuid.data(), encoded_data.uuid.data(), 8);
  90. nfc_data.static_lock = encoded_data.static_lock;
  91. nfc_data.compability_container = encoded_data.compability_container;
  92. nfc_data.user_memory.unfixed_hash = encoded_data.unfixed_hash;
  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.locked_hash = encoded_data.locked_hash;
  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. .data =
  123. {
  124. .magic = data.write_counter,
  125. .padding = {},
  126. .uuid1 = {},
  127. .uuid2 = {},
  128. .keygen_salt = data.keygen_salt,
  129. },
  130. };
  131. // Copy the first 8 bytes of uuid
  132. memcpy(seed.data.uuid1.data(), data.uuid.data(), sizeof(seed.data.uuid1));
  133. memcpy(seed.data.uuid2.data(), data.uuid.data(), sizeof(seed.data.uuid2));
  134. return seed;
  135. }
  136. void PreGenerateKey(const InternalKey& key, const HashSeed& seed, u8* output,
  137. std::size_t& outputLen) {
  138. std::size_t index = 0;
  139. // Copy whole type string
  140. memccpy(output + index, key.type_string.data(), '\0', key.type_string.size());
  141. index += key.type_string.size();
  142. // Append (16 - magic_length) from the input seed
  143. std::size_t seedPart1Len = 16 - key.magic_length;
  144. memcpy(output + index, &seed, seedPart1Len);
  145. index += seedPart1Len;
  146. // Append all bytes from magicBytes
  147. memcpy(output + index, &key.magic_bytes, key.magic_length);
  148. index += key.magic_length;
  149. // Seed 16 bytes at +0x10
  150. memcpy(output + index, &seed.raw[0x10], 16);
  151. index += 16;
  152. // 32 bytes at +0x20 from input seed xored with xor pad
  153. for (std::size_t i = 0; i < 32; i++)
  154. output[index + i] = seed.raw[i + 32] ^ key.xor_pad[i];
  155. index += 32;
  156. outputLen = index;
  157. }
  158. void CryptoInit(CryptoCtx& ctx, mbedtls_md_context_t& hmac_ctx, const HmacKey& hmac_key,
  159. const u8* seed, std::size_t seed_size) {
  160. // Initialize context
  161. ctx.used = false;
  162. ctx.counter = 0;
  163. ctx.buffer_size = sizeof(ctx.counter) + seed_size;
  164. memcpy(ctx.buffer.data() + sizeof(u16), seed, seed_size);
  165. // Initialize HMAC context
  166. mbedtls_md_init(&hmac_ctx);
  167. mbedtls_md_setup(&hmac_ctx, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 1);
  168. mbedtls_md_hmac_starts(&hmac_ctx, hmac_key.data(), hmac_key.size());
  169. }
  170. void CryptoStep(CryptoCtx& ctx, mbedtls_md_context_t& hmac_ctx, DrgbOutput& output) {
  171. // If used at least once, reinitialize the HMAC
  172. if (ctx.used) {
  173. mbedtls_md_hmac_reset(&hmac_ctx);
  174. }
  175. ctx.used = true;
  176. // Store counter in big endian, and increment it
  177. ctx.buffer[0] = static_cast<u8>(ctx.counter >> 8);
  178. ctx.buffer[1] = static_cast<u8>(ctx.counter >> 0);
  179. ctx.counter++;
  180. // Do HMAC magic
  181. mbedtls_md_hmac_update(&hmac_ctx, reinterpret_cast<const unsigned char*>(ctx.buffer.data()),
  182. ctx.buffer_size);
  183. mbedtls_md_hmac_finish(&hmac_ctx, output.data());
  184. }
  185. DerivedKeys GenerateKey(const InternalKey& key, const NTAG215File& data) {
  186. constexpr std::size_t OUTPUT_SIZE = 512;
  187. const auto seed = GetSeed(data);
  188. // Generate internal seed
  189. u8 internal_key[OUTPUT_SIZE];
  190. std::size_t internal_key_lenght = 0;
  191. PreGenerateKey(key, seed, internal_key, internal_key_lenght);
  192. // Initialize context
  193. CryptoCtx ctx{};
  194. mbedtls_md_context_t hmac_ctx;
  195. CryptoInit(ctx, hmac_ctx, key.hmac_key, internal_key, internal_key_lenght);
  196. // Generate derived keys
  197. DerivedKeys derived_keys{};
  198. std::array<DrgbOutput, 2> temp{};
  199. CryptoStep(ctx, hmac_ctx, temp[0]);
  200. CryptoStep(ctx, hmac_ctx, temp[1]);
  201. memcpy(&derived_keys, temp.data(), sizeof(DerivedKeys));
  202. // Cleanup context
  203. mbedtls_md_free(&hmac_ctx);
  204. return derived_keys;
  205. }
  206. void Cipher(const DerivedKeys& keys, const NTAG215File& in_data, NTAG215File& out_data) {
  207. mbedtls_aes_context aes;
  208. std::size_t nc_off = 0;
  209. std::array<u8, 0x10> nonce_counter{};
  210. std::array<u8, 0x10> stream_block{};
  211. mbedtls_aes_setkey_enc(&aes, keys.aes_key.data(), 128);
  212. memcpy(nonce_counter.data(), keys.aes_iv.data(), sizeof(nonce_counter));
  213. std::array<u8, sizeof(NTAG215File)> in_data_byes{};
  214. std::array<u8, sizeof(NTAG215File)> out_data_bytes{};
  215. memcpy(in_data_byes.data(), &in_data, sizeof(NTAG215File));
  216. memcpy(out_data_bytes.data(), &out_data, sizeof(NTAG215File));
  217. mbedtls_aes_crypt_ctr(&aes, 0x188, &nc_off, nonce_counter.data(), stream_block.data(),
  218. in_data_byes.data() + 0x2c, out_data_bytes.data() + 0x2c);
  219. memcpy(out_data_bytes.data(), in_data_byes.data(), 0x008);
  220. // Data signature NOT copied
  221. memcpy(out_data_bytes.data() + 0x028, in_data_byes.data() + 0x028, 0x004);
  222. // Tag signature NOT copied
  223. memcpy(out_data_bytes.data() + 0x1D4, in_data_byes.data() + 0x1D4, 0x048);
  224. memcpy(&out_data, out_data_bytes.data(), sizeof(NTAG215File));
  225. }
  226. bool LoadKeys(InternalKey& locked_secret, InternalKey& unfixed_info) {
  227. const auto yuzu_keys_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::KeysDir);
  228. const Common::FS::IOFile keys_file{yuzu_keys_dir / "key_retail.bin",
  229. Common::FS::FileAccessMode::Read,
  230. Common::FS::FileType::BinaryFile};
  231. if (!keys_file.IsOpen()) {
  232. LOG_ERROR(Service_NFP, "No keys detected");
  233. return false;
  234. }
  235. if (keys_file.Read(unfixed_info) != 1) {
  236. LOG_ERROR(Service_NFP, "Failed to read unfixed_info");
  237. return false;
  238. }
  239. if (keys_file.Read(locked_secret) != 1) {
  240. LOG_ERROR(Service_NFP, "Failed to read locked-secret");
  241. return false;
  242. }
  243. return true;
  244. }
  245. bool DecodeAmiibo(const EncryptedNTAG215File& encrypted_tag_data, NTAG215File& tag_data) {
  246. InternalKey locked_secret{};
  247. InternalKey unfixed_info{};
  248. if (!LoadKeys(locked_secret, unfixed_info)) {
  249. return false;
  250. }
  251. // Generate keys
  252. NTAG215File encoded_data = NfcDataToEncodedData(encrypted_tag_data);
  253. const auto data_keys = GenerateKey(unfixed_info, encoded_data);
  254. const auto tag_keys = GenerateKey(locked_secret, encoded_data);
  255. // Decrypt
  256. Cipher(data_keys, encoded_data, tag_data);
  257. std::array<u8, sizeof(NTAG215File)> out{};
  258. memcpy(out.data(), &tag_data, sizeof(NTAG215File));
  259. // Regenerate tag HMAC. Note: order matters, data HMAC depends on tag HMAC!
  260. mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), tag_keys.hmac_key.data(),
  261. sizeof(HmacKey), out.data() + 0x1D4, 0x34, out.data() + HMAC_POS_TAG);
  262. // Regenerate data HMAC
  263. mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), data_keys.hmac_key.data(),
  264. sizeof(HmacKey), out.data() + 0x29, 0x1DF, out.data() + HMAC_POS_DATA);
  265. memcpy(&tag_data, out.data(), sizeof(NTAG215File));
  266. if (memcmp(tag_data.unfixed_hash.data(), encrypted_tag_data.user_memory.unfixed_hash.data(),
  267. 32) != 0) {
  268. return false;
  269. }
  270. if (memcmp(tag_data.locked_hash.data(), encrypted_tag_data.user_memory.locked_hash.data(),
  271. 32) != 0) {
  272. return false;
  273. }
  274. return true;
  275. }
  276. bool EncodeAmiibo(const NTAG215File& tag_data, EncryptedNTAG215File& encrypted_tag_data) {
  277. InternalKey locked_secret{};
  278. InternalKey unfixed_info{};
  279. if (!LoadKeys(locked_secret, unfixed_info)) {
  280. return false;
  281. }
  282. // Generate keys
  283. const auto data_keys = GenerateKey(unfixed_info, tag_data);
  284. const auto tag_keys = GenerateKey(locked_secret, tag_data);
  285. std::array<u8, sizeof(NTAG215File)> plain{};
  286. std::array<u8, sizeof(NTAG215File)> cipher{};
  287. memcpy(plain.data(), &tag_data, sizeof(NTAG215File));
  288. // Generate tag HMAC
  289. mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), tag_keys.hmac_key.data(),
  290. sizeof(HmacKey), plain.data() + 0x1D4, 0x34, cipher.data() + HMAC_POS_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, plain.data() + 0x029, 0x18B); // Data
  298. mbedtls_md_hmac_update(&ctx, cipher.data() + HMAC_POS_TAG, 0x20); // Tag HMAC
  299. mbedtls_md_hmac_update(&ctx, plain.data() + 0x1D4, 0x34);
  300. mbedtls_md_hmac_finish(&ctx, cipher.data() + HMAC_POS_DATA);
  301. // HMAC cleanup
  302. mbedtls_md_free(&ctx);
  303. // Encrypt
  304. NTAG215File encoded_tag_data{};
  305. memcpy(&encoded_tag_data, cipher.data(), sizeof(NTAG215File));
  306. Cipher(data_keys, tag_data, encoded_tag_data);
  307. // Convert back to hardware
  308. encrypted_tag_data = EncodedDataToNfcData(encoded_tag_data);
  309. return true;
  310. }
  311. } // namespace Service::NFP::AmiiboCrypto