acvp: add TLS KDF support

Change-Id: I4f4a89f97e2513d8b5b740620989b187a7b44a58
Reviewed-on: https://boringssl-review.googlesource.com/c/boringssl/+/44386
Commit-Queue: Adam Langley <agl@google.com>
Reviewed-by: David Benjamin <davidben@google.com>
diff --git a/util/fipstools/acvp/acvptool/subprocess/subprocess.go b/util/fipstools/acvp/acvptool/subprocess/subprocess.go
index c297c8e..e5c1d1a 100644
--- a/util/fipstools/acvp/acvptool/subprocess/subprocess.go
+++ b/util/fipstools/acvp/acvptool/subprocess/subprocess.go
@@ -71,31 +71,32 @@
 	}
 
 	m.primitives = map[string]primitive{
-		"SHA-1":         &hashPrimitive{"SHA-1", 20},
-		"SHA2-224":      &hashPrimitive{"SHA2-224", 28},
-		"SHA2-256":      &hashPrimitive{"SHA2-256", 32},
-		"SHA2-384":      &hashPrimitive{"SHA2-384", 48},
-		"SHA2-512":      &hashPrimitive{"SHA2-512", 64},
-		"SHA2-512/256":  &hashPrimitive{"SHA2-512/256", 32},
-		"ACVP-AES-ECB":  &blockCipher{"AES", 16, 2, true, false, iterateAES},
-		"ACVP-AES-CBC":  &blockCipher{"AES-CBC", 16, 2, true, true, iterateAESCBC},
-		"ACVP-AES-CTR":  &blockCipher{"AES-CTR", 16, 1, false, true, nil},
-		"ACVP-TDES-ECB": &blockCipher{"3DES-ECB", 8, 3, true, false, iterate3DES},
-		"ACVP-TDES-CBC": &blockCipher{"3DES-CBC", 8, 3, true, true, iterate3DESCBC},
-		"ACVP-AES-GCM":  &aead{"AES-GCM", false},
-		"ACVP-AES-CCM":  &aead{"AES-CCM", true},
-		"ACVP-AES-KW":   &aead{"AES-KW", false},
-		"ACVP-AES-KWP":  &aead{"AES-KWP", false},
-		"HMAC-SHA-1":    &hmacPrimitive{"HMAC-SHA-1", 20},
-		"HMAC-SHA2-224": &hmacPrimitive{"HMAC-SHA2-224", 28},
-		"HMAC-SHA2-256": &hmacPrimitive{"HMAC-SHA2-256", 32},
-		"HMAC-SHA2-384": &hmacPrimitive{"HMAC-SHA2-384", 48},
-		"HMAC-SHA2-512": &hmacPrimitive{"HMAC-SHA2-512", 64},
-		"ctrDRBG":       &drbg{"ctrDRBG", map[string]bool{"AES-128": true, "AES-192": true, "AES-256": true}},
-		"hmacDRBG":      &drbg{"hmacDRBG", map[string]bool{"SHA-1": true, "SHA2-224": true, "SHA2-256": true, "SHA2-384": true, "SHA2-512": true}},
-		"KDF":           &kdfPrimitive{},
-		"CMAC-AES":      &keyedMACPrimitive{"CMAC-AES"},
-		"RSA":           &rsa{},
+		"SHA-1":          &hashPrimitive{"SHA-1", 20},
+		"SHA2-224":       &hashPrimitive{"SHA2-224", 28},
+		"SHA2-256":       &hashPrimitive{"SHA2-256", 32},
+		"SHA2-384":       &hashPrimitive{"SHA2-384", 48},
+		"SHA2-512":       &hashPrimitive{"SHA2-512", 64},
+		"SHA2-512/256":   &hashPrimitive{"SHA2-512/256", 32},
+		"ACVP-AES-ECB":   &blockCipher{"AES", 16, 2, true, false, iterateAES},
+		"ACVP-AES-CBC":   &blockCipher{"AES-CBC", 16, 2, true, true, iterateAESCBC},
+		"ACVP-AES-CTR":   &blockCipher{"AES-CTR", 16, 1, false, true, nil},
+		"ACVP-TDES-ECB":  &blockCipher{"3DES-ECB", 8, 3, true, false, iterate3DES},
+		"ACVP-TDES-CBC":  &blockCipher{"3DES-CBC", 8, 3, true, true, iterate3DESCBC},
+		"ACVP-AES-GCM":   &aead{"AES-GCM", false},
+		"ACVP-AES-CCM":   &aead{"AES-CCM", true},
+		"ACVP-AES-KW":    &aead{"AES-KW", false},
+		"ACVP-AES-KWP":   &aead{"AES-KWP", false},
+		"HMAC-SHA-1":     &hmacPrimitive{"HMAC-SHA-1", 20},
+		"HMAC-SHA2-224":  &hmacPrimitive{"HMAC-SHA2-224", 28},
+		"HMAC-SHA2-256":  &hmacPrimitive{"HMAC-SHA2-256", 32},
+		"HMAC-SHA2-384":  &hmacPrimitive{"HMAC-SHA2-384", 48},
+		"HMAC-SHA2-512":  &hmacPrimitive{"HMAC-SHA2-512", 64},
+		"ctrDRBG":        &drbg{"ctrDRBG", map[string]bool{"AES-128": true, "AES-192": true, "AES-256": true}},
+		"hmacDRBG":       &drbg{"hmacDRBG", map[string]bool{"SHA-1": true, "SHA2-224": true, "SHA2-256": true, "SHA2-384": true, "SHA2-512": true}},
+		"KDF":            &kdfPrimitive{},
+		"CMAC-AES":       &keyedMACPrimitive{"CMAC-AES"},
+		"RSA":            &rsa{},
+		"kdf-components": &tlsKDF{},
 	}
 	m.primitives["ECDSA"] = &ecdsa{"ECDSA", map[string]bool{"P-224": true, "P-256": true, "P-384": true, "P-521": true}, m.primitives}
 
