You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MainClass.cpp 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. //
  2. // Created by robin on 8/8/15.
  3. //
  4. #include <iostream>
  5. #include <sysexits.h>
  6. #include <iomanip>
  7. #include <fstream>
  8. #include <DBO/StringUtils.h>
  9. #include <Business/FreeFareDeviceBusiness.h>
  10. #include "DBO/Result.h"
  11. #include "Business/LibNfcBusiness.h"
  12. #include "CommandLineParser.h"
  13. #include "MainClass.h"
  14. #define EX_OUTPUT_ERROR 1
  15. #define EX_INPUT_ERROR 2
  16. #define EX_KEY_ERROR 10
  17. #define EX_LIB_NFC_ERROR 12
  18. #define EX_NFC_DEVICE_NOT_FOUND 13
  19. #define EX_NFC_TAG_NOT_FOUND 14
  20. #define EX_MAP_KEYS_ERROR 15
  21. #define EX_READ_ERROR 16
  22. #define EX_WRITE_ERROR 17
  23. MainClass::MainClass(int argc, char *argv[])
  24. : _argc(argc)
  25. , _argv(argv)
  26. {
  27. }
  28. int MainClass::main()
  29. {
  30. CommandLineParser parser(_argc, _argv);
  31. CommandLineOption optionVersion(&parser, "version", 'v', "Show libnfc and mifare-tools versions");
  32. CommandLineOption optionHelp(&parser, "help", 'h', "Show this help");
  33. CommandLineOption optionMap(&parser, "map", 'm', "Map keys for the tag");
  34. CommandLineOption optionRead(&parser, "read", 'r', "Read the tag");
  35. CommandLineOption optionWrite(&parser, "write", 'w', "Write the tag");
  36. CommandLineOption optionDevices(&parser, "devices", 'd', "List NFC devices");
  37. CommandLineOption optionTags(&parser, "tags", 't', "List NFC tags");
  38. CommandLineOption optionDevice(&parser, "device", 'e', "Use the device DEVICE", "DEVICE");
  39. CommandLineOption optionTag(&parser, "tag", 'u', "Use the UID tag", "UID");
  40. CommandLineOption optionKeyFile(&parser, "key-file", 'f', "Path to a file containing keys", "FILE");
  41. CommandLineOption optionKey(&parser, "key", 'k', "Key to use to authenticate", "KEY");
  42. CommandLineOption optionOutput(&parser, "output", 'o', "Redirect output to FILE. '-' to use stdout", "FILE", "-");
  43. CommandLineOption optionInput(&parser, "input", 'i', "Read input from FILE. '-' to use stdin", "FILE", "-");
  44. if (!parser.parse()) {
  45. return parser.showHelp(EX_USAGE);
  46. }
  47. std::string outputFile = optionOutput.getDefaultValue();
  48. if (optionOutput.isSet()) {
  49. outputFile = optionOutput.getValue();
  50. }
  51. if (outputFile != "-" && !outputFile.empty()) {
  52. std::shared_ptr<std::ofstream> fileCout = std::make_shared<std::ofstream>();
  53. fileCout->open(outputFile);
  54. if (!*fileCout) {
  55. std::cerr << "Failed to redirect output: " << strerror(errno) << std::endl;
  56. return EX_OUTPUT_ERROR;
  57. }
  58. _outputStream = fileCout;
  59. }
  60. std::string inputFile = optionInput.getDefaultValue();
  61. if (optionInput.isSet()) {
  62. inputFile = optionInput.getValue();
  63. }
  64. if (inputFile != "-" && !inputFile.empty()) {
  65. std::shared_ptr<std::ifstream> fileCin = std::make_shared<std::ifstream>();
  66. fileCin->open(inputFile);
  67. if (!*fileCin) {
  68. std::cerr << "Failed to open input file: " << strerror(errno) << std::endl;
  69. return EX_INPUT_ERROR;
  70. }
  71. _inputStream = fileCin;
  72. }
  73. if (optionVersion.isSet()) {
  74. printVersion();
  75. return EX_OK;
  76. }
  77. if (optionHelp.isSet()) {
  78. return parser.showHelp(EX_OK, false);
  79. }
  80. std::string deviceName = optionDevice.getDefaultValue();
  81. if (optionDevice.isSet()) {
  82. deviceName = optionDevice.getValue();
  83. }
  84. std::string tagUid = optionTag.getDefaultValue();
  85. if (optionTag.isSet()) {
  86. tagUid = optionTag.getValue();
  87. }
  88. std::vector<std::string> keys;
  89. if (optionKeyFile.isSet()) {
  90. for (auto filePath : optionKeyFile.getValues()) {
  91. auto keysResult = readFile(filePath);
  92. if (!keysResult) {
  93. keysResult.print();
  94. return EX_KEY_ERROR;
  95. }
  96. auto fileKeys = keysResult.getData();
  97. keys.insert(keys.end(), fileKeys.begin(), fileKeys.end());
  98. }
  99. }
  100. if (optionKey.isSet()) {
  101. for (auto key : optionKey.getValues()) {
  102. auto keyResult = StringUtils::humanToRaw(key);
  103. key = keyResult.getData();
  104. if (!keyResult || key.length() != 6) {
  105. std::cerr << "Invalid key" << std::endl;
  106. return EX_KEY_ERROR;
  107. }
  108. keys.push_back(key);
  109. }
  110. }
  111. std::string inputData = "";
  112. int res = EX_OK;
  113. Actions action;
  114. if (optionRead.isSet()) {
  115. action = Read;
  116. }
  117. else if (optionMap.isSet()) {
  118. action = Map;
  119. }
  120. else if (optionWrite.isSet()) {
  121. auto readResult = readStream(cin());
  122. if (!readResult) {
  123. readResult.print();
  124. return EX_INPUT_ERROR;
  125. }
  126. for (auto data : readResult.getData()) {
  127. inputData += data;
  128. }
  129. action = Write;
  130. }
  131. else if (optionDevices.isSet()) {
  132. action = Devices;
  133. }
  134. else if (optionTags.isSet()) {
  135. action = Tags;
  136. }
  137. else {
  138. std::cerr << "Must select an action (map|read|write|devices|tags)" << std::endl;
  139. return EX_USAGE;
  140. }
  141. LibNfcBusiness libNfc;
  142. auto init = libNfc.init();
  143. if (!init) {
  144. init.print();
  145. res = EX_LIB_NFC_ERROR;
  146. }
  147. else
  148. {
  149. auto devicesResult = libNfc.getDevices();
  150. if (!devicesResult)
  151. {
  152. devicesResult.print();
  153. res = EX_LIB_NFC_ERROR;
  154. }
  155. else
  156. {
  157. auto devices = devicesResult.getData();
  158. if (action == Devices)
  159. {
  160. for (auto device : devices) {
  161. cout() << device->getConnStr() << std::endl;
  162. }
  163. }
  164. else
  165. {
  166. auto device = getDevice(deviceName, devices);
  167. if (device == 0)
  168. {
  169. std::cerr << "NFC device not found" << std::endl;
  170. res = EX_NFC_DEVICE_NOT_FOUND;
  171. }
  172. else {
  173. auto open = device->open();
  174. if (!open) {
  175. open.print();
  176. res = EX_LIB_NFC_ERROR;
  177. }
  178. else {
  179. FreeFareDeviceBusiness freeFareDevice(device);
  180. auto tagsResult = freeFareDevice.getTags();
  181. if (!tagsResult) {
  182. tagsResult.print();
  183. res = EX_LIB_NFC_ERROR;
  184. }
  185. auto tags = tagsResult.getData();
  186. if (action == Tags) {
  187. for (auto tag : tags) {
  188. cout() << "UID=" << tag->getUid() << " \tType=" << tag->getType() << std::endl;
  189. }
  190. }
  191. else {
  192. auto tag = getTag(tagUid, tags);
  193. if (tag == 0) {
  194. std::cerr << "Tag not found" << std::endl;
  195. res = EX_NFC_TAG_NOT_FOUND;
  196. }
  197. else {
  198. if (action == Read) {
  199. res = read(tag, keys);
  200. }
  201. else if (action == Map) {
  202. res = mapKeys(tag, keys);
  203. }
  204. else if (action == Write) {
  205. res = write(tag, keys, inputData);
  206. }
  207. }
  208. }
  209. }
  210. device->close();
  211. }
  212. }
  213. }
  214. libNfc.clean();
  215. }
  216. if (_outputStream != 0) {
  217. _outputStream->close();
  218. }
  219. if (_inputStream != 0) {
  220. _inputStream->close();
  221. }
  222. return res;
  223. }
  224. int MainClass::mapKeys(std::shared_ptr<FreeFareTagBusiness> tag, std::vector<std::string> keys)
  225. {
  226. auto mappedKeysResult = tag->mapKeys(keys, printPercentMapKeys);
  227. if (!mappedKeysResult) {
  228. mappedKeysResult.print();
  229. return EX_MAP_KEYS_ERROR;
  230. }
  231. else {
  232. auto mappedKeys = mappedKeysResult.getData();
  233. for (int s = 0; s < mappedKeys.size(); ++s) {
  234. auto sectorKey = mappedKeys[s];
  235. cout() << "+Sector: " << s << std::endl;
  236. for (int b = 0; b < 4; ++b) {
  237. cout() << "+Block: " << b << std::endl;
  238. cout() << "+Key: A" << std::endl << (!sectorKey.first.empty() ? StringUtils::rawToHuman(sectorKey.first) : std::string(12, '-')) << std::endl;
  239. cout() << "+Key: B" << std::endl << (!sectorKey.second.empty() ? StringUtils::rawToHuman(sectorKey.second) : std::string(12, '-')) << std::endl;
  240. }
  241. }
  242. }
  243. return EX_OK;
  244. }
  245. int MainClass::read(std::shared_ptr<FreeFareTagBusiness> tag, std::vector<std::string> keys)
  246. {
  247. auto readResult = tag->read(keys, printPercentMapKeys, printPercentDump);
  248. if (!readResult) {
  249. readResult.print();
  250. return EX_READ_ERROR;
  251. }
  252. auto read = readResult.getData();
  253. printSectors(read);
  254. return EX_OK;
  255. }
  256. int MainClass::write(std::shared_ptr<FreeFareTagBusiness> tag, std::vector<std::string> keys, const std::string &data)
  257. {
  258. auto writeResult = tag->write(keys, data, false, printPercentMapKeys, printPercentWrite);
  259. if (!writeResult) {
  260. writeResult.print();
  261. return EX_WRITE_ERROR;
  262. }
  263. // std::vector<SectorDbo> sectors;
  264. // std::string d = StringUtils::ensureSize(data, 1024);
  265. // for (int i = 0; i < 16; ++i) {
  266. // SectorDbo sectorDbo(d.substr(i * 64, 64));
  267. // sectors.push_back(sectorDbo);
  268. // }
  269. // printSectors(sectors);
  270. return EX_OK;
  271. }
  272. void MainClass::printSectors(const std::vector<SectorDbo> &sectors)
  273. {
  274. for(int s = 0; s < sectors.size(); ++s) {
  275. cout() << "+Sector: " << s << std::endl;
  276. auto sector = sectors[s];
  277. for (int b = 0; b < 3; ++b) {
  278. cout() << (sector.hasBlock(b) ? StringUtils::rawToHuman(sector.getBlock(b)) : std::string(32, '-')) << std::endl;
  279. }
  280. cout() << (sector.hasKeyA() ? StringUtils::rawToHuman(sector.getKeyA()) : std::string(12, '-'))
  281. << (sector.hasAccessBits() ? StringUtils::rawToHuman(sector.getAccessBits()) : std::string(8, '-'))
  282. << (sector.hasKeyB() ? StringUtils::rawToHuman(sector.getKeyB()) : std::string(12, '-')) << std::endl;
  283. cout() << "+Trailer key A: " << (sector.hasKeyA() ? StringUtils::rawToHuman(sector.getKeyA()) : std::string(12, '-'))
  284. << "\t AC bits: " << (sector.hasAccessBits() ? StringUtils::rawToHuman(sector.getAccessBits()) : std::string(8, '-'))
  285. << "\t key B: " << (sector.hasKeyB() ? StringUtils::rawToHuman(sector.getKeyB()) : std::string(12, '-')) << std::endl;
  286. AccessBitsDbo accessBitsDbo = sector.getAccessBitsDbo();
  287. for (int b = 0; b < 3; ++b) {
  288. cout() << "+Block: " << b << " ";
  289. printBlockAccessBits(accessBitsDbo, b);
  290. }
  291. cout() << "+Block: 3 ";
  292. printTrailerAccessBits(accessBitsDbo);
  293. }
  294. }
  295. void MainClass::printBlockAccessBits(const AccessBitsDbo &accessBits, int block)
  296. {
  297. cout() << "read: " << (accessBits.canKeyAReadBlock(block) ? "A" : " ") << (accessBits.canKeyBReadBlock(block) ? "B" : " ");
  298. cout() << "\t write: " << (accessBits.canKeyAWriteBlock(block) ? "A" : " ") << (accessBits.canKeyBWriteBlock(block) ? "B" : " ");
  299. cout() << "\t increment: " << (accessBits.canKeyAIncrementBlock(block) ? "A" : " ") << (accessBits.canKeyBIncrementBlock(block) ? "B" : " ");
  300. cout() << "\t decrement: " << (accessBits.canKeyADecrementBlock(block) ? "A" : " ") << (accessBits.canKeyBDecrementBlock(block) ? "B" : " ") << std::endl;
  301. }
  302. void MainClass::printTrailerAccessBits(const AccessBitsDbo &accessBits)
  303. {
  304. cout() << "key A read: " << (accessBits.canKeyAReadKeyATrailer() ? "A" : " ") << (accessBits.canKeyBReadKeyATrailer() ? "B" : " ");
  305. cout() << "\t key A write: " << (accessBits.canKeyAWriteKeyATrailer() ? "A" : " ") << (accessBits.canKeyBWriteKeyATrailer() ? "B" : " ");
  306. cout() << "\t AC bits read: " << (accessBits.canKeyAReadAccessBitsTrailer() ? "A" : " ") << (accessBits.canKeyBReadAccessBitsTrailer() ? "B" : " ");
  307. cout() << "\t AC bits write: " << (accessBits.canKeyAWriteAccessBitsTrailer() ? "A" : " ") << (accessBits.canKeyBWriteAccessBitsTrailer() ? "B" : " ");
  308. cout() << "\t key B read: " << (accessBits.canKeyAReadKeyBTrailer() ? "A" : " ") << (accessBits.canKeyBReadKeyBTrailer() ? "B" : " ");
  309. cout() << "\t key B write: " << (accessBits.canKeyAWriteKeyBTrailer() ? "A" : " ") << (accessBits.canKeyBWriteKeyBTrailer() ? "B" : " ") << std::endl;;
  310. }
  311. void MainClass::printPercent(int done, int total, const std::string& header)
  312. {
  313. if (isatty(fileno(stdout))) {
  314. std::cout << "\r\033[2K" << header << ": " << std::fixed << std::setprecision(1)
  315. << ((float) done / (float) total * 100.0) << "%" << std::flush;
  316. if (done == total) {
  317. std::cout << std::endl;
  318. }
  319. }
  320. }
  321. void MainClass::printPercentMapKeys(int done, int total)
  322. {
  323. printPercent(done, total, "Mapping keys");
  324. }
  325. void MainClass::printPercentDump(int done, int total)
  326. {
  327. printPercent(done, total, "Dumping");
  328. }
  329. void MainClass::printPercentWrite(int done, int total)
  330. {
  331. printPercent(done, total, "Writing");
  332. }
  333. void MainClass::printVersion()
  334. {
  335. cout() << "LibNfc version: " << LibNfcBusiness::getLibNfcVersion() << std::endl;
  336. cout() << "Mifare-tools version: " << LibNfcBusiness::getMifareToolsVersion() << std::endl;
  337. }
  338. std::shared_ptr<NfcDeviceBusiness> MainClass::getDevice(const std::string &deviceName, std::vector<std::shared_ptr<NfcDeviceBusiness>> devices)
  339. {
  340. if (deviceName.empty()) {
  341. if (devices.size() > 0) {
  342. return devices[0];
  343. }
  344. }
  345. else {
  346. for (auto d : devices) {
  347. if (d->getConnStr() == deviceName) {
  348. return d;
  349. }
  350. }
  351. }
  352. return 0;
  353. }
  354. std::shared_ptr<FreeFareTagBusiness> MainClass::getTag(const std::string &tagUid,
  355. std::vector<std::shared_ptr<FreeFareTagBusiness>> tags)
  356. {
  357. if (tagUid.empty()) {
  358. if (tags.size() > 0) {
  359. return tags[0];
  360. }
  361. }
  362. else {
  363. for (auto t : tags) {
  364. if (t->getUid() == tagUid) {
  365. return t;
  366. }
  367. }
  368. }
  369. return 0;
  370. }
  371. Result<std::vector<std::string>> MainClass::readFile(const std::string &filePath)
  372. {
  373. std::ifstream fileInput(filePath);
  374. if (fileInput) {
  375. return readStream(fileInput);
  376. }
  377. else {
  378. return Result<std::vector<std::string>>::error("Failed to open file: " + std::string(strerror(errno)));
  379. }
  380. }
  381. Result<std::vector<std::string>> MainClass::readStream(std::istream &stream)
  382. {
  383. std::vector<std::string> lines;
  384. while (!stream.eof()) {
  385. std::string line;
  386. std::getline(stream, line);
  387. line = StringUtils::removeSpaces(line);
  388. if (line.compare(0, 1, "#") != 0 && line.compare(0, 1, "+") != 0) {
  389. std::replace(line.begin(), line.end(), '-', '0');
  390. auto keyResult = StringUtils::humanToRaw(line);
  391. if (!keyResult) {
  392. return Result<std::vector<std::string>>::error("Invalid data");
  393. }
  394. line = keyResult.getData();
  395. lines.push_back(line);
  396. }
  397. }
  398. return Result<std::vector<std::string>>::ok(lines);
  399. }
  400. std::ostream &MainClass::cout()
  401. {
  402. return _outputStream == 0 ? std::cout : *_outputStream;
  403. }
  404. std::istream &MainClass::cin()
  405. {
  406. return _inputStream == 0 ? std::cin : *_inputStream;
  407. }