Source file src/crypto/internal/fips140/tls12/tls12.go

     1  // Copyright 2024 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package tls12
     6  
     7  import (
     8  	"crypto/internal/fips140"
     9  	"crypto/internal/fips140/hmac"
    10  	"crypto/internal/fips140/sha256"
    11  	"crypto/internal/fips140/sha512"
    12  )
    13  
    14  // PRF implements the TLS 1.2 pseudo-random function, as defined in RFC 5246,
    15  // Section 5 and allowed by SP 800-135, Revision 1, Section 4.2.2.
    16  func PRF[H fips140.Hash](hash func() H, secret []byte, label string, seed []byte, keyLen int) []byte {
    17  	labelAndSeed := make([]byte, len(label)+len(seed))
    18  	copy(labelAndSeed, label)
    19  	copy(labelAndSeed[len(label):], seed)
    20  
    21  	result := make([]byte, keyLen)
    22  	pHash(hash, result, secret, labelAndSeed)
    23  	return result
    24  }
    25  
    26  // pHash implements the P_hash function, as defined in RFC 5246, Section 5.
    27  func pHash[H fips140.Hash](hash func() H, result, secret, seed []byte) {
    28  	h := hmac.New(hash, secret)
    29  	h.Write(seed)
    30  	a := h.Sum(nil)
    31  
    32  	for len(result) > 0 {
    33  		h.Reset()
    34  		h.Write(a)
    35  		h.Write(seed)
    36  		b := h.Sum(nil)
    37  		n := copy(result, b)
    38  		result = result[n:]
    39  
    40  		h.Reset()
    41  		h.Write(a)
    42  		a = h.Sum(nil)
    43  	}
    44  }
    45  
    46  const masterSecretLength = 48
    47  const extendedMasterSecretLabel = "extended master secret"
    48  
    49  // MasterSecret implements the TLS 1.2 extended master secret derivation, as
    50  // defined in RFC 7627 and allowed by SP 800-135, Revision 1, Section 4.2.2.
    51  func MasterSecret[H fips140.Hash](hash func() H, preMasterSecret, transcript []byte) []byte {
    52  	// "The TLS 1.2 KDF is an approved KDF when the following conditions are
    53  	// satisfied: [...] (3) P_HASH uses either SHA-256, SHA-384 or SHA-512."
    54  	h := hash()
    55  	switch any(h).(type) {
    56  	case *sha256.Digest:
    57  		if h.Size() != 32 {
    58  			fips140.RecordNonApproved()
    59  		}
    60  	case *sha512.Digest:
    61  		if h.Size() != 46 && h.Size() != 64 {
    62  			fips140.RecordNonApproved()
    63  		}
    64  	default:
    65  		fips140.RecordNonApproved()
    66  	}
    67  
    68  	return PRF(hash, preMasterSecret, extendedMasterSecretLabel, transcript, masterSecretLength)
    69  }
    70  

View as plain text