mifare_nested_worker.c 53 KB

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