amiibo_crypto.cpp 16 KB

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