mfkey.c 31 KB

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