bip.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. /*
  2. * Parser for bip card (Georgia).
  3. *
  4. * Copyright 2023 Leptoptilos <leptoptilos@icloud.com>
  5. *
  6. * This program is free software: you can redistribute it and/or modify it
  7. * under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful, but
  12. * WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include <flipper_application.h>
  20. #include "../../metroflip_i.h"
  21. #include <nfc/protocols/mf_classic/mf_classic_poller_sync.h>
  22. #include <nfc/protocols/mf_classic/mf_classic.h>
  23. #include <nfc/protocols/mf_classic/mf_classic_poller.h>
  24. #include <dolphin/dolphin.h>
  25. #include <bit_lib.h>
  26. #include <furi_hal.h>
  27. #include <nfc/nfc.h>
  28. #include <nfc/nfc_device.h>
  29. #include <nfc/nfc_listener.h>
  30. #include <locale/locale.h>
  31. #include "../../api/metroflip/metroflip_api.h"
  32. #include "../../metroflip_plugins.h"
  33. #define TAG "Metroflip:Scene:Bip"
  34. #define BIP_CARD_ID_SECTOR_NUMBER (0)
  35. #define BIP_BALANCE_SECTOR_NUMBER (8)
  36. #define BIP_TRIP_TIME_WINDOW_SECTOR_NUMBER (5)
  37. #define BIP_LAST_TOP_UPS_SECTOR_NUMBER (10)
  38. #define BIP_TRIPS_INFO_SECTOR_NUMBER (11)
  39. const MfClassicKeyPair bip_1k_keys[16] = {
  40. {.a = 0x3a42f33af429, .b = 0x1fc235ac1309},
  41. {.a = 0x6338a371c0ed, .b = 0x243f160918d1},
  42. {.a = 0xf124c2578ad0, .b = 0x9afc42372af1},
  43. {.a = 0x32ac3b90ac13, .b = 0x682d401abb09},
  44. {.a = 0x4ad1e273eaf1, .b = 0x067db45454a9},
  45. {.a = 0xe2c42591368a, .b = 0x15fc4c7613fe},
  46. {.a = 0x2a3c347a1200, .b = 0x68d30288910a},
  47. {.a = 0x16f3d5ab1139, .b = 0xf59a36a2546d},
  48. {.a = 0x937a4fff3011, .b = 0x64e3c10394c2},
  49. {.a = 0x35c3d2caee88, .b = 0xb736412614af},
  50. {.a = 0x693143f10368, .b = 0x324f5df65310},
  51. {.a = 0xa3f97428dd01, .b = 0x643fb6de2217},
  52. {.a = 0x63f17a449af0, .b = 0x82f435dedf01},
  53. {.a = 0xc4652c54261c, .b = 0x0263de1278f3},
  54. {.a = 0xd49e2826664f, .b = 0x51284c3686a6},
  55. {.a = 0x3df14c8000a1, .b = 0x6a470d54127c},
  56. };
  57. typedef struct {
  58. DateTime datetime;
  59. uint16_t amount;
  60. } BipTransaction;
  61. static void bip_parse_datetime(const MfClassicBlock* block, DateTime* parsed_data) {
  62. furi_assert(block);
  63. furi_assert(parsed_data);
  64. parsed_data->day = (((block->data[1] << 8) + block->data[0]) >> 6) & 0x1f;
  65. parsed_data->month = (((block->data[1] << 8) + block->data[0]) >> 11) & 0xf;
  66. parsed_data->year = 2000 + ((((block->data[2] << 8) + block->data[1]) >> 7) & 0x1f);
  67. parsed_data->hour = (((block->data[3] << 8) + block->data[2]) >> 4) & 0x1f;
  68. parsed_data->minute = (((block->data[3] << 8) + block->data[2]) >> 9) & 0x3f;
  69. parsed_data->second = (((block->data[4] << 8) + block->data[3]) >> 7) & 0x3f;
  70. }
  71. static void bip_print_datetime(const DateTime* datetime, FuriString* str) {
  72. furi_assert(datetime);
  73. furi_assert(str);
  74. LocaleDateFormat date_format = locale_get_date_format();
  75. const char* separator = (date_format == LocaleDateFormatDMY) ? "." : "/";
  76. FuriString* date_str = furi_string_alloc();
  77. locale_format_date(date_str, datetime, date_format, separator);
  78. FuriString* time_str = furi_string_alloc();
  79. locale_format_time(time_str, datetime, locale_get_time_format(), true);
  80. furi_string_cat_printf(
  81. str, "%s %s", furi_string_get_cstr(date_str), furi_string_get_cstr(time_str));
  82. furi_string_free(date_str);
  83. furi_string_free(time_str);
  84. }
  85. static int datetime_cmp(const DateTime* dt_1, const DateTime* dt_2) {
  86. furi_assert(dt_1);
  87. furi_assert(dt_2);
  88. if(dt_1->year != dt_2->year) {
  89. return dt_1->year - dt_2->year;
  90. }
  91. if(dt_1->month != dt_2->month) {
  92. return dt_1->month - dt_2->month;
  93. }
  94. if(dt_1->day != dt_2->day) {
  95. return dt_1->day - dt_2->day;
  96. }
  97. if(dt_1->hour != dt_2->hour) {
  98. return dt_1->hour - dt_2->hour;
  99. }
  100. if(dt_1->minute != dt_2->minute) {
  101. return dt_1->minute - dt_2->minute;
  102. }
  103. if(dt_1->second != dt_2->second) {
  104. return dt_1->second - dt_2->second;
  105. }
  106. return 0;
  107. }
  108. static bool is_bip_block_empty(const MfClassicBlock* block) {
  109. furi_assert(block);
  110. // check if all but last byte are zero (last is checksum)
  111. for(size_t i = 0; i < sizeof(block->data) - 1; i++) {
  112. if(block->data[i] != 0) {
  113. return false;
  114. }
  115. }
  116. return true;
  117. }
  118. static bool bip_parse(FuriString* parsed_data, const MfClassicData* data) {
  119. furi_assert(parsed_data);
  120. struct {
  121. uint32_t card_id;
  122. uint16_t balance;
  123. uint16_t flags;
  124. DateTime trip_time_window;
  125. BipTransaction top_ups[3];
  126. BipTransaction charges[3];
  127. } bip_data = {0};
  128. bool parsed = false;
  129. do {
  130. // verify sector 0 key A
  131. MfClassicSectorTrailer* sec_tr = mf_classic_get_sector_trailer_by_sector(data, 0);
  132. if(data->type != MfClassicType1k) break;
  133. uint64_t key = bit_lib_bytes_to_num_be(sec_tr->key_a.data, 6);
  134. if(key != bip_1k_keys[0].a) {
  135. break;
  136. }
  137. // Get Card ID, little-endian 4 bytes at sector 0 block 1, bytes 4-7
  138. const uint8_t card_id_start_block_num =
  139. mf_classic_get_first_block_num_of_sector(BIP_CARD_ID_SECTOR_NUMBER);
  140. const uint8_t* block_start_ptr = &data->block[card_id_start_block_num + 1].data[0];
  141. bip_data.card_id = bit_lib_bytes_to_num_le(block_start_ptr + 4, 4);
  142. // Get balance, little-endian 2 bytes at sector 8 block 1, bytes 0-1
  143. const uint8_t balance_start_block_num =
  144. mf_classic_get_first_block_num_of_sector(BIP_BALANCE_SECTOR_NUMBER);
  145. block_start_ptr = &data->block[balance_start_block_num + 1].data[0];
  146. bip_data.balance = bit_lib_bytes_to_num_le(block_start_ptr, 2);
  147. // Get balance flags (negative balance, etc.), little-endian 2 bytes at sector 8 block 1, bytes 2-3
  148. bip_data.flags = bit_lib_bytes_to_num_le(block_start_ptr + 2, 2);
  149. // Get trip time window, proprietary format, at sector 5 block 1, bytes 0-7
  150. const uint8_t trip_time_window_start_block_num =
  151. mf_classic_get_first_block_num_of_sector(BIP_TRIP_TIME_WINDOW_SECTOR_NUMBER);
  152. const MfClassicBlock* trip_window_block_ptr =
  153. &data->block[trip_time_window_start_block_num + 1];
  154. bip_parse_datetime(trip_window_block_ptr, &bip_data.trip_time_window);
  155. // Last 3 top-ups: sector 10, ring-buffer of 3 blocks, timestamp in bytes 0-7, amount in bytes 9-10
  156. const uint8_t top_ups_start_block_num =
  157. mf_classic_get_first_block_num_of_sector(BIP_LAST_TOP_UPS_SECTOR_NUMBER);
  158. for(size_t i = 0; i < 3; i++) {
  159. const MfClassicBlock* block = &data->block[top_ups_start_block_num + i];
  160. if(is_bip_block_empty(block)) continue;
  161. BipTransaction* top_up = &bip_data.top_ups[i];
  162. bip_parse_datetime(block, &top_up->datetime);
  163. top_up->amount = bit_lib_bytes_to_num_le(&block->data[9], 2) >> 2;
  164. }
  165. // Last 3 charges (i.e. trips), sector 11, ring-buffer of 3 blocks, timestamp in bytes 0-7, amount in bytes 10-11
  166. const uint8_t trips_start_block_num =
  167. mf_classic_get_first_block_num_of_sector(BIP_TRIPS_INFO_SECTOR_NUMBER);
  168. for(size_t i = 0; i < 3; i++) {
  169. const MfClassicBlock* block = &data->block[trips_start_block_num + i];
  170. if(is_bip_block_empty(block)) continue;
  171. BipTransaction* charge = &bip_data.charges[i];
  172. bip_parse_datetime(block, &charge->datetime);
  173. charge->amount = bit_lib_bytes_to_num_le(&block->data[10], 2) >> 2;
  174. }
  175. // All data is now parsed and stored in bip_data, now print it
  176. // Print basic info
  177. furi_string_printf(
  178. parsed_data,
  179. "\e#Tarjeta Bip!\n"
  180. "Card Number: %lu\n"
  181. "Balance: $%hu (flags %hu)\n"
  182. "Current Trip Window Ends:\n @",
  183. bip_data.card_id,
  184. bip_data.balance,
  185. bip_data.flags);
  186. bip_print_datetime(&bip_data.trip_time_window, parsed_data);
  187. // Find newest top-up
  188. size_t newest_top_up = 0;
  189. for(size_t i = 1; i < 3; i++) {
  190. const DateTime* newest = &bip_data.top_ups[newest_top_up].datetime;
  191. const DateTime* current = &bip_data.top_ups[i].datetime;
  192. if(datetime_cmp(current, newest) > 0) {
  193. newest_top_up = i;
  194. }
  195. }
  196. // Print top-ups, newest first
  197. furi_string_cat_printf(parsed_data, "\n\e#Last Top-ups");
  198. for(size_t i = 0; i < 3; i++) {
  199. const BipTransaction* top_up = &bip_data.top_ups[(3u + newest_top_up - i) % 3];
  200. furi_string_cat_printf(parsed_data, "\n+$%d\n @", top_up->amount);
  201. bip_print_datetime(&top_up->datetime, parsed_data);
  202. }
  203. // Find newest charge
  204. size_t newest_charge = 0;
  205. for(size_t i = 1; i < 3; i++) {
  206. const DateTime* newest = &bip_data.charges[newest_charge].datetime;
  207. const DateTime* current = &bip_data.charges[i].datetime;
  208. if(datetime_cmp(current, newest) > 0) {
  209. newest_charge = i;
  210. }
  211. }
  212. // Print charges
  213. furi_string_cat_printf(parsed_data, "\n\e#Last Charges (Trips)");
  214. for(size_t i = 0; i < 3; i++) {
  215. const BipTransaction* charge = &bip_data.charges[(3u + newest_charge - i) % 3];
  216. furi_string_cat_printf(parsed_data, "\n-$%d\n @", charge->amount);
  217. bip_print_datetime(&charge->datetime, parsed_data);
  218. }
  219. parsed = true;
  220. } while(false);
  221. return parsed;
  222. }
  223. static NfcCommand bip_poller_callback(NfcGenericEvent event, void* context) {
  224. furi_assert(context);
  225. furi_assert(event.event_data);
  226. furi_assert(event.protocol == NfcProtocolMfClassic);
  227. NfcCommand command = NfcCommandContinue;
  228. const MfClassicPollerEvent* mfc_event = event.event_data;
  229. Metroflip* app = context;
  230. if(mfc_event->type == MfClassicPollerEventTypeCardDetected) {
  231. view_dispatcher_send_custom_event(app->view_dispatcher, MetroflipCustomEventCardDetected);
  232. command = NfcCommandContinue;
  233. } else if(mfc_event->type == MfClassicPollerEventTypeCardLost) {
  234. view_dispatcher_send_custom_event(app->view_dispatcher, MetroflipCustomEventCardLost);
  235. app->sec_num = 0;
  236. command = NfcCommandStop;
  237. } else if(mfc_event->type == MfClassicPollerEventTypeRequestMode) {
  238. mfc_event->data->poller_mode.mode = MfClassicPollerModeRead;
  239. } else if(mfc_event->type == MfClassicPollerEventTypeRequestReadSector) {
  240. MfClassicKey key = {0};
  241. bit_lib_num_to_bytes_be(bip_1k_keys[app->sec_num].a, COUNT_OF(key.data), key.data);
  242. MfClassicKeyType key_type = MfClassicKeyTypeA;
  243. mfc_event->data->read_sector_request_data.sector_num = app->sec_num;
  244. mfc_event->data->read_sector_request_data.key = key;
  245. mfc_event->data->read_sector_request_data.key_type = key_type;
  246. mfc_event->data->read_sector_request_data.key_provided = true;
  247. if(app->sec_num == 16) {
  248. mfc_event->data->read_sector_request_data.key_provided = false;
  249. app->sec_num = 0;
  250. }
  251. app->sec_num++;
  252. } else if(mfc_event->type == MfClassicPollerEventTypeSuccess) {
  253. nfc_device_set_data(
  254. app->nfc_device, NfcProtocolMfClassic, nfc_poller_get_data(app->poller));
  255. const MfClassicData* mfc_data = nfc_device_get_data(app->nfc_device, NfcProtocolMfClassic);
  256. FuriString* parsed_data = furi_string_alloc();
  257. Widget* widget = app->widget;
  258. dolphin_deed(DolphinDeedNfcReadSuccess);
  259. furi_string_reset(app->text_box_store);
  260. if(!bip_parse(parsed_data, mfc_data)) {
  261. furi_string_reset(app->text_box_store);
  262. FURI_LOG_I(TAG, "Unknown card type");
  263. furi_string_printf(parsed_data, "\e#Unknown card\n");
  264. }
  265. metroflip_app_blink_stop(app);
  266. widget_add_text_scroll_element(widget, 0, 0, 128, 64, furi_string_get_cstr(parsed_data));
  267. widget_add_button_element(
  268. widget, GuiButtonTypeRight, "Exit", metroflip_exit_widget_callback, app);
  269. widget_add_button_element(
  270. widget, GuiButtonTypeCenter, "Save", metroflip_save_widget_callback, app);
  271. furi_string_free(parsed_data);
  272. view_dispatcher_switch_to_view(app->view_dispatcher, MetroflipViewWidget);
  273. command = NfcCommandStop;
  274. } else if(mfc_event->type == MfClassicPollerEventTypeFail) {
  275. FURI_LOG_I(TAG, "fail");
  276. command = NfcCommandStop;
  277. }
  278. return command;
  279. }
  280. static void bip_on_enter(Metroflip* app) {
  281. dolphin_deed(DolphinDeedNfcRead);
  282. app->sec_num = 0;
  283. if(app->data_loaded) {
  284. Storage* storage = furi_record_open(RECORD_STORAGE);
  285. FlipperFormat* ff = flipper_format_file_alloc(storage);
  286. if(flipper_format_file_open_existing(ff, app->file_path)) {
  287. MfClassicData* mfc_data = mf_classic_alloc();
  288. mf_classic_load(mfc_data, ff, 2);
  289. FuriString* parsed_data = furi_string_alloc();
  290. Widget* widget = app->widget;
  291. furi_string_reset(app->text_box_store);
  292. if(!bip_parse(parsed_data, mfc_data)) {
  293. furi_string_reset(app->text_box_store);
  294. FURI_LOG_I(TAG, "Unknown card type");
  295. furi_string_printf(parsed_data, "\e#Unknown card\n");
  296. }
  297. widget_add_text_scroll_element(
  298. widget, 0, 0, 128, 64, furi_string_get_cstr(parsed_data));
  299. widget_add_button_element(
  300. widget, GuiButtonTypeRight, "Exit", metroflip_exit_widget_callback, app);
  301. widget_add_button_element(
  302. widget, GuiButtonTypeCenter, "Delete", metroflip_delete_widget_callback, app);
  303. mf_classic_free(mfc_data);
  304. furi_string_free(parsed_data);
  305. view_dispatcher_switch_to_view(app->view_dispatcher, MetroflipViewWidget);
  306. }
  307. flipper_format_free(ff);
  308. } else {
  309. // Setup view
  310. Popup* popup = app->popup;
  311. popup_set_header(popup, "Apply\n card to\nthe back", 68, 30, AlignLeft, AlignTop);
  312. popup_set_icon(popup, 0, 3, &I_RFIDDolphinReceive_97x61);
  313. // Start worker
  314. view_dispatcher_switch_to_view(app->view_dispatcher, MetroflipViewPopup);
  315. app->poller = nfc_poller_alloc(app->nfc, NfcProtocolMfClassic);
  316. nfc_poller_start(app->poller, bip_poller_callback, app);
  317. metroflip_app_blink_start(app);
  318. }
  319. }
  320. static bool bip_on_event(Metroflip* app, SceneManagerEvent event) {
  321. bool consumed = false;
  322. if(event.type == SceneManagerEventTypeCustom) {
  323. if(event.event == MetroflipCustomEventCardDetected) {
  324. Popup* popup = app->popup;
  325. popup_set_header(popup, "DON'T\nMOVE", 68, 30, AlignLeft, AlignTop);
  326. consumed = true;
  327. } else if(event.event == MetroflipCustomEventCardLost) {
  328. Popup* popup = app->popup;
  329. popup_set_header(popup, "Card \n lost", 68, 30, AlignLeft, AlignTop);
  330. consumed = true;
  331. } else if(event.event == MetroflipCustomEventWrongCard) {
  332. Popup* popup = app->popup;
  333. popup_set_header(popup, "WRONG \n CARD", 68, 30, AlignLeft, AlignTop);
  334. consumed = true;
  335. } else if(event.event == MetroflipCustomEventPollerFail) {
  336. Popup* popup = app->popup;
  337. popup_set_header(popup, "Failed", 68, 30, AlignLeft, AlignTop);
  338. consumed = true;
  339. }
  340. } else if(event.type == SceneManagerEventTypeBack) {
  341. scene_manager_search_and_switch_to_previous_scene(app->scene_manager, MetroflipSceneStart);
  342. consumed = true;
  343. }
  344. return consumed;
  345. }
  346. static void bip_on_exit(Metroflip* app) {
  347. widget_reset(app->widget);
  348. if(app->poller && !app->data_loaded) {
  349. nfc_poller_stop(app->poller);
  350. nfc_poller_free(app->poller);
  351. }
  352. // Clear view
  353. popup_reset(app->popup);
  354. metroflip_app_blink_stop(app);
  355. }
  356. /* Actual implementation of app<>plugin interface */
  357. static const MetroflipPlugin bip_plugin = {
  358. .card_name = "Bip",
  359. .plugin_on_enter = bip_on_enter,
  360. .plugin_on_event = bip_on_event,
  361. .plugin_on_exit = bip_on_exit,
  362. };
  363. /* Plugin descriptor to comply with basic plugin specification */
  364. static const FlipperAppPluginDescriptor bip_plugin_descriptor = {
  365. .appid = METROFLIP_SUPPORTED_CARD_PLUGIN_APP_ID,
  366. .ep_api_version = METROFLIP_SUPPORTED_CARD_PLUGIN_API_VERSION,
  367. .entry_point = &bip_plugin,
  368. };
  369. /* Plugin entry point - must return a pointer to const descriptor */
  370. const FlipperAppPluginDescriptor* bip_plugin_ep(void) {
  371. return &bip_plugin_descriptor;
  372. }