mifare_nested_worker.c 53 KB

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