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 13KB

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