Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

file_test.cc 14 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. /* Copyright (c) 2015, Google Inc.
  2. *
  3. * Permission to use, copy, modify, and/or distribute this software for any
  4. * purpose with or without fee is hereby granted, provided that the above
  5. * copyright notice and this permission notice appear in all copies.
  6. *
  7. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  10. * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  12. * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
  14. #include "file_test.h"
  15. #include <algorithm>
  16. #include <utility>
  17. #include <assert.h>
  18. #include <ctype.h>
  19. #include <errno.h>
  20. #include <stdarg.h>
  21. #include <stdio.h>
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #include <openssl/err.h>
  25. #include "../internal.h"
  26. FileTest::FileTest(std::unique_ptr<FileTest::LineReader> reader,
  27. std::function<void(const std::string &)> comment_callback,
  28. bool is_kas_test)
  29. : reader_(std::move(reader)),
  30. is_kas_test_(is_kas_test),
  31. comment_callback_(std::move(comment_callback)) {}
  32. FileTest::~FileTest() {}
  33. // FindDelimiter returns a pointer to the first '=' or ':' in |str| or nullptr
  34. // if there is none.
  35. static const char *FindDelimiter(const char *str) {
  36. while (*str) {
  37. if (*str == ':' || *str == '=') {
  38. return str;
  39. }
  40. str++;
  41. }
  42. return nullptr;
  43. }
  44. // StripSpace returns a string containing up to |len| characters from |str| with
  45. // leading and trailing whitespace removed.
  46. static std::string StripSpace(const char *str, size_t len) {
  47. // Remove leading space.
  48. while (len > 0 && isspace(*str)) {
  49. str++;
  50. len--;
  51. }
  52. while (len > 0 && isspace(str[len - 1])) {
  53. len--;
  54. }
  55. return std::string(str, len);
  56. }
  57. static std::pair<std::string, std::string> ParseKeyValue(const char *str, const size_t len) {
  58. const char *delimiter = FindDelimiter(str);
  59. std::string key, value;
  60. if (delimiter == nullptr) {
  61. key = StripSpace(str, len);
  62. } else {
  63. key = StripSpace(str, delimiter - str);
  64. value = StripSpace(delimiter + 1, str + len - delimiter - 1);
  65. }
  66. return {key, value};
  67. }
  68. FileTest::ReadResult FileTest::ReadNext() {
  69. // If the previous test had unused attributes or instructions, it is an error.
  70. if (!unused_attributes_.empty()) {
  71. for (const std::string &key : unused_attributes_) {
  72. PrintLine("Unused attribute: %s", key.c_str());
  73. }
  74. return kReadError;
  75. }
  76. if (!unused_instructions_.empty()) {
  77. for (const std::string &key : unused_instructions_) {
  78. PrintLine("Unused instruction: %s", key.c_str());
  79. }
  80. return kReadError;
  81. }
  82. ClearTest();
  83. static const size_t kBufLen = 8192 * 4;
  84. std::unique_ptr<char[]> buf(new char[kBufLen]);
  85. bool in_instruction_block = false;
  86. is_at_new_instruction_block_ = false;
  87. while (true) {
  88. // Read the next line.
  89. switch (reader_->ReadLine(buf.get(), kBufLen)) {
  90. case kReadError:
  91. fprintf(stderr, "Error reading from input at line %u.\n", line_ + 1);
  92. return kReadError;
  93. case kReadEOF:
  94. // EOF is a valid terminator for a test.
  95. return start_line_ > 0 ? kReadSuccess : kReadEOF;
  96. case kReadSuccess:
  97. break;
  98. }
  99. line_++;
  100. size_t len = strlen(buf.get());
  101. if (buf[0] == '\n' || buf[0] == '\r' || buf[0] == '\0') {
  102. // Empty lines delimit tests.
  103. if (start_line_ > 0) {
  104. return kReadSuccess;
  105. }
  106. if (in_instruction_block) {
  107. in_instruction_block = false;
  108. // Delimit instruction block from test with a blank line.
  109. current_test_ += "\r\n";
  110. } else if (is_kas_test_) {
  111. // KAS tests have random blank lines scattered around.
  112. current_test_ += "\r\n";
  113. }
  114. } else if (buf[0] == '#') {
  115. if (is_kas_test_ && seen_non_comment_) {
  116. // KAS tests have comments after the initial comment block which need
  117. // to be included in the corresponding place in the output.
  118. current_test_ += std::string(buf.get());
  119. } else if (comment_callback_) {
  120. comment_callback_(buf.get());
  121. }
  122. // Otherwise ignore comments.
  123. } else if (strcmp("[B.4.2 Key Pair Generation by Testing Candidates]\r\n",
  124. buf.get()) == 0) {
  125. // The above instruction-like line is ignored because the FIPS lab's
  126. // request files are hopelessly inconsistent.
  127. } else if (buf[0] == '[') { // Inside an instruction block.
  128. is_at_new_instruction_block_ = true;
  129. seen_non_comment_ = true;
  130. if (start_line_ != 0) {
  131. // Instructions should be separate blocks.
  132. fprintf(stderr, "Line %u is an instruction in a test case.\n", line_);
  133. return kReadError;
  134. }
  135. if (!in_instruction_block) {
  136. ClearInstructions();
  137. in_instruction_block = true;
  138. }
  139. // Parse the line as an instruction ("[key = value]" or "[key]").
  140. // KAS tests contain invalid syntax.
  141. std::string kv = buf.get();
  142. const bool is_broken_kas_instruction =
  143. is_kas_test_ &&
  144. (kv == "[SHA(s) supported (Used for hashing Z): SHA512 \r\n");
  145. if (!is_broken_kas_instruction) {
  146. kv = StripSpace(buf.get(), len);
  147. if (kv[kv.size() - 1] != ']') {
  148. fprintf(stderr, "Line %u, invalid instruction: '%s'\n", line_,
  149. kv.c_str());
  150. return kReadError;
  151. }
  152. } else {
  153. // Just remove the newline for the broken instruction.
  154. kv = kv.substr(0, kv.size() - 2);
  155. }
  156. current_test_ += kv + "\r\n";
  157. kv = std::string(kv.begin() + 1, kv.end() - 1);
  158. for (;;) {
  159. size_t idx = kv.find(",");
  160. if (idx == std::string::npos) {
  161. idx = kv.size();
  162. }
  163. std::string key, value;
  164. std::tie(key, value) = ParseKeyValue(kv.c_str(), idx);
  165. instructions_[key] = value;
  166. if (idx == kv.size())
  167. break;
  168. kv = kv.substr(idx + 1);
  169. }
  170. } else {
  171. // Parsing a test case.
  172. if (in_instruction_block) {
  173. // Some NIST CAVP test files (TDES) have a test case immediately
  174. // following an instruction block, without a separate blank line, some
  175. // of the time.
  176. in_instruction_block = false;
  177. }
  178. current_test_ += std::string(buf.get(), len);
  179. std::string key, value;
  180. std::tie(key, value) = ParseKeyValue(buf.get(), len);
  181. // Duplicate keys are rewritten to have “/2”, “/3”, … suffixes.
  182. std::string mapped_key = key;
  183. for (unsigned i = 2; attributes_.count(mapped_key) != 0; i++) {
  184. char suffix[32];
  185. snprintf(suffix, sizeof(suffix), "/%u", i);
  186. suffix[sizeof(suffix)-1] = 0;
  187. mapped_key = key + suffix;
  188. }
  189. unused_attributes_.insert(mapped_key);
  190. attributes_[mapped_key] = value;
  191. if (start_line_ == 0) {
  192. // This is the start of a test.
  193. type_ = mapped_key;
  194. parameter_ = value;
  195. start_line_ = line_;
  196. for (const auto &kv : instructions_) {
  197. unused_instructions_.insert(kv.first);
  198. }
  199. }
  200. }
  201. }
  202. }
  203. void FileTest::PrintLine(const char *format, ...) {
  204. va_list args;
  205. va_start(args, format);
  206. fprintf(stderr, "Line %u: ", start_line_);
  207. vfprintf(stderr, format, args);
  208. fprintf(stderr, "\n");
  209. va_end(args);
  210. }
  211. const std::string &FileTest::GetType() {
  212. OnKeyUsed(type_);
  213. return type_;
  214. }
  215. const std::string &FileTest::GetParameter() {
  216. OnKeyUsed(type_);
  217. return parameter_;
  218. }
  219. bool FileTest::HasAttribute(const std::string &key) {
  220. OnKeyUsed(key);
  221. return attributes_.count(key) > 0;
  222. }
  223. bool FileTest::GetAttribute(std::string *out_value, const std::string &key) {
  224. OnKeyUsed(key);
  225. auto iter = attributes_.find(key);
  226. if (iter == attributes_.end()) {
  227. PrintLine("Missing attribute '%s'.", key.c_str());
  228. return false;
  229. }
  230. *out_value = iter->second;
  231. return true;
  232. }
  233. const std::string &FileTest::GetAttributeOrDie(const std::string &key) {
  234. if (!HasAttribute(key)) {
  235. abort();
  236. }
  237. return attributes_[key];
  238. }
  239. bool FileTest::HasInstruction(const std::string &key) {
  240. OnInstructionUsed(key);
  241. return instructions_.count(key) > 0;
  242. }
  243. bool FileTest::GetInstruction(std::string *out_value, const std::string &key) {
  244. OnInstructionUsed(key);
  245. auto iter = instructions_.find(key);
  246. if (iter == instructions_.end()) {
  247. PrintLine("Missing instruction '%s'.", key.c_str());
  248. return false;
  249. }
  250. *out_value = iter->second;
  251. return true;
  252. }
  253. const std::string &FileTest::GetInstructionOrDie(const std::string &key) {
  254. if (!HasInstruction(key)) {
  255. abort();
  256. }
  257. return instructions_[key];
  258. }
  259. bool FileTest::GetInstructionBytes(std::vector<uint8_t> *out,
  260. const std::string &key) {
  261. std::string value;
  262. return GetInstruction(&value, key) && ConvertToBytes(out, value);
  263. }
  264. const std::string &FileTest::CurrentTestToString() const {
  265. return current_test_;
  266. }
  267. bool FileTest::GetBytes(std::vector<uint8_t> *out, const std::string &key) {
  268. std::string value;
  269. return GetAttribute(&value, key) && ConvertToBytes(out, value);
  270. }
  271. static std::string EncodeHex(const uint8_t *in, size_t in_len) {
  272. static const char kHexDigits[] = "0123456789abcdef";
  273. std::string ret;
  274. ret.reserve(in_len * 2);
  275. for (size_t i = 0; i < in_len; i++) {
  276. ret += kHexDigits[in[i] >> 4];
  277. ret += kHexDigits[in[i] & 0xf];
  278. }
  279. return ret;
  280. }
  281. bool FileTest::ExpectBytesEqual(const uint8_t *expected, size_t expected_len,
  282. const uint8_t *actual, size_t actual_len) {
  283. if (expected_len == actual_len &&
  284. OPENSSL_memcmp(expected, actual, expected_len) == 0) {
  285. return true;
  286. }
  287. std::string expected_hex = EncodeHex(expected, expected_len);
  288. std::string actual_hex = EncodeHex(actual, actual_len);
  289. PrintLine("Expected: %s", expected_hex.c_str());
  290. PrintLine("Actual: %s", actual_hex.c_str());
  291. return false;
  292. }
  293. void FileTest::ClearTest() {
  294. start_line_ = 0;
  295. type_.clear();
  296. parameter_.clear();
  297. attributes_.clear();
  298. unused_attributes_.clear();
  299. unused_instructions_.clear();
  300. current_test_ = "";
  301. }
  302. void FileTest::ClearInstructions() {
  303. instructions_.clear();
  304. unused_attributes_.clear();
  305. }
  306. void FileTest::OnKeyUsed(const std::string &key) {
  307. unused_attributes_.erase(key);
  308. }
  309. void FileTest::OnInstructionUsed(const std::string &key) {
  310. unused_instructions_.erase(key);
  311. }
  312. static bool FromHexDigit(uint8_t *out, char c) {
  313. if ('0' <= c && c <= '9') {
  314. *out = c - '0';
  315. return true;
  316. }
  317. if ('a' <= c && c <= 'f') {
  318. *out = c - 'a' + 10;
  319. return true;
  320. }
  321. if ('A' <= c && c <= 'F') {
  322. *out = c - 'A' + 10;
  323. return true;
  324. }
  325. return false;
  326. }
  327. bool FileTest::ConvertToBytes(std::vector<uint8_t> *out,
  328. const std::string &value) {
  329. if (value.size() >= 2 && value[0] == '"' && value[value.size() - 1] == '"') {
  330. out->assign(value.begin() + 1, value.end() - 1);
  331. return true;
  332. }
  333. if (value.size() % 2 != 0) {
  334. PrintLine("Error decoding value: %s", value.c_str());
  335. return false;
  336. }
  337. out->clear();
  338. out->reserve(value.size() / 2);
  339. for (size_t i = 0; i < value.size(); i += 2) {
  340. uint8_t hi, lo;
  341. if (!FromHexDigit(&hi, value[i]) || !FromHexDigit(&lo, value[i + 1])) {
  342. PrintLine("Error decoding value: %s", value.c_str());
  343. return false;
  344. }
  345. out->push_back((hi << 4) | lo);
  346. }
  347. return true;
  348. }
  349. bool FileTest::IsAtNewInstructionBlock() const {
  350. return is_at_new_instruction_block_;
  351. }
  352. void FileTest::InjectInstruction(const std::string &key,
  353. const std::string &value) {
  354. instructions_[key] = value;
  355. }
  356. class FileLineReader : public FileTest::LineReader {
  357. public:
  358. explicit FileLineReader(const char *path) : file_(fopen(path, "r")) {}
  359. ~FileLineReader() override {
  360. if (file_ != nullptr) {
  361. fclose(file_);
  362. }
  363. }
  364. // is_open returns true if the file was successfully opened.
  365. bool is_open() const { return file_ != nullptr; }
  366. FileTest::ReadResult ReadLine(char *out, size_t len) override {
  367. assert(len > 0);
  368. if (file_ == nullptr) {
  369. return FileTest::kReadError;
  370. }
  371. if (fgets(out, len, file_) == nullptr) {
  372. return feof(file_) ? FileTest::kReadEOF : FileTest::kReadError;
  373. }
  374. if (strlen(out) == len - 1 && out[len - 2] != '\n' && !feof(file_)) {
  375. fprintf(stderr, "Line too long.\n");
  376. return FileTest::kReadError;
  377. }
  378. return FileTest::kReadSuccess;
  379. }
  380. private:
  381. FILE *file_;
  382. FileLineReader(const FileLineReader &) = delete;
  383. FileLineReader &operator=(const FileLineReader &) = delete;
  384. };
  385. int FileTestMain(FileTestFunc run_test, void *arg, const char *path) {
  386. FileTest::Options opts;
  387. opts.callback = run_test;
  388. opts.arg = arg;
  389. opts.path = path;
  390. return FileTestMain(opts);
  391. }
  392. int FileTestMain(const FileTest::Options &opts) {
  393. std::unique_ptr<FileLineReader> reader(
  394. new FileLineReader(opts.path));
  395. if (!reader->is_open()) {
  396. fprintf(stderr, "Could not open file %s: %s.\n", opts.path,
  397. strerror(errno));
  398. return 1;
  399. }
  400. FileTest t(std::move(reader), opts.comment_callback, opts.is_kas_test);
  401. bool failed = false;
  402. while (true) {
  403. FileTest::ReadResult ret = t.ReadNext();
  404. if (ret == FileTest::kReadError) {
  405. return 1;
  406. } else if (ret == FileTest::kReadEOF) {
  407. break;
  408. }
  409. bool result = opts.callback(&t, opts.arg);
  410. if (t.HasAttribute("Error")) {
  411. if (result) {
  412. t.PrintLine("Operation unexpectedly succeeded.");
  413. failed = true;
  414. continue;
  415. }
  416. uint32_t err = ERR_peek_error();
  417. if (ERR_reason_error_string(err) != t.GetAttributeOrDie("Error")) {
  418. t.PrintLine("Unexpected error; wanted '%s', got '%s'.",
  419. t.GetAttributeOrDie("Error").c_str(),
  420. ERR_reason_error_string(err));
  421. failed = true;
  422. ERR_clear_error();
  423. continue;
  424. }
  425. ERR_clear_error();
  426. } else if (!result) {
  427. // In case the test itself doesn't print output, print something so the
  428. // line number is reported.
  429. t.PrintLine("Test failed");
  430. ERR_print_errors_fp(stderr);
  431. failed = true;
  432. continue;
  433. }
  434. }
  435. if (!opts.silent && !failed) {
  436. printf("PASS\n");
  437. }
  438. return failed ? 1 : 0;
  439. }
  440. void FileTest::SkipCurrent() {
  441. ClearTest();
  442. }