Add a CAVP tool for ECDSA2 PKV tests.

Change-Id: I9729714a1f8ccae26edead33270202501559ac10
Reviewed-on: https://boringssl-review.googlesource.com/15666
Reviewed-by: Adam Langley <agl@google.com>
diff --git a/crypto/fipsoracle/CMakeLists.txt b/crypto/fipsoracle/CMakeLists.txt
index 71b2ee1..68ac252 100644
--- a/crypto/fipsoracle/CMakeLists.txt
+++ b/crypto/fipsoracle/CMakeLists.txt
@@ -5,7 +5,6 @@
     cavp_aes_test
 
     cavp_aes_test.cc
-    cavp_test_util.h
     cavp_test_util.cc
     $<TARGET_OBJECTS:test_support>
   )
@@ -14,11 +13,19 @@
     cavp_aes_gcm_test
 
     cavp_aes_gcm_test.cc
-    cavp_test_util.h
+    cavp_test_util.cc
+    $<TARGET_OBJECTS:test_support>
+  )
+
+  add_executable(
+    cavp_ecdsa2_pkv_test
+
+    cavp_ecdsa2_pkv_test.cc
     cavp_test_util.cc
     $<TARGET_OBJECTS:test_support>
   )
 
   target_link_libraries(cavp_aes_test crypto)
   target_link_libraries(cavp_aes_gcm_test crypto)
+  target_link_libraries(cavp_ecdsa2_pkv_test crypto)
 endif()
