github.com/Psiphon-Labs/tls-tris@v0.0.0-20230824155421-58bf6d336a9a/prf.go (about)

     1  // Copyright 2009 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 tls
     6  
     7  import (
     8  	"crypto"
     9  	"crypto/hmac"
    10  	"crypto/md5"
    11  	"crypto/sha1"
    12  	"crypto/sha256"
    13  	"crypto/sha512"
    14  	"errors"
    15  	"fmt"
    16  	"hash"
    17  )
    18  
    19  // Split a premaster secret in two as specified in RFC 4346, section 5.
    20  func splitPreMasterSecret(secret []byte) (s1, s2 []byte) {
    21  	s1 = secret[0 : (len(secret)+1)/2]
    22  	s2 = secret[len(secret)/2:]
    23  	return
    24  }
    25  
    26  // pHash implements the P_hash function, as defined in RFC 4346, section 5.
    27  func pHash(result, secret, seed []byte, hash func() hash.Hash) {
    28  	h := hmac.New(hash, secret)
    29  	h.Write(seed)
    30  	a := h.Sum(nil)
    31  
    32  	j := 0
    33  	for j < len(result) {
    34  		h.Reset()
    35  		h.Write(a)
    36  		h.Write(seed)
    37  		b := h.Sum(nil)
    38  		copy(result[j:], b)
    39  		j += len(b)
    40  
    41  		h.Reset()
    42  		h.Write(a)
    43  		a = h.Sum(nil)
    44  	}
    45  }
    46  
    47  // prf10 implements the TLS 1.0 pseudo-random function, as defined in RFC 2246, section 5.
    48  func prf10(result, secret, label, seed []byte) {
    49  	hashSHA1 := sha1.New
    50  	hashMD5 := md5.New
    51  
    52  	labelAndSeed := make([]byte, len(label)+len(seed))
    53  	copy(labelAndSeed, label)
    54  	copy(labelAndSeed[len(label):], seed)
    55  
    56  	s1, s2 := splitPreMasterSecret(secret)
    57  	pHash(result, s1, labelAndSeed, hashMD5)
    58  	result2 := make([]byte, len(result))
    59  	pHash(result2, s2, labelAndSeed, hashSHA1)
    60  
    61  	for i, b := range result2 {
    62  		result[i] ^= b
    63  	}
    64  }
    65  
    66  // prf12 implements the TLS 1.2 pseudo-random function, as defined in RFC 5246, section 5.
    67  func prf12(hashFunc func() hash.Hash) func(result, secret, label, seed []byte) {
    68  	return func(result, secret, label, seed []byte) {
    69  		labelAndSeed := make([]byte, len(label)+len(seed))
    70  		copy(labelAndSeed, label)
    71  		copy(labelAndSeed[len(label):], seed)
    72  
    73  		pHash(result, secret, labelAndSeed, hashFunc)
    74  	}
    75  }
    76  
    77  // prf30 implements the SSL 3.0 pseudo-random function, as defined in
    78  // www.mozilla.org/projects/security/pki/nss/ssl/draft302.txt section 6.
    79  func prf30(result, secret, label, seed []byte) {
    80  	hashSHA1 := sha1.New()
    81  	hashMD5 := md5.New()
    82  
    83  	done := 0
    84  	i := 0
    85  	// RFC 5246 section 6.3 says that the largest PRF output needed is 128
    86  	// bytes. Since no more ciphersuites will be added to SSLv3, this will
    87  	// remain true. Each iteration gives us 16 bytes so 10 iterations will
    88  	// be sufficient.
    89  	var b [11]byte
    90  	for done < len(result) {
    91  		for j := 0; j <= i; j++ {
    92  			b[j] = 'A' + byte(i)
    93  		}
    94  
    95  		hashSHA1.Reset()
    96  		hashSHA1.Write(b[:i+1])
    97  		hashSHA1.Write(secret)
    98  		hashSHA1.Write(seed)
    99  		digest := hashSHA1.Sum(nil)
   100  
   101  		hashMD5.Reset()
   102  		hashMD5.Write(secret)
   103  		hashMD5.Write(digest)
   104  
   105  		done += copy(result[done:], hashMD5.Sum(nil))
   106  		i++
   107  	}
   108  }
   109  
   110  const (
   111  	tlsRandomLength      = 32 // Length of a random nonce in TLS 1.1.
   112  	masterSecretLength   = 48 // Length of a master secret in TLS 1.1.
   113  	finishedVerifyLength = 12 // Length of verify_data in a Finished message.
   114  )
   115  
   116  var masterSecretLabel = []byte("master secret")
   117  var keyExpansionLabel = []byte("key expansion")
   118  var clientFinishedLabel = []byte("client finished")
   119  var serverFinishedLabel = []byte("server finished")
   120  var extendedMasterSecretLabel = []byte("extended master secret")
   121  
   122  func prfAndHashForVersion(version uint16, suite *cipherSuite) (func(result, secret, label, seed []byte), crypto.Hash) {
   123  	switch version {
   124  	case VersionSSL30:
   125  		return prf30, crypto.Hash(0)
   126  	case VersionTLS10, VersionTLS11:
   127  		return prf10, crypto.Hash(0)
   128  	case VersionTLS12:
   129  		if suite.flags&suiteSHA384 != 0 {
   130  			return prf12(sha512.New384), crypto.SHA384
   131  		}
   132  		return prf12(sha256.New), crypto.SHA256
   133  	default:
   134  		panic("unknown version")
   135  	}
   136  }
   137  
   138  func prfForVersion(version uint16, suite *cipherSuite) func(result, secret, label, seed []byte) {
   139  	prf, _ := prfAndHashForVersion(version, suite)
   140  	return prf
   141  }
   142  
   143  // masterFromPreMasterSecret generates the master secret from the pre-master
   144  // secret. See http://tools.ietf.org/html/rfc5246#section-8.1
   145  func masterFromPreMasterSecret(version uint16, suite *cipherSuite, preMasterSecret, clientRandom, serverRandom []byte, fin finishedHash, ems bool) []byte {
   146  	if ems {
   147  		session_hash := fin.Sum()
   148  		masterSecret := make([]byte, masterSecretLength)
   149  		prfForVersion(version, suite)(masterSecret, preMasterSecret, extendedMasterSecretLabel, session_hash)
   150  		return masterSecret
   151  	} else {
   152  		seed := make([]byte, 0, len(clientRandom)+len(serverRandom))
   153  		seed = append(seed, clientRandom...)
   154  		seed = append(seed, serverRandom...)
   155  
   156  		masterSecret := make([]byte, masterSecretLength)
   157  		prfForVersion(version, suite)(masterSecret, preMasterSecret, masterSecretLabel, seed)
   158  		return masterSecret
   159  	}
   160  }
   161  
   162  // keysFromMasterSecret generates the connection keys from the master
   163  // secret, given the lengths of the MAC key, cipher key and IV, as defined in
   164  // RFC 2246, section 6.3.
   165  func keysFromMasterSecret(version uint16, suite *cipherSuite, masterSecret, clientRandom, serverRandom []byte, macLen, keyLen, ivLen int) (clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV []byte) {
   166  	seed := make([]byte, 0, len(serverRandom)+len(clientRandom))
   167  	seed = append(seed, serverRandom...)
   168  	seed = append(seed, clientRandom...)
   169  
   170  	n := 2*macLen + 2*keyLen + 2*ivLen
   171  	keyMaterial := make([]byte, n)
   172  	prfForVersion(version, suite)(keyMaterial, masterSecret, keyExpansionLabel, seed)
   173  	clientMAC = keyMaterial[:macLen]
   174  	keyMaterial = keyMaterial[macLen:]
   175  	serverMAC = keyMaterial[:macLen]
   176  	keyMaterial = keyMaterial[macLen:]
   177  	clientKey = keyMaterial[:keyLen]
   178  	keyMaterial = keyMaterial[keyLen:]
   179  	serverKey = keyMaterial[:keyLen]
   180  	keyMaterial = keyMaterial[keyLen:]
   181  	clientIV = keyMaterial[:ivLen]
   182  	keyMaterial = keyMaterial[ivLen:]
   183  	serverIV = keyMaterial[:ivLen]
   184  	return
   185  }
   186  
   187  // lookupTLSHash looks up the corresponding crypto.Hash for a given
   188  // hash from a TLS SignatureScheme.
   189  func lookupTLSHash(signatureAlgorithm SignatureScheme) (crypto.Hash, error) {
   190  	switch signatureAlgorithm {
   191  	case PKCS1WithSHA1, ECDSAWithSHA1:
   192  		return crypto.SHA1, nil
   193  	case PKCS1WithSHA256, PSSWithSHA256, ECDSAWithP256AndSHA256:
   194  		return crypto.SHA256, nil
   195  	case PKCS1WithSHA384, PSSWithSHA384, ECDSAWithP384AndSHA384:
   196  		return crypto.SHA384, nil
   197  	case PKCS1WithSHA512, PSSWithSHA512, ECDSAWithP521AndSHA512:
   198  		return crypto.SHA512, nil
   199  	default:
   200  		return 0, fmt.Errorf("tls: unsupported signature algorithm: %#04x", signatureAlgorithm)
   201  	}
   202  }
   203  
   204  func newFinishedHash(version uint16, cipherSuite *cipherSuite) finishedHash {
   205  	var buffer []byte
   206  	if version == VersionSSL30 || version >= VersionTLS12 {
   207  		buffer = []byte{}
   208  	}
   209  
   210  	prf, hash := prfAndHashForVersion(version, cipherSuite)
   211  	if hash != 0 {
   212  		return finishedHash{hash.New(), hash.New(), nil, nil, buffer, version, prf}
   213  	}
   214  
   215  	return finishedHash{sha1.New(), sha1.New(), md5.New(), md5.New(), buffer, version, prf}
   216  }
   217  
   218  // A finishedHash calculates the hash of a set of handshake messages suitable
   219  // for including in a Finished message.
   220  type finishedHash struct {
   221  	client hash.Hash
   222  	server hash.Hash
   223  
   224  	// Prior to TLS 1.2, an additional MD5 hash is required.
   225  	clientMD5 hash.Hash
   226  	serverMD5 hash.Hash
   227  
   228  	// In TLS 1.2, a full buffer is sadly required.
   229  	buffer []byte
   230  
   231  	version uint16
   232  	prf     func(result, secret, label, seed []byte)
   233  }
   234  
   235  func (h *finishedHash) Write(msg []byte) (n int, err error) {
   236  	h.client.Write(msg)
   237  	h.server.Write(msg)
   238  
   239  	if h.version < VersionTLS12 {
   240  		h.clientMD5.Write(msg)
   241  		h.serverMD5.Write(msg)
   242  	}
   243  
   244  	if h.buffer != nil {
   245  		h.buffer = append(h.buffer, msg...)
   246  	}
   247  
   248  	return len(msg), nil
   249  }
   250  
   251  func (h finishedHash) Sum() []byte {
   252  	if h.version >= VersionTLS12 {
   253  		return h.client.Sum(nil)
   254  	}
   255  
   256  	out := make([]byte, 0, md5.Size+sha1.Size)
   257  	out = h.clientMD5.Sum(out)
   258  	return h.client.Sum(out)
   259  }
   260  
   261  // finishedSum30 calculates the contents of the verify_data member of a SSLv3
   262  // Finished message given the MD5 and SHA1 hashes of a set of handshake
   263  // messages.
   264  func finishedSum30(md5, sha1 hash.Hash, masterSecret []byte, magic []byte) []byte {
   265  	md5.Write(magic)
   266  	md5.Write(masterSecret)
   267  	md5.Write(ssl30Pad1[:])
   268  	md5Digest := md5.Sum(nil)
   269  
   270  	md5.Reset()
   271  	md5.Write(masterSecret)
   272  	md5.Write(ssl30Pad2[:])
   273  	md5.Write(md5Digest)
   274  	md5Digest = md5.Sum(nil)
   275  
   276  	sha1.Write(magic)
   277  	sha1.Write(masterSecret)
   278  	sha1.Write(ssl30Pad1[:40])
   279  	sha1Digest := sha1.Sum(nil)
   280  
   281  	sha1.Reset()
   282  	sha1.Write(masterSecret)
   283  	sha1.Write(ssl30Pad2[:40])
   284  	sha1.Write(sha1Digest)
   285  	sha1Digest = sha1.Sum(nil)
   286  
   287  	ret := make([]byte, len(md5Digest)+len(sha1Digest))
   288  	copy(ret, md5Digest)
   289  	copy(ret[len(md5Digest):], sha1Digest)
   290  	return ret
   291  }
   292  
   293  var ssl3ClientFinishedMagic = [4]byte{0x43, 0x4c, 0x4e, 0x54}
   294  var ssl3ServerFinishedMagic = [4]byte{0x53, 0x52, 0x56, 0x52}
   295  
   296  // clientSum returns the contents of the verify_data member of a client's
   297  // Finished message.
   298  func (h finishedHash) clientSum(masterSecret []byte) []byte {
   299  	if h.version == VersionSSL30 {
   300  		return finishedSum30(h.clientMD5, h.client, masterSecret, ssl3ClientFinishedMagic[:])
   301  	}
   302  
   303  	out := make([]byte, finishedVerifyLength)
   304  	h.prf(out, masterSecret, clientFinishedLabel, h.Sum())
   305  	return out
   306  }
   307  
   308  // serverSum returns the contents of the verify_data member of a server's
   309  // Finished message.
   310  func (h finishedHash) serverSum(masterSecret []byte) []byte {
   311  	if h.version == VersionSSL30 {
   312  		return finishedSum30(h.serverMD5, h.server, masterSecret, ssl3ServerFinishedMagic[:])
   313  	}
   314  
   315  	out := make([]byte, finishedVerifyLength)
   316  	h.prf(out, masterSecret, serverFinishedLabel, h.Sum())
   317  	return out
   318  }
   319  
   320  // hashForClientCertificate returns a digest over the handshake messages so far,
   321  // suitable for signing by a TLS client certificate.
   322  func (h finishedHash) hashForClientCertificate(sigType uint8, hashAlg crypto.Hash, masterSecret []byte) ([]byte, error) {
   323  	if (h.version == VersionSSL30 || h.version >= VersionTLS12) && h.buffer == nil {
   324  		panic("a handshake hash for a client-certificate was requested after discarding the handshake buffer")
   325  	}
   326  
   327  	if h.version == VersionSSL30 {
   328  		if sigType != signaturePKCS1v15 {
   329  			return nil, errors.New("tls: unsupported signature type for client certificate")
   330  		}
   331  
   332  		md5Hash := md5.New()
   333  		md5Hash.Write(h.buffer)
   334  		sha1Hash := sha1.New()
   335  		sha1Hash.Write(h.buffer)
   336  		return finishedSum30(md5Hash, sha1Hash, masterSecret, nil), nil
   337  	}
   338  	if h.version >= VersionTLS12 {
   339  		hash := hashAlg.New()
   340  		hash.Write(h.buffer)
   341  		return hash.Sum(nil), nil
   342  	}
   343  
   344  	if sigType == signatureECDSA {
   345  		return h.server.Sum(nil), nil
   346  	}
   347  
   348  	return h.Sum(), nil
   349  }
   350  
   351  // discardHandshakeBuffer is called when there is no more need to
   352  // buffer the entirety of the handshake messages.
   353  func (h *finishedHash) discardHandshakeBuffer() {
   354  	h.buffer = nil
   355  }