fipsoracle: Add MCT mode for TDES.

Change-Id: I0dafd669a6d4e435d7597c0db26ef467e4beef0d
Reviewed-on: https://boringssl-review.googlesource.com/15805
Reviewed-by: Adam Langley <agl@google.com>
diff --git a/crypto/test/file_test.cc b/crypto/test/file_test.cc
index b48100e..473094b 100644
--- a/crypto/test/file_test.cc
+++ b/crypto/test/file_test.cc
@@ -367,12 +367,16 @@
   return is_at_new_instruction_block_;
 }
 
+void FileTest::InjectInstruction(const std::string &key,
+                                 const std::string &value) {
+  instructions_[key] = value;
+}
+
 void FileTest::SetIgnoreUnusedAttributes(bool ignore) {
   ignore_unused_attributes_ = ignore;
 }
 
-int FileTestMainSilent(bool (*run_test)(FileTest *t, void *arg), void *arg,
-                       const char *path) {
+int FileTestMainSilent(FileTestFunc run_test, void *arg, const char *path) {
   FileTest t(path);
   if (!t.is_open()) {
     return 1;
@@ -417,8 +421,7 @@
   return failed ? 1 : 0;
 }
 
-int FileTestMain(bool (*run_test)(FileTest *t, void *arg), void *arg,
-                 const char *path) {
+int FileTestMain(FileTestFunc run_test, void *arg, const char *path) {
   int result = FileTestMainSilent(run_test, arg, path);
   if (!result) {
     printf("PASS\n");
diff --git a/crypto/test/file_test.h b/crypto/test/file_test.h
index 8a3108e..17213d9 100644
--- a/crypto/test/file_test.h
+++ b/crypto/test/file_test.h
@@ -158,6 +158,10 @@
   // other blank or comment lines are omitted.
   const std::string &CurrentTestToString() const;
 
+  // InjectInstruction adds a key value pair to the most recently parsed set of
+  // instructions.
+  void InjectInstruction(const std::string &key, const std::string &value);
+
   void SetIgnoreUnusedAttributes(bool ignore);
 
  private:
@@ -197,6 +201,8 @@
   FileTest &operator=(const FileTest &) = delete;
 };
 
+typedef bool (*FileTestFunc)(FileTest *t, void *arg);
+
 // FileTestMain runs a file-based test out of |path| and returns an exit code
 // suitable to return out of |main|. |run_test| should return true on pass and
 // false on failure. FileTestMain also implements common handling of the 'Error'
@@ -208,12 +214,10 @@
 // list of keys. This may be used to initialize a shared set of keys for many
 // tests. However, if one test fails, the framework will continue to run
 // subsequent tests.
-int FileTestMain(bool (*run_test)(FileTest *t, void *arg), void *arg,
-                 const char *path);
+int FileTestMain(FileTestFunc run_test, void *arg, const char *path);
 
 // FileTestMainSilent behaves like FileTestMain but does not print a final
 // FAIL/PASS message to stdout.
-int FileTestMainSilent(bool (*run_test)(FileTest *t, void *arg), void *arg,
-                       const char *path);
+int FileTestMainSilent(FileTestFunc run_test, void *arg, const char *path);
 
 #endif /* OPENSSL_HEADER_CRYPTO_TEST_FILE_TEST_H */
diff --git a/fipsoracle/cavp_tdes_test.cc b/fipsoracle/cavp_tdes_test.cc
index 31e850c..f499ebe 100644
--- a/fipsoracle/cavp_tdes_test.cc
+++ b/fipsoracle/cavp_tdes_test.cc
@@ -32,7 +32,6 @@
   enum Mode {
     kKAT,  // Known Answer Test
     kMCT,  // Monte Carlo Test
-    kMMT,  // Multi Message Test
   };
   bool has_iv;
   Mode mode;
@@ -50,41 +49,99 @@
     kDecrypt,
   } operation = t->HasInstruction("ENCRYPT") ? kEncrypt : kDecrypt;
 
+  if (t->HasAttribute("NumKeys")) {
+    // Another file format quirk: NumKeys is a single attribute line immediately
+    // following an instruction and should probably have been an instruction
+    // instead. If it is present, the file has separate attributes "KEY{1,2,3}".
+    // If it is not, the keys are concatenated in a single attribute "KEYs".
+    std::string num_keys;
+    t->GetAttribute(&num_keys, "NumKeys");
+    t->InjectInstruction("NumKeys", num_keys);
+
+    std::string header = operation == kEncrypt ? "[ENCRYPT]" : "[DECRYPT]";
+    printf("%s\r\n\r\n", header.c_str());
+
+    return true;
+  }
+
+  enum {
+    kNotPresent,
+    kTwo,
+    kThree,
+  } num_keys = kNotPresent;
+  if (t->HasInstruction("NumKeys")) {
+    std::string num_keys_str;
+    t->GetInstruction(&num_keys_str, "NumKeys");
+    const int n = strtoul(num_keys_str.c_str(), nullptr, 0);
+    if (n == 2) {
+      num_keys = kTwo;
+    } else if (n == 3) {
+      num_keys = kThree;
+    } else {
+      t->PrintLine("invalid NumKeys value");
+      return false;
+    }
+  }
+
   std::string count;
-  std::vector<uint8_t> key, iv, in, result;
-  const std::string op_label = operation == kEncrypt ? "PLAINTEXT" : "CIPHERTEXT";
+  std::vector<uint8_t> keys, key1, key2, key3, iv, in, result;
+  const std::string in_label =
+      operation == kEncrypt ? "PLAINTEXT" : "CIPHERTEXT";
+  // clang-format off
   if (!t->GetAttribute(&count, "COUNT") ||
-      !t->GetBytes(&key, "KEYs") ||
+      (num_keys == 0 && !t->GetBytes(&keys, "KEYs")) ||
+      (num_keys > 0 &&
+       (!t->GetBytes(&key1, "KEY1") ||
+        !t->GetBytes(&key2, "KEY2") ||
+        !t->GetBytes(&key3, "KEY3"))) ||
       (ctx->has_iv && !t->GetBytes(&iv, "IV")) ||
-      !t->GetBytes(&in, op_label)) {
+      !t->GetBytes(&in, in_label)) {
     return false;
   }
-  std::vector<uint8_t> triple_key(key);
-  triple_key.insert(triple_key.end(), key.begin(), key.end());
-  triple_key.insert(triple_key.end(), key.begin(), key.end());
+  // clang-format on
+  std::vector<uint8_t> key;
+  if (num_keys != kNotPresent) {
+    key.insert(key.end(), key1.begin(), key1.end());
+    key.insert(key.end(), key2.begin(), key2.end());
+    if (num_keys == kThree) {
+      key.insert(key.end(), key3.begin(), key3.end());
+    }
+  } else {
+    key.insert(key.end(), keys.begin(), keys.end());
+    key.insert(key.end(), keys.begin(), keys.end());
+    key.insert(key.end(), keys.begin(), keys.end());
+  }
 
-  const EVP_CIPHER *cipher = ctx->cipher;
-
-  if (!CipherOperation(cipher, &result, operation == kEncrypt, triple_key, iv,
+  if (!CipherOperation(ctx->cipher, &result, operation == kEncrypt, key, iv,
                        in)) {
     return false;
   }
-  const std::string result_label =
-      operation == kEncrypt ? "CIPHERTEXT" : "PLAINTEXT";
 
-  // TDES fax files output format differs from its input format, so we
-  // construct it manually rather than printing CurrentTestToString().
-  if (t->IsAtNewInstructionBlock()) {
+  // TDES fax files output format differs from file to file, and the input
+  // format is inconsistent with the output, so we construct the output manually
+  // rather than printing CurrentTestToString().
+  if (t->IsAtNewInstructionBlock() && num_keys == kNotPresent) {
+    // If NumKeys is present, header is printed when parsing NumKeys.
     std::string header = operation == kEncrypt ? "[ENCRYPT]" : "[DECRYPT]";
     printf("%s\r\n", header.c_str());
   }
-  printf("COUNT = %s\r\nKEYs = %s\r\n", count.c_str(),
-         EncodeHex(key.data(), key.size()).c_str());
+  const std::string result_label =
+      operation == kEncrypt ? "CIPHERTEXT" : "PLAINTEXT";
+  printf("COUNT = %s\r\n", count.c_str());
+  if (num_keys == kNotPresent) {
+    printf("KEYs = %s\r\n", EncodeHex(keys.data(), keys.size()).c_str());
+  } else {
+    printf("KEY1 = %s\r\nKEY2 = %s\r\nKEY3 = %s\r\n",
+           EncodeHex(key1.data(), key1.size()).c_str(),
+           EncodeHex(key2.data(), key2.size()).c_str(),
+           EncodeHex(key3.data(), key3.size()).c_str());
+  }
   if (ctx->has_iv) {
     printf("IV = %s\r\n", EncodeHex(iv.data(), iv.size()).c_str());
   }
-  printf("%s = %s\r\n%s = %s\r\n\r\n", op_label.c_str(),
-         EncodeHex(in.data(), in.size()).c_str(), result_label.c_str(),
+  printf("%s = %s\r\n", in_label.c_str(),
+         EncodeHex(in.data(), in.size()).c_str());
+  printf("%s = %s\r\n\r\n", result_label.c_str(),
          EncodeHex(result.data(), result.size()).c_str());
 
   // Check if sample response file matches.
@@ -108,11 +165,163 @@
   return true;
 }
 
+// XORKeyWithOddParityLSB sets |*key| to |key| XOR |value| and then writes
+// the LSB of each byte to establish odd parity for that byte. This parity-based
+// embedded of a DES key into 64 bits is an old tradition and something that
+// NIST's tests require.
+static void XORKeyWithOddParityLSB(std::vector<uint8_t> *key,
+                                        const std::vector<uint8_t> &value) {
+  for (size_t i = 0; i < key->size(); i++) {
+    uint8_t v = (*key)[i] ^ value[i];
+
+    // Use LSB to establish odd parity.
+    v |= 0x01;
+    for (uint8_t j = 1; j < 8; j++) {
+      v ^= ((v >> j) & 0x01);
+    }
+    (*key)[i] = v;
+  }
+}
+
+static bool TestMCT(FileTest *t, void *arg) {
+  TestCtx *ctx = reinterpret_cast<TestCtx *>(arg);
+
+  if (t->HasInstruction("ENCRYPT") == t->HasInstruction("DECRYPT")) {
+    t->PrintLine("Want either ENCRYPT or DECRYPT");
+    return false;
+  }
+  enum {
+    kEncrypt,
+    kDecrypt,
+  } operation = t->HasInstruction("ENCRYPT") ? kEncrypt : kDecrypt;
+
+  if (t->HasAttribute("NumKeys")) {
+    // Another file format quirk: NumKeys is a single attribute line immediately
+    // following an instruction and should probably have been an instruction
+    // instead.
+    std::string num_keys;
+    t->GetAttribute(&num_keys, "NumKeys");
+    t->InjectInstruction("NumKeys", num_keys);
+    return true;
+  }
+
+  enum {
+    kTwo,
+    kThree,
+  } num_keys;
+  std::string num_keys_str;
+  if (!t->GetInstruction(&num_keys_str, "NumKeys")) {
+    return false;
+  } else {
+    const int n = strtoul(num_keys_str.c_str(), nullptr, 0);
+    if (n == 2) {
+      num_keys = kTwo;
+    } else if (n == 3) {
+      num_keys = kThree;
+    } else {
+      t->PrintLine("invalid NumKeys value");
+      return false;
+    }
+  }
+
+  std::string count;
+  std::vector<uint8_t> key1, key2, key3, iv, in, result;
+  const std::string in_label =
+      operation == kEncrypt ? "PLAINTEXT" : "CIPHERTEXT";
+  // clang-format off
+  if (!t->GetBytes(&key1, "KEY1") ||
+      !t->GetBytes(&key2, "KEY2") ||
+      !t->GetBytes(&key3, "KEY3") ||
+      (ctx->has_iv && !t->GetBytes(&iv, "IV")) ||
+      !t->GetBytes(&in, in_label)) {
+    return false;
+  }
+  // clang-format on
+
+  for (int i = 0; i < 400; i++) {
+    std::vector<uint8_t> current_iv = iv, current_in = in, prev_result,
+                         prev_prev_result;
+
+    std::vector<uint8_t> key(key1);
+    key.insert(key.end(), key2.begin(), key2.end());
+    key.insert(key.end(), key3.begin(), key3.end());
+
+    for (int j = 0; j < 10000; j++) {
+      prev_prev_result = prev_result;
+      prev_result = result;
+      const EVP_CIPHER *cipher = ctx->cipher;
+      if (!CipherOperation(cipher, &result, operation == kEncrypt, key,
+                           current_iv, current_in)) {
+        t->PrintLine("CipherOperation failed");
+        return false;
+      }
+      if (ctx->has_iv) {
+        if (operation == kEncrypt) {
+          if (j == 0) {
+            current_in = current_iv;
+          } else {
+            current_in = prev_result;
+          }
+          current_iv = result;
+        } else {  // operation == kDecrypt
+          current_iv = current_in;
+          current_in = result;
+        }
+      } else {
+        current_in = result;
+      }
+    }
+
+    // Output result for COUNT = i.
+    const std::string result_label =
+        operation == kEncrypt ? "CIPHERTEXT" : "PLAINTEXT";
+    if (i == 0) {
+      const std::string op_label =
+          operation == kEncrypt ? "ENCRYPT" : "DECRYPT";
+      printf("[%s]\n\n", op_label.c_str());
+    }
+    printf("COUNT = %d\r\nKEY1 = %s\r\nKEY2 = %s\r\nKEY3 = %s\r\n", i,
+           EncodeHex(key1.data(), key1.size()).c_str(),
+           EncodeHex(key2.data(), key2.size()).c_str(),
+           EncodeHex(key3.data(), key3.size()).c_str());
+    if (ctx->has_iv) {
+      printf("IV = %s\r\n", EncodeHex(iv.data(), iv.size()).c_str());
+    }
+    printf("%s = %s\r\n", in_label.c_str(),
+           EncodeHex(in.data(), in.size()).c_str());
+    printf("%s = %s\r\n\r\n", result_label.c_str(),
+           EncodeHex(result.data(), result.size()).c_str());
+
+
+    XORKeyWithOddParityLSB(&key1, result);
+    XORKeyWithOddParityLSB(&key2, prev_result);
+    if (num_keys == kThree) {
+      XORKeyWithOddParityLSB(&key3, prev_prev_result);
+    } else {
+      XORKeyWithOddParityLSB(&key3, result);
+    }
+
+    if (ctx->has_iv) {
+      if (operation == kEncrypt) {
+        in = prev_result;
+        iv = result;
+      } else {
+        iv = current_iv;
+        in = current_in;
+      }
+    } else {
+      in = result;
+    }
+  }
+
+  return true;
+}
+
 static int usage(char *arg) {
-  fprintf(
-      stderr,
-      "usage: %s (kat|mct|mmt) <cipher> <test file> [<sample response file>]\n",
-      arg);
+  fprintf(stderr,
+          "usage: %s (kat|mct) <cipher> <test file> [<sample response "
+          "file>]\n",
+          arg);
   return 1;
 }
 
@@ -127,8 +336,6 @@
   enum TestCtx::Mode test_mode;
   if (tm == "kat") {
     test_mode = TestCtx::kKAT;
-  } else if (tm == "mmt") {
-    test_mode = TestCtx::kMMT;
   } else if (tm == "mct") {
     test_mode = TestCtx::kMCT;
   } else {
@@ -142,7 +349,7 @@
     fprintf(stderr, "invalid cipher: %s\n", argv[2]);
     return 1;
   }
-  bool has_iv = cipher_name != "des-ede3";
+  bool has_iv = cipher_name != "des-ede" && cipher_name != "des-ede3";
   TestCtx ctx = {cipher, nullptr, has_iv, test_mode};
 
   if (argc == 5) {
@@ -159,6 +366,6 @@
   }
   printf("\r\n\r\n");
 
-  // TODO(martinkr): Add MMT, MCT.
-  return FileTestMainSilent(TestKAT, &ctx, argv[3]);
+  FileTestFunc test_fn = test_mode == TestCtx::kKAT ? &TestKAT : &TestMCT;
+  return FileTestMainSilent(test_fn, &ctx, argv[3]);
 }
diff --git a/fipsoracle/run_cavp.go b/fipsoracle/run_cavp.go
index df48b56..051bfcf 100644
--- a/fipsoracle/run_cavp.go
+++ b/fipsoracle/run_cavp.go
@@ -227,19 +227,19 @@
 	"cavp_tdes_test",
 	nil,
 	[]test{
-		// {"TCBCMMT2", []string{"mmt"}, false},
-		// {"TCBCMMT3", []string{"mmt"}, false},
-		// {"TCBCMonte2", []string{"mct"}, false},
-		// {"TCBCMonte3", []string{"mct"}, false},
+		{"TCBCMMT2", []string{"kat", "des-ede-cbc"}, false},
+		{"TCBCMMT3", []string{"kat", "des-ede3-cbc"}, false},
+		{"TCBCMonte2", []string{"mct", "des-ede3-cbc"}, false},
+		{"TCBCMonte3", []string{"mct", "des-ede3-cbc"}, false},
 		{"TCBCinvperm", []string{"kat", "des-ede3-cbc"}, false},
 		{"TCBCpermop", []string{"kat", "des-ede3-cbc"}, false},
 		{"TCBCsubtab", []string{"kat", "des-ede3-cbc"}, false},
 		{"TCBCvarkey", []string{"kat", "des-ede3-cbc"}, false},
 		{"TCBCvartext", []string{"kat", "des-ede3-cbc"}, false},
-		// {"TECBMMT2", []string{"mmt"}, false},
-		// {"TECBMMT3", []string{"mmt"}, false},
-		// {"TECBMonte2", []string{"mct"}, false},
-		// {"TECBMonte3", []string{"mct"}, false},
+		{"TECBMMT2", []string{"kat", "des-ede"}, false},
+		{"TECBMMT3", []string{"kat", "des-ede3"}, false},
+		{"TECBMonte2", []string{"mct", "des-ede3"}, false},
+		{"TECBMonte3", []string{"mct", "des-ede3"}, false},
 		{"TECBinvperm", []string{"kat", "des-ede3"}, false},
 		{"TECBpermop", []string{"kat", "des-ede3"}, false},
 		{"TECBsubtab", []string{"kat", "des-ede3"}, false},