mifare_nested_worker.c 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651
  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. memcpy(&info->target_nt, result.target_nt, sizeof(result.target_nt));
  636. memcpy(&info->target_ks, result.target_ks, sizeof(result.target_ks));
  637. nonces.nonces[sector][key_type][0] = info;
  638. nonces.cuid = result.cuid;
  639. nonces.sector_count = sector_count;
  640. mifare_nested_worker->context->nonces = &nonces;
  641. mifare_nested_worker->callback(
  642. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  643. break;
  644. } else {
  645. mifare_nested_worker->callback(
  646. MifareNestedWorkerEventNoTagDetected, mifare_nested_worker->context);
  647. }
  648. }
  649. }
  650. }
  651. break;
  652. }
  653. mifare_nested_worker_write_nonces(&data, storage, &nonces, 1, 1, sector_count, 0, 0);
  654. free(mf_data);
  655. mifare_nested_worker->callback(
  656. MifareNestedWorkerEventNoncesCollected, mifare_nested_worker->context);
  657. nfc_deactivate();
  658. }
  659. void mifare_nested_worker_collect_nonces_hard(MifareNestedWorker* mifare_nested_worker) {
  660. NonceList_t nonces;
  661. Storage* storage = furi_record_open(RECORD_STORAGE);
  662. NfcDevice* dev = mifare_nested_worker->context->nfc_dev;
  663. MfClassicData* mf_data = &dev->dev_data.mf_classic_data;
  664. FuriString* folder_path = furi_string_alloc();
  665. FuriHalNfcDevData data = {};
  666. nested_get_data(&data);
  667. MfClassicType type = mifare_nested_worker_get_tag_type(data.atqa[0], data.atqa[1], data.sak);
  668. uint64_t key = 0; // Found key for attack
  669. uint32_t found_key_type = 0;
  670. uint32_t key_block = 0;
  671. uint32_t sector_count = 0;
  672. uint32_t cuid = 0;
  673. furi_hal_nfc_activate_nfca(200, &cuid);
  674. FURI_LOG_I(TAG, "Running Hard Nested attack");
  675. FuriString* tag_info = furi_string_alloc_printf("Tag UID: ");
  676. mifare_nested_worker_write_uid_string(&data, tag_info);
  677. FURI_LOG_I(TAG, "%s", furi_string_get_cstr(tag_info));
  678. furi_string_free(tag_info);
  679. if(type == MfClassicType4k) {
  680. sector_count = 40;
  681. FURI_LOG_I(TAG, "Found Mifare Classic 4K tag");
  682. } else if(type == MfClassicType1k) {
  683. sector_count = 16;
  684. FURI_LOG_I(TAG, "Found Mifare Classic 1K tag");
  685. } else { // if(type == MfClassicTypeMini)
  686. sector_count = 5;
  687. FURI_LOG_I(TAG, "Found Mifare Classic Mini tag");
  688. }
  689. mifare_nested_worker_get_hardnested_folder_path(&data, folder_path);
  690. storage_common_mkdir(storage, furi_string_get_cstr(folder_path));
  691. furi_string_free(folder_path);
  692. if(!mifare_nested_worker_read_key_cache(&data, mf_data) ||
  693. !mifare_nested_worker_check_initial_keys(
  694. &nonces, mf_data, 1, sector_count, &key, &key_block, &found_key_type)) {
  695. mifare_nested_worker->callback(
  696. MifareNestedWorkerEventNeedKey, mifare_nested_worker->context);
  697. nfc_deactivate();
  698. free(mf_data);
  699. free_nonces(&nonces, sector_count, 1);
  700. return;
  701. }
  702. FURI_LOG_I(
  703. TAG, "Using %c key for block %lu: %012llX", !found_key_type ? 'A' : 'B', key_block, key);
  704. FuriHalNfcTxRxContext tx_rx = {};
  705. nonces.tries = 1;
  706. nonces.hardnested_states = 0;
  707. nonces.sector_count = sector_count;
  708. mifare_nested_worker->context->nonces = &nonces;
  709. mifare_nested_worker->callback(MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  710. mifare_nested_worker->callback(
  711. MifareNestedWorkerEventHardnestedStatesFound, mifare_nested_worker->context);
  712. for(uint8_t sector = 0; sector < sector_count &&
  713. mifare_nested_worker->state == MifareNestedWorkerStateCollectingHard;
  714. sector++) {
  715. for(uint8_t key_type = 0;
  716. key_type < 2 && mifare_nested_worker->state == MifareNestedWorkerStateCollectingHard;
  717. key_type++) {
  718. Nonces* info = nonces.nonces[sector][key_type][0];
  719. if(info->collected) {
  720. FURI_LOG_I(
  721. TAG,
  722. "Skipping sector %u, block %u, key_type: %u as we already have a key",
  723. sector,
  724. mifare_nested_worker_get_block_by_sector(sector),
  725. key_type);
  726. info->skipped = true;
  727. nonces.nonces[sector][key_type][0] = info;
  728. mifare_nested_worker->context->nonces = &nonces;
  729. mifare_nested_worker->callback(
  730. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  731. continue;
  732. }
  733. if(!nested_check_block(
  734. &tx_rx, mifare_nested_worker_get_block_by_sector(sector), key_type)) {
  735. FURI_LOG_E(
  736. TAG,
  737. "Skipping sector %u, block %u, key_type: %u as we can't auth on it",
  738. sector,
  739. mifare_nested_worker_get_block_by_sector(sector),
  740. key_type);
  741. info->skipped = true;
  742. nonces.nonces[sector][key_type][0] = info;
  743. mifare_nested_worker->context->nonces = &nonces;
  744. mifare_nested_worker->callback(
  745. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  746. continue;
  747. }
  748. while(!info->collected &&
  749. mifare_nested_worker->state == MifareNestedWorkerStateCollectingHard) {
  750. Stream* file_stream = file_stream_alloc(storage);
  751. FuriString* hardnested_file = furi_string_alloc();
  752. mifare_nested_worker_get_hardnested_file_path(
  753. &data, hardnested_file, sector, key_type);
  754. file_stream_open(
  755. file_stream,
  756. furi_string_get_cstr(hardnested_file),
  757. FSAM_READ_WRITE,
  758. FSOM_CREATE_ALWAYS);
  759. FuriString* header = furi_string_alloc_printf(
  760. "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",
  761. NESTED_NONCE_FORMAT_VERSION,
  762. NESTED_RECOVER_KEYS_GITHUB_LINK,
  763. !key_type ? 'A' : 'B',
  764. cuid,
  765. sector);
  766. stream_write_string(file_stream, header);
  767. furi_string_free(header);
  768. uint32_t first_byte_sum = 0;
  769. uint32_t* found = malloc(sizeof(uint32_t) * 256);
  770. for(uint32_t i = 0; i < 256; i++) {
  771. found[i] = 0;
  772. }
  773. while(mifare_nested_worker->state == MifareNestedWorkerStateCollectingHard) {
  774. struct nonce_info_hard result = nested_hard_nonce_attack(
  775. &tx_rx,
  776. key_block,
  777. found_key_type,
  778. mifare_nested_worker_get_block_by_sector(sector),
  779. key_type,
  780. key,
  781. found,
  782. &first_byte_sum,
  783. file_stream);
  784. if(result.static_encrypted) {
  785. file_stream_close(file_stream);
  786. storage_simply_remove(storage, furi_string_get_cstr(hardnested_file));
  787. furi_string_free(hardnested_file);
  788. free(found);
  789. free(mf_data);
  790. nfc_deactivate();
  791. mifare_nested_worker->callback(
  792. MifareNestedWorkerEventStaticEncryptedNonce,
  793. mifare_nested_worker->context);
  794. return;
  795. }
  796. if(result.full) {
  797. uint32_t states = 0;
  798. for(uint32_t i = 0; i < 256; i++) {
  799. states += found[i];
  800. }
  801. nonces.hardnested_states = states;
  802. mifare_nested_worker->callback(
  803. MifareNestedWorkerEventHardnestedStatesFound,
  804. mifare_nested_worker->context);
  805. FURI_LOG_D(TAG, "Found states: %lu", states);
  806. if(states == 256) {
  807. FURI_LOG_D(
  808. TAG, "All states collected, first_byte_sum: %lu", first_byte_sum);
  809. bool valid = false;
  810. for(uint8_t i = 0; i < sizeof(sums); i++) {
  811. if(sums[i] == first_byte_sum) {
  812. valid = true;
  813. break;
  814. }
  815. }
  816. if(!valid) {
  817. FURI_LOG_E(TAG, "Invalid first_byte_sum!");
  818. break;
  819. }
  820. info->collected = true;
  821. info->hardnested = true;
  822. nonces.cuid = result.cuid;
  823. nonces.nonces[sector][key_type][0] = info;
  824. mifare_nested_worker->context->nonces = &nonces;
  825. mifare_nested_worker->callback(
  826. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  827. break;
  828. }
  829. } else {
  830. mifare_nested_worker->callback(
  831. MifareNestedWorkerEventNoTagDetected, mifare_nested_worker->context);
  832. }
  833. }
  834. free(found);
  835. furi_string_free(hardnested_file);
  836. file_stream_close(file_stream);
  837. }
  838. }
  839. }
  840. mifare_nested_worker_write_nonces(&data, storage, &nonces, 1, 1, sector_count, 0, 0);
  841. free(mf_data);
  842. mifare_nested_worker->callback(
  843. MifareNestedWorkerEventNoncesCollected, mifare_nested_worker->context);
  844. nfc_deactivate();
  845. }
  846. void mifare_nested_worker_collect_nonces(MifareNestedWorker* mifare_nested_worker) {
  847. NonceList_t nonces;
  848. Storage* storage = furi_record_open(RECORD_STORAGE);
  849. NfcDevice* dev = mifare_nested_worker->context->nfc_dev;
  850. MfClassicData* mf_data = &dev->dev_data.mf_classic_data;
  851. FuriString* folder_path = furi_string_alloc();
  852. FuriHalNfcDevData data = {};
  853. nested_get_data(&data);
  854. MfClassicType type = mifare_nested_worker_get_tag_type(data.atqa[0], data.atqa[1], data.sak);
  855. uint64_t key = 0; // Found key for attack
  856. uint32_t found_key_type = 0;
  857. uint32_t key_block = 0;
  858. uint32_t sector_count = 0;
  859. uint32_t delay = 0;
  860. uint32_t distance = 0;
  861. uint32_t tries_count = 1;
  862. FURI_LOG_I(TAG, "Running Nested attack");
  863. FuriString* tag_info = furi_string_alloc_printf("Tag UID: ");
  864. mifare_nested_worker_write_uid_string(&data, tag_info);
  865. FURI_LOG_I(TAG, "%s", furi_string_get_cstr(tag_info));
  866. furi_string_free(tag_info);
  867. if(type == MfClassicType4k) {
  868. sector_count = 40;
  869. FURI_LOG_I(TAG, "Found Mifare Classic 4K tag");
  870. } else if(type == MfClassicType1k) {
  871. sector_count = 16;
  872. FURI_LOG_I(TAG, "Found Mifare Classic 1K tag");
  873. } else { // if(type == MfClassicTypeMini)
  874. sector_count = 5;
  875. FURI_LOG_I(TAG, "Found Mifare Classic Mini tag");
  876. }
  877. furi_string_set(folder_path, NESTED_FOLDER);
  878. storage_common_mkdir(storage, furi_string_get_cstr(folder_path));
  879. furi_string_free(folder_path);
  880. if(!mifare_nested_worker_read_key_cache(&data, mf_data) ||
  881. !mifare_nested_worker_check_initial_keys(
  882. &nonces, mf_data, 3, sector_count, &key, &key_block, &found_key_type)) {
  883. mifare_nested_worker->callback(
  884. MifareNestedWorkerEventNeedKey, mifare_nested_worker->context);
  885. nfc_deactivate();
  886. free(mf_data);
  887. free_nonces(&nonces, sector_count, 3);
  888. return;
  889. }
  890. FURI_LOG_I(
  891. TAG, "Using %c key for block %lu: %012llX", !found_key_type ? 'A' : 'B', key_block, key);
  892. while(mifare_nested_worker->state == MifareNestedWorkerStateCollecting) {
  893. FuriHalNfcTxRxContext tx_rx = {};
  894. uint32_t first_distance = 0;
  895. uint32_t second_distance = 0;
  896. mifare_nested_worker->callback(
  897. MifareNestedWorkerEventCalibrating, mifare_nested_worker->context);
  898. distance = nested_calibrate_distance(&tx_rx, key_block, found_key_type, key, delay, false);
  899. if(mifare_nested_worker->state == MifareNestedWorkerStateCollecting) {
  900. first_distance =
  901. nested_calibrate_distance(&tx_rx, key_block, found_key_type, key, delay, true);
  902. }
  903. if(mifare_nested_worker->state == MifareNestedWorkerStateCollecting) {
  904. second_distance =
  905. nested_calibrate_distance(&tx_rx, key_block, found_key_type, key, 10000, true);
  906. }
  907. if(first_distance == 0 && second_distance == 0) {
  908. nfc_deactivate();
  909. free(mf_data);
  910. free_nonces(&nonces, sector_count, 3);
  911. mifare_nested_worker_collect_nonces_hard(mifare_nested_worker);
  912. return;
  913. }
  914. if(first_distance < second_distance - 100 && second_distance > 100) {
  915. FURI_LOG_E(
  916. TAG,
  917. "Discovered tag with PRNG that depends on time. PRNG values: %lu, %lu",
  918. first_distance,
  919. second_distance);
  920. struct distance_info info =
  921. nested_calibrate_distance_info(&tx_rx, key_block, found_key_type, key);
  922. if(info.max_prng - info.min_prng > 150) {
  923. FURI_LOG_W(
  924. TAG,
  925. "PRNG is too unpredictable (min/max values more than 150: %lu - %lu = %lu), fallback to delay method",
  926. info.max_prng,
  927. info.min_prng,
  928. info.max_prng - info.min_prng);
  929. delay = 1;
  930. } else {
  931. FURI_LOG_I(
  932. TAG,
  933. "PRNG is stable, using method without delay! (May be false positive, still will collect x3 times)");
  934. distance =
  935. nested_calibrate_distance(&tx_rx, key_block, found_key_type, key, delay, true);
  936. delay = 2;
  937. tries_count = 3;
  938. }
  939. }
  940. if(distance == 0 || delay == 1) {
  941. bool failed = false;
  942. // Tag need delay or unpredictable PRNG
  943. FURI_LOG_W(TAG, "Can't determine distance, trying to find timing...");
  944. mifare_nested_worker->callback(
  945. MifareNestedWorkerEventNeedPrediction, mifare_nested_worker->context);
  946. delay = mifare_nested_worker_predict_delay(
  947. &tx_rx, key_block, found_key_type, key, 0, mifare_nested_worker);
  948. if(delay == 1) {
  949. FURI_LOG_E(TAG, "Can't determine delay");
  950. // Check that we didn't lost tag
  951. FuriHalNfcDevData lost_tag_data = {};
  952. nested_get_data(&lost_tag_data);
  953. if(lost_tag_data.uid_len == 0) {
  954. // We lost it.
  955. mifare_nested_worker->callback(
  956. MifareNestedWorkerEventNoTagDetected, mifare_nested_worker->context);
  957. while(mifare_nested_worker->state == MifareNestedWorkerStateCollecting &&
  958. lost_tag_data.cuid != data.cuid) {
  959. furi_delay_ms(250);
  960. nested_get_data(&lost_tag_data);
  961. }
  962. mifare_nested_worker->callback(
  963. MifareNestedWorkerEventCalibrating, mifare_nested_worker->context);
  964. continue;
  965. }
  966. failed = true;
  967. }
  968. if(delay == 2) {
  969. FURI_LOG_E(TAG, "Can't determine delay in 25 tries, fallback to hardnested");
  970. nfc_deactivate();
  971. free(mf_data);
  972. free_nonces(&nonces, sector_count, 3);
  973. mifare_nested_worker_collect_nonces_hard(mifare_nested_worker);
  974. return;
  975. }
  976. if(mifare_nested_worker->state == MifareNestedWorkerStateCollecting && !failed) {
  977. distance = nested_calibrate_distance(
  978. &tx_rx, key_block, found_key_type, key, delay, false);
  979. }
  980. if(distance == 0 && !failed) {
  981. FURI_LOG_E(TAG, "Found delay, but can't find distance");
  982. failed = true;
  983. }
  984. if(failed) {
  985. nfc_deactivate();
  986. mifare_nested_worker->callback(
  987. MifareNestedWorkerEventAttackFailed, mifare_nested_worker->context);
  988. free(mf_data);
  989. free_nonces(&nonces, sector_count, 3);
  990. return;
  991. }
  992. tries_count = 3;
  993. }
  994. mifare_nested_worker->context->nonces = &nonces;
  995. mifare_nested_worker->callback(
  996. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  997. for(uint8_t tries = 0; tries < tries_count; tries++) {
  998. for(uint8_t sector = 0; sector < sector_count; sector++) {
  999. for(uint8_t key_type = 0; key_type < 2; key_type++) {
  1000. Nonces* info = nonces.nonces[sector][key_type][tries];
  1001. if(info->collected) {
  1002. FURI_LOG_I(
  1003. TAG,
  1004. "Skipping sector %u, block %u, key_type: %u as we already have a key",
  1005. sector,
  1006. mifare_nested_worker_get_block_by_sector(sector),
  1007. key_type);
  1008. info->skipped = true;
  1009. nonces.nonces[sector][key_type][tries] = info;
  1010. mifare_nested_worker->context->nonces = &nonces;
  1011. mifare_nested_worker->callback(
  1012. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  1013. continue;
  1014. }
  1015. if(!nested_check_block(
  1016. &tx_rx, mifare_nested_worker_get_block_by_sector(sector), key_type)) {
  1017. FURI_LOG_E(
  1018. TAG,
  1019. "Skipping sector %u, block %u, key_type: %u as we can't auth on it",
  1020. sector,
  1021. mifare_nested_worker_get_block_by_sector(sector),
  1022. key_type);
  1023. info->skipped = true;
  1024. nonces.nonces[sector][key_type][0] = info;
  1025. mifare_nested_worker->context->nonces = &nonces;
  1026. mifare_nested_worker->callback(
  1027. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  1028. continue;
  1029. }
  1030. while(!info->collected) {
  1031. if(mifare_nested_worker->state != MifareNestedWorkerStateCollecting) {
  1032. break;
  1033. }
  1034. struct nonce_info result = nested_attack(
  1035. &tx_rx,
  1036. key_block,
  1037. found_key_type,
  1038. mifare_nested_worker_get_block_by_sector(sector),
  1039. key_type,
  1040. key,
  1041. distance,
  1042. delay);
  1043. if(result.full) {
  1044. FURI_LOG_I(
  1045. TAG,
  1046. "Accured nonces for sector %u, block %u, key_type: %u",
  1047. sector,
  1048. mifare_nested_worker_get_block_by_sector(sector),
  1049. key_type);
  1050. info = nonces.nonces[sector][key_type][tries];
  1051. info->collected = true;
  1052. memcpy(&info->target_nt, result.target_nt, sizeof(result.target_nt));
  1053. memcpy(&info->target_ks, result.target_ks, sizeof(result.target_ks));
  1054. memcpy(&info->parity, result.parity, sizeof(result.parity));
  1055. nonces.nonces[sector][key_type][tries] = info;
  1056. nonces.cuid = result.cuid;
  1057. nonces.sector_count = sector_count;
  1058. nonces.tries = tries_count;
  1059. mifare_nested_worker->context->nonces = &nonces;
  1060. mifare_nested_worker->callback(
  1061. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  1062. break;
  1063. } else {
  1064. mifare_nested_worker->callback(
  1065. MifareNestedWorkerEventNoTagDetected,
  1066. mifare_nested_worker->context);
  1067. }
  1068. }
  1069. }
  1070. }
  1071. }
  1072. break;
  1073. }
  1074. mifare_nested_worker_write_nonces(
  1075. &data, storage, &nonces, tries_count, 3, sector_count, delay, distance);
  1076. free(mf_data);
  1077. mifare_nested_worker->callback(
  1078. MifareNestedWorkerEventNoncesCollected, mifare_nested_worker->context);
  1079. nfc_deactivate();
  1080. }
  1081. bool* mifare_nested_worker_check_keys_exists(
  1082. Storage* storage,
  1083. char* path,
  1084. uint64_t* keys,
  1085. uint32_t key_count,
  1086. MifareNestedWorker* mifare_nested_worker) {
  1087. bool* old_keys = malloc(sizeof(bool) * key_count);
  1088. Stream* file_stream = file_stream_alloc(storage);
  1089. file_stream_open(file_stream, path, FSAM_READ, FSOM_OPEN_ALWAYS);
  1090. FuriString* key_strings[key_count];
  1091. for(uint32_t i = 0; i < key_count; i++) {
  1092. old_keys[i] = false;
  1093. key_strings[i] = furi_string_alloc_printf("%012llX\n", keys[i]);
  1094. }
  1095. while(mifare_nested_worker->state == MifareNestedWorkerStateValidating) {
  1096. FuriString* next_line = furi_string_alloc();
  1097. if(!stream_read_line(file_stream, next_line)) {
  1098. break;
  1099. }
  1100. for(uint32_t i = 0; i < key_count; i++) {
  1101. if(keys[i] == (uint64_t)-1) continue;
  1102. if(furi_string_cmp(next_line, key_strings[i]) == 0) {
  1103. old_keys[i] = true;
  1104. }
  1105. }
  1106. furi_string_free(next_line);
  1107. }
  1108. for(uint32_t i = 0; i < key_count; i++) {
  1109. furi_string_free(key_strings[i]);
  1110. }
  1111. file_stream_close(file_stream);
  1112. free(file_stream);
  1113. return old_keys;
  1114. }
  1115. void mifare_nested_worker_write_key(Storage* storage, FuriString* key) {
  1116. Stream* file_stream = file_stream_alloc(storage);
  1117. file_stream_open(
  1118. file_stream,
  1119. EXT_PATH("nfc/assets/mf_classic_dict_user.nfc"),
  1120. FSAM_READ_WRITE,
  1121. FSOM_OPEN_APPEND);
  1122. stream_write_string(file_stream, key);
  1123. file_stream_close(file_stream);
  1124. }
  1125. void mifare_nested_worker_check_keys(MifareNestedWorker* mifare_nested_worker) {
  1126. KeyInfo_t* key_info = mifare_nested_worker->context->keys;
  1127. Storage* storage = furi_record_open(RECORD_STORAGE);
  1128. Stream* file_stream = file_stream_alloc(storage);
  1129. FuriString* next_line = furi_string_alloc();
  1130. FuriString* path = furi_string_alloc();
  1131. FuriHalNfcDevData data = {};
  1132. nested_get_data(&data);
  1133. MfClassicType type = mifare_nested_worker_get_tag_type(data.atqa[0], data.atqa[1], data.sak);
  1134. NestedCheckKeyResult result = NestedCheckKeyNoTag;
  1135. FuriHalNfcTxRxContext tx_rx = {};
  1136. uint32_t key_count = 0;
  1137. uint32_t sector_key_count = 0;
  1138. uint64_t keys[80];
  1139. bool found_keys[2][40];
  1140. bool unique_keys[2][40];
  1141. uint32_t sector_count = 0;
  1142. if(type == MfClassicType4k) {
  1143. sector_count = 40;
  1144. FURI_LOG_I(TAG, "Found Mifare Classic 4K tag");
  1145. } else if(type == MfClassicType1k) {
  1146. sector_count = 16;
  1147. FURI_LOG_I(TAG, "Found Mifare Classic 1K tag");
  1148. } else { // if(type == MfClassicTypeMini)
  1149. sector_count = 5;
  1150. FURI_LOG_I(TAG, "Found Mifare Classic Mini tag");
  1151. }
  1152. uint32_t keys_count = sector_count * 2;
  1153. for(uint8_t key = 0; key < 2; key++) {
  1154. for(uint8_t i = 0; i < sector_count; i++) {
  1155. found_keys[key][i] = false;
  1156. unique_keys[key][i] = false;
  1157. }
  1158. }
  1159. for(uint8_t i = 0; i < keys_count; i++) {
  1160. keys[i] = -1;
  1161. }
  1162. mifare_nested_worker_get_found_keys_file_path(&data, path);
  1163. if(!file_stream_open(file_stream, furi_string_get_cstr(path), FSAM_READ, FSOM_OPEN_EXISTING)) {
  1164. FURI_LOG_E(TAG, "Can't open %s", furi_string_get_cstr(path));
  1165. file_stream_close(file_stream);
  1166. mifare_nested_worker_get_nonces_file_path(&data, path);
  1167. if(!file_stream_open(
  1168. file_stream, furi_string_get_cstr(path), FSAM_READ, FSOM_OPEN_EXISTING)) {
  1169. mifare_nested_worker->callback(
  1170. MifareNestedWorkerEventNeedCollection, mifare_nested_worker->context);
  1171. } else {
  1172. mifare_nested_worker->callback(
  1173. MifareNestedWorkerEventNeedKeyRecovery, mifare_nested_worker->context);
  1174. }
  1175. file_stream_close(file_stream);
  1176. free(file_stream);
  1177. furi_string_free(path);
  1178. furi_string_free(next_line);
  1179. furi_record_close(RECORD_STORAGE);
  1180. return;
  1181. };
  1182. while(true) {
  1183. if(!stream_read_line(file_stream, next_line)) {
  1184. break;
  1185. }
  1186. if(furi_string_start_with_str(next_line, "Key")) {
  1187. uint8_t key_type = furi_string_get_char(next_line, 4) == 'B';
  1188. uint8_t sector = atoi((char[]){furi_string_get_char(next_line, 13)}) * 10 +
  1189. atoi((char[]){furi_string_get_char(next_line, 14)});
  1190. if(!unique_keys[key_type][sector]) {
  1191. unique_keys[key_type][sector] = true;
  1192. sector_key_count++;
  1193. }
  1194. }
  1195. key_count++;
  1196. }
  1197. stream_rewind(file_stream);
  1198. key_info->total_keys = key_count;
  1199. key_info->sector_keys = sector_key_count;
  1200. while(mifare_nested_worker->state == MifareNestedWorkerStateValidating) {
  1201. if(!stream_read_line(file_stream, next_line)) {
  1202. break;
  1203. }
  1204. if(furi_string_start_with_str(next_line, "Key")) {
  1205. // Key X sector XX: XX XX XX XX XX XX
  1206. // 0000000000111111111122222222223333
  1207. // 0123456789012345678901234567890123
  1208. uint8_t keyChar[6];
  1209. uint8_t count = 0;
  1210. uint8_t key_type = furi_string_get_char(next_line, 4) == 'B';
  1211. uint8_t sector = atoi((char[]){furi_string_get_char(next_line, 13)}) * 10 +
  1212. atoi((char[]){furi_string_get_char(next_line, 14)});
  1213. for(uint8_t i = 17; i < 33; i += 3) {
  1214. hex_char_to_uint8(
  1215. furi_string_get_char(next_line, i),
  1216. furi_string_get_char(next_line, i + 1),
  1217. &keyChar[count]);
  1218. count++;
  1219. }
  1220. uint64_t key = nfc_util_bytes2num(keyChar, 6);
  1221. key_info->checked_keys++;
  1222. if(found_keys[key_type][sector]) {
  1223. mifare_nested_worker->callback(
  1224. MifareNestedWorkerEventKeyChecked, mifare_nested_worker->context);
  1225. continue;
  1226. }
  1227. while(mifare_nested_worker->state == MifareNestedWorkerStateValidating) {
  1228. result = nested_check_key(
  1229. &tx_rx, mifare_nested_worker_get_block_by_sector(sector), key_type, key);
  1230. if(result == NestedCheckKeyNoTag) {
  1231. mifare_nested_worker->callback(
  1232. MifareNestedWorkerEventNoTagDetected, mifare_nested_worker->context);
  1233. furi_delay_ms(250);
  1234. } else {
  1235. break;
  1236. }
  1237. }
  1238. if(result == NestedCheckKeyValid) {
  1239. FURI_LOG_I(
  1240. TAG, "Found valid %c key for sector %u: %012llX", key_type, sector, key);
  1241. bool exists = false;
  1242. for(uint8_t i = 0; i < keys_count; i++) {
  1243. if(keys[i] == key) {
  1244. exists = true;
  1245. }
  1246. }
  1247. if(!exists) {
  1248. keys[key_info->found_keys] = key;
  1249. }
  1250. key_info->found_keys++;
  1251. found_keys[key_type][sector] = true;
  1252. }
  1253. mifare_nested_worker->callback(
  1254. MifareNestedWorkerEventKeyChecked, mifare_nested_worker->context);
  1255. }
  1256. }
  1257. furi_string_free(next_line);
  1258. file_stream_close(file_stream);
  1259. free(file_stream);
  1260. mifare_nested_worker->callback(
  1261. MifareNestedWorkerEventProcessingKeys, mifare_nested_worker->context);
  1262. bool* old_keys = mifare_nested_worker_check_keys_exists(
  1263. storage,
  1264. EXT_PATH("nfc/assets/mf_classic_dict_user.nfc"),
  1265. keys,
  1266. keys_count,
  1267. mifare_nested_worker);
  1268. for(uint8_t i = 0; i < keys_count; i++) {
  1269. if(old_keys[i]) {
  1270. keys[i] = -1;
  1271. }
  1272. }
  1273. old_keys = mifare_nested_worker_check_keys_exists(
  1274. storage,
  1275. EXT_PATH("nfc/assets/mf_classic_dict.nfc"),
  1276. keys,
  1277. keys_count,
  1278. mifare_nested_worker);
  1279. for(uint8_t i = 0; i < keys_count; i++) {
  1280. if(old_keys[i]) {
  1281. keys[i] = -1;
  1282. }
  1283. }
  1284. for(uint8_t i = 0; i < keys_count; i++) {
  1285. if(keys[i] == (uint64_t)-1) continue;
  1286. FuriString* key_string = furi_string_alloc_printf("%012llX\n", keys[i]);
  1287. mifare_nested_worker_write_key(storage, key_string);
  1288. FURI_LOG_I(TAG, "Added new key: %s", furi_string_get_cstr(key_string));
  1289. key_info->added_keys++;
  1290. furi_string_free(key_string);
  1291. }
  1292. if(!storage_simply_remove(storage, furi_string_get_cstr(path))) {
  1293. FURI_LOG_E(TAG, "Failed to remove .keys file");
  1294. }
  1295. furi_record_close(RECORD_STORAGE);
  1296. furi_string_free(path);
  1297. mifare_nested_worker->callback(
  1298. MifareNestedWorkerEventKeysFound, mifare_nested_worker->context);
  1299. return;
  1300. }