diff --git a/crypto/fipsoracle/cavp_ecdsa2_pkv_test.cc b/crypto/fipsoracle/cavp_ecdsa2_pkv_test.cc
new file mode 100644
index 0000000..25117b4
--- /dev/null
+++ b/crypto/fipsoracle/cavp_ecdsa2_pkv_test.cc
@@ -0,0 +1,70 @@
+/* Copyright (c) 2017, 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_ecdsa2_pkv_test processes a NIST CAVP ECDSA2 PKV test vector request file
+// and emits the corresponding response. An optional sample vector file can be
+// passed to verify the result.
+
+#include <vector>
+
+#include <openssl/bn.h>
+#include <openssl/crypto.h>
+#include <openssl/ec_key.h>
+#include <openssl/err.h>
+#include <openssl/nid.h>
+
+#include "../test/file_test.h"
+#include "cavp_test_util.h"
+
+
+static bool TestECDSA2PKV(FileTest *t, void *arg) {
+  int nid = GetECGroupNIDFromInstruction(t);
+  if (nid == NID_undef) {
+    return false;
+  }
+  bssl::UniquePtr<EC_KEY> key(EC_KEY_new_by_curve_name(nid));
+  bssl::UniquePtr<BIGNUM> qx = GetBIGNUM(t, "Qx");
+  bssl::UniquePtr<BIGNUM> qy = GetBIGNUM(t, "Qy");
+  if (!key || !qx || !qy) {
+    return false;
+  }
+
+  if (EC_KEY_set_public_key_affine_coordinates(key.get(), qx.get(), qy.get())) {
+    printf("%sResult = P\r\n\r\n", t->CurrentTestToString().c_str());
+  } else {
+    char buf[256];
+    ERR_error_string_n(ERR_get_error(), buf, sizeof(buf));
+    printf("%sResult = F (%s)\r\n\r\n", t->CurrentTestToString().c_str(), buf);
+  }
+  ERR_clear_error();
+  return true;
+}
+
+int main(int argc, char **argv) {
+  CRYPTO_library_init();
+
+  if (argc != 2) {
+    fprintf(stderr, "usage: %s <test file>\n",
+            argv[0]);
+    return 1;
+  }
+
+  printf("# Generated by");
+  for (int i = 0; i < argc; i++) {
+    printf(" %s", argv[i]);
+  }
+  printf("\r\n\r\n");
+
+  return FileTestMainSilent(TestECDSA2PKV, nullptr, argv[1]);
+}
diff --git a/crypto/fipsoracle/cavp_test_util.cc b/crypto/fipsoracle/cavp_test_util.cc
index 0f5b196..39bc773 100644
--- a/crypto/fipsoracle/cavp_test_util.cc
+++ b/crypto/fipsoracle/cavp_test_util.cc
@@ -14,6 +14,10 @@
 
 #include "cavp_test_util.h"
 
+#include <openssl/bn.h>
+#include <openssl/ec.h>
+#include <openssl/nid.h>
+
 
 std::string EncodeHex(const uint8_t *in, size_t in_len) {
   static const char kHexDigits[] = "0123456789abcdef";
@@ -154,3 +158,41 @@
   }
   return true;
 }
+
+static int HexToBIGNUM(bssl::UniquePtr<BIGNUM> *out, const char *in) {
+  BIGNUM *raw = NULL;
+  int ret = BN_hex2bn(&raw, in);
+  out->reset(raw);
+  return ret;
+}
+
+bssl::UniquePtr<BIGNUM> GetBIGNUM(FileTest *t, const char *attribute) {
+  std::string hex;
+  if (!t->GetAttribute(&hex, attribute)) {
+    return nullptr;
+  }
+
+  bssl::UniquePtr<BIGNUM> ret;
+  if (HexToBIGNUM(&ret, hex.c_str()) != static_cast<int>(hex.size())) {
+    t->PrintLine("Could not decode '%s'.", hex.c_str());
+    return nullptr;
+  }
+  return ret;
+}
+
+int GetECGroupNIDFromInstruction(FileTest *t) {
+  if (t->HasInstruction("P-224")) {
+    return NID_secp224r1;
+  }
+  if (t->HasInstruction("P-256")) {
+    return NID_X9_62_prime256v1;
+  }
+  if (t->HasInstruction("P-384")) {
+    return NID_secp384r1;
+  }
+  if (t->HasInstruction("P-521")) {
+    return NID_secp521r1;
+  }
+  t->PrintLine("No supported group specified.");
+  return NID_undef;
+}
diff --git a/crypto/fipsoracle/cavp_test_util.h b/crypto/fipsoracle/cavp_test_util.h
index 6b4966c..fa7ac32 100644
--- a/crypto/fipsoracle/cavp_test_util.h
+++ b/crypto/fipsoracle/cavp_test_util.h
@@ -22,6 +22,8 @@
 #include <openssl/aead.h>
 #include <openssl/cipher.h>
 
+#include "../test/file_test.h"
+
 
 std::string EncodeHex(const uint8_t *in, size_t in_len);
 
@@ -44,5 +46,9 @@
                  const std::vector<uint8_t> &ct,
                  const std::vector<uint8_t> &tag, std::vector<uint8_t> &iv);
 
+bssl::UniquePtr<BIGNUM> GetBIGNUM(FileTest *t, const char *attribute);
+
+int GetECGroupNIDFromInstruction(FileTest *t);
+
 
 #endif  // OPENSSL_HEADER_CRYPTO_FIPSMODULE_CAVP_TEST_UTIL_H
diff --git a/crypto/fipsoracle/run_cavp.go b/crypto/fipsoracle/run_cavp.go
index 88ef35d..08b6400 100644
--- a/crypto/fipsoracle/run_cavp.go
+++ b/crypto/fipsoracle/run_cavp.go
@@ -23,7 +23,7 @@
 	inFile string
 	// args are the arguments (not including the input filename) to the
 	// oracle binary.
-	args   []string
+	args []string
 	// noFAX, if true, indicates that the output cannot be compared against
 	// the FAX file. (E.g. because the primitive is non-deterministic.)
 	noFAX bool
@@ -35,8 +35,8 @@
 	// directory is the name of the directory in the CAVP input, i.e. “AES”.
 	directory string
 	// binary is the name of the binary that can process these tests.
-	binary    string
-	tests     []test
+	binary string
+	tests  []test
 }
 
 var aesGCMTests = testSuite{
@@ -95,9 +95,16 @@
 //{"CBCMCT192", []string{"aes-192-cbc"}, false},
 //{"CBCMCT256", []string{"aes-256-cbc"}, false},
 
+var ecdsa2PKVTests = testSuite{
+	"ECDSA2",
+	"cavp_ecdsa2_pkv_test",
+	[]test{{"PKV", nil, false}},
+}
+
 var allTestSuites = []*testSuite{
 	&aesGCMTests,
 	&aesTests,
+	&ecdsa2PKVTests,
 }
 
 func main() {
@@ -150,6 +157,16 @@
 	return nil
 }
 
+func canonicalizeLine(in string) string {
+	if strings.HasPrefix(in, "Result = P (") {
+		return "Result = P"
+	}
+	if strings.HasPrefix(in, "Result = F (") {
+		return "Result = F"
+	}
+	return in
+}
+
 func compareFAX(suite *testSuite, test test) error {
 	respPath := filepath.Join(suite.directory, "resp", test.inFile+".resp")
 	respFile, err := os.Open(respPath)
@@ -211,7 +228,7 @@
 			break
 		}
 
-		if faxLine == respLine {
+		if canonicalizeLine(faxLine) == canonicalizeLine(respLine) {
 			continue
 		}