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.
 
 
 
 
 
 

496 lines
14 KiB

  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::CurrentTestToString() const {
  254. return current_test_;
  255. }
  256. static bool FromHexDigit(uint8_t *out, char c) {
  257. if ('0' <= c && c <= '9') {
  258. *out = c - '0';
  259. return true;
  260. }
  261. if ('a' <= c && c <= 'f') {
  262. *out = c - 'a' + 10;
  263. return true;
  264. }
  265. if ('A' <= c && c <= 'F') {
  266. *out = c - 'A' + 10;
  267. return true;
  268. }
  269. return false;
  270. }
  271. bool FileTest::GetBytes(std::vector<uint8_t> *out, const std::string &key) {
  272. std::string value;
  273. if (!GetAttribute(&value, key)) {
  274. return false;
  275. }
  276. if (value.size() >= 2 && value[0] == '"' && value[value.size() - 1] == '"') {
  277. out->assign(value.begin() + 1, value.end() - 1);
  278. return true;
  279. }
  280. if (value.size() % 2 != 0) {
  281. PrintLine("Error decoding value: %s", value.c_str());
  282. return false;
  283. }
  284. out->clear();
  285. out->reserve(value.size() / 2);
  286. for (size_t i = 0; i < value.size(); i += 2) {
  287. uint8_t hi, lo;
  288. if (!FromHexDigit(&hi, value[i]) || !FromHexDigit(&lo, value[i + 1])) {
  289. PrintLine("Error decoding value: %s", value.c_str());
  290. return false;
  291. }
  292. out->push_back((hi << 4) | lo);
  293. }
  294. return true;
  295. }
  296. static std::string EncodeHex(const uint8_t *in, size_t in_len) {
  297. static const char kHexDigits[] = "0123456789abcdef";
  298. std::string ret;
  299. ret.reserve(in_len * 2);
  300. for (size_t i = 0; i < in_len; i++) {
  301. ret += kHexDigits[in[i] >> 4];
  302. ret += kHexDigits[in[i] & 0xf];
  303. }
  304. return ret;
  305. }
  306. bool FileTest::ExpectBytesEqual(const uint8_t *expected, size_t expected_len,
  307. const uint8_t *actual, size_t actual_len) {
  308. if (expected_len == actual_len &&
  309. OPENSSL_memcmp(expected, actual, expected_len) == 0) {
  310. return true;
  311. }
  312. std::string expected_hex = EncodeHex(expected, expected_len);
  313. std::string actual_hex = EncodeHex(actual, actual_len);
  314. PrintLine("Expected: %s", expected_hex.c_str());
  315. PrintLine("Actual: %s", actual_hex.c_str());
  316. return false;
  317. }
  318. void FileTest::ClearTest() {
  319. start_line_ = 0;
  320. type_.clear();
  321. parameter_.clear();
  322. attributes_.clear();
  323. unused_attributes_.clear();
  324. current_test_ = "";
  325. }
  326. void FileTest::ClearInstructions() {
  327. instructions_.clear();
  328. unused_attributes_.clear();
  329. }
  330. void FileTest::OnKeyUsed(const std::string &key) {
  331. unused_attributes_.erase(key);
  332. }
  333. void FileTest::OnInstructionUsed(const std::string &key) {
  334. unused_instructions_.erase(key);
  335. }
  336. bool FileTest::IsAtNewInstructionBlock() const {
  337. return is_at_new_instruction_block_;
  338. }
  339. void FileTest::InjectInstruction(const std::string &key,
  340. const std::string &value) {
  341. instructions_[key] = value;
  342. }
  343. class FileLineReader : public FileTest::LineReader {
  344. public:
  345. explicit FileLineReader(const char *path) : file_(fopen(path, "r")) {}
  346. ~FileLineReader() override {
  347. if (file_ != nullptr) {
  348. fclose(file_);
  349. }
  350. }
  351. // is_open returns true if the file was successfully opened.
  352. bool is_open() const { return file_ != nullptr; }
  353. FileTest::ReadResult ReadLine(char *out, size_t len) override {
  354. assert(len > 0);
  355. if (file_ == nullptr) {
  356. return FileTest::kReadError;
  357. }
  358. if (fgets(out, len, file_) == nullptr) {
  359. return feof(file_) ? FileTest::kReadEOF : FileTest::kReadError;
  360. }
  361. if (strlen(out) == len - 1 && out[len - 2] != '\n' && !feof(file_)) {
  362. fprintf(stderr, "Line too long.\n");
  363. return FileTest::kReadError;
  364. }
  365. return FileTest::kReadSuccess;
  366. }
  367. private:
  368. FILE *file_;
  369. FileLineReader(const FileLineReader &) = delete;
  370. FileLineReader &operator=(const FileLineReader &) = delete;
  371. };
  372. int FileTestMain(FileTestFunc run_test, void *arg, const char *path) {
  373. FileTest::Options opts;
  374. opts.callback = run_test;
  375. opts.arg = arg;
  376. opts.path = path;
  377. return FileTestMain(opts);
  378. }
  379. int FileTestMain(const FileTest::Options &opts) {
  380. std::unique_ptr<FileLineReader> reader(
  381. new FileLineReader(opts.path));
  382. if (!reader->is_open()) {
  383. fprintf(stderr, "Could not open file %s: %s.\n", opts.path,
  384. strerror(errno));
  385. return 1;
  386. }
  387. FileTest t(std::move(reader), opts.comment_callback, opts.is_kas_test);
  388. bool failed = false;
  389. while (true) {
  390. FileTest::ReadResult ret = t.ReadNext();
  391. if (ret == FileTest::kReadError) {
  392. return 1;
  393. } else if (ret == FileTest::kReadEOF) {
  394. break;
  395. }
  396. bool result = opts.callback(&t, opts.arg);
  397. if (t.HasAttribute("Error")) {
  398. if (result) {
  399. t.PrintLine("Operation unexpectedly succeeded.");
  400. failed = true;
  401. continue;
  402. }
  403. uint32_t err = ERR_peek_error();
  404. if (ERR_reason_error_string(err) != t.GetAttributeOrDie("Error")) {
  405. t.PrintLine("Unexpected error; wanted '%s', got '%s'.",
  406. t.GetAttributeOrDie("Error").c_str(),
  407. ERR_reason_error_string(err));
  408. failed = true;
  409. ERR_clear_error();
  410. continue;
  411. }
  412. ERR_clear_error();
  413. } else if (!result) {
  414. // In case the test itself doesn't print output, print something so the
  415. // line number is reported.
  416. t.PrintLine("Test failed");
  417. ERR_print_errors_fp(stderr);
  418. failed = true;
  419. continue;
  420. }
  421. }
  422. if (!opts.silent && !failed) {
  423. printf("PASS\n");
  424. }
  425. return failed ? 1 : 0;
  426. }
  427. void FileTest::SkipCurrent() {
  428. ClearTest();
  429. }