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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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 {
  132. std::cerr << "Must select an action (map|read|write|devices|tags)" << std::endl;
  133. return EX_USAGE;
  134. }
  135. LibNfcBusiness libNfc;
  136. auto init = libNfc.init();
  137. if (!init) {
  138. init.print();
  139. res = EX_LIB_NFC_ERROR;
  140. }
  141. else
  142. {
  143. auto devicesResult = libNfc.getDevices();
  144. if (!devicesResult)
  145. {
  146. devicesResult.print();
  147. res = EX_LIB_NFC_ERROR;
  148. }
  149. else
  150. {
  151. auto devices = devicesResult.getData();
  152. if (optionDevices.isSet())
  153. {
  154. for (auto device : devices) {
  155. cout() << device->getConnStr() << std::endl;
  156. }
  157. }
  158. else
  159. {
  160. auto device = getDevice(deviceName, devices);
  161. if (device == 0)
  162. {
  163. std::cerr << "NFC device not found" << std::endl;
  164. res = EX_NFC_DEVICE_NOT_FOUND;
  165. }
  166. else {
  167. auto open = device->open();
  168. if (!open) {
  169. open.print();
  170. res = EX_LIB_NFC_ERROR;
  171. }
  172. else {
  173. FreeFareDeviceBusiness freeFareDevice(device);
  174. auto tagsResult = freeFareDevice.getTags();
  175. if (!tagsResult)
  176. {
  177. tagsResult.print();
  178. res = EX_LIB_NFC_ERROR;
  179. }
  180. auto tags = tagsResult.getData();
  181. if (optionTags.isSet()) {
  182. for (auto tag : tags)
  183. {
  184. cout() << "UID=" << tag->getUid() << " \tType=" << tag->getType() << std::endl;
  185. }
  186. }
  187. else {
  188. auto tag = getTag(tagUid, tags);
  189. if (tag == 0) {
  190. std::cerr << "Tag not found" << std::endl;
  191. res = EX_NFC_TAG_NOT_FOUND;
  192. }
  193. else {
  194. if (action == Read) {
  195. res = read(tag, keys);
  196. }
  197. else if (action == Map) {
  198. res = mapKeys(tag, keys);
  199. }
  200. else if (action == Write) {
  201. res = write(tag, keys, inputData);
  202. }
  203. }
  204. }
  205. }
  206. device->close();
  207. }
  208. }
  209. }
  210. libNfc.clean();
  211. }
  212. if (_outputStream != 0) {
  213. _outputStream->close();
  214. }
  215. if (_inputStream != 0) {
  216. _inputStream->close();
  217. }
  218. return res;
  219. }
  220. int MainClass::mapKeys(std::shared_ptr<FreeFareTagBusiness> tag, std::vector<std::string> keys)
  221. {
  222. auto mappedKeysResult = tag->mapKeys(keys, printPercentMapKeys);
  223. if (!mappedKeysResult) {
  224. mappedKeysResult.print();
  225. return EX_MAP_KEYS_ERROR;
  226. }
  227. else {
  228. auto mappedKeys = mappedKeysResult.getData();
  229. for (int s = 0; s < mappedKeys.size(); ++s) {
  230. auto sectorKey = mappedKeys[s];
  231. cout() << "+Sector: " << s << std::endl;
  232. for (int b = 0; b < 4; ++b) {
  233. cout() << "+Block: " << b << std::endl;
  234. cout() << "+Key: A" << std::endl << (!sectorKey.first.empty() ? StringUtils::rawToHuman(sectorKey.first) : std::string(12, '-')) << std::endl;
  235. cout() << "+Key: B" << std::endl << (!sectorKey.second.empty() ? StringUtils::rawToHuman(sectorKey.second) : std::string(12, '-')) << std::endl;
  236. }
  237. }
  238. }
  239. return EX_OK;
  240. }
  241. int MainClass::read(std::shared_ptr<FreeFareTagBusiness> tag, std::vector<std::string> keys)
  242. {
  243. auto readResult = tag->read(keys, printPercentMapKeys, printPercentDump);
  244. if (!readResult) {
  245. readResult.print();
  246. return EX_READ_ERROR;
  247. }
  248. auto read = readResult.getData();
  249. printSectors(read);
  250. return EX_OK;
  251. }
  252. int MainClass::write(std::shared_ptr<FreeFareTagBusiness> tag, std::vector<std::string> keys, const std::string &data)
  253. {
  254. auto writeResult = tag->write(keys, data, false, printPercentMapKeys, printPercentWrite);
  255. if (!writeResult) {
  256. writeResult.print();
  257. return EX_WRITE_ERROR;
  258. }
  259. // std::vector<SectorDbo> sectors;
  260. // std::string d = StringUtils::ensureSize(data, 1024);
  261. // for (int i = 0; i < 16; ++i) {
  262. // SectorDbo sectorDbo(d.substr(i * 64, 64));
  263. // sectors.push_back(sectorDbo);
  264. // }
  265. // printSectors(sectors);
  266. return EX_OK;
  267. }
  268. void MainClass::printSectors(const std::vector<SectorDbo> &sectors)
  269. {
  270. for(int s = 0; s < sectors.size(); ++s) {
  271. cout() << "+Sector: " << s << std::endl;
  272. auto sector = sectors[s];
  273. for (int b = 0; b < 3; ++b) {
  274. cout() << (sector.hasBlock(b) ? StringUtils::rawToHuman(sector.getBlock(b)) : std::string(32, '-')) << std::endl;
  275. }
  276. cout() << (sector.hasKeyA() ? StringUtils::rawToHuman(sector.getKeyA()) : std::string(12, '-'))
  277. << (sector.hasAccessBits() ? StringUtils::rawToHuman(sector.getAccessBits()) : std::string(8, '-'))
  278. << (sector.hasKeyB() ? StringUtils::rawToHuman(sector.getKeyB()) : std::string(12, '-')) << std::endl;
  279. cout() << "+Trailer key A: " << (sector.hasKeyA() ? StringUtils::rawToHuman(sector.getKeyA()) : std::string(12, '-'))
  280. << "\t AC bits: " << (sector.hasAccessBits() ? StringUtils::rawToHuman(sector.getAccessBits()) : std::string(8, '-'))
  281. << "\t key B: " << (sector.hasKeyB() ? StringUtils::rawToHuman(sector.getKeyB()) : std::string(12, '-')) << std::endl;
  282. AccessBitsDbo accessBitsDbo = sector.getAccessBitsDbo();
  283. for (int b = 0; b < 3; ++b) {
  284. cout() << "+Block: " << b << " ";
  285. printBlockAccessBits(accessBitsDbo, b);
  286. }
  287. cout() << "+Block: 3 ";
  288. printTrailerAccessBits(accessBitsDbo);
  289. }
  290. }
  291. void MainClass::printBlockAccessBits(const AccessBitsDbo &accessBits, int block)
  292. {
  293. cout() << "read: " << (accessBits.canKeyAReadBlock(block) ? "A" : " ") << (accessBits.canKeyBReadBlock(block) ? "B" : " ");
  294. cout() << "\t write: " << (accessBits.canKeyAWriteBlock(block) ? "A" : " ") << (accessBits.canKeyBWriteBlock(block) ? "B" : " ");
  295. cout() << "\t increment: " << (accessBits.canKeyAIncrementBlock(block) ? "A" : " ") << (accessBits.canKeyBIncrementBlock(block) ? "B" : " ");
  296. cout() << "\t decrement: " << (accessBits.canKeyADecrementBlock(block) ? "A" : " ") << (accessBits.canKeyBDecrementBlock(block) ? "B" : " ") << std::endl;
  297. }
  298. void MainClass::printTrailerAccessBits(const AccessBitsDbo &accessBits)
  299. {
  300. cout() << "key A read: " << (accessBits.canKeyAReadKeyATrailer() ? "A" : " ") << (accessBits.canKeyBReadKeyATrailer() ? "B" : " ");
  301. cout() << "\t key A write: " << (accessBits.canKeyAWriteKeyATrailer() ? "A" : " ") << (accessBits.canKeyBWriteKeyATrailer() ? "B" : " ");
  302. cout() << "\t AC bits read: " << (accessBits.canKeyAReadAccessBitsTrailer() ? "A" : " ") << (accessBits.canKeyBReadAccessBitsTrailer() ? "B" : " ");
  303. cout() << "\t AC bits write: " << (accessBits.canKeyAWriteAccessBitsTrailer() ? "A" : " ") << (accessBits.canKeyBWriteAccessBitsTrailer() ? "B" : " ");
  304. cout() << "\t key B read: " << (accessBits.canKeyAReadKeyBTrailer() ? "A" : " ") << (accessBits.canKeyBReadKeyBTrailer() ? "B" : " ");
  305. cout() << "\t key B write: " << (accessBits.canKeyAWriteKeyBTrailer() ? "A" : " ") << (accessBits.canKeyBWriteKeyBTrailer() ? "B" : " ") << std::endl;;
  306. }
  307. void MainClass::printPercent(int done, int total, const std::string& header)
  308. {
  309. if (isatty(fileno(stdout))) {
  310. std::cout << "\r\033[2K" << header << ": " << std::fixed << std::setprecision(1)
  311. << ((float) done / (float) total * 100.0) << "%" << std::flush;
  312. if (done == total) {
  313. std::cout << std::endl;
  314. }
  315. }
  316. }
  317. void MainClass::printPercentMapKeys(int done, int total)
  318. {
  319. printPercent(done, total, "Mapping keys");
  320. }
  321. void MainClass::printPercentDump(int done, int total)
  322. {
  323. printPercent(done, total, "Dumping");
  324. }
  325. void MainClass::printPercentWrite(int done, int total)
  326. {
  327. printPercent(done, total, "Writing");
  328. }
  329. void MainClass::printVersion()
  330. {
  331. cout() << "LibNfc version: " << LibNfcBusiness::getLibNfcVersion() << std::endl;
  332. cout() << "Mifare-tools version: " << LibNfcBusiness::getMifareToolsVersion() << std::endl;
  333. }
  334. std::shared_ptr<NfcDeviceBusiness> MainClass::getDevice(const std::string &deviceName, std::vector<std::shared_ptr<NfcDeviceBusiness>> devices)
  335. {
  336. if (deviceName.empty()) {
  337. if (devices.size() > 0) {
  338. return devices[0];
  339. }
  340. }
  341. else {
  342. for (auto d : devices) {
  343. if (d->getConnStr() == deviceName) {
  344. return d;
  345. }
  346. }
  347. }
  348. return 0;
  349. }
  350. std::shared_ptr<FreeFareTagBusiness> MainClass::getTag(const std::string &tagUid,
  351. std::vector<std::shared_ptr<FreeFareTagBusiness>> tags)
  352. {
  353. if (tagUid.empty()) {
  354. if (tags.size() > 0) {
  355. return tags[0];
  356. }
  357. }
  358. else {
  359. for (auto t : tags) {
  360. if (t->getUid() == tagUid) {
  361. return t;
  362. }
  363. }
  364. }
  365. return 0;
  366. }
  367. Result<std::vector<std::string>> MainClass::readFile(const std::string &filePath)
  368. {
  369. std::ifstream fileInput(filePath);
  370. if (fileInput) {
  371. return readStream(fileInput);
  372. }
  373. else {
  374. return Result<std::vector<std::string>>::error("Failed to open file: " + std::string(strerror(errno)));
  375. }
  376. }
  377. Result<std::vector<std::string>> MainClass::readStream(std::istream &stream)
  378. {
  379. std::vector<std::string> lines;
  380. while (!stream.eof()) {
  381. std::string line;
  382. std::getline(stream, line);
  383. line = StringUtils::removeSpaces(line);
  384. if (line.compare(0, 1, "#") != 0 && line.compare(0, 1, "+") != 0) {
  385. std::replace(line.begin(), line.end(), '-', '0');
  386. auto keyResult = StringUtils::humanToRaw(line);
  387. if (!keyResult) {
  388. return Result<std::vector<std::string>>::error("Invalid data");
  389. }
  390. line = keyResult.getData();
  391. lines.push_back(line);
  392. }
  393. }
  394. return Result<std::vector<std::string>>::ok(lines);
  395. }
  396. std::ostream &MainClass::cout()
  397. {
  398. return _outputStream == 0 ? std::cout : *_outputStream;
  399. }
  400. std::istream &MainClass::cin()
  401. {
  402. return _inputStream == 0 ? std::cin : *_inputStream;
  403. }