charliecard.c 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363
  1. /*
  2. * Parser for MBTA CharlieCard (Boston, MA, USA).
  3. *
  4. * Copyright 2024 Zachary Weiss <me@zachary.ws>
  5. *
  6. * Public security research on the MBTA's fare system stretches back to 2008,
  7. * starting with Russel Ryan, Zack Anderson, and Alessandro Chiesa's
  8. * "Anatomy of a Subway Hack", for which they were famously issued a gag order.
  9. * A thorough history of research & researchers deserving of credit is
  10. * detailed by @bobbyrsec in his 2022 blog post (& presentation):
  11. * "Operation Charlie: Hacking the MBTA CharlieCard from 2008 to Present"
  12. * https://medium.com/@bobbyrsec/operation-charlie-hacking-the-mbta-charliecard-from-2008-to-present-24ea9f0aaa38
  13. *
  14. * Fare gate IDs, card types, and general assistance courtesy of the
  15. * minds behind DEFCON 31's "Boston Infinite Money Glitch" presentation:
  16. * — Matthew Harris; mattyharris.net <matty@mattyharris.net>
  17. * — Zachary Bertocchi; zackbertocchi.com <zach@zachbertocci.com>
  18. * — Scott Campbell; josephscottcampbell.com <scott@josephscottcampbell.com>
  19. * — Noah Gibson; <noahgibson06@proton.me>
  20. * Talk available at: https://www.youtube.com/watch?v=1JT_lTfK69Q
  21. *
  22. * TODOs:
  23. * — Reverse engineer passes (sectors 4 & 5?), impl.
  24. * — Infer transaction flag meanings
  25. * — Infer remaining unknown bytes in the balance sectors (2 & 3)
  26. * — Improve string output formatting, esp. of transaction log
  27. * — Mapping of buses to garages, and subsequently, route subsets via
  28. * http://roster.transithistory.org/ data
  29. * — Mapping of stations to lines
  30. * — Add'l data fields for side of station fare gates are on? Some stations
  31. * separate inbound & outbound sides, so direction could be inferred
  32. * from gates used.
  33. * — Continually gather data on fare gate ID mappings, update as collected;
  34. * check locations this might be scrapable / inferrable from:
  35. * [X] MBTA GTFS spec (https://www.mbta.com/developers/gtfs) features & IDs
  36. * seem too-coarse-grained & uncorrelated
  37. * [X] MBTA ArcGIS (https://mbta-massdot.opendata.arcgis.com/) & Tableau
  38. * (https://public.tableau.com/app/profile/mbta.office.of.performance.management.and.innovation/vizzes)
  39. * files don't seem to have anything of that resolution (only down to ridership by station)
  40. * [X] (skim of) MBTA public GitHub (https://github.com/mbta) repos make no reference to fare-gate-level data
  41. * [X] (skim of) MBTA public engineering docs (https://www.mbta.com/engineering) unfruitful;
  42. * Closest mention spotted is 2014 "Ridership and Service Statistics"
  43. * (https://cdn.mbta.com/sites/default/files/fmcb-meeting-docs/reports-policies/2014-07-mbta-bluebook-ed14.pdf)
  44. * where on pg.40, "Equipment at Stations" is enumerated, and fare gates counts are given,
  45. * listed as "AFC Gates" (presumably standing for "Automated Fare Collection")
  46. * [X] Josiah Zachery criminal trial public evidence — convicted partially on
  47. * data on his CharlieCard, appeals partially on basis of legality of this search.
  48. * Prev. court case (gag order mentioned in preamble) leaked some data in the files
  49. * entered into evidence. Seemingly did not happen here; fare gate IDs unmentioned,
  50. * only ever the nature of stored/saved data and methods of retrieval.
  51. * Appelate case dockets 2019-P-0401, SJC-12952, SJ-2017-0390
  52. * (https://www.ma-appellatecourts.org/party)
  53. * Trial court indictment 04/02/2015, Case# 1584CR10265 @Suffolk County Criminal Superior Court
  54. * (https://www.masscourts.org/eservices/home.page.16)
  55. * [ ] FOIA / public records request?
  56. * (https://massachusettsdot.mycusthelp.com/WEBAPP/_rs/(S(tbcygdlm0oojy35p1wv0y2y5))/supporthome.aspx)
  57. * [X] MBTA data blog? (https://www.massdottracker.com/datablog/)
  58. * [ ] MassDOT developers Google group? (https://groups.google.com/g/massdotdevelopers)
  59. * [X] preexisting posts
  60. * [ ] ask directly?
  61. * [ ] Other?
  62. *
  63. * This program is free software: you can redistribute it and/or modify it
  64. * under the terms of the GNU General Public License as published by
  65. * the Free Software Foundation, either version 3 of the License, or
  66. * (at your option) any later version.
  67. *
  68. * This program is distributed in the hope that it will be useful, but
  69. * WITHOUT ANY WARRANTY; without even the implied warranty of
  70. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  71. * General Public License for more details.
  72. *
  73. * You should have received a copy of the GNU General Public License
  74. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  75. */
  76. #include <flipper_application.h>
  77. #include "../../metroflip_i.h"
  78. #include "../../metroflip_plugins.h"
  79. #include "../../api/metroflip/metroflip_api.h"
  80. #include <nfc/protocols/mf_classic/mf_classic_poller_sync.h>
  81. #include <nfc/protocols/mf_classic/mf_classic.h>
  82. #include <nfc/protocols/mf_classic/mf_classic_poller.h>
  83. #include <dolphin/dolphin.h>
  84. #include <bit_lib.h>
  85. #include <datetime.h>
  86. #include <furi_hal.h>
  87. #include <locale/locale.h>
  88. #include <nfc/nfc.h>
  89. #include <nfc/nfc_device.h>
  90. #include <nfc/nfc_listener.h>
  91. #include "../../api/metroflip/metroflip_api.h"
  92. #define TAG "Metroflip:Scene:CharlieCard"
  93. // starts Wednesday 2003/1/1 @ midnight
  94. #define CHARLIE_EPOCH \
  95. (DateTime) { \
  96. 0, 0, 0, 1, 1, 2003, 4 \
  97. }
  98. // timestep is one minute
  99. #define CHARLIE_TIME_DELTA_SECS 60
  100. #define CHARLIE_END_VALID_DELTA_SECS 60 * 8
  101. #define CHARLIE_N_TRANSACTION_HISTORY 10
  102. #define CHARLIE_N_PASSES 4
  103. // always from the same set of keys (cf. default keys dict for list w/o multiplicity)
  104. // we only care about the data in the first half of the sectors
  105. // second half sectors keys seemingly change position sometimes across cards?
  106. // no data stored there, but might want to impl some custom read function
  107. // accounting for this such that reading is faster (else it seems to fall back on dict
  108. // approach for remaining keys)...
  109. typedef struct {
  110. uint16_t dollars;
  111. uint8_t cents;
  112. } Money;
  113. // always from the same set of keys (cf. default keys dict for list w/o multiplicity)
  114. // we only care about the data in the first half of the sectors
  115. // second half sectors keys seemingly change position sometimes across cards?
  116. // no data stored there, but might want to impl some custom read function
  117. // accounting for this such that reading is faster (else it seems to fall back on dict
  118. // approach for remaining keys)...
  119. const MfClassicKeyPair charliecard_1k_keys[] = {
  120. {.a = 0x3060206F5B0A, .b = 0xF1B9F5669CC8},
  121. {.a = 0x5EC39B022F2B, .b = 0xF662248E7E89},
  122. {.a = 0x5EC39B022F2B, .b = 0xF662248E7E89},
  123. {.a = 0x5EC39B022F2B, .b = 0xF662248E7E89},
  124. {.a = 0x5EC39B022F2B, .b = 0xF662248E7E89},
  125. {.a = 0x5EC39B022F2B, .b = 0xF662248E7E89},
  126. {.a = 0x5EC39B022F2B, .b = 0xF662248E7E89},
  127. {.a = 0x5EC39B022F2B, .b = 0xF662248E7E89},
  128. {.a = 0x3A09594C8587, .b = 0x62387B8D250D},
  129. {.a = 0xF238D78FF48F, .b = 0x9DC282D46217},
  130. {.a = 0xAFD0BA94D624, .b = 0x92EE4DC87191},
  131. {.a = 0xB35A0E4ACC09, .b = 0x756EF55E2507},
  132. {.a = 0x447AB7FD5A6B, .b = 0x932B9CB730EF},
  133. {.a = 0x1F1A0A111B5B, .b = 0xAD9E0A1CA2F7},
  134. {.a = 0xD58023BA2BDC, .b = 0x62CED42A6D87},
  135. {.a = 0x2548A443DF28, .b = 0x2ED3B15E7C0F},
  136. };
  137. #define FARE_BUS \
  138. (Money) { \
  139. 1, 70 \
  140. }
  141. #define FARE_SUB \
  142. (Money) { \
  143. 2, 40 \
  144. }
  145. typedef struct {
  146. DateTime date;
  147. uint16_t gate;
  148. uint8_t g_flag;
  149. Money fare;
  150. uint16_t f_flag;
  151. } Transaction;
  152. typedef struct {
  153. bool valid;
  154. uint16_t pre;
  155. uint16_t post;
  156. DateTime date;
  157. } Pass;
  158. typedef struct {
  159. uint16_t n_uses;
  160. uint8_t active_balance_sector;
  161. } CounterSector;
  162. typedef struct {
  163. Money balance;
  164. uint16_t type;
  165. DateTime issued;
  166. DateTime end_validity;
  167. } BalanceSector;
  168. // IdMapping approach borrowed from Jeremy Cooper's 'clipper.c'
  169. typedef struct {
  170. uint16_t id;
  171. const char* name;
  172. } IdMapping;
  173. // this should be a complete accounting of types, (1 and 7 day pass types maybe missing?)
  174. static const IdMapping charliecard_types[] = {
  175. // Regular card types
  176. {.id = 367, .name = "Adult"},
  177. {.id = 366, .name = "SV Adult"},
  178. {.id = 418, .name = "Student"},
  179. {.id = 419, .name = "Senior"},
  180. {.id = 420, .name = "TAP"},
  181. {.id = 417, .name = "Blind"},
  182. {.id = 426, .name = "Child"},
  183. {.id = 410, .name = "Employee ID Without Passback"},
  184. {.id = 414, .name = "Employee ID With Passback"},
  185. {.id = 415, .name = "Retiree"},
  186. {.id = 416, .name = "Police/Fire"},
  187. // Passes
  188. {.id = 135, .name = "30 Day Local Bus Pass"},
  189. {.id = 136, .name = "30 Day Inner Express Bus Pass"},
  190. {.id = 137, .name = "30 Day Outer Express Bus Pass"},
  191. {.id = 138, .name = "30 Day LinkPass"},
  192. {.id = 139, .name = "30 Day Senior LinkPass"},
  193. {.id = 148, .name = "30 Day TAP LinkPass"},
  194. {.id = 150, .name = "Monthly Student LinkPass"},
  195. {.id = 424, .name = "Monthly TAP LinkPass"},
  196. {.id = 425, .name = "Monthly Senior LinkPass"},
  197. {.id = 421, .name = "Senior TAP/Permit"},
  198. {.id = 422, .name = "Senior TAP/Permit 30 Days"},
  199. // Commuter rail passes
  200. {.id = 166, .name = "30 Day Commuter Rail Zone 1A Pass"},
  201. {.id = 167, .name = "30 Day Commuter Rail Zone 1 Pass"},
  202. {.id = 168, .name = "30 Day Commuter Rail Zone 2 Pass"},
  203. {.id = 169, .name = "30 Day Commuter Rail Zone 3 Pass"},
  204. {.id = 170, .name = "30 Day Commuter Rail Zone 4 Pass"},
  205. {.id = 171, .name = "30 Day Commuter Rail Zone 5 Pass"},
  206. {.id = 172, .name = "30 Day Commuter Rail Zone 6 Pass"},
  207. {.id = 173, .name = "30 Day Commuter Rail Zone 7 Pass"},
  208. {.id = 174, .name = "30 Day Commuter Rail Zone 8 Pass"},
  209. {.id = 175, .name = "30 Day Interzone 1 Pass"},
  210. {.id = 176, .name = "30 Day Interzone 2 Pass"},
  211. {.id = 177, .name = "30 Day Interzone 3 Pass"},
  212. {.id = 178, .name = "30 Day Interzone 4 Pass"},
  213. {.id = 179, .name = "30 Day Interzone 5 Pass"},
  214. {.id = 180, .name = "30 Day Interzone 6 Pass"},
  215. {.id = 181, .name = "30 Day Interzone 7 Pass"},
  216. {.id = 182, .name = "30 Day Interzone 8 Pass"},
  217. {.id = 140, .name = "One Way Interzone Adult 1 Zone"},
  218. {.id = 141, .name = "One Way Interzone Adult 2 Zones"},
  219. {.id = 142, .name = "One Way Interzone Adult 3 Zones"},
  220. {.id = 143, .name = "One Way Interzone Adult 4 Zones"},
  221. {.id = 144, .name = "One Way Interzone Adult 5 Zones"},
  222. {.id = 145, .name = "One Way Interzone Adult 6 Zones"},
  223. {.id = 146, .name = "One Way Interzone Adult 7 Zones"},
  224. {.id = 147, .name = "One Way Interzone Adult 8 Zones"},
  225. {.id = 428, .name = "One Way Half Fare Zone 1"},
  226. {.id = 429, .name = "One Way Half Fare Zone 2"},
  227. {.id = 430, .name = "One Way Half Fare Zone 3"},
  228. {.id = 431, .name = "One Way Half Fare Zone 4"},
  229. {.id = 432, .name = "One Way Half Fare Zone 5"},
  230. {.id = 433, .name = "One Way Half Fare Zone 6"},
  231. {.id = 434, .name = "One Way Half Fare Zone 7"},
  232. {.id = 435, .name = "One Way Half Fare Zone 8"},
  233. {.id = 436, .name = "One Way Interzone Half Fare 1 Zone"},
  234. {.id = 437, .name = "One Way Interzone Half Fare 2 Zones"},
  235. {.id = 438, .name = "One Way Interzone Half Fare 3 Zones"},
  236. {.id = 439, .name = "One Way Interzone Half Fare 4 Zones"},
  237. {.id = 440, .name = "One Way Interzone Half Fare 5 Zones"},
  238. {.id = 441, .name = "One Way Interzone Half Fare 6 Zones"},
  239. {.id = 442, .name = "One Way Interzone Half Fare 7 Zones"},
  240. {.id = 443, .name = "One Way Interzone Half Fare 8 Zones"},
  241. {.id = 509, .name = "Group Interzone 1 Zones"},
  242. {.id = 510, .name = "Group Interzone 2 Zones"},
  243. {.id = 511, .name = "Group Interzone 3 Zones"},
  244. {.id = 512, .name = "Group Interzone 4 Zones"},
  245. {.id = 513, .name = "Group Interzone 5 Zones"},
  246. {.id = 514, .name = "Group Interzone 6 Zones"},
  247. {.id = 515, .name = "Group Interzone 7 Zones"},
  248. {.id = 516, .name = "Group Interzone 8 Zones"},
  249. {.id = 952, .name = "Zone 1 Student Monthly Pass"},
  250. {.id = 953, .name = "Zone 2 Student Monthly Pass"},
  251. {.id = 954, .name = "Zone 3 Student Monthly Pass"},
  252. {.id = 955, .name = "Zone 4 Student Monthly Pass"},
  253. {.id = 956, .name = "Zone 5 Student Monthly Pass"},
  254. {.id = 957, .name = "Zone 6 Student Monthly Pass"},
  255. {.id = 958, .name = "Zone 7 Student Monthly Pass"},
  256. {.id = 959, .name = "Zone 8 Student Monthly Pass"},
  257. {.id = 960, .name = "Zone 9 Student Monthly Pass"},
  258. {.id = 961, .name = "Zone 10 Student Monthly Pass"},
  259. {.id = 963, .name = "Interzone 1 Zone Student Monthly Pass"},
  260. {.id = 964, .name = "Interzone 2 Zone Student Monthly Pass"},
  261. {.id = 965, .name = "Interzone 3 Zone Student Monthly Pass"},
  262. {.id = 966, .name = "Interzone 4 Zone Student Monthly Pass"},
  263. {.id = 967, .name = "Interzone 5 Zone Student Monthly Pass"},
  264. {.id = 968, .name = "Interzone 6 Zone Student Monthly Pass"},
  265. {.id = 969, .name = "Interzone 7 Zone Student Monthly Pass"},
  266. {.id = 970, .name = "Interzone 8 Zone Student Monthly Pass"},
  267. {.id = 971, .name = "Interzone 9 Zone Student Monthly Pass"},
  268. {.id = 972, .name = "Interzone 10 Zone Student Monthly Pass"},
  269. };
  270. static const size_t kNumTypes = COUNT_OF(charliecard_types);
  271. // Incomplete, and subject to change
  272. // Only covers Orange & Blue line stations
  273. // Gathered manually, and provided courtesy of, DEFCON31 researchers
  274. // as cited above.
  275. static const IdMapping charliecard_fare_gate_ids[] = {
  276. // Davis
  277. {.id = 6766, .name = "Davis"},
  278. {.id = 6767, .name = "Davis"},
  279. {.id = 6768, .name = "Davis"},
  280. {.id = 6769, .name = "Davis"},
  281. {.id = 6770, .name = "Davis"},
  282. {.id = 6771, .name = "Davis"},
  283. {.id = 6772, .name = "Davis"},
  284. {.id = 2167, .name = "Davis"},
  285. {.id = 7020, .name = "Davis"},
  286. // Porter
  287. {.id = 6781, .name = "Porter"},
  288. {.id = 6780, .name = "Porter"},
  289. {.id = 6779, .name = "Porter"},
  290. {.id = 6778, .name = "Porter"},
  291. {.id = 6777, .name = "Porter"},
  292. {.id = 6776, .name = "Porter"},
  293. {.id = 6775, .name = "Porter"},
  294. {.id = 2168, .name = "Porter"},
  295. {.id = 7021, .name = "Porter"},
  296. {.id = 6782, .name = "Porter"},
  297. // Oak Grove
  298. {.id = 6640, .name = "Oak Grove"},
  299. {.id = 6641, .name = "Oak Grove"},
  300. {.id = 6639, .name = "Oak Grove"},
  301. {.id = 2036, .name = "Oak Grove"},
  302. {.id = 6642, .name = "Oak Grove"},
  303. {.id = 6979, .name = "Oak Grove"},
  304. // Downtown Crossing
  305. {.id = 2091, .name = "Downtown Crossing"},
  306. {.id = 6995, .name = "Downtown Crossing"},
  307. {.id = 6699, .name = "Downtown Crossing"},
  308. {.id = 6700, .name = "Downtown Crossing"},
  309. {.id = 1926, .name = "Downtown Crossing"},
  310. {.id = 2084, .name = "Downtown Crossing"},
  311. {.id = 6994, .name = "Downtown Crossing"},
  312. {.id = 6695, .name = "Downtown Crossing"},
  313. {.id = 6694, .name = "Downtown Crossing"},
  314. {.id = 6696, .name = "Downtown Crossing"},
  315. {.id = 2336, .name = "Downtown Crossing"},
  316. {.id = 1056, .name = "Downtown Crossing"},
  317. {.id = 6814, .name = "Downtown Crossing"},
  318. {.id = 6813, .name = "Downtown Crossing"},
  319. {.id = 2212, .name = "Downtown Crossing"},
  320. {.id = 7038, .name = "Downtown Crossing"},
  321. // State
  322. {.id = 7092, .name = "State"},
  323. {.id = 1844, .name = "State"},
  324. {.id = 6689, .name = "State"},
  325. {.id = 6988, .name = "State"},
  326. {.id = 6991, .name = "State"},
  327. {.id = 2083, .name = "State"},
  328. {.id = 6688, .name = "State"},
  329. {.id = 6687, .name = "State"},
  330. {.id = 6686, .name = "State"},
  331. {.id = 2078, .name = "State"},
  332. {.id = 6987, .name = "State"},
  333. {.id = 7090, .name = "State"},
  334. {.id = 1842, .name = "State"},
  335. // Haymarket
  336. {.id = 6684, .name = "Haymarket"},
  337. {.id = 6683, .name = "Haymarket"},
  338. {.id = 6682, .name = "Haymarket"},
  339. {.id = 6681, .name = "Haymarket"},
  340. {.id = 2073, .name = "Haymarket"},
  341. {.id = 7074, .name = "Haymarket"},
  342. {.id = 6883, .name = "Haymarket"},
  343. {.id = 6884, .name = "Haymarket"},
  344. {.id = 6885, .name = "Haymarket"},
  345. {.id = 6886, .name = "Haymarket"},
  346. {.id = 2303, .name = "Haymarket"},
  347. {.id = 6986, .name = "Haymarket"},
  348. // North Station
  349. {.id = 6985, .name = "North Station"},
  350. {.id = 2063, .name = "North Station"},
  351. {.id = 6671, .name = "North Station"},
  352. {.id = 6672, .name = "North Station"},
  353. {.id = 6673, .name = "North Station"},
  354. {.id = 6674, .name = "North Station"},
  355. {.id = 6675, .name = "North Station"},
  356. {.id = 6676, .name = "North Station"},
  357. {.id = 6677, .name = "North Station"},
  358. {.id = 6678, .name = "North Station"},
  359. {.id = 6984, .name = "North Station"},
  360. {.id = 2062, .name = "North Station"},
  361. {.id = 6668, .name = "North Station"},
  362. {.id = 6667, .name = "North Station"},
  363. {.id = 6666, .name = "North Station"},
  364. {.id = 6665, .name = "North Station"},
  365. {.id = 6664, .name = "North Station"},
  366. // Sullivan Square
  367. {.id = 6654, .name = "Sullivan Square"},
  368. {.id = 6655, .name = "Sullivan Square"},
  369. {.id = 6656, .name = "Sullivan Square"},
  370. {.id = 6657, .name = "Sullivan Square"},
  371. {.id = 6658, .name = "Sullivan Square"},
  372. {.id = 6659, .name = "Sullivan Square"},
  373. {.id = 2053, .name = "Sullivan Square"},
  374. {.id = 6982, .name = "Sullivan Square"},
  375. // Community College
  376. {.id = 6661, .name = "Community College"},
  377. {.id = 6662, .name = "Community College"},
  378. {.id = 2056, .name = "Community College"},
  379. {.id = 6983, .name = "Community College"},
  380. // Assembly
  381. {.id = 3876, .name = "Assembly"},
  382. {.id = 3875, .name = "Assembly"},
  383. {.id = 6957, .name = "Assembly"},
  384. {.id = 6956, .name = "Assembly"},
  385. {.id = 6955, .name = "Assembly"},
  386. {.id = 6954, .name = "Assembly"},
  387. {.id = 6953, .name = "Assembly"},
  388. {.id = 7101, .name = "Assembly"},
  389. {.id = 3873, .name = "Assembly"},
  390. {.id = 3872, .name = "Assembly"},
  391. // Wellington
  392. {.id = 6981, .name = "Wellington"},
  393. {.id = 2042, .name = "Wellington"},
  394. {.id = 6650, .name = "Wellington"},
  395. {.id = 6651, .name = "Wellington"},
  396. {.id = 6652, .name = "Wellington"},
  397. {.id = 6653, .name = "Wellington"},
  398. // Malden
  399. {.id = 6980, .name = "Malden Center"},
  400. {.id = 2037, .name = "Malden Center"},
  401. {.id = 6645, .name = "Malden Center"},
  402. {.id = 6646, .name = "Malden Center"},
  403. {.id = 6647, .name = "Malden Center"},
  404. {.id = 6648, .name = "Malden Center"},
  405. // Chinatown
  406. {.id = 6704, .name = "Chinatown"},
  407. {.id = 6705, .name = "Chinatown"},
  408. {.id = 2099, .name = "Chinatown"},
  409. {.id = 7003, .name = "Chinatown"},
  410. {.id = 7002, .name = "Chinatown"},
  411. {.id = 2096, .name = "Chinatown"},
  412. {.id = 6702, .name = "Chinatown"},
  413. {.id = 6701, .name = "Chinatown"},
  414. // Tufts Medical Center
  415. {.id = 6707, .name = "Tufts Medical Center"},
  416. {.id = 6708, .name = "Tufts Medical Center"},
  417. {.id = 6709, .name = "Tufts Medical Center"},
  418. {.id = 6710, .name = "Tufts Medical Center"},
  419. {.id = 6711, .name = "Tufts Medical Center"},
  420. {.id = 2105, .name = "Tufts Medical Center"},
  421. {.id = 7004, .name = "Tufts Medical Center"},
  422. {.id = 1941, .name = "Tufts Medical Center"},
  423. {.id = 7006, .name = "Tufts Medical Center"},
  424. // Back Bay
  425. {.id = 7007, .name = "Back Bay"},
  426. {.id = 1480, .name = "Back Bay"},
  427. {.id = 6714, .name = "Back Bay"},
  428. {.id = 6715, .name = "Back Bay"},
  429. {.id = 6716, .name = "Back Bay"},
  430. {.id = 6717, .name = "Back Bay"},
  431. {.id = 6718, .name = "Back Bay"},
  432. {.id = 6719, .name = "Back Bay"},
  433. {.id = 6720, .name = "Back Bay"},
  434. {.id = 1801, .name = "Back Bay"},
  435. {.id = 7009, .name = "Back Bay"},
  436. // Massachusetts Avenue
  437. {.id = 7010, .name = "Massachusetts Avenue"},
  438. {.id = 2118, .name = "Massachusetts Avenue"},
  439. {.id = 6724, .name = "Massachusetts Avenue"},
  440. {.id = 6723, .name = "Massachusetts Avenue"},
  441. {.id = 6722, .name = "Massachusetts Avenue"},
  442. {.id = 6721, .name = "Massachusetts Avenue"},
  443. // Ruggles
  444. {.id = 6726, .name = "Ruggles"},
  445. {.id = 6727, .name = "Ruggles"},
  446. {.id = 6728, .name = "Ruggles"},
  447. {.id = 2122, .name = "Ruggles"},
  448. {.id = 2123, .name = "Ruggles"},
  449. {.id = 2124, .name = "Ruggles"},
  450. {.id = 1804, .name = "Ruggles"},
  451. // Roxbury Crossing
  452. {.id = 6737, .name = "Roxbury Crossing"},
  453. {.id = 6736, .name = "Roxbury Crossing"},
  454. {.id = 6735, .name = "Roxbury Crossing"},
  455. {.id = 6734, .name = "Roxbury Crossing"},
  456. {.id = 6733, .name = "Roxbury Crossing"},
  457. {.id = 2125, .name = "Roxbury Crossing"},
  458. {.id = 7012, .name = "Roxbury Crossing"},
  459. // Jackson Square
  460. {.id = 6741, .name = "Jackson Square"},
  461. {.id = 6740, .name = "Jackson Square"},
  462. {.id = 6739, .name = "Jackson Square"},
  463. {.id = 2131, .name = "Jackson Square"},
  464. {.id = 7013, .name = "Jackson Square"},
  465. {.id = 7014, .name = "Jackson Square"},
  466. {.id = 2135, .name = "Jackson Square"},
  467. {.id = 6743, .name = "Jackson Square"},
  468. {.id = 6744, .name = "Jackson Square"},
  469. {.id = 6745, .name = "Jackson Square"},
  470. // Green Street
  471. {.id = 6746, .name = "Green Street"},
  472. {.id = 6747, .name = "Green Street"},
  473. {.id = 6748, .name = "Green Street"},
  474. {.id = 2142, .name = "Green Street"},
  475. {.id = 7015, .name = "Green Street"},
  476. // Forest Hills
  477. {.id = 6750, .name = "Forest Hills"},
  478. {.id = 6751, .name = "Forest Hills"},
  479. {.id = 6752, .name = "Forest Hills"},
  480. {.id = 6753, .name = "Forest Hills"},
  481. {.id = 6754, .name = "Forest Hills"},
  482. {.id = 6755, .name = "Forest Hills"},
  483. {.id = 2150, .name = "Forest Hills"},
  484. {.id = 7016, .name = "Forest Hills"},
  485. {.id = 6950, .name = "Forest Hills"},
  486. {.id = 6951, .name = "Forest Hills"},
  487. {.id = 604, .name = "Forest Hills"},
  488. {.id = 7096, .name = "Forest Hills"},
  489. // South Station
  490. {.id = 7039, .name = "South Station"},
  491. {.id = 2215, .name = "South Station"},
  492. {.id = 6816, .name = "South Station"},
  493. {.id = 6817, .name = "South Station"},
  494. {.id = 6818, .name = "South Station"},
  495. {.id = 6819, .name = "South Station"},
  496. {.id = 6820, .name = "South Station"},
  497. {.id = 6821, .name = "South Station"},
  498. {.id = 6822, .name = "South Station"},
  499. {.id = 6823, .name = "South Station"},
  500. {.id = 7040, .name = "South Station"},
  501. {.id = 2228, .name = "South Station"},
  502. {.id = 6827, .name = "South Station"},
  503. {.id = 6826, .name = "South Station"},
  504. {.id = 6825, .name = "South Station"},
  505. {.id = 6824, .name = "South Station"},
  506. // Courthouse
  507. {.id = 6929, .name = "Courthouse"},
  508. {.id = 2357, .name = "Courthouse"},
  509. {.id = 7079, .name = "Courthouse"},
  510. {.id = 6933, .name = "Courthouse"},
  511. {.id = 6932, .name = "Courthouse"},
  512. {.id = 2358, .name = "Courthouse"},
  513. {.id = 6792, .name = "Courthouse"},
  514. // Bowdoin
  515. {.id = 6937, .name = "Bowdoin"},
  516. {.id = 2367, .name = "Bowdoin"},
  517. {.id = 7085, .name = "Bowdoin"},
  518. // Government Center
  519. {.id = 6963, .name = "Government Center"},
  520. {.id = 6962, .name = "Government Center"},
  521. {.id = 6961, .name = "Government Center"},
  522. {.id = 6960, .name = "Government Center"},
  523. {.id = 6959, .name = "Government Center"},
  524. {.id = 6958, .name = "Government Center"},
  525. {.id = 5298, .name = "Government Center"},
  526. // Aquarium
  527. {.id = 6609, .name = "Aquarium"},
  528. {.id = 6608, .name = "Aquarium"},
  529. {.id = 1877, .name = "Aquarium"},
  530. {.id = 6965, .name = "Aquarium"},
  531. {.id = 6610, .name = "Aquarium"},
  532. {.id = 1880, .name = "Aquarium"},
  533. {.id = 1871, .name = "Aquarium"},
  534. {.id = 6966, .name = "Aquarium"},
  535. // Maverick
  536. {.id = 7088, .name = "Maverick"},
  537. {.id = 6944, .name = "Maverick"},
  538. {.id = 4384, .name = "Maverick"},
  539. {.id = 6946, .name = "Maverick"},
  540. {.id = 6947, .name = "Maverick"},
  541. {.id = 6948, .name = "Maverick"},
  542. {.id = 6949, .name = "Maverick"},
  543. {.id = 1840, .name = "Maverick"},
  544. {.id = 7083, .name = "Maverick"},
  545. // Airport
  546. {.id = 6613, .name = "Airport"},
  547. {.id = 6612, .name = "Airport"},
  548. {.id = 6611, .name = "Airport"},
  549. {.id = 6968, .name = "Airport"},
  550. {.id = 2009, .name = "Airport"},
  551. {.id = 6616, .name = "Airport"},
  552. {.id = 6615, .name = "Airport"},
  553. {.id = 6614, .name = "Airport"},
  554. {.id = 6970, .name = "Airport"},
  555. {.id = 1847, .name = "Airport"},
  556. // Wood Island
  557. {.id = 6618, .name = "Wood Island"},
  558. {.id = 6619, .name = "Wood Island"},
  559. {.id = 2010, .name = "Wood Island"},
  560. {.id = 6971, .name = "Wood Island"},
  561. // Orient Heights
  562. {.id = 6621, .name = "Orient Heights"},
  563. {.id = 6622, .name = "Orient Heights"},
  564. {.id = 6623, .name = "Orient Heights"},
  565. {.id = 2014, .name = "Orient Heights"},
  566. {.id = 6972, .name = "Orient Heights"},
  567. {.id = 6974, .name = "Orient Heights"},
  568. {.id = 1868, .name = "Orient Heights"},
  569. // Suffolk Downs
  570. {.id = 6625, .name = "Suffolk Downs"},
  571. {.id = 6626, .name = "Suffolk Downs"},
  572. {.id = 2017, .name = "Suffolk Downs"},
  573. {.id = 6975, .name = "Suffolk Downs"},
  574. // Beachmont
  575. {.id = 6628, .name = "Beachmont"},
  576. {.id = 6629, .name = "Beachmont"},
  577. {.id = 6630, .name = "Beachmont"},
  578. {.id = 2021, .name = "Beachmont"},
  579. {.id = 6976, .name = "Beachmont"},
  580. // Revere Beach
  581. {.id = 6632, .name = "Revere Beach"},
  582. {.id = 6633, .name = "Revere Beach"},
  583. {.id = 2024, .name = "Revere Beach"},
  584. {.id = 6977, .name = "Revere Beach"},
  585. // Wonderland
  586. {.id = 6638, .name = "Wonderland"},
  587. {.id = 6637, .name = "Wonderland"},
  588. {.id = 6636, .name = "Wonderland"},
  589. {.id = 2025, .name = "Wonderland"},
  590. {.id = 6978, .name = "Wonderland"},
  591. };
  592. static const size_t kNumFareGateIds = COUNT_OF(charliecard_fare_gate_ids);
  593. // **********************************************************
  594. // ********************* MISC HELPERS ***********************
  595. // **********************************************************
  596. static const uint8_t*
  597. pos_to_ptr(const MfClassicData* data, uint8_t sector_num, uint8_t block_num, uint8_t byte_num) {
  598. // returns pointer to specified sector/block/byte of MFClassic card data
  599. uint8_t block_offset = mf_classic_get_first_block_num_of_sector(sector_num);
  600. return &data->block[block_offset + block_num].data[byte_num];
  601. }
  602. static uint64_t pos_to_num(
  603. const MfClassicData* data,
  604. uint8_t sector_num,
  605. uint8_t block_num,
  606. uint8_t byte_num,
  607. uint8_t byte_len) {
  608. // returns numeric values at specified card location, for given byte length.
  609. // assumes big endian.
  610. return bit_lib_bytes_to_num_be(pos_to_ptr(data, sector_num, block_num, byte_num), byte_len);
  611. }
  612. static DateTime dt_delta(DateTime dt, uint64_t delta_secs) {
  613. // returns shifted DateTime, from initial DateTime and time offset in seconds
  614. DateTime dt_shifted = {0};
  615. datetime_timestamp_to_datetime(datetime_datetime_to_timestamp(&dt) + delta_secs, &dt_shifted);
  616. return dt_shifted;
  617. }
  618. static bool dt_ge(DateTime dt1, DateTime dt2) {
  619. // compares two DateTimes
  620. return datetime_datetime_to_timestamp(&dt1) >= datetime_datetime_to_timestamp(&dt2);
  621. }
  622. static bool dt_eq(DateTime dt1, DateTime dt2) {
  623. // compares two DateTimes
  624. return datetime_datetime_to_timestamp(&dt1) == datetime_datetime_to_timestamp(&dt2);
  625. }
  626. static bool get_map_item(uint16_t id, const IdMapping* map, size_t sz, const char** out) {
  627. // code borrowed from Jeremy Cooper's 'clipper.c'. Used as follows:
  628. // const char* s; if(!get_map_item(_,_,_,&s)) {s="Default str";}
  629. // TODO: change to furistring out?
  630. for(size_t i = 0; i < sz; i++) {
  631. if(map[i].id == id) {
  632. *out = map[i].name;
  633. return true;
  634. }
  635. }
  636. return false;
  637. }
  638. uint32_t time_now() {
  639. return furi_hal_rtc_get_timestamp();
  640. }
  641. static bool is_debug() {
  642. return furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug);
  643. }
  644. // **********************************************************
  645. // ******************** FIELD PARSING ***********************
  646. // **********************************************************
  647. static Money money_parse(
  648. const MfClassicData* data,
  649. uint8_t sector_num,
  650. uint8_t block_num,
  651. uint8_t byte_num) {
  652. // CharlieCards store all money values in two bytes as half-cents
  653. // bitmask removes sign/flag, bitshift converts half-cents to cents, div & mod yield dollars & cents
  654. uint16_t amt = (pos_to_num(data, sector_num, block_num, byte_num, 2) & 0x7FFF) >> 1;
  655. return (Money){amt / 100, amt % 100};
  656. }
  657. static DateTime
  658. date_parse(const MfClassicData* data, uint8_t sector_num, uint8_t block_num, uint8_t byte_num) {
  659. // Dates are 3 bytes, in minutes since 2003/1/1 ("CHARLIE_EPOCH")
  660. uint32_t ts_charlie = pos_to_num(data, sector_num, block_num, byte_num, 3);
  661. return dt_delta(CHARLIE_EPOCH, ts_charlie * CHARLIE_TIME_DELTA_SECS);
  662. }
  663. static DateTime end_validity_parse(
  664. const MfClassicData* data,
  665. uint8_t sector_num,
  666. uint8_t block_num,
  667. uint8_t byte_num) {
  668. // End validity field is weird; shares first byte with another variable (the card type field),
  669. // occupying the last 5 bits (and subsequent two bytes), hence bitmask
  670. uint32_t ts_charlie_ev = pos_to_num(data, sector_num, block_num, byte_num, 3) & 0x1FFFFF;
  671. // additionally, instead of minute deltas, is in 8 minute increments
  672. // relative to CHARLIE_EPOCH (2003/1/1), per DEFCON31 researcher's work
  673. return dt_delta(CHARLIE_EPOCH, ts_charlie_ev * CHARLIE_END_VALID_DELTA_SECS);
  674. }
  675. static Pass
  676. pass_parse(const MfClassicData* data, uint8_t sector_num, uint8_t block_num, uint8_t byte_num) {
  677. // WIP; testing only. Speculating it may be structured as follows
  678. // Sub-byte field divisions not drawn to scale, see code for exact bit offsets
  679. //
  680. // 0 1 2 3 4 5
  681. // +----.----.----.----+----.----+
  682. // | uk1 | date | uk2 |
  683. // +----.----.----.----+----.----+
  684. //
  685. // "Blank" entries are as follows:
  686. // 0 1 2 3 4 5
  687. // +----.----.----.----.----.----+
  688. // | 00 20 00 00 00 00 |
  689. // +----.----.----.----.----.----+
  690. //
  691. // even when not blank, uk1 LSB seems to always be set to 1...
  692. // the sole bit set to 1 on the blank entry seems to divide
  693. // the uk1 and date fields, and is always set to 1 regardless
  694. // same is true of type & end-validity split found in balance sector
  695. //
  696. // likely fields incl
  697. // — type #,
  698. // — a secondary date field (eg start/end, end validity or normal format)
  699. // — ID of FVM from which the pass was loaded
  700. // check for empty, if so, return struct filled w/ 0s
  701. // (incl "valid" field: hence, "valid" is false-y)
  702. if(pos_to_num(data, sector_num, block_num, byte_num, 6) == 0x002000000000) {
  703. return (Pass){0};
  704. }
  705. // const DateTime start = date_parse(data, sector_num, block_num, byte_num + 1);
  706. const uint16_t pre = pos_to_num(data, sector_num, block_num, byte_num, 2) >> 6;
  707. const uint16_t post = (pos_to_num(data, sector_num, block_num, byte_num + 4, 2) >> 2) & 0x3ff;
  708. // these values make sense for a date, but implied position of type
  709. // before end validity, as seen in balance sector, doesn't seem
  710. // to produce sensible values
  711. const DateTime date = end_validity_parse(data, sector_num, block_num, byte_num + 1);
  712. // DateTime start = date_parse(data, sector_num, block_num, byte_num);
  713. // uint16_t type = 0; // pos_to_num(data, sector_num, block_num, byte_num + 3, 2) >> 6;
  714. return (Pass){true, pre, post, date};
  715. }
  716. static Transaction
  717. transaction_parse(const MfClassicData* data, uint8_t sector, uint8_t block, uint8_t byte) {
  718. // This function parses individual transactions. Each transaction packs 7 bytes, stored as follows:
  719. //
  720. // 0 1 2 3 4 5 6
  721. // +----.----.----+----.--+-+----.----+
  722. // | date | loc |f| amt |
  723. // +----.----.----+----.--+-+----.----+
  724. //
  725. // Where date is in the typical format, loc represents the fare gate tapped, and amt is the fare amount.
  726. // Amount appears to contain some flag bits, however, it is unclear what precisely their function is.
  727. //
  728. // Gate ID ("loc") is only the first 13 bits of 0x3:0x5, the final three bits appear to be flags ("f").
  729. // Least significant flag bit seems to indicate:
  730. // — When f & 1 == 1, fare (the amount by which balance is decremented)
  731. // — When f & 1 == 0, refill (the amount by which balance is incremented)
  732. // MSB (sign bit) of amt seems to serve the same role, just inverted, ie
  733. // — When amt & 0x8000 == 0, fare
  734. // — When amt & 0x8000 == 0x8000, refill
  735. // Only contradiction between the two observed is on cards w/ passes;
  736. // MSB of amt seems to be set for every transaction when (remaining bits of) amt is 0 on a card w/ a pass
  737. // Hence, using f's LSB as method for inferring fare v. refill
  738. //
  739. // Remaining unknown bits:
  740. // — f & 0b100; seems to be set on fares where the card has a pass, and amt is 0
  741. // — f & 0b010
  742. // — amt & 1; does not seem to correspond with card type, last transaction, first transaction, refill v. fare, etc
  743. const DateTime date = date_parse(data, sector, block, byte);
  744. const uint16_t gate = pos_to_num(data, sector, block, byte + 3, 2) >> 3;
  745. const uint8_t g_flag = pos_to_num(data, sector, block, byte + 3, 2) & 0b111;
  746. const Money fare = money_parse(data, sector, block, byte + 5);
  747. const uint16_t f_flag = pos_to_num(data, sector, block, byte + 5, 2) & 0x8001;
  748. return (Transaction){date, gate, g_flag, fare, f_flag};
  749. }
  750. // **********************************************************
  751. // ******************* SECTOR PARSING ***********************
  752. // **********************************************************
  753. static uint32_t mfg_sector_parse(const MfClassicData* data) {
  754. // Manufacturer data (Sector 0)
  755. //
  756. // 0 1 2 3 4 5 6 7 8 9 A B C D E F
  757. // +----.----.----.----+----+----.----.----.----+----+----.----.----.----.----+----+
  758. // 0x000 | UID | rc | 88 04 00 C8 | uk | 00 20 00 00 00 | uk |
  759. // +----.----.----.----+----+----.----.----.----+----+----.----.----.----.----+----+
  760. // 0x010 | 4E 0F 04 10 04 10 04 10 04 10 04 10 04 10 04 10 |
  761. // +----.----.----.----.----.----.----.----.----.----.----.----.----.----.----.----+
  762. // 0x020 | ... 00 00 ... |
  763. // +----.----.----.----.----.----.----.----.----.----.----.----.----.----.----.----+
  764. //
  765. // rc := "redundancy check" (lrc / bcc)
  766. // uk := "unknown"
  767. size_t uid_len = 0;
  768. const uint8_t* uid = mf_classic_get_uid(data, &uid_len);
  769. const uint32_t card_number = bit_lib_bytes_to_num_be(uid, 4);
  770. return card_number;
  771. }
  772. static CounterSector counter_sector_parse(const MfClassicData* data) {
  773. // Trip/transaction counters (Sector 1)
  774. //
  775. // 0 1 2 3 4 5 6 7 8 9 A B C D E F
  776. // +----.----.----.----.----.----.----.----.----.----.----.----.----.----.----.----+
  777. // 0x040 | 04 10 23 45 66 77 ... 00 00 ... |
  778. // +----.----+----+----.----.----.----.----.----.----.----.----.----.----.----.----+
  779. // 0x050 | uses1 | uk | ... 00 00 ... |
  780. // +----.----+----+----.----.----.----.----.----.----.----.----.----.----.----.----+
  781. // 0x060 | uses2 | uk | ... 00 00 ... |
  782. // +----.----+----+----.----.----.----.----.----.----.----.----.----.----.----.----+
  783. //
  784. // uk := "unknown"; if nonzero, seems to only occupy the first 4 bits (ie, uk & 0xF0 == uk),
  785. // with the remaining 4 zero
  786. // Card has two sectors (2 & 3) containing balance data, with two
  787. // corresponding trip counters in 0x50:0x51 & 0x60:0x61 (sector 1, byte 0:1 of blocks 1 & 2).
  788. // The *lower* of the two values *minus one* is the true use count,
  789. // and corresponds to the active balance sector,
  790. // (0x50 counter lower -> sector 2 active, 0x60 counter lower -> 3 active)
  791. // per DEFCON31 researcher's findings
  792. const uint16_t n_uses1 = pos_to_num(data, 1, 1, 0, 2);
  793. const uint16_t n_uses2 = pos_to_num(data, 1, 2, 0, 2);
  794. const bool is_sec2_active = n_uses1 <= n_uses2;
  795. const uint8_t active_sector = is_sec2_active ? 2 : 3;
  796. const uint16_t n_uses = (is_sec2_active ? n_uses1 : n_uses2) - 1;
  797. return (CounterSector){n_uses, active_sector};
  798. }
  799. static BalanceSector balance_sector_parse(const MfClassicData* data, uint8_t active_sector) {
  800. // Balance & misc card info (Sector 2 or 3)
  801. //
  802. // 0 1 2 3 4 5 6 7 8 9 A B C D E F
  803. // +----+----.----.----+----.----+----.----.----+----.----+----.----+----+----.----+
  804. // 0x080 | 11 | date last | loc last| date issued | 65 00 | unknown | 00 | crc | 0x0C0
  805. // +----+----.----.----+----+----+----+----+----+----.----+----.----+----+----.----+
  806. // 0x090 | type |end validity| uk | balance | 00 | unknown | crc | 0x0D0
  807. // +----.----.----.----+----+----.----+----+----.----.----.----.----.----+----.----+
  808. // 0x0A0 | 20 ... 00 00 ... 04 | crc | 0x0E0
  809. // +----.----.----.----.----.----.----.----.----.----.----.----.----.----+----.----+
  810. //
  811. // "Active" balance sector alternates between 2 and 3
  812. // Last trip/transaction info in balance sector ("date last" & "loc last")
  813. // is also included in transaction log, hence don't bother to read here
  814. //
  815. // Inactive balance sector represent the transaction N-1 version
  816. // (where active sector represents data from transaction N).
  817. const DateTime issued = date_parse(data, active_sector, 0, 6);
  818. const DateTime end_validity = end_validity_parse(data, active_sector, 1, 1);
  819. // Card type data stored in the first 10bits of block 1
  820. // (0x90 or 0xD0 depending on active sector)
  821. // bitshift (2bytes = 16 bits) by 6bits for just first 10bits
  822. const uint16_t type = pos_to_num(data, active_sector, 1, 0, 2) >> 6;
  823. const Money bal = money_parse(data, active_sector, 1, 5);
  824. return (BalanceSector){bal, type, issued, end_validity};
  825. }
  826. static Pass* passes_parse(const MfClassicData* data) {
  827. // Passes, speculative (Sectors 4 &/or 5)
  828. //
  829. // 0 1 2 3 4 5 6 7 8 9 A B C D E F
  830. // +----.----.----.----.----.----+----+----.----.----.----.----.----+----+----.----+
  831. // 0x100 | pass0/2? | 00 | pass1/3? | 00 | crc | 0x140
  832. // +----.----.----.----.----.----+----+----.----.----.----.----.----+----+----.----+
  833. // 0x110 | ... 00 00 ... | crc | 0x150
  834. // +----.----.----.----.----.----.----.----.----.----.----.----.----.----+----.----+
  835. // 0x120 | ... 00 ... 05 | crc | 0x160
  836. // +----.----.----.----.----.----.----.----.----.----.----.----.----.----+----.----+
  837. //
  838. // WIP. Read in all speculative passes into array
  839. // 4 separate fields? active vs inactive sector for 2 passes?
  840. // something else entirely?
  841. Pass* passes = malloc(sizeof(Pass) * CHARLIE_N_PASSES);
  842. for(size_t i = 0; i < CHARLIE_N_PASSES; i++) {
  843. passes[i] = pass_parse(data, 4 + (i / 2), 0, (i % 2) * 7);
  844. }
  845. return passes;
  846. }
  847. static Transaction* transactions_parse(const MfClassicData* data) {
  848. // Transaction history (Sectors 6–7)
  849. //
  850. // 0 1 2 3 4 5 6 7 8 9 A B C D E F
  851. // +----.----.----.----.----.----.----+----.----.----.----.----.----.----+----.----+
  852. // 0x180 | transaction0 | transaction1 | crc |
  853. // +----.----.----.----.----.----.----+----.----.----.----.----.----.----+----.----+
  854. // ... ... ... ...
  855. // +----.----.----.----.----.----.----+----.----.----.----.----.----.----+----.----+
  856. // 0x1D0 | transaction8 | transaction9 | crc |
  857. // +----.----.----.----.----.----.----+----.----.----.----.----.----.----+----.----+
  858. // 0x1E0 | ... 00 00 ... | crc |
  859. // +----.----.----.----.----.----.----.----.----.----.----.----.----.----+----.----+
  860. //
  861. // Transactions are not sorted, rather, appear to get overwritten
  862. // sequentially. (eg, sorted modulo array rotation)
  863. Transaction* transactions = malloc(sizeof(Transaction) * CHARLIE_N_TRANSACTION_HISTORY);
  864. // Parse each transaction field using some modular math magic to get the offsets:
  865. // move from sector 6 -> 7 after the first 6 transactions
  866. // move a block within a given sector every 2 transactions, reset every 3 blocks (as sector has changed)
  867. // alternate between a start byte of 0 and 7 with every iteration
  868. for(size_t i = 0; i < CHARLIE_N_TRANSACTION_HISTORY; i++) {
  869. transactions[i] = transaction_parse(data, 6 + (i / 6), (i / 2) % 3, (i % 2) * 7);
  870. }
  871. // Iterate through the array to find the maximum (newest) date value
  872. int max_idx = 0;
  873. for(int i = 1; i < CHARLIE_N_TRANSACTION_HISTORY; i++) {
  874. if(dt_ge(transactions[i].date, transactions[max_idx].date)) {
  875. max_idx = i;
  876. }
  877. }
  878. // Sort by rotating
  879. for(int r = 0; r < (max_idx + 1); r++) {
  880. // Store the first element
  881. Transaction temp = transactions[0];
  882. // Shift elements to the left
  883. for(int i = 0; i < CHARLIE_N_TRANSACTION_HISTORY - 1; i++) {
  884. transactions[i] = transactions[i + 1];
  885. }
  886. // Move the first element to the last
  887. transactions[CHARLIE_N_TRANSACTION_HISTORY - 1] = temp;
  888. }
  889. // Reverse order, such that newest is first, oldest last
  890. for(int i = 0; i < CHARLIE_N_TRANSACTION_HISTORY / 2; i++) {
  891. // Swap elements at index i and size - i - 1
  892. Transaction temp = transactions[i];
  893. transactions[i] = transactions[CHARLIE_N_TRANSACTION_HISTORY - i - 1];
  894. transactions[CHARLIE_N_TRANSACTION_HISTORY - i - 1] = temp;
  895. }
  896. return transactions;
  897. }
  898. /*
  899. static DateTime expiry(DateTime iss) {
  900. // Per Metrodroid CharlieCard parser (https://github.com/metrodroid/metrodroid/blob/master/src/commonMain/kotlin/au/id/micolous/metrodroid/transit/charlie/CharlieCardTransitData.kt)
  901. // Expiry not explicitly stored in card data; rather, calculated from date of issue
  902. // Cards were first issued in 2006, expired in 5 years, w/ no printed expiry date
  903. // Cards issued after 2011 expire in 10 years
  904. //
  905. // Per DEFCON31 researcher's work (cited above):
  906. // Student cards last one school year and expire at the end of August the following year
  907. // Pre-2011 issued cards expire in 7 years, not 5 as claimed by Metrodroid
  908. // Post-2011 expire in 10 years, less one day
  909. // Redundant function given the existance of the end validity field?
  910. // Any important distinctions between the two?
  911. // perhaps additionally clipping to 2030-12-__ in anticipation of upcoming system migration?
  912. // need to get a new card to confirm.
  913. // TODO add card type logic for student card expiry
  914. DateTime exp;
  915. if(iss.year < 2011) {
  916. // add 7 years; assumes average year of 8766 hrs (to account for leap years)
  917. // may be off by a few hours as a result
  918. exp = dt_delta(iss, 7 * 8766 * 60 * 60);
  919. } else {
  920. // add 10 years, subtract a day. Same assumption as above
  921. exp = dt_delta(iss, ((10 * 8766) - 24) * 60 * 60);
  922. }
  923. return exp;
  924. }
  925. static bool expired(DateTime expiry, DateTime last_transaction) {
  926. // if a card has sat unused for >2 years, expired (verify this claim?)
  927. // else expired if current date > expiry date
  928. uint32_t ts_exp = datetime_datetime_to_timestamp(&expiry);
  929. uint32_t ts_last = datetime_datetime_to_timestamp(&last_transaction);
  930. uint32_t ts_now = time_now();
  931. return (ts_exp <= ts_now) | ((ts_now - ts_last) >= (2 * 365 * 24 * 60 * 60));
  932. }
  933. */
  934. // **********************************************************
  935. // ****************** STRING FORMATTING *********************
  936. // **********************************************************
  937. void locale_format_dt_cat(FuriString* out, const DateTime* dt) {
  938. // helper to print datetimes
  939. FuriString* s = furi_string_alloc();
  940. LocaleDateFormat date_format = locale_get_date_format();
  941. const char* separator = (date_format == LocaleDateFormatDMY) ? "." : "/";
  942. locale_format_date(s, dt, date_format, separator);
  943. furi_string_cat(out, s);
  944. locale_format_time(s, dt, locale_get_time_format(), false);
  945. furi_string_cat_printf(out, " ");
  946. furi_string_cat(out, s);
  947. furi_string_free(s);
  948. }
  949. void type_format_cat(FuriString* out, uint16_t type) {
  950. const char* s;
  951. if(!get_map_item(type, charliecard_types, kNumTypes, &s)) {
  952. s = "";
  953. furi_string_cat_printf(out, "Unknown-%u", type);
  954. }
  955. furi_string_cat_str(out, s);
  956. }
  957. void pass_format_cat(FuriString* out, Pass pass) {
  958. furi_string_cat_printf(out, "\n-Pre: %b", pass.pre);
  959. // type_format_cat(out, pass.type);
  960. furi_string_cat_printf(out, "\n-Post: ");
  961. type_format_cat(out, pass.post);
  962. // locale_format_dt_cat(out, &pass.start);
  963. furi_string_cat_printf(out, "\n-Date: ");
  964. locale_format_dt_cat(out, &pass.date);
  965. }
  966. void passes_format_cat(FuriString* out, Pass* passes) {
  967. // only print passes if DEBUG on
  968. if(!is_debug()) {
  969. return;
  970. }
  971. // only print if there is at least 1 valid pass to print
  972. bool any_valid = false;
  973. for(size_t i = 0; i < CHARLIE_N_PASSES; i++) {
  974. any_valid |= passes[i].valid;
  975. }
  976. if(!any_valid) {
  977. return;
  978. }
  979. furi_string_cat_printf(out, "\nPasses (DEBUG / WIP):");
  980. for(size_t i = 0; i < CHARLIE_N_PASSES; i++) {
  981. if(passes[i].valid) {
  982. furi_string_cat_printf(out, "\nPass %u", i + 1);
  983. pass_format_cat(out, passes[i]);
  984. furi_string_cat_printf(out, "\n");
  985. }
  986. }
  987. }
  988. void money_format_cat(FuriString* out, Money money) {
  989. furi_string_cat_printf(out, "$%u.%02u", money.dollars, money.cents);
  990. }
  991. void transaction_format_cat(FuriString* out, Transaction transaction) {
  992. const char* sep = " ";
  993. const char* sta;
  994. locale_format_dt_cat(out, &transaction.date);
  995. furi_string_cat_printf(out, "\n%s", !!(transaction.g_flag & 0x1) ? "-" : "+");
  996. money_format_cat(out, transaction.fare);
  997. if(!!(transaction.g_flag & 0x1) && (transaction.fare.dollars == FARE_BUS.dollars) &&
  998. (transaction.fare.cents == FARE_BUS.cents)) {
  999. // if not a refill, and the fare amount is equal to bus fare (any better approach? flag bits for modality?)
  1000. // format for bus — supposedly some correlation between gate ID & bus #, haven't investigated
  1001. furi_string_cat_printf(out, "%s#%u", sep, transaction.gate);
  1002. } else if(get_map_item(transaction.gate, charliecard_fare_gate_ids, kNumFareGateIds, &sta)) {
  1003. // station found in fare gate ID map, append station name
  1004. furi_string_cat_str(out, sep);
  1005. furi_string_cat_str(out, sta);
  1006. } else {
  1007. // no found station in fare gate ID map & not a bus, just print ID w/o add'l info
  1008. furi_string_cat_printf(out, "%s#%u", sep, transaction.gate);
  1009. }
  1010. // print flags for debugging purposes
  1011. if(is_debug()) {
  1012. furi_string_cat_printf(out, "%s%x%s%x", sep, transaction.g_flag, sep, transaction.f_flag);
  1013. }
  1014. }
  1015. void transactions_format_cat(FuriString* out, Transaction* transactions) {
  1016. furi_string_cat_printf(out, "\nTransactions:");
  1017. for(size_t i = 0; i < CHARLIE_N_TRANSACTION_HISTORY; i++) {
  1018. furi_string_cat_printf(out, "\n");
  1019. transaction_format_cat(out, transactions[i]);
  1020. furi_string_cat_printf(out, "\n");
  1021. }
  1022. }
  1023. // **********************************************************
  1024. // **************** NFC PLUGIN BOILERPLATE ******************
  1025. // **********************************************************
  1026. static bool charliecard_parse(FuriString* parsed_data, const MfClassicData* data) {
  1027. bool parsed = false;
  1028. do {
  1029. // Verify key
  1030. // arbitrary sector in the main data portion
  1031. const uint8_t verify_sector = 3;
  1032. const MfClassicSectorTrailer* sec_tr =
  1033. mf_classic_get_sector_trailer_by_sector(data, verify_sector);
  1034. const uint64_t key_a =
  1035. bit_lib_bytes_to_num_be(sec_tr->key_a.data, COUNT_OF(sec_tr->key_a.data));
  1036. if(key_a != charliecard_1k_keys[verify_sector].a) break;
  1037. // parse card data
  1038. const uint32_t card_number = mfg_sector_parse(data);
  1039. const CounterSector counter_sector = counter_sector_parse(data);
  1040. const BalanceSector balance_sector =
  1041. balance_sector_parse(data, counter_sector.active_balance_sector);
  1042. Pass* passes = passes_parse(data);
  1043. Transaction* transactions = transactions_parse(data);
  1044. // print/append card data
  1045. furi_string_cat_printf(parsed_data, "\e#CharlieCard");
  1046. furi_string_cat_printf(parsed_data, "\nSerial: 5-%lu", card_number);
  1047. // Type and balance 0 on some (Perq) cards
  1048. // (ie no "main" type / balance / end validity,
  1049. // essentially only pass & trip info)
  1050. // skip/change formatting for that case?
  1051. furi_string_cat_printf(parsed_data, "\nBal: ");
  1052. money_format_cat(parsed_data, balance_sector.balance);
  1053. furi_string_cat_printf(parsed_data, "\nType: ");
  1054. type_format_cat(parsed_data, balance_sector.type);
  1055. furi_string_cat_printf(parsed_data, "\nTrip Count: %u", counter_sector.n_uses);
  1056. furi_string_cat_printf(parsed_data, "\nIssued: ");
  1057. locale_format_dt_cat(parsed_data, &balance_sector.issued);
  1058. if(!dt_eq(balance_sector.end_validity, CHARLIE_EPOCH) &
  1059. dt_ge(balance_sector.end_validity, balance_sector.issued)) {
  1060. // sometimes (seen on Perq cards) end validity field is all 0
  1061. // When this is the case, calc'd end validity is equal to CHARLIE_EPOCH).
  1062. // Only print if not 0, & end validity after issuance date
  1063. furi_string_cat_printf(parsed_data, "\nExpiry: ");
  1064. locale_format_dt_cat(parsed_data, &balance_sector.end_validity);
  1065. }
  1066. // const DateTime last = date_parse(data, active_sector, 0, 1);
  1067. // furi_string_cat_printf(parsed_data, "\nExpired: %s", expired(e_v, last) ? "Yes" : "No");
  1068. transactions_format_cat(parsed_data, transactions);
  1069. free(transactions);
  1070. passes_format_cat(parsed_data, passes);
  1071. free(passes);
  1072. parsed = true;
  1073. } while(false);
  1074. return parsed;
  1075. }
  1076. static NfcCommand
  1077. metroflip_scene_charlicard_poller_callback(NfcGenericEvent event, void* context) {
  1078. furi_assert(context);
  1079. furi_assert(event.event_data);
  1080. furi_assert(event.protocol == NfcProtocolMfClassic);
  1081. NfcCommand command = NfcCommandContinue;
  1082. const MfClassicPollerEvent* mfc_event = event.event_data;
  1083. Metroflip* app = context;
  1084. if(mfc_event->type == MfClassicPollerEventTypeCardDetected) {
  1085. view_dispatcher_send_custom_event(app->view_dispatcher, MetroflipCustomEventCardDetected);
  1086. command = NfcCommandContinue;
  1087. } else if(mfc_event->type == MfClassicPollerEventTypeCardLost) {
  1088. view_dispatcher_send_custom_event(app->view_dispatcher, MetroflipCustomEventCardLost);
  1089. app->sec_num = 0;
  1090. command = NfcCommandStop;
  1091. } else if(mfc_event->type == MfClassicPollerEventTypeRequestMode) {
  1092. mfc_event->data->poller_mode.mode = MfClassicPollerModeRead;
  1093. } else if(mfc_event->type == MfClassicPollerEventTypeRequestReadSector) {
  1094. MfClassicKey key = {0};
  1095. bit_lib_num_to_bytes_be(charliecard_1k_keys[app->sec_num].a, COUNT_OF(key.data), key.data);
  1096. MfClassicKeyType key_type = MfClassicKeyTypeA;
  1097. mfc_event->data->read_sector_request_data.sector_num = app->sec_num;
  1098. mfc_event->data->read_sector_request_data.key = key;
  1099. mfc_event->data->read_sector_request_data.key_type = key_type;
  1100. mfc_event->data->read_sector_request_data.key_provided = true;
  1101. if(app->sec_num == 16) {
  1102. mfc_event->data->read_sector_request_data.key_provided = false;
  1103. app->sec_num = 0;
  1104. }
  1105. app->sec_num++;
  1106. } else if(mfc_event->type == MfClassicPollerEventTypeSuccess) {
  1107. nfc_device_set_data(
  1108. app->nfc_device, NfcProtocolMfClassic, nfc_poller_get_data(app->poller));
  1109. const MfClassicData* mfc_data = nfc_device_get_data(app->nfc_device, NfcProtocolMfClassic);
  1110. FuriString* parsed_data = furi_string_alloc();
  1111. Widget* widget = app->widget;
  1112. dolphin_deed(DolphinDeedNfcReadSuccess);
  1113. furi_string_reset(app->text_box_store);
  1114. if(!charliecard_parse(parsed_data, mfc_data)) {
  1115. furi_string_reset(app->text_box_store);
  1116. FURI_LOG_I(TAG, "Unknown card type");
  1117. furi_string_printf(parsed_data, "\e#Unknown card\n");
  1118. }
  1119. widget_add_text_scroll_element(widget, 0, 0, 128, 64, furi_string_get_cstr(parsed_data));
  1120. widget_add_button_element(
  1121. widget, GuiButtonTypeRight, "Exit", metroflip_exit_widget_callback, app);
  1122. widget_add_button_element(
  1123. widget, GuiButtonTypeCenter, "Save", metroflip_save_widget_callback, app);
  1124. furi_string_free(parsed_data);
  1125. view_dispatcher_switch_to_view(app->view_dispatcher, MetroflipViewWidget);
  1126. command = NfcCommandStop;
  1127. metroflip_app_blink_stop(app);
  1128. } else if(mfc_event->type == MfClassicPollerEventTypeFail) {
  1129. FURI_LOG_I(TAG, "fail");
  1130. command = NfcCommandContinue;
  1131. }
  1132. return command;
  1133. }
  1134. static void charliecard_on_enter(Metroflip* app) {
  1135. dolphin_deed(DolphinDeedNfcRead);
  1136. app->sec_num = 0;
  1137. if(app->data_loaded) {
  1138. Storage* storage = furi_record_open(RECORD_STORAGE);
  1139. FlipperFormat* ff = flipper_format_file_alloc(storage);
  1140. if(flipper_format_file_open_existing(ff, app->file_path)) {
  1141. MfClassicData* mfc_data = mf_classic_alloc();
  1142. mf_classic_load(mfc_data, ff, 2);
  1143. FuriString* parsed_data = furi_string_alloc();
  1144. Widget* widget = app->widget;
  1145. furi_string_reset(app->text_box_store);
  1146. if(!charliecard_parse(parsed_data, mfc_data)) {
  1147. furi_string_reset(app->text_box_store);
  1148. FURI_LOG_I(TAG, "Unknown card type");
  1149. furi_string_printf(parsed_data, "\e#Unknown card\n");
  1150. }
  1151. widget_add_text_scroll_element(
  1152. widget, 0, 0, 128, 64, furi_string_get_cstr(parsed_data));
  1153. widget_add_button_element(
  1154. widget, GuiButtonTypeRight, "Exit", metroflip_exit_widget_callback, app);
  1155. widget_add_button_element(
  1156. widget, GuiButtonTypeCenter, "Delete", metroflip_delete_widget_callback, app);
  1157. mf_classic_free(mfc_data);
  1158. furi_string_free(parsed_data);
  1159. view_dispatcher_switch_to_view(app->view_dispatcher, MetroflipViewWidget);
  1160. }
  1161. flipper_format_free(ff);
  1162. } else {
  1163. // Setup view
  1164. Popup* popup = app->popup;
  1165. popup_set_header(popup, "Apply\n card to\nthe back", 68, 30, AlignLeft, AlignTop);
  1166. popup_set_icon(popup, 0, 3, &I_RFIDDolphinReceive_97x61);
  1167. // Start worker
  1168. view_dispatcher_switch_to_view(app->view_dispatcher, MetroflipViewPopup);
  1169. app->poller = nfc_poller_alloc(app->nfc, NfcProtocolMfClassic);
  1170. nfc_poller_start(app->poller, metroflip_scene_charlicard_poller_callback, app);
  1171. metroflip_app_blink_start(app);
  1172. }
  1173. }
  1174. static bool charliecard_on_event(Metroflip* app, SceneManagerEvent event) {
  1175. bool consumed = false;
  1176. if(event.type == SceneManagerEventTypeCustom) {
  1177. if(event.event == MetroflipCustomEventCardDetected) {
  1178. Popup* popup = app->popup;
  1179. popup_set_header(popup, "DON'T\nMOVE", 68, 30, AlignLeft, AlignTop);
  1180. consumed = true;
  1181. } else if(event.event == MetroflipCustomEventCardLost) {
  1182. Popup* popup = app->popup;
  1183. popup_set_header(popup, "Card \n lost", 68, 30, AlignLeft, AlignTop);
  1184. consumed = true;
  1185. } else if(event.event == MetroflipCustomEventWrongCard) {
  1186. Popup* popup = app->popup;
  1187. popup_set_header(popup, "WRONG \n CARD", 68, 30, AlignLeft, AlignTop);
  1188. consumed = true;
  1189. } else if(event.event == MetroflipCustomEventPollerFail) {
  1190. Popup* popup = app->popup;
  1191. popup_set_header(popup, "Failed", 68, 30, AlignLeft, AlignTop);
  1192. consumed = true;
  1193. }
  1194. } else if(event.type == SceneManagerEventTypeBack) {
  1195. scene_manager_search_and_switch_to_previous_scene(app->scene_manager, MetroflipSceneStart);
  1196. scene_manager_set_scene_state(app->scene_manager, MetroflipSceneStart, MetroflipSceneAuto);
  1197. consumed = true;
  1198. }
  1199. return consumed;
  1200. }
  1201. static void charliecard_on_exit(Metroflip* app) {
  1202. widget_reset(app->widget);
  1203. if(app->poller && !app->data_loaded) {
  1204. nfc_poller_stop(app->poller);
  1205. nfc_poller_free(app->poller);
  1206. }
  1207. // Clear view
  1208. popup_reset(app->popup);
  1209. metroflip_app_blink_stop(app);
  1210. }
  1211. /* Actual implementation of app<>plugin interface */
  1212. static const MetroflipPlugin charliecard_plugin = {
  1213. .card_name = "Charliecard",
  1214. .plugin_on_enter = charliecard_on_enter,
  1215. .plugin_on_event = charliecard_on_event,
  1216. .plugin_on_exit = charliecard_on_exit,
  1217. };
  1218. /* Plugin descriptor to comply with basic plugin specification */
  1219. static const FlipperAppPluginDescriptor charliecard_plugin_descriptor = {
  1220. .appid = METROFLIP_SUPPORTED_CARD_PLUGIN_APP_ID,
  1221. .ep_api_version = METROFLIP_SUPPORTED_CARD_PLUGIN_API_VERSION,
  1222. .entry_point = &charliecard_plugin,
  1223. };
  1224. /* Plugin entry point - must return a pointer to const descriptor */
  1225. const FlipperAppPluginDescriptor* charliecard_plugin_ep(void) {
  1226. return &charliecard_plugin_descriptor;
  1227. }