gitee.com/zhaochuninhefei/gmgo@v0.0.31-0.20240209061119-069254a02979/gmtls/prf.go (about)

     1  // Copyright (c) 2022 zhaochun
     2  // gmgo is licensed under Mulan PSL v2.
     3  // You can use this software according to the terms and conditions of the Mulan PSL v2.
     4  // You may obtain a copy of Mulan PSL v2 at:
     5  //          http://license.coscl.org.cn/MulanPSL2
     6  // THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
     7  // See the Mulan PSL v2 for more details.
     8  
     9  /*
    10  gmtls是基于`golang/go`的`tls`包实现的国密改造版本。
    11  对应版权声明: thrid_licenses/github.com/golang/go/LICENSE
    12  */
    13  
    14  package gmtls
    15  
    16  import (
    17  	"crypto"
    18  	"crypto/hmac"
    19  	"crypto/md5"
    20  	"crypto/sha1"
    21  	"crypto/sha256"
    22  	"crypto/sha512"
    23  	"errors"
    24  	"fmt"
    25  	"hash"
    26  
    27  	"gitee.com/zhaochuninhefei/gmgo/x509"
    28  )
    29  
    30  // Split a premaster secret in two as specified in RFC 4346, Section 5.
    31  func splitPreMasterSecret(secret []byte) (s1, s2 []byte) {
    32  	s1 = secret[0 : (len(secret)+1)/2]
    33  	s2 = secret[len(secret)/2:]
    34  	return
    35  }
    36  
    37  // pHash implements the P_hash function, as defined in RFC 4346, Section 5.
    38  func pHash(result, secret, seed []byte, hash func() hash.Hash) {
    39  	h := hmac.New(hash, secret)
    40  	h.Write(seed)
    41  	a := h.Sum(nil)
    42  
    43  	j := 0
    44  	for j < len(result) {
    45  		h.Reset()
    46  		h.Write(a)
    47  		h.Write(seed)
    48  		b := h.Sum(nil)
    49  		copy(result[j:], b)
    50  		j += len(b)
    51  
    52  		h.Reset()
    53  		h.Write(a)
    54  		a = h.Sum(nil)
    55  	}
    56  }
    57  
    58  // prf10 implements the TLS 1.0 pseudo-random function, as defined in RFC 2246, Section 5.
    59  func prf10(result, secret, label, seed []byte) {
    60  	hashSHA1 := sha1.New
    61  	hashMD5 := md5.New
    62  
    63  	labelAndSeed := make([]byte, len(label)+len(seed))
    64  	copy(labelAndSeed, label)
    65  	copy(labelAndSeed[len(label):], seed)
    66  
    67  	s1, s2 := splitPreMasterSecret(secret)
    68  	pHash(result, s1, labelAndSeed, hashMD5)
    69  	result2 := make([]byte, len(result))
    70  	pHash(result2, s2, labelAndSeed, hashSHA1)
    71  
    72  	for i, b := range result2 {
    73  		result[i] ^= b
    74  	}
    75  }
    76  
    77  // prf12 implements the TLS 1.2 pseudo-random function, as defined in RFC 5246, Section 5.
    78  func prf12(hashFunc func() hash.Hash) func(result, secret, label, seed []byte) {
    79  	return func(result, secret, label, seed []byte) {
    80  		labelAndSeed := make([]byte, len(label)+len(seed))
    81  		copy(labelAndSeed, label)
    82  		copy(labelAndSeed[len(label):], seed)
    83  
    84  		pHash(result, secret, labelAndSeed, hashFunc)
    85  	}
    86  }
    87  
    88  const (
    89  	masterSecretLength   = 48 // Length of a master secret in TLS 1.1.
    90  	finishedVerifyLength = 12 // Length of verify_data in a Finished message.
    91  )
    92  
    93  var masterSecretLabel = []byte("master secret")
    94  var keyExpansionLabel = []byte("key expansion")
    95  var clientFinishedLabel = []byte("client finished")
    96  var serverFinishedLabel = []byte("server finished")
    97  
    98  func prfAndHashForVersion(version uint16, suite *cipherSuite) (func(result, secret, label, seed []byte), crypto.Hash) {
    99  	switch version {
   100  	case VersionTLS10, VersionTLS11:
   101  		return prf10, crypto.Hash(0)
   102  	case VersionTLS12:
   103  		if suite.flags&suiteSHA384 != 0 {
   104  			return prf12(sha512.New384), crypto.SHA384
   105  		}
   106  		return prf12(sha256.New), crypto.SHA256
   107  	default:
   108  		panic("unknown version")
   109  	}
   110  }
   111  
   112  func prfForVersion(version uint16, suite *cipherSuite) func(result, secret, label, seed []byte) {
   113  	prf, _ := prfAndHashForVersion(version, suite)
   114  	return prf
   115  }
   116  
   117  // 根据预主密钥计算主密钥
   118  //  算法使用PRF函数;
   119  //  使用clientRandom与serverRandom拼接起来的随机数作为种子;
   120  //
   121  // masterFromPreMasterSecret generates the master secret from the pre-master
   122  // secret. See RFC 5246, Section 8.1.
   123  func masterFromPreMasterSecret(version uint16, suite *cipherSuite, preMasterSecret, clientRandom, serverRandom []byte) []byte {
   124  	seed := make([]byte, 0, len(clientRandom)+len(serverRandom))
   125  	seed = append(seed, clientRandom...)
   126  	seed = append(seed, serverRandom...)
   127  
   128  	masterSecret := make([]byte, masterSecretLength)
   129  	prfForVersion(version, suite)(masterSecret, preMasterSecret, masterSecretLabel, seed)
   130  	return masterSecret
   131  }
   132  
   133  // 根据主密钥派生出会话密钥
   134  //  算法使用PRF函数;
   135  //  使用clientRandom与serverRandom拼接起来的随机数作为种子;
   136  //  派生出六个会话密钥:clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV
   137  //
   138  // keysFromMasterSecret generates the connection keys from the master
   139  // secret, given the lengths of the MAC key, cipher key and IV, as defined in
   140  // RFC 2246, Section 6.3.
   141  func keysFromMasterSecret(version uint16, suite *cipherSuite, masterSecret, clientRandom, serverRandom []byte, macLen, keyLen, ivLen int) (clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV []byte) {
   142  	seed := make([]byte, 0, len(serverRandom)+len(clientRandom))
   143  	seed = append(seed, serverRandom...)
   144  	seed = append(seed, clientRandom...)
   145  
   146  	n := 2*macLen + 2*keyLen + 2*ivLen
   147  	keyMaterial := make([]byte, n)
   148  	prfForVersion(version, suite)(keyMaterial, masterSecret, keyExpansionLabel, seed)
   149  	clientMAC = keyMaterial[:macLen]
   150  	keyMaterial = keyMaterial[macLen:]
   151  	serverMAC = keyMaterial[:macLen]
   152  	keyMaterial = keyMaterial[macLen:]
   153  	clientKey = keyMaterial[:keyLen]
   154  	keyMaterial = keyMaterial[keyLen:]
   155  	serverKey = keyMaterial[:keyLen]
   156  	keyMaterial = keyMaterial[keyLen:]
   157  	clientIV = keyMaterial[:ivLen]
   158  	keyMaterial = keyMaterial[ivLen:]
   159  	serverIV = keyMaterial[:ivLen]
   160  	return
   161  }
   162  
   163  func newFinishedHash(version uint16, cipherSuite *cipherSuite) finishedHash {
   164  	var buffer []byte
   165  	if version >= VersionTLS12 {
   166  		buffer = []byte{}
   167  	}
   168  
   169  	prf, hashVal := prfAndHashForVersion(version, cipherSuite)
   170  	if hashVal != 0 {
   171  		return finishedHash{hashVal.New(), hashVal.New(), nil, nil, buffer, version, prf}
   172  	}
   173  
   174  	return finishedHash{sha1.New(), sha1.New(), md5.New(), md5.New(), buffer, version, prf}
   175  }
   176  
   177  // A finishedHash calculates the hash of a set of handshake messages suitable
   178  // for including in a Finished message.
   179  type finishedHash struct {
   180  	client hash.Hash
   181  	server hash.Hash
   182  
   183  	// Prior to TLS 1.2, an additional MD5 hash is required.
   184  	clientMD5 hash.Hash
   185  	serverMD5 hash.Hash
   186  
   187  	// In TLS 1.2, a full buffer is sadly required.
   188  	buffer []byte
   189  
   190  	version uint16
   191  	prf     func(result, secret, label, seed []byte)
   192  }
   193  
   194  //goland:noinspection GoMixedReceiverTypes
   195  func (h *finishedHash) Write(msg []byte) (n int, err error) {
   196  	h.client.Write(msg)
   197  	h.server.Write(msg)
   198  
   199  	if h.version < VersionTLS12 {
   200  		h.clientMD5.Write(msg)
   201  		h.serverMD5.Write(msg)
   202  	}
   203  
   204  	if h.buffer != nil {
   205  		h.buffer = append(h.buffer, msg...)
   206  	}
   207  
   208  	return len(msg), nil
   209  }
   210  
   211  //goland:noinspection GoMixedReceiverTypes
   212  func (h finishedHash) Sum() []byte {
   213  	if h.version >= VersionTLS12 {
   214  		return h.client.Sum(nil)
   215  	}
   216  
   217  	out := make([]byte, 0, md5.Size+sha1.Size)
   218  	out = h.clientMD5.Sum(out)
   219  	return h.client.Sum(out)
   220  }
   221  
   222  // clientSum returns the contents of the verify_data member of a client's
   223  // Finished message.
   224  //goland:noinspection GoMixedReceiverTypes
   225  func (h finishedHash) clientSum(masterSecret []byte) []byte {
   226  	out := make([]byte, finishedVerifyLength)
   227  	h.prf(out, masterSecret, clientFinishedLabel, h.Sum())
   228  	return out
   229  }
   230  
   231  // serverSum returns the contents of the verify_data member of a server's
   232  // Finished message.
   233  //goland:noinspection GoMixedReceiverTypes
   234  func (h finishedHash) serverSum(masterSecret []byte) []byte {
   235  	out := make([]byte, finishedVerifyLength)
   236  	h.prf(out, masterSecret, serverFinishedLabel, h.Sum())
   237  	return out
   238  }
   239  
   240  // hashForClientCertificate returns the handshake messages so far, pre-hashed if
   241  // necessary, suitable for signing by a TLS client certificate.
   242  //goland:noinspection GoMixedReceiverTypes,GoUnusedParameter
   243  func (h finishedHash) hashForClientCertificate(sigType uint8, hashAlg x509.Hash, masterSecret []byte) []byte {
   244  	if (h.version >= VersionTLS12 || sigType == signatureEd25519) && h.buffer == nil {
   245  		panic("gmtls: handshake hash for a client certificate requested after discarding the handshake buffer")
   246  	}
   247  
   248  	if sigType == signatureEd25519 {
   249  		return h.buffer
   250  	}
   251  
   252  	if h.version >= VersionTLS12 {
   253  		hashVal := hashAlg.New()
   254  		hashVal.Write(h.buffer)
   255  		return hashVal.Sum(nil)
   256  	}
   257  
   258  	if sigType == signatureECDSA || sigType == signatureECDSAEXT {
   259  		return h.server.Sum(nil)
   260  	}
   261  
   262  	return h.Sum()
   263  }
   264  
   265  // discardHandshakeBuffer is called when there is no more need to
   266  // buffer the entirety of the handshake messages.
   267  //goland:noinspection GoMixedReceiverTypes
   268  func (h *finishedHash) discardHandshakeBuffer() {
   269  	h.buffer = nil
   270  }
   271  
   272  // noExportedKeyingMaterial is used as a value of
   273  // ConnectionState.ekm when renegotiation is enabled and thus
   274  // we wish to fail all key-material export requests.
   275  //goland:noinspection GoUnusedParameter
   276  func noExportedKeyingMaterial(label string, context []byte, length int) ([]byte, error) {
   277  	return nil, errors.New("crypto/tls: ExportKeyingMaterial is unavailable when renegotiation is enabled")
   278  }
   279  
   280  // ekmFromMasterSecret generates exported keying material as defined in RFC 5705.
   281  func ekmFromMasterSecret(version uint16, suite *cipherSuite, masterSecret, clientRandom, serverRandom []byte) func(string, []byte, int) ([]byte, error) {
   282  	return func(label string, context []byte, length int) ([]byte, error) {
   283  		switch label {
   284  		case "client finished", "server finished", "master secret", "key expansion":
   285  			// These values are reserved and may not be used.
   286  			return nil, fmt.Errorf("crypto/tls: reserved ExportKeyingMaterial label: %s", label)
   287  		}
   288  
   289  		seedLen := len(serverRandom) + len(clientRandom)
   290  		if context != nil {
   291  			seedLen += 2 + len(context)
   292  		}
   293  		seed := make([]byte, 0, seedLen)
   294  
   295  		seed = append(seed, clientRandom...)
   296  		seed = append(seed, serverRandom...)
   297  
   298  		if context != nil {
   299  			if len(context) >= 1<<16 {
   300  				return nil, fmt.Errorf("crypto/tls: ExportKeyingMaterial context too long")
   301  			}
   302  			seed = append(seed, byte(len(context)>>8), byte(len(context)))
   303  			seed = append(seed, context...)
   304  		}
   305  
   306  		keyMaterial := make([]byte, length)
   307  		prfForVersion(version, suite)(keyMaterial, masterSecret, []byte(label), seed)
   308  		return keyMaterial, nil
   309  	}
   310  }