diff --git a/util/fipstools/acvp/acvptool/subprocess/tlskdf.go b/util/fipstools/acvp/acvptool/subprocess/tlskdf.go
new file mode 100644
index 0000000..96a0a5c
--- /dev/null
+++ b/util/fipstools/acvp/acvptool/subprocess/tlskdf.go
@@ -0,0 +1,165 @@
+// Copyright (c) 2020, 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.
+
+package subprocess
+
+import (
+	"encoding/binary"
+	"encoding/hex"
+	"encoding/json"
+	"fmt"
+)
+
+type tlsKDFVectorSet struct {
+	Groups []tlsKDFTestGroup `json:"testGroups"`
+}
+
+type tlsKDFTestGroup struct {
+	ID           uint64       `json:"tgId"`
+	Hash         string       `json:"hashAlg"`
+	TLSVersion   string       `json:"tlsVersion"`
+	KeyBlockBits uint64       `json:"keyBlockLength"`
+	PMSLength    uint64       `json:"preMasterSecretLength"`
+	Tests        []tlsKDFTest `json:"tests"`
+}
+
+type tlsKDFTest struct {
+	ID                   uint64 `json:"tcId"`
+	PMSHex               string `json:"preMasterSecret"`
+	// ClientHelloRandomHex and ServerHelloRandomHex are used for deriving the
+	// master secret. ClientRandomHex and ServerRandomHex are used for deriving the
+	// key block. Having different values for these is not possible in a TLS
+	// handshake unless you squint at a resumption handshake and somehow rederive
+	// the master secret from the session information during resumption.
+	ClientHelloRandomHex string `json:"clientHelloRandom"`
+	ServerHelloRandomHex string `json:"serverHelloRandom"`
+	ClientRandomHex      string `json:"clientRandom"`
+	ServerRandomHex      string `json:"serverRandom"`
+}
+
+type tlsKDFTestGroupResponse struct {
+	ID    uint64               `json:"tgId"`
+	Tests []tlsKDFTestResponse `json:"tests"`
+}
+
+type tlsKDFTestResponse struct {
+	ID              uint64 `json:"tcId"`
+	MasterSecretHex string `json:"masterSecret"`
+	KeyBlockHex     string `json:"keyBlock"`
+}
+
+type tlsKDF struct{}
+
+func (k *tlsKDF) Process(vectorSet []byte, m Transactable) (interface{}, error) {
+	var parsed tlsKDFVectorSet
+	if err := json.Unmarshal(vectorSet, &parsed); err != nil {
+		return nil, err
+	}
+
+	// See https://usnistgov.github.io/ACVP/draft-celi-acvp-kdf-tls.html
+	var ret []tlsKDFTestGroupResponse
+	for _, group := range parsed.Groups {
+		response := tlsKDFTestGroupResponse{
+			ID: group.ID,
+		}
+
+		var tlsVer string
+		switch group.TLSVersion {
+		case "v1.0/1.1":
+			tlsVer = "1.0"
+		case "v1.2":
+			tlsVer = "1.2"
+		default:
+			return nil, fmt.Errorf("unknown TLS version %q", group.TLSVersion)
+		}
+
+		hashIsTLS10 := false
+		switch group.Hash {
+		case "SHA-1":
+			hashIsTLS10 = true
+		case "SHA2-256", "SHA2-384", "SHA2-512":
+			break
+		default:
+			return nil, fmt.Errorf("unknown hash %q", group.Hash)
+		}
+
+		if (tlsVer == "1.0") != hashIsTLS10 {
+			return nil, fmt.Errorf("hash %q not permitted with TLS version %q", group.Hash, group.TLSVersion)
+		}
+
+		if group.KeyBlockBits%8 != 0 {
+			return nil, fmt.Errorf("requested key-block length (%d bits) is not a whole number of bytes", group.KeyBlockBits)
+		}
+
+		method := "TLSKDF/" + tlsVer + "/" + group.Hash
+
+		for _, test := range group.Tests {
+			pms, err := hex.DecodeString(test.PMSHex)
+			if err != nil {
+				return nil, err
+			}
+
+			clientHelloRandom, err := hex.DecodeString(test.ClientHelloRandomHex)
+			if err != nil {
+				return nil, err
+			}
+
+			serverHelloRandom, err := hex.DecodeString(test.ServerHelloRandomHex)
+			if err != nil {
+				return nil, err
+			}
+
+			clientRandom, err := hex.DecodeString(test.ClientRandomHex)
+			if err != nil {
+				return nil, err
+			}
+
+			serverRandom, err := hex.DecodeString(test.ServerRandomHex)
+			if err != nil {
+				return nil, err
+			}
+
+			const (
+				masterSecretLength = 48
+				masterSecretLabel  = "master secret"
+				keyBlockLabel      = "key expansion"
+			)
+
+			var outLenBytes [4]byte
+			binary.LittleEndian.PutUint32(outLenBytes[:], uint32(masterSecretLength))
+			result, err := m.Transact(method, 1, outLenBytes[:], pms, []byte(masterSecretLabel), clientHelloRandom, serverHelloRandom)
+			if err != nil {
+				return nil, err
+			}
+
+			binary.LittleEndian.PutUint32(outLenBytes[:], uint32(group.KeyBlockBits/8))
+			// TLS 1.0, 1.1, and 1.2 use a different order for the client and server
+			// randoms when computing the key block.
+			result2, err := m.Transact(method, 1, outLenBytes[:], result[0], []byte(keyBlockLabel), serverRandom, clientRandom)
+			if err != nil {
+				return nil, err
+			}
+
+			response.Tests = append(response.Tests, tlsKDFTestResponse{
+				ID:              test.ID,
+				MasterSecretHex: hex.EncodeToString(result[0]),
+				KeyBlockHex:     hex.EncodeToString(result2[0]),
+			})
+		}
+
+		ret = append(ret, response)
+	}
+
+	return ret, nil
+}
diff --git a/util/fipstools/acvp/modulewrapper/modulewrapper.cc b/util/fipstools/acvp/modulewrapper/modulewrapper.cc
index 12aa2f8..9d915ab 100644
--- a/util/fipstools/acvp/modulewrapper/modulewrapper.cc
+++ b/util/fipstools/acvp/modulewrapper/modulewrapper.cc
@@ -41,6 +41,7 @@
 #include <openssl/span.h>
 
 #include "../../../../crypto/fipsmodule/rand/internal.h"
+#include "../../../../crypto/fipsmodule/tls/internal.h"
 
 static constexpr size_t kMaxArgs = 8;
 static constexpr size_t kMaxArgLength = (1 << 20);
@@ -702,6 +703,20 @@
             "increment": 8
           }]
         }]
+      },
+      {
+        "algorithm": "kdf-components",
+        "revision": "1.0",
+        "mode": "tls",
+        "tlsVersion": [
+          "v1.0/1.1",
+          "v1.2"
+        ],
+        "hashAlg": [
+          "SHA2-256",
+          "SHA2-384",
+          "SHA2-512"
+        ]
       }
     ])";
   return WriteReply(
@@ -1553,6 +1568,32 @@
   return WriteReply(STDOUT_FILENO, Span<const uint8_t>(&ok, 1));
 }
 
+template<const EVP_MD *(MDFunc)()>
+static bool TLSKDF(const Span<const uint8_t> args[]) {
+  const Span<const uint8_t> out_len_bytes = args[0];
+  const Span<const uint8_t> secret = args[1];
+  const Span<const uint8_t> label = args[2];
+  const Span<const uint8_t> seed1 = args[3];
+  const Span<const uint8_t> seed2 = args[4];
+  const EVP_MD *md = MDFunc();
+
+  uint32_t out_len;
+  if (out_len_bytes.size() != sizeof(out_len)) {
+    return 0;
+  }
+  memcpy(&out_len, out_len_bytes.data(), sizeof(out_len));
+
+  std::vector<uint8_t> out(static_cast<size_t>(out_len));
+  if (!CRYPTO_tls1_prf(md, out.data(), out.size(), secret.data(), secret.size(),
+                       reinterpret_cast<const char *>(label.data()),
+                       label.size(), seed1.data(), seed1.size(), seed2.data(),
+                       seed2.size())) {
+    return 0;
+  }
+
+  return WriteReply(STDOUT_FILENO, out);
+}
+
 static constexpr struct {
   const char name[kMaxNameLength + 1];
   uint8_t expected_args;
@@ -1615,6 +1656,10 @@
     {"RSA/sigVer/SHA2-384/pss", 4, RSASigVer<EVP_sha384, true>},
     {"RSA/sigVer/SHA2-512/pss", 4, RSASigVer<EVP_sha512, true>},
     {"RSA/sigVer/SHA-1/pss", 4, RSASigVer<EVP_sha1, true>},
+    {"TLSKDF/1.0/SHA-1", 5, TLSKDF<EVP_md5_sha1>},
+    {"TLSKDF/1.2/SHA2-256", 5, TLSKDF<EVP_sha256>},
+    {"TLSKDF/1.2/SHA2-384", 5, TLSKDF<EVP_sha384>},
+    {"TLSKDF/1.2/SHA2-512", 5, TLSKDF<EVP_sha512>},
 };
 
 int main() {