mifare_nested_worker.c 53 KB

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