mifare_nested_worker.c 60 KB

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