mifare_nested_worker.c 60 KB

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