mfkey.c 32 KB

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