mifare_nested_worker.c 53 KB

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