mifare_nested_worker.c 57 KB

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