mfkey.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  1. #pragma GCC optimize("O3")
  2. #pragma GCC optimize("-funroll-all-loops")
  3. // TODO: Add keys to top of the user dictionary, not the bottom
  4. // TODO: More efficient dictionary bruteforce by scanning through hardcoded very common keys and previously found dictionary keys first?
  5. // (a cache for key_already_found_for_nonce_in_dict)
  6. // TODO: Selectively unroll loops to reduce binary size
  7. // TODO: Collect parity during Mfkey32 attacks to further optimize the attack
  8. // TODO: Why different sscanf between Mfkey32 and Nested?
  9. // TODO: "Read tag again with NFC app" message upon completion, "Complete. Keys added: <n>"
  10. // TODO: Separate Mfkey32 and Nested functions where possible to reduce branch statements
  11. // TODO: Find ~1 KB memory leak
  12. #include <furi.h>
  13. #include <furi_hal.h>
  14. #include <gui/gui.h>
  15. #include <gui/elements.h>
  16. #include "mfkey_icons.h"
  17. #include <inttypes.h>
  18. #include <toolbox/keys_dict.h>
  19. #include <bit_lib/bit_lib.h>
  20. #include <toolbox/stream/buffered_file_stream.h>
  21. #include <dolphin/dolphin.h>
  22. #include <notification/notification_messages.h>
  23. #include <nfc/protocols/mf_classic/mf_classic.h>
  24. #include "mfkey.h"
  25. #include "crypto1.h"
  26. #include "plugin_interface.h"
  27. #include <flipper_application/flipper_application.h>
  28. #include <loader/firmware_api/firmware_api.h>
  29. #include <storage/storage.h>
  30. // TODO: Remove defines that are not needed
  31. #define KEYS_DICT_SYSTEM_PATH EXT_PATH("nfc/assets/mf_classic_dict.nfc")
  32. #define KEYS_DICT_USER_PATH EXT_PATH("nfc/assets/mf_classic_dict_user.nfc")
  33. #define MF_CLASSIC_NONCE_PATH EXT_PATH("nfc/.mfkey32.log")
  34. #define MF_CLASSIC_NESTED_NONCE_PATH EXT_PATH("nfc/.nested")
  35. #define TAG "MFKey"
  36. #define MAX_NAME_LEN 32
  37. #define MAX_PATH_LEN 64
  38. #define LF_POLY_ODD (0x29CE5C)
  39. #define LF_POLY_EVEN (0x870804)
  40. #define CONST_M1_1 (LF_POLY_EVEN << 1 | 1)
  41. #define CONST_M2_1 (LF_POLY_ODD << 1)
  42. #define CONST_M1_2 (LF_POLY_ODD)
  43. #define CONST_M2_2 (LF_POLY_EVEN << 1 | 1)
  44. #define BIT(x, n) ((x) >> (n) & 1)
  45. #define BEBIT(x, n) BIT(x, (n) ^ 24)
  46. #define SWAPENDIAN(x) \
  47. ((x) = ((x) >> 8 & 0xff00ff) | ((x) & 0xff00ff) << 8, (x) = (x) >> 16 | (x) << 16)
  48. //#define SIZEOF(arr) sizeof(arr) / sizeof(*arr)
  49. static int eta_round_time = 44;
  50. static int eta_total_time = 705;
  51. // MSB_LIMIT: Chunk size (out of 256)
  52. static int MSB_LIMIT = 16;
  53. int check_state(struct Crypto1State* t, MfClassicNonce* n) {
  54. if(!(t->odd | t->even)) return 0;
  55. if(n->attack == mfkey32) {
  56. uint32_t rb = (napi_lfsr_rollback_word(t, 0, 0) ^ n->p64);
  57. if(rb != n->ar0_enc) {
  58. return 0;
  59. }
  60. rollback_word_noret(t, n->nr0_enc, 1);
  61. rollback_word_noret(t, n->uid_xor_nt0, 0);
  62. struct Crypto1State temp = {t->odd, t->even};
  63. crypt_word_noret(t, n->uid_xor_nt1, 0);
  64. crypt_word_noret(t, n->nr1_enc, 1);
  65. if(n->ar1_enc == (crypt_word(t) ^ n->p64b)) {
  66. crypto1_get_lfsr(&temp, &(n->key));
  67. return 1;
  68. }
  69. return 0;
  70. } else if(n->attack == static_nested) {
  71. struct Crypto1State temp = {t->odd, t->even};
  72. rollback_word_noret(t, n->uid_xor_nt1, 0);
  73. if(n->ks1_1_enc == crypt_word_ret(t, n->uid_xor_nt0, 0)) {
  74. rollback_word_noret(&temp, n->uid_xor_nt1, 0);
  75. crypto1_get_lfsr(&temp, &(n->key));
  76. return 1;
  77. }
  78. return 0;
  79. }
  80. return 0;
  81. }
  82. static inline int state_loop(
  83. unsigned int* states_buffer,
  84. int xks,
  85. int m1,
  86. int m2,
  87. unsigned int in,
  88. uint8_t and_val) {
  89. int states_tail = 0;
  90. int round = 0, s = 0, xks_bit = 0, round_in = 0;
  91. for(round = 1; round <= 12; round++) {
  92. xks_bit = BIT(xks, round);
  93. if(round > 4) {
  94. round_in = ((in >> (2 * (round - 4))) & and_val) << 24;
  95. }
  96. for(s = 0; s <= states_tail; s++) {
  97. states_buffer[s] <<= 1;
  98. if((filter(states_buffer[s]) ^ filter(states_buffer[s] | 1)) != 0) {
  99. states_buffer[s] |= filter(states_buffer[s]) ^ xks_bit;
  100. if(round > 4) {
  101. update_contribution(states_buffer, s, m1, m2);
  102. states_buffer[s] ^= round_in;
  103. }
  104. } else if(filter(states_buffer[s]) == xks_bit) {
  105. // TODO: Refactor
  106. if(round > 4) {
  107. states_buffer[++states_tail] = states_buffer[s + 1];
  108. states_buffer[s + 1] = states_buffer[s] | 1;
  109. update_contribution(states_buffer, s, m1, m2);
  110. states_buffer[s++] ^= round_in;
  111. update_contribution(states_buffer, s, m1, m2);
  112. states_buffer[s] ^= round_in;
  113. } else {
  114. states_buffer[++states_tail] = states_buffer[++s];
  115. states_buffer[s] = states_buffer[s - 1] | 1;
  116. }
  117. } else {
  118. states_buffer[s--] = states_buffer[states_tail--];
  119. }
  120. }
  121. }
  122. return states_tail;
  123. }
  124. int binsearch(unsigned int data[], int start, int stop) {
  125. int mid, val = data[stop] & 0xff000000;
  126. while(start != stop) {
  127. mid = (stop - start) >> 1;
  128. if((data[start + mid] ^ 0x80000000) > (val ^ 0x80000000))
  129. stop = start + mid;
  130. else
  131. start += mid + 1;
  132. }
  133. return start;
  134. }
  135. void quicksort(unsigned int array[], int low, int high) {
  136. //if (SIZEOF(array) == 0)
  137. // return;
  138. if(low >= high) return;
  139. int middle = low + (high - low) / 2;
  140. unsigned int pivot = array[middle];
  141. int i = low, j = high;
  142. while(i <= j) {
  143. while(array[i] < pivot) {
  144. i++;
  145. }
  146. while(array[j] > pivot) {
  147. j--;
  148. }
  149. if(i <= j) { // swap
  150. int temp = array[i];
  151. array[i] = array[j];
  152. array[j] = temp;
  153. i++;
  154. j--;
  155. }
  156. }
  157. if(low < j) {
  158. quicksort(array, low, j);
  159. }
  160. if(high > i) {
  161. quicksort(array, i, high);
  162. }
  163. }
  164. int extend_table(unsigned int data[], int tbl, int end, int bit, int m1, int m2, unsigned int in) {
  165. in <<= 24;
  166. for(data[tbl] <<= 1; tbl <= end; data[++tbl] <<= 1) {
  167. if((filter(data[tbl]) ^ filter(data[tbl] | 1)) != 0) {
  168. data[tbl] |= filter(data[tbl]) ^ bit;
  169. update_contribution(data, tbl, m1, m2);
  170. data[tbl] ^= in;
  171. } else if(filter(data[tbl]) == bit) {
  172. data[++end] = data[tbl + 1];
  173. data[tbl + 1] = data[tbl] | 1;
  174. update_contribution(data, tbl, m1, m2);
  175. data[tbl++] ^= in;
  176. update_contribution(data, tbl, m1, m2);
  177. data[tbl] ^= in;
  178. } else {
  179. data[tbl--] = data[end--];
  180. }
  181. }
  182. return end;
  183. }
  184. int old_recover(
  185. unsigned int odd[],
  186. int o_head,
  187. int o_tail,
  188. int oks,
  189. unsigned int even[],
  190. int e_head,
  191. int e_tail,
  192. int eks,
  193. int rem,
  194. int s,
  195. MfClassicNonce* n,
  196. unsigned int in,
  197. int first_run) {
  198. int o, e, i;
  199. if(rem == -1) {
  200. for(e = e_head; e <= e_tail; ++e) {
  201. even[e] = (even[e] << 1) ^ evenparity32(even[e] & LF_POLY_EVEN) ^ (!!(in & 4));
  202. for(o = o_head; o <= o_tail; ++o, ++s) {
  203. struct Crypto1State temp = {0, 0};
  204. temp.even = odd[o];
  205. temp.odd = even[e] ^ evenparity32(odd[o] & LF_POLY_ODD);
  206. if(check_state(&temp, n)) {
  207. return -1;
  208. }
  209. }
  210. }
  211. return s;
  212. }
  213. if(first_run == 0) {
  214. for(i = 0; (i < 4) && (rem-- != 0); i++) {
  215. oks >>= 1;
  216. eks >>= 1;
  217. in >>= 2;
  218. o_tail = extend_table(
  219. odd, o_head, o_tail, oks & 1, LF_POLY_EVEN << 1 | 1, LF_POLY_ODD << 1, 0);
  220. if(o_head > o_tail) return s;
  221. e_tail = extend_table(
  222. even, e_head, e_tail, eks & 1, LF_POLY_ODD, LF_POLY_EVEN << 1 | 1, in & 3);
  223. if(e_head > e_tail) return s;
  224. }
  225. }
  226. first_run = 0;
  227. quicksort(odd, o_head, o_tail);
  228. quicksort(even, e_head, e_tail);
  229. while(o_tail >= o_head && e_tail >= e_head) {
  230. if(((odd[o_tail] ^ even[e_tail]) >> 24) == 0) {
  231. o_tail = binsearch(odd, o_head, o = o_tail);
  232. e_tail = binsearch(even, e_head, e = e_tail);
  233. s = old_recover(
  234. odd, o_tail--, o, oks, even, e_tail--, e, eks, rem, s, n, in, first_run);
  235. if(s == -1) {
  236. break;
  237. }
  238. } else if((odd[o_tail] ^ 0x80000000) > (even[e_tail] ^ 0x80000000)) {
  239. o_tail = binsearch(odd, o_head, o_tail) - 1;
  240. } else {
  241. e_tail = binsearch(even, e_head, e_tail) - 1;
  242. }
  243. }
  244. return s;
  245. }
  246. static inline int sync_state(ProgramState* program_state) {
  247. int ts = furi_hal_rtc_get_timestamp();
  248. int elapsed_time = ts - program_state->eta_timestamp;
  249. if(elapsed_time < program_state->eta_round) {
  250. program_state->eta_round -= elapsed_time;
  251. } else {
  252. program_state->eta_round = 0;
  253. }
  254. if(elapsed_time < program_state->eta_total) {
  255. program_state->eta_total -= elapsed_time;
  256. } else {
  257. program_state->eta_total = 0;
  258. }
  259. program_state->eta_timestamp = ts;
  260. if(program_state->close_thread_please) {
  261. return 1;
  262. }
  263. return 0;
  264. }
  265. int calculate_msb_tables(
  266. int oks,
  267. int eks,
  268. int msb_round,
  269. MfClassicNonce* n,
  270. unsigned int* states_buffer,
  271. struct Msb* odd_msbs,
  272. struct Msb* even_msbs,
  273. unsigned int* temp_states_odd,
  274. unsigned int* temp_states_even,
  275. unsigned int in,
  276. ProgramState* program_state) {
  277. //FURI_LOG_I(TAG, "MSB GO %i", msb_iter); // DEBUG
  278. unsigned int msb_head = (MSB_LIMIT * msb_round); // msb_iter ranges from 0 to (256/MSB_LIMIT)-1
  279. unsigned int msb_tail = (MSB_LIMIT * (msb_round + 1));
  280. int states_tail = 0, tail = 0;
  281. int i = 0, j = 0, semi_state = 0, found = 0;
  282. unsigned int msb = 0;
  283. in = ((in >> 16 & 0xff) | (in << 16) | (in & 0xff00)) << 1;
  284. // TODO: Why is this necessary?
  285. memset(odd_msbs, 0, MSB_LIMIT * sizeof(struct Msb));
  286. memset(even_msbs, 0, MSB_LIMIT * sizeof(struct Msb));
  287. for(semi_state = 1 << 20; semi_state >= 0; semi_state--) {
  288. if(semi_state % 32768 == 0) {
  289. if(sync_state(program_state) == 1) {
  290. return 0;
  291. }
  292. }
  293. if(filter(semi_state) == (oks & 1)) { //-V547
  294. states_buffer[0] = semi_state;
  295. states_tail = state_loop(states_buffer, oks, CONST_M1_1, CONST_M2_1, 0, 0);
  296. for(i = states_tail; i >= 0; i--) {
  297. msb = states_buffer[i] >> 24;
  298. if((msb >= msb_head) && (msb < msb_tail)) {
  299. found = 0;
  300. for(j = 0; j < odd_msbs[msb - msb_head].tail - 1; j++) {
  301. if(odd_msbs[msb - msb_head].states[j] == states_buffer[i]) {
  302. found = 1;
  303. break;
  304. }
  305. }
  306. if(!found) {
  307. tail = odd_msbs[msb - msb_head].tail++;
  308. odd_msbs[msb - msb_head].states[tail] = states_buffer[i];
  309. }
  310. }
  311. }
  312. }
  313. if(filter(semi_state) == (eks & 1)) { //-V547
  314. states_buffer[0] = semi_state;
  315. states_tail = state_loop(states_buffer, eks, CONST_M1_2, CONST_M2_2, in, 3);
  316. for(i = 0; i <= states_tail; i++) {
  317. msb = states_buffer[i] >> 24;
  318. if((msb >= msb_head) && (msb < msb_tail)) {
  319. found = 0;
  320. for(j = 0; j < even_msbs[msb - msb_head].tail; j++) {
  321. if(even_msbs[msb - msb_head].states[j] == states_buffer[i]) {
  322. found = 1;
  323. break;
  324. }
  325. }
  326. if(!found) {
  327. tail = even_msbs[msb - msb_head].tail++;
  328. even_msbs[msb - msb_head].states[tail] = states_buffer[i];
  329. }
  330. }
  331. }
  332. }
  333. }
  334. oks >>= 12;
  335. eks >>= 12;
  336. for(i = 0; i < MSB_LIMIT; i++) {
  337. if(sync_state(program_state) == 1) {
  338. return 0;
  339. }
  340. // TODO: Why is this necessary?
  341. memset(temp_states_even, 0, sizeof(unsigned int) * (1280));
  342. memset(temp_states_odd, 0, sizeof(unsigned int) * (1280));
  343. memcpy(temp_states_odd, odd_msbs[i].states, odd_msbs[i].tail * sizeof(unsigned int));
  344. memcpy(temp_states_even, even_msbs[i].states, even_msbs[i].tail * sizeof(unsigned int));
  345. int res = old_recover(
  346. temp_states_odd,
  347. 0,
  348. odd_msbs[i].tail,
  349. oks,
  350. temp_states_even,
  351. 0,
  352. even_msbs[i].tail,
  353. eks,
  354. 3,
  355. 0,
  356. n,
  357. in >> 16,
  358. 1);
  359. if(res == -1) {
  360. return 1;
  361. }
  362. //odd_msbs[i].tail = 0;
  363. //even_msbs[i].tail = 0;
  364. }
  365. return 0;
  366. }
  367. void** allocate_blocks(const size_t* block_sizes, int num_blocks) {
  368. void** block_pointers = malloc(num_blocks * sizeof(void*));
  369. for(int i = 0; i < num_blocks; i++) {
  370. if(memmgr_heap_get_max_free_block() < block_sizes[i]) {
  371. // Not enough memory, free previously allocated blocks
  372. for(int j = 0; j < i; j++) {
  373. free(block_pointers[j]);
  374. }
  375. free(block_pointers);
  376. return NULL;
  377. }
  378. block_pointers[i] = malloc(block_sizes[i]);
  379. }
  380. return block_pointers;
  381. }
  382. bool is_full_speed() {
  383. return MSB_LIMIT == 16;
  384. }
  385. bool recover(MfClassicNonce* n, int ks2, unsigned int in, ProgramState* program_state) {
  386. bool found = false;
  387. const size_t block_sizes[] = {49216, 49216, 5120, 5120, 4096};
  388. const size_t reduced_block_sizes[] = {24608, 24608, 5120, 5120, 4096};
  389. const int num_blocks = sizeof(block_sizes) / sizeof(block_sizes[0]);
  390. void** block_pointers = allocate_blocks(block_sizes, num_blocks);
  391. if(block_pointers == NULL) {
  392. // System has less than the guaranteed amount of RAM (140 KB) - adjust some parameters to run anyway at half speed
  393. if(is_full_speed()) {
  394. //eta_round_time *= 2;
  395. eta_total_time *= 2;
  396. MSB_LIMIT /= 2;
  397. }
  398. block_pointers = allocate_blocks(reduced_block_sizes, num_blocks);
  399. if(block_pointers == NULL) {
  400. // System has less than 70 KB of RAM - should never happen so we don't reduce speed further
  401. program_state->err = InsufficientRAM;
  402. program_state->mfkey_state = Error;
  403. return false;
  404. }
  405. }
  406. struct Msb* odd_msbs = block_pointers[0];
  407. struct Msb* even_msbs = block_pointers[1];
  408. unsigned int* temp_states_odd = block_pointers[2];
  409. unsigned int* temp_states_even = block_pointers[3];
  410. unsigned int* states_buffer = block_pointers[4];
  411. int oks = 0, eks = 0;
  412. int i = 0, msb = 0;
  413. for(i = 31; i >= 0; i -= 2) {
  414. oks = oks << 1 | BEBIT(ks2, i);
  415. }
  416. for(i = 30; i >= 0; i -= 2) {
  417. eks = eks << 1 | BEBIT(ks2, i);
  418. }
  419. int bench_start = furi_hal_rtc_get_timestamp();
  420. program_state->eta_total = eta_total_time;
  421. program_state->eta_timestamp = bench_start;
  422. for(msb = 0; msb <= ((256 / MSB_LIMIT) - 1); msb++) {
  423. program_state->search = msb;
  424. program_state->eta_round = eta_round_time;
  425. program_state->eta_total = eta_total_time - (eta_round_time * msb);
  426. if(calculate_msb_tables(
  427. oks,
  428. eks,
  429. msb,
  430. n,
  431. states_buffer,
  432. odd_msbs,
  433. even_msbs,
  434. temp_states_odd,
  435. temp_states_even,
  436. in,
  437. program_state)) {
  438. //int bench_stop = furi_hal_rtc_get_timestamp();
  439. //FURI_LOG_I(TAG, "Cracked in %i seconds", bench_stop - bench_start);
  440. found = true;
  441. break;
  442. }
  443. if(program_state->close_thread_please) {
  444. break;
  445. }
  446. }
  447. // Free the allocated blocks
  448. for(int i = 0; i < num_blocks; i++) {
  449. free(block_pointers[i]);
  450. }
  451. free(block_pointers);
  452. return found;
  453. }
  454. bool key_already_found_for_nonce_in_solved(
  455. MfClassicKey* keyarray,
  456. int keyarray_size,
  457. MfClassicNonce* nonce) {
  458. for(int k = 0; k < keyarray_size; k++) {
  459. uint64_t key_as_int = bit_lib_bytes_to_num_be(keyarray[k].data, sizeof(MfClassicKey));
  460. struct Crypto1State temp = {0, 0};
  461. for(int i = 0; i < 24; i++) {
  462. (&temp)->odd |= (BIT(key_as_int, 2 * i + 1) << (i ^ 3));
  463. (&temp)->even |= (BIT(key_as_int, 2 * i) << (i ^ 3));
  464. }
  465. if(nonce->attack == mfkey32) {
  466. crypt_word_noret(&temp, nonce->uid_xor_nt1, 0);
  467. crypt_word_noret(&temp, nonce->nr1_enc, 1);
  468. if(nonce->ar1_enc == (crypt_word(&temp) ^ nonce->p64b)) {
  469. return true;
  470. }
  471. } else if(nonce->attack == static_nested) {
  472. uint32_t expected_ks1 = crypt_word_ret(&temp, nonce->uid_xor_nt0, 0);
  473. if(nonce->ks1_1_enc == expected_ks1) {
  474. return true;
  475. }
  476. }
  477. }
  478. return false;
  479. }
  480. #pragma GCC push_options
  481. #pragma GCC optimize("Os")
  482. static void finished_beep() {
  483. // Beep to indicate completion
  484. NotificationApp* notification = furi_record_open("notification");
  485. notification_message(notification, &sequence_audiovisual_alert);
  486. notification_message(notification, &sequence_display_backlight_on);
  487. furi_record_close("notification");
  488. }
  489. void mfkey(ProgramState* program_state) {
  490. MfClassicKey found_key; // recovered key
  491. size_t keyarray_size = 0;
  492. MfClassicKey* keyarray = malloc(sizeof(MfClassicKey) * 1);
  493. uint32_t i = 0, j = 0;
  494. //FURI_LOG_I(TAG, "Free heap before alloc(): %zub", memmgr_get_free_heap());
  495. Storage* storage = furi_record_open(RECORD_STORAGE);
  496. FlipperApplication* app = flipper_application_alloc(storage, firmware_api_interface);
  497. flipper_application_preload(app, APP_ASSETS_PATH("plugins/mfkey_init_plugin.fal"));
  498. flipper_application_map_to_memory(app);
  499. const FlipperAppPluginDescriptor* app_descriptor =
  500. flipper_application_plugin_get_descriptor(app);
  501. const MfkeyPlugin* init_plugin = app_descriptor->entry_point;
  502. // Check for nonces
  503. program_state->mfkey32_present = init_plugin->napi_mf_classic_mfkey32_nonces_check_presence();
  504. program_state->nested_present = init_plugin->napi_mf_classic_nested_nonces_check_presence();
  505. if(!(program_state->mfkey32_present) && !(program_state->nested_present)) {
  506. program_state->err = MissingNonces;
  507. program_state->mfkey_state = Error;
  508. flipper_application_free(app);
  509. furi_record_close(RECORD_STORAGE);
  510. free(keyarray);
  511. return;
  512. }
  513. // Read dictionaries (optional)
  514. KeysDict* system_dict = {0};
  515. bool system_dict_exists = keys_dict_check_presence(KEYS_DICT_SYSTEM_PATH);
  516. KeysDict* user_dict = {0};
  517. bool user_dict_exists = keys_dict_check_presence(KEYS_DICT_USER_PATH);
  518. uint32_t total_dict_keys = 0;
  519. if(system_dict_exists) {
  520. system_dict =
  521. keys_dict_alloc(KEYS_DICT_SYSTEM_PATH, KeysDictModeOpenExisting, sizeof(MfClassicKey));
  522. total_dict_keys += keys_dict_get_total_keys(system_dict);
  523. }
  524. user_dict = keys_dict_alloc(KEYS_DICT_USER_PATH, KeysDictModeOpenAlways, sizeof(MfClassicKey));
  525. if(user_dict_exists) {
  526. total_dict_keys += keys_dict_get_total_keys(user_dict);
  527. }
  528. user_dict_exists = true;
  529. program_state->dict_count = total_dict_keys;
  530. program_state->mfkey_state = DictionaryAttack;
  531. // Read nonces
  532. MfClassicNonceArray* nonce_arr;
  533. nonce_arr = init_plugin->napi_mf_classic_nonce_array_alloc(
  534. system_dict, system_dict_exists, user_dict, program_state);
  535. if(system_dict_exists) {
  536. keys_dict_free(system_dict);
  537. }
  538. if(nonce_arr->total_nonces == 0) {
  539. // Nothing to crack
  540. program_state->err = ZeroNonces;
  541. program_state->mfkey_state = Error;
  542. init_plugin->napi_mf_classic_nonce_array_free(nonce_arr);
  543. flipper_application_free(app);
  544. furi_record_close(RECORD_STORAGE);
  545. keys_dict_free(user_dict);
  546. free(keyarray);
  547. return;
  548. }
  549. flipper_application_free(app);
  550. furi_record_close(RECORD_STORAGE);
  551. // TODO: Track free state at the time this is called to ensure double free does not happen
  552. furi_assert(nonce_arr);
  553. furi_assert(nonce_arr->stream);
  554. buffered_file_stream_close(nonce_arr->stream);
  555. stream_free(nonce_arr->stream);
  556. //FURI_LOG_I(TAG, "Free heap after free(): %zub", memmgr_get_free_heap());
  557. program_state->mfkey_state = MFKeyAttack;
  558. // TODO: Work backwards on this array and free memory
  559. for(i = 0; i < nonce_arr->total_nonces; i++) {
  560. MfClassicNonce next_nonce = nonce_arr->remaining_nonce_array[i];
  561. if(key_already_found_for_nonce_in_solved(keyarray, keyarray_size, &next_nonce)) {
  562. nonce_arr->remaining_nonces--;
  563. (program_state->cracked)++;
  564. (program_state->num_completed)++;
  565. continue;
  566. }
  567. //FURI_LOG_I(TAG, "Beginning recovery for %8lx", next_nonce.uid);
  568. if(next_nonce.attack == mfkey32) {
  569. if(!recover(&next_nonce, next_nonce.ar0_enc ^ next_nonce.p64, 0, program_state)) {
  570. if(program_state->close_thread_please) {
  571. break;
  572. }
  573. // No key found in recover()
  574. (program_state->num_completed)++;
  575. continue;
  576. }
  577. } else if(next_nonce.attack == static_nested) {
  578. if(!recover(
  579. &next_nonce,
  580. next_nonce.ks1_2_enc,
  581. next_nonce.nt1 ^ next_nonce.uid,
  582. program_state)) {
  583. if(program_state->close_thread_please) {
  584. break;
  585. }
  586. // No key found in recover()
  587. (program_state->num_completed)++;
  588. continue;
  589. }
  590. }
  591. (program_state->cracked)++;
  592. (program_state->num_completed)++;
  593. found_key = next_nonce.key;
  594. bool already_found = false;
  595. for(j = 0; j < keyarray_size; j++) {
  596. if(memcmp(keyarray[j].data, found_key.data, MF_CLASSIC_KEY_SIZE) == 0) {
  597. already_found = true;
  598. break;
  599. }
  600. }
  601. if(already_found == false) {
  602. // New key
  603. keyarray = realloc(keyarray, sizeof(MfClassicKey) * (keyarray_size + 1)); //-V701
  604. keyarray_size += 1;
  605. keyarray[keyarray_size - 1] = found_key;
  606. (program_state->unique_cracked)++;
  607. }
  608. }
  609. // TODO: Update display to show all keys were found
  610. // TODO: Prepend found key(s) to user dictionary file
  611. //FURI_LOG_I(TAG, "Unique keys found:");
  612. for(i = 0; i < keyarray_size; i++) {
  613. //FURI_LOG_I(TAG, "%012" PRIx64, keyarray[i]);
  614. keys_dict_add_key(user_dict, keyarray[i].data, sizeof(MfClassicKey));
  615. }
  616. if(keyarray_size > 0) {
  617. dolphin_deed(DolphinDeedNfcMfcAdd);
  618. }
  619. free(nonce_arr);
  620. keys_dict_free(user_dict);
  621. free(keyarray);
  622. if(program_state->mfkey_state == Error) {
  623. return;
  624. }
  625. //FURI_LOG_I(TAG, "mfkey function completed normally"); // DEBUG
  626. program_state->mfkey_state = Complete;
  627. // No need to alert the user if they asked it to stop
  628. if(!(program_state->close_thread_please)) {
  629. finished_beep();
  630. }
  631. return;
  632. }
  633. // Screen is 128x64 px
  634. static void render_callback(Canvas* const canvas, void* ctx) {
  635. furi_assert(ctx);
  636. ProgramState* program_state = ctx;
  637. furi_mutex_acquire(program_state->mutex, FuriWaitForever);
  638. char draw_str[44] = {};
  639. canvas_draw_frame(canvas, 0, 0, 128, 64);
  640. canvas_draw_frame(canvas, 0, 15, 128, 64);
  641. canvas_set_font(canvas, FontPrimary);
  642. canvas_draw_str_aligned(canvas, 5, 4, AlignLeft, AlignTop, "MFKey");
  643. snprintf(draw_str, sizeof(draw_str), "RAM: %zub", memmgr_get_free_heap());
  644. canvas_set_font(canvas, FontSecondary);
  645. canvas_draw_str_aligned(canvas, 48, 5, AlignLeft, AlignTop, draw_str);
  646. canvas_draw_icon(canvas, 114, 4, &I_mfkey);
  647. if(program_state->is_thread_running && program_state->mfkey_state == MFKeyAttack) {
  648. float eta_round = (float)1 - ((float)program_state->eta_round / (float)eta_round_time);
  649. float eta_total = (float)1 - ((float)program_state->eta_total / (float)eta_total_time);
  650. float progress = (float)program_state->num_completed / (float)program_state->total;
  651. if(eta_round < 0) {
  652. // Round ETA miscalculated
  653. eta_round = 1;
  654. program_state->eta_round = 0;
  655. }
  656. if(eta_total < 0) {
  657. // Total ETA miscalculated
  658. eta_total = 1;
  659. program_state->eta_total = 0;
  660. }
  661. canvas_set_font(canvas, FontSecondary);
  662. snprintf(
  663. draw_str,
  664. sizeof(draw_str),
  665. "Cracking: %d/%d - in prog.",
  666. program_state->num_completed,
  667. program_state->total);
  668. elements_progress_bar_with_text(canvas, 5, 18, 118, progress, draw_str);
  669. snprintf(
  670. draw_str,
  671. sizeof(draw_str),
  672. "Round: %d/%d - ETA %02d Sec",
  673. (program_state->search) + 1, // Zero indexed
  674. 256 / MSB_LIMIT,
  675. program_state->eta_round);
  676. elements_progress_bar_with_text(canvas, 5, 31, 118, eta_round, draw_str);
  677. snprintf(draw_str, sizeof(draw_str), "Total ETA %03d Sec", program_state->eta_total);
  678. elements_progress_bar_with_text(canvas, 5, 44, 118, eta_total, draw_str);
  679. } else if(program_state->is_thread_running && program_state->mfkey_state == DictionaryAttack) {
  680. canvas_set_font(canvas, FontSecondary);
  681. snprintf(
  682. draw_str, sizeof(draw_str), "Dict solves: %d (in progress)", program_state->cracked);
  683. canvas_draw_str_aligned(canvas, 10, 18, AlignLeft, AlignTop, draw_str);
  684. snprintf(draw_str, sizeof(draw_str), "Keys in dict: %d", program_state->dict_count);
  685. canvas_draw_str_aligned(canvas, 26, 28, AlignLeft, AlignTop, draw_str);
  686. } else if(program_state->mfkey_state == Complete) {
  687. // TODO: Scrollable list view to see cracked keys if user presses down
  688. elements_progress_bar(canvas, 5, 18, 118, 1);
  689. canvas_set_font(canvas, FontSecondary);
  690. snprintf(draw_str, sizeof(draw_str), "Complete");
  691. canvas_draw_str_aligned(canvas, 40, 31, AlignLeft, AlignTop, draw_str);
  692. snprintf(
  693. draw_str,
  694. sizeof(draw_str),
  695. "Keys added to user dict: %d",
  696. program_state->unique_cracked);
  697. canvas_draw_str_aligned(canvas, 10, 41, AlignLeft, AlignTop, draw_str);
  698. } else if(program_state->mfkey_state == Ready) {
  699. canvas_set_font(canvas, FontSecondary);
  700. canvas_draw_str_aligned(canvas, 50, 30, AlignLeft, AlignTop, "Ready");
  701. elements_button_center(canvas, "Start");
  702. elements_button_right(canvas, "Help");
  703. } else if(program_state->mfkey_state == Help) {
  704. canvas_set_font(canvas, FontSecondary);
  705. canvas_draw_str_aligned(canvas, 7, 20, AlignLeft, AlignTop, "Collect nonces by reading");
  706. canvas_draw_str_aligned(canvas, 7, 30, AlignLeft, AlignTop, "tag or reader in NFC app:");
  707. canvas_draw_str_aligned(canvas, 7, 40, AlignLeft, AlignTop, "https://docs.flipper.net/");
  708. canvas_draw_str_aligned(canvas, 7, 50, AlignLeft, AlignTop, "nfc/mfkey32");
  709. } else if(program_state->mfkey_state == Error) {
  710. canvas_draw_str_aligned(canvas, 50, 25, AlignLeft, AlignTop, "Error");
  711. canvas_set_font(canvas, FontSecondary);
  712. if(program_state->err == MissingNonces) {
  713. canvas_draw_str_aligned(canvas, 25, 36, AlignLeft, AlignTop, "No nonces found");
  714. } else if(program_state->err == ZeroNonces) {
  715. canvas_draw_str_aligned(canvas, 15, 36, AlignLeft, AlignTop, "Nonces already cracked");
  716. } else if(program_state->err == InsufficientRAM) {
  717. canvas_draw_str_aligned(canvas, 35, 36, AlignLeft, AlignTop, "No free RAM");
  718. } else {
  719. // Unhandled error
  720. }
  721. } else {
  722. // Unhandled program state
  723. }
  724. furi_mutex_release(program_state->mutex);
  725. }
  726. static void input_callback(InputEvent* input_event, void* event_queue) {
  727. furi_assert(event_queue);
  728. furi_message_queue_put((FuriMessageQueue*)event_queue, input_event, FuriWaitForever);
  729. }
  730. static void mfkey_state_init(ProgramState* program_state) {
  731. program_state->is_thread_running = false;
  732. program_state->mfkey_state = Ready;
  733. program_state->cracked = 0;
  734. program_state->unique_cracked = 0;
  735. program_state->num_completed = 0;
  736. program_state->total = 0;
  737. program_state->dict_count = 0;
  738. }
  739. // Entrypoint for worker thread
  740. static int32_t mfkey_worker_thread(void* ctx) {
  741. ProgramState* program_state = ctx;
  742. program_state->is_thread_running = true;
  743. program_state->mfkey_state = Initializing;
  744. //FURI_LOG_I(TAG, "Hello from the mfkey worker thread"); // DEBUG
  745. mfkey(program_state);
  746. program_state->is_thread_running = false;
  747. return 0;
  748. }
  749. int32_t mfkey_main() {
  750. FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(InputEvent));
  751. ProgramState* program_state = malloc(sizeof(ProgramState));
  752. mfkey_state_init(program_state);
  753. program_state->mutex = furi_mutex_alloc(FuriMutexTypeNormal);
  754. // Set system callbacks
  755. ViewPort* view_port = view_port_alloc();
  756. view_port_draw_callback_set(view_port, render_callback, program_state);
  757. view_port_input_callback_set(view_port, input_callback, event_queue);
  758. // Open GUI and register view_port
  759. Gui* gui = furi_record_open(RECORD_GUI);
  760. gui_add_view_port(gui, view_port, GuiLayerFullscreen);
  761. program_state->mfkeythread = furi_thread_alloc();
  762. furi_thread_set_name(program_state->mfkeythread, "MFKeyWorker");
  763. furi_thread_set_stack_size(program_state->mfkeythread, 2048);
  764. furi_thread_set_context(program_state->mfkeythread, program_state);
  765. furi_thread_set_callback(program_state->mfkeythread, mfkey_worker_thread);
  766. InputEvent input_event;
  767. for(bool main_loop = true; main_loop;) {
  768. FuriStatus event_status = furi_message_queue_get(event_queue, &input_event, 100);
  769. furi_mutex_acquire(program_state->mutex, FuriWaitForever);
  770. if(event_status == FuriStatusOk) {
  771. if(input_event.type == InputTypePress) {
  772. switch(input_event.key) {
  773. case InputKeyRight:
  774. if(!program_state->is_thread_running && program_state->mfkey_state == Ready) {
  775. program_state->mfkey_state = Help;
  776. }
  777. break;
  778. case InputKeyOk:
  779. if(!program_state->is_thread_running && program_state->mfkey_state == Ready) {
  780. furi_thread_start(program_state->mfkeythread);
  781. }
  782. break;
  783. case InputKeyBack:
  784. if(!program_state->is_thread_running && program_state->mfkey_state == Help) {
  785. program_state->mfkey_state = Ready;
  786. } else {
  787. program_state->close_thread_please = true;
  788. if(program_state->is_thread_running) {
  789. // Wait until thread is finished
  790. furi_thread_join(program_state->mfkeythread);
  791. }
  792. program_state->close_thread_please = false;
  793. main_loop = false;
  794. }
  795. break;
  796. default:
  797. break;
  798. }
  799. }
  800. }
  801. furi_mutex_release(program_state->mutex);
  802. view_port_update(view_port);
  803. }
  804. furi_thread_free(program_state->mfkeythread);
  805. view_port_enabled_set(view_port, false);
  806. gui_remove_view_port(gui, view_port);
  807. furi_record_close(RECORD_GUI);
  808. view_port_free(view_port);
  809. furi_message_queue_free(event_queue);
  810. furi_mutex_free(program_state->mutex);
  811. free(program_state);
  812. return 0;
  813. }
  814. #pragma GCC pop_options