Support KAS tests for NIAP.

This change adds support for two specific CAVP tests, in order to
meet NIAP requirements.

These tests are currently only run when “-niap” is passed to run_cavp.go
because they are not part of our FIPS validation (yet).

Change-Id: I511279651aae094702332130fac5ab64d11ddfdb
Reviewed-on: https://boringssl-review.googlesource.com/24665
Reviewed-by: Adam Langley <agl@google.com>
diff --git a/crypto/test/file_test.cc b/crypto/test/file_test.cc
index ea1fc3c..cbb9f7f 100644
--- a/crypto/test/file_test.cc
+++ b/crypto/test/file_test.cc
@@ -31,8 +31,10 @@
 
 
 FileTest::FileTest(std::unique_ptr<FileTest::LineReader> reader,
-                   std::function<void(const std::string &)> comment_callback)
+                   std::function<void(const std::string &)> comment_callback,
+                   bool is_kas_test)
     : reader_(std::move(reader)),
+      is_kas_test_(is_kas_test),
       comment_callback_(std::move(comment_callback)) {}
 
 FileTest::~FileTest() {}
@@ -122,9 +124,16 @@
         in_instruction_block = false;
         // Delimit instruction block from test with a blank line.
         current_test_ += "\r\n";
+      } else if (is_kas_test_) {
+        // KAS tests have random blank lines scattered around.
+        current_test_ += "\r\n";
       }
     } else if (buf[0] == '#') {
-      if (comment_callback_) {
+      if (is_kas_test_ && seen_non_comment_) {
+        // KAS tests have comments after the initial comment block which need
+        // to be included in the corresponding place in the output.
+        current_test_ += std::string(buf.get());
+      } else if (comment_callback_) {
         comment_callback_(buf.get());
       }
       // Otherwise ignore comments.
@@ -134,6 +143,7 @@
       // request files are hopelessly inconsistent.
     } else if (buf[0] == '[') {  // Inside an instruction block.
       is_at_new_instruction_block_ = true;
+      seen_non_comment_ = true;
       if (start_line_ != 0) {
         // Instructions should be separate blocks.
         fprintf(stderr, "Line %u is an instruction in a test case.\n", line_);
@@ -145,12 +155,25 @@
       }
 
       // Parse the line as an instruction ("[key = value]" or "[key]").
-      std::string kv = StripSpace(buf.get(), len);
-      if (kv[kv.size() - 1] != ']') {
-        fprintf(stderr, "Line %u, invalid instruction: %s\n", line_,
-                kv.c_str());
-        return kReadError;
+
+      // KAS tests contain invalid syntax.
+      std::string kv = buf.get();
+      const bool is_broken_kas_instruction =
+          is_kas_test_ &&
+          (kv == "[SHA(s) supported (Used for hashing Z): SHA512 \r\n");
+
+      if (!is_broken_kas_instruction) {
+        kv = StripSpace(buf.get(), len);
+        if (kv[kv.size() - 1] != ']') {
+          fprintf(stderr, "Line %u, invalid instruction: '%s'\n", line_,
+                  kv.c_str());
+          return kReadError;
+        }
+      } else {
+        // Just remove the newline for the broken instruction.
+        kv = kv.substr(0, kv.size() - 2);
       }
+
       current_test_ += kv + "\r\n";
       kv = std::string(kv.begin() + 1, kv.end() - 1);
 
@@ -422,7 +445,7 @@
     return 1;
   }
 
-  FileTest t(std::move(reader), opts.comment_callback);
+  FileTest t(std::move(reader), opts.comment_callback, opts.is_kas_test);
 
   bool failed = false;
   while (true) {
diff --git a/crypto/test/file_test.h b/crypto/test/file_test.h
index 204ef9c..002b350 100644
--- a/crypto/test/file_test.h
+++ b/crypto/test/file_test.h
@@ -114,10 +114,15 @@
     bool silent = false;
     // comment_callback is called after each comment in the input is parsed.
     std::function<void(const std::string&)> comment_callback;
+    // is_kas_test is true if a NIST “KAS” test is being parsed. These tests
+    // are inconsistent with the other NIST files to such a degree that they
+    // need their own boolean.
+    bool is_kas_test = false;
   };
 
   explicit FileTest(std::unique_ptr<LineReader> reader,
-                    std::function<void(const std::string &)> comment_callback);
+                    std::function<void(const std::string &)> comment_callback,
+                    bool is_kas_test);
   ~FileTest();
 
   // ReadNext reads the next test from the file. It returns |kReadSuccess| if
@@ -217,6 +222,8 @@
   std::string current_test_;
 
   bool is_at_new_instruction_block_ = false;
+  bool seen_non_comment_ = false;
+  bool is_kas_test_ = false;
 
   // comment_callback_, if set, is a callback function that is called with the
   // contents of each comment as they are parsed.
diff --git a/crypto/test/file_test_gtest.cc b/crypto/test/file_test_gtest.cc
index bfa8d27..8ff7a2b 100644
--- a/crypto/test/file_test_gtest.cc
+++ b/crypto/test/file_test_gtest.cc
@@ -68,7 +68,7 @@
 void FileTestGTest(const char *path, std::function<void(FileTest *)> run_test) {
   std::unique_ptr<StringLineReader> reader(
       new StringLineReader(GetTestData(path)));
-  FileTest t(std::move(reader), nullptr);
+  FileTest t(std::move(reader), nullptr, false);
 
   while (true) {
     switch (t.ReadNext()) {
diff --git a/fipstools/CMakeLists.txt b/fipstools/CMakeLists.txt
index 8fd294f..3d32538 100644
--- a/fipstools/CMakeLists.txt
+++ b/fipstools/CMakeLists.txt
@@ -14,6 +14,7 @@
     cavp_ecdsa2_siggen_test.cc
     cavp_ecdsa2_sigver_test.cc
     cavp_hmac_test.cc
+    cavp_kas_test.cc
     cavp_keywrap_test.cc
     cavp_rsa2_keygen_test.cc
     cavp_rsa2_siggen_test.cc
diff --git a/fipstools/cavp_kas_test.cc b/fipstools/cavp_kas_test.cc
new file mode 100644
index 0000000..a304a48
--- /dev/null
+++ b/fipstools/cavp_kas_test.cc
@@ -0,0 +1,160 @@
+/* Copyright (c) 2018, Google Inc.
+ *
+ * Permission to use, copy, modify, and/or distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+ * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
+ * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
+ * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
+
+// cavp_kas_test processes NIST CAVP ECC KAS test vector request files and
+// emits the corresponding response.
+
+#include <vector>
+
+#include <openssl/bn.h>
+#include <openssl/crypto.h>
+#include <openssl/digest.h>
+#include <openssl/ecdh.h>
+#include <openssl/ecdsa.h>
+#include <openssl/ec_key.h>
+#include <openssl/err.h>
+#include <openssl/nid.h>
+
+#include "../crypto/internal.h"
+#include "../crypto/test/file_test.h"
+#include "cavp_test_util.h"
+
+
+static bool TestKAS(FileTest *t, void *arg) {
+  const bool validate = *reinterpret_cast<bool *>(arg);
+
+  int nid = NID_undef;
+  const EVP_MD *md = nullptr;
+
+  if (t->HasInstruction("EB - SHA224")) {
+    nid = NID_secp224r1;
+    md = EVP_sha224();
+  } else if (t->HasInstruction("EC - SHA256")) {
+    nid = NID_X9_62_prime256v1;
+    md = EVP_sha256();
+  } else if (t->HasInstruction("ED - SHA384")) {
+    nid = NID_secp384r1;
+    md = EVP_sha384();
+  } else if (t->HasInstruction("EE - SHA512")) {
+    nid = NID_secp521r1;
+    md = EVP_sha512();
+  } else {
+    return false;
+  }
+
+  if (!t->HasAttribute("COUNT")) {
+    return false;
+  }
+
+  bssl::UniquePtr<BIGNUM> their_x(GetBIGNUM(t, "QeCAVSx"));
+  bssl::UniquePtr<BIGNUM> their_y(GetBIGNUM(t, "QeCAVSy"));
+  bssl::UniquePtr<EC_KEY> ec_key(EC_KEY_new_by_curve_name(nid));
+  bssl::UniquePtr<BN_CTX> ctx(BN_CTX_new());
+  if (!their_x || !their_y || !ec_key || !ctx) {
+    return false;
+  }
+
+  const EC_GROUP *const group = EC_KEY_get0_group(ec_key.get());
+  bssl::UniquePtr<EC_POINT> their_point(EC_POINT_new(group));
+  if (!their_point ||
+      !EC_POINT_set_affine_coordinates_GFp(
+          group, their_point.get(), their_x.get(), their_y.get(), ctx.get())) {
+    return false;
+  }
+
+  if (validate) {
+    bssl::UniquePtr<BIGNUM> our_k(GetBIGNUM(t, "deIUT"));
+    if (!our_k ||
+        !EC_KEY_set_private_key(ec_key.get(), our_k.get()) ||
+        // These attributes are ignored.
+        !t->HasAttribute("QeIUTx") ||
+        !t->HasAttribute("QeIUTy")) {
+      return false;
+    }
+  } else if (!EC_KEY_generate_key(ec_key.get())) {
+    return false;
+  }
+
+  constexpr size_t kMaxCurveFieldBits = 521;
+  uint8_t shared_bytes[(kMaxCurveFieldBits + 7)/8];
+  const int shared_bytes_len =
+      ECDH_compute_key(shared_bytes, sizeof(shared_bytes), their_point.get(),
+                       ec_key.get(), nullptr);
+
+  uint8_t digest[EVP_MAX_MD_SIZE];
+  unsigned digest_len;
+  if (shared_bytes_len < 0 ||
+      !EVP_Digest(shared_bytes, shared_bytes_len, digest, &digest_len, md,
+                  nullptr)) {
+    return false;
+  }
+
+  if (validate) {
+    std::vector<uint8_t> expected_shared_bytes;
+    if (!t->GetBytes(&expected_shared_bytes, "CAVSHashZZ")) {
+      return false;
+    }
+    const bool ok =
+        digest_len == expected_shared_bytes.size() &&
+        OPENSSL_memcmp(digest, expected_shared_bytes.data(), digest_len) == 0;
+
+    printf("%sIUTHashZZ = %s\r\nResult = %c\r\n\r\n\r\n",
+           t->CurrentTestToString().c_str(),
+           EncodeHex(digest, digest_len).c_str(), ok ? 'P' : 'F');
+  } else {
+    const EC_POINT *pub = EC_KEY_get0_public_key(ec_key.get());
+    bssl::UniquePtr<BIGNUM> x(BN_new());
+    bssl::UniquePtr<BIGNUM> y(BN_new());
+    if (!x || !y ||
+        !EC_POINT_get_affine_coordinates_GFp(group, pub, x.get(), y.get(),
+                                             ctx.get())) {
+      return false;
+    }
+    bssl::UniquePtr<char> x_hex(BN_bn2hex(x.get()));
+    bssl::UniquePtr<char> y_hex(BN_bn2hex(y.get()));
+
+    printf("%sQeIUTx = %s\r\nQeIUTy = %s\r\nHashZZ = %s\r\n",
+           t->CurrentTestToString().c_str(), x_hex.get(), y_hex.get(),
+           EncodeHex(digest, digest_len).c_str());
+  }
+
+  return true;
+}
+
+int cavp_kas_test_main(int argc, char **argv) {
+  if (argc != 3) {
+    fprintf(stderr, "usage: %s (validity|function) <test file>\n",
+            argv[0]);
+    return 1;
+  }
+
+  bool validity;
+  if (strcmp(argv[1], "validity") == 0) {
+    validity = true;
+  } else if (strcmp(argv[1], "function") == 0) {
+    validity = false;
+  } else {
+    fprintf(stderr, "Unknown test type: %s\n", argv[1]);
+    return 1;
+  }
+
+  FileTest::Options opts;
+  opts.path = argv[2];
+  opts.arg = &validity;
+  opts.callback = TestKAS;
+  opts.silent = true;
+  opts.comment_callback = EchoComment;
+  opts.is_kas_test = true;
+  return FileTestMain(opts);
+}
diff --git a/fipstools/cavp_main.cc b/fipstools/cavp_main.cc
index e7bbfb4..9ed7591 100644
--- a/fipstools/cavp_main.cc
+++ b/fipstools/cavp_main.cc
@@ -43,6 +43,7 @@
     {"ecdsa2_siggen", &cavp_ecdsa2_siggen_test_main},
     {"ecdsa2_sigver", &cavp_ecdsa2_sigver_test_main},
     {"hmac", &cavp_hmac_test_main},
+    {"kas", &cavp_kas_test_main},
     {"keywrap", &cavp_keywrap_test_main},
     {"rsa2_keygen", &cavp_rsa2_keygen_test_main},
     {"rsa2_siggen", &cavp_rsa2_siggen_test_main},
diff --git a/fipstools/cavp_test_util.h b/fipstools/cavp_test_util.h
index 0cbd9a7..8c0624e 100644
--- a/fipstools/cavp_test_util.h
+++ b/fipstools/cavp_test_util.h
@@ -64,6 +64,7 @@
 int cavp_ecdsa2_siggen_test_main(int argc, char **argv);
 int cavp_ecdsa2_sigver_test_main(int argc, char **argv);
 int cavp_hmac_test_main(int argc, char **argv);
+int cavp_kas_test_main(int argc, char **argv);
 int cavp_keywrap_test_main(int argc, char **argv);
 int cavp_rsa2_keygen_test_main(int argc, char **argv);
 int cavp_rsa2_siggen_test_main(int argc, char **argv);
diff --git a/fipstools/run_cavp.go b/fipstools/run_cavp.go
index 577334a..11a01a1 100644
--- a/fipstools/run_cavp.go
+++ b/fipstools/run_cavp.go
@@ -19,6 +19,7 @@
 	oraclePath = flag.String("oracle-bin", "", "Path to the oracle binary")
 	suiteDir   = flag.String("suite-dir", "", "Base directory containing the CAVP test suite")
 	noFAX      = flag.Bool("no-fax", false, "Skip comparing against FAX files")
+	niap       = flag.Bool("niap", false, "Perform NIAP tests rather than FIPS tests")
 )
 
 // test describes a single request file.
@@ -36,6 +37,8 @@
 
 // nextLineState can be used by FAX next-line function to store state.
 type nextLineState struct {
+	// State used by the KAS test.
+	nextIsIUTHash bool
 }
 
 // testSuite describes a series of tests that are handled by a single oracle
@@ -278,7 +281,42 @@
 	},
 }
 
-var allTestSuites = []*testSuite{
+var kasTests = testSuite{
+	"KAS",
+	"kas",
+	func(s *bufio.Scanner, state *nextLineState) (line string, isWildcard, ok bool) {
+		for {
+			// If the response file will include the IUT hash next,
+			// return a wildcard signal because this cannot be
+			// matched against the FAX file.
+			if state.nextIsIUTHash {
+				state.nextIsIUTHash = false
+				return "", true, true
+			}
+
+			if !s.Scan() {
+				return "", false, false
+			}
+
+			line := s.Text()
+			if strings.HasPrefix(line, "deCAVS = ") || strings.HasPrefix(line, "Z = ") {
+				continue
+			}
+			if strings.HasPrefix(line, "CAVSHashZZ = ") {
+				state.nextIsIUTHash = true
+			}
+			return line, false, true
+		}
+	},
+	[]test{
+		{"KASFunctionTest_ECCEphemeralUnified_NOKC_ZZOnly_init", []string{"function"}, true},
+		{"KASFunctionTest_ECCEphemeralUnified_NOKC_ZZOnly_resp", []string{"function"}, true},
+		{"KASValidityTest_ECCEphemeralUnified_NOKC_ZZOnly_init", []string{"validity"}, false},
+		{"KASValidityTest_ECCEphemeralUnified_NOKC_ZZOnly_resp", []string{"validity"}, false},
+	},
+}
+
+var fipsTestSuites = []*testSuite{
 	&aesGCMTests,
 	&aesTests,
 	&ctrDRBGTests,
@@ -296,6 +334,10 @@
 	&tdesTests,
 }
 
+var niapTestSuites = []*testSuite{
+	&kasTests,
+}
+
 // testInstance represents a specific test in a testSuite.
 type testInstance struct {
 	suite     *testSuite
@@ -338,7 +380,12 @@
 		go worker(&wg, work)
 	}
 
-	for _, suite := range allTestSuites {
+	testSuites := fipsTestSuites
+	if *niap {
+		testSuites = niapTestSuites
+	}
+
+	for _, suite := range testSuites {
 		for i := range suite.tests {
 			work <- testInstance{suite, i}
 		}