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

     1  // Copyright 2010 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/aes"
    10  	"crypto/cipher"
    11  	"crypto/des"
    12  	"crypto/hmac"
    13  	"crypto/rc4"
    14  	"crypto/sha1"
    15  	"crypto/sha256"
    16  	"hash"
    17  
    18  	"golang.org/x/crypto/chacha20poly1305"
    19  )
    20  
    21  // a keyAgreement implements the client and server side of a TLS key agreement
    22  // protocol by generating and processing key exchange messages.
    23  type keyAgreement interface {
    24  	// On the server side, the first two methods are called in order.
    25  
    26  	// In the case that the key agreement protocol doesn't use a
    27  	// ServerKeyExchange message, generateServerKeyExchange can return nil,
    28  	// nil.
    29  	generateServerKeyExchange(*Config, crypto.PrivateKey, *clientHelloMsg, *serverHelloMsg) (*serverKeyExchangeMsg, error)
    30  	processClientKeyExchange(*Config, crypto.PrivateKey, *clientKeyExchangeMsg, uint16) ([]byte, error)
    31  
    32  	// On the client side, the next two methods are called in order.
    33  
    34  	// This method may not be called if the server doesn't send a
    35  	// ServerKeyExchange message.
    36  	processServerKeyExchange(*Config, *clientHelloMsg, *serverHelloMsg, crypto.PublicKey, *serverKeyExchangeMsg) error
    37  	generateClientKeyExchange(*Config, *clientHelloMsg, crypto.PublicKey) ([]byte, *clientKeyExchangeMsg, error)
    38  }
    39  
    40  const (
    41  	// suiteECDH indicates that the cipher suite involves elliptic curve
    42  	// Diffie-Hellman. This means that it should only be selected when the
    43  	// client indicates that it supports ECC with a curve and point format
    44  	// that we're happy with.
    45  	suiteECDHE = 1 << iota
    46  	// suiteECDSA indicates that the cipher suite involves an ECDSA
    47  	// signature and therefore may only be selected when the server's
    48  	// certificate is ECDSA. If this is not set then the cipher suite is
    49  	// RSA based.
    50  	suiteECDSA
    51  	// suiteTLS12 indicates that the cipher suite should only be advertised
    52  	// and accepted when using TLS 1.2.
    53  	suiteTLS12
    54  	// suiteTLS13 indicates that the ones and only cipher suites to be
    55  	// advertised and accepted when using TLS 1.3.
    56  	suiteTLS13
    57  	// suiteSHA384 indicates that the cipher suite uses SHA384 as the
    58  	// handshake hash.
    59  	suiteSHA384
    60  	// suiteDefaultOff indicates that this cipher suite is not included by
    61  	// default.
    62  	suiteDefaultOff
    63  )
    64  
    65  // A cipherSuite is a specific combination of key agreement, cipher and MAC
    66  // function.
    67  type cipherSuite struct {
    68  	id uint16
    69  	// the lengths, in bytes, of the key material needed for each component.
    70  	keyLen int
    71  	macLen int
    72  	ivLen  int
    73  	ka     func(version uint16) keyAgreement
    74  	// flags is a bitmask of the suite* values, above.
    75  	flags  int
    76  	cipher func(key, iv []byte, isRead bool) interface{}
    77  	mac    func(version uint16, macKey []byte) macFunction
    78  	aead   func(key, fixedNonce []byte) cipher.AEAD
    79  }
    80  
    81  var cipherSuites = []*cipherSuite{
    82  	// TLS 1.3 ciphersuites specify only the AEAD and the HKDF hash.
    83  	{TLS_CHACHA20_POLY1305_SHA256, 32, 0, 12, nil, suiteTLS13, nil, nil, aeadChaCha20Poly1305},
    84  	{TLS_AES_128_GCM_SHA256, 16, 0, 12, nil, suiteTLS13, nil, nil, aeadAESGCM13},
    85  	{TLS_AES_256_GCM_SHA384, 32, 0, 12, nil, suiteTLS13 | suiteSHA384, nil, nil, aeadAESGCM13},
    86  
    87  	// Ciphersuite order is chosen so that ECDHE comes before plain RSA and
    88  	// AEADs are the top preference.
    89  	{TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 32, 0, 12, ecdheRSAKA, suiteECDHE | suiteTLS12, nil, nil, aeadChaCha20Poly1305},
    90  	{TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, 32, 0, 12, ecdheECDSAKA, suiteECDHE | suiteECDSA | suiteTLS12, nil, nil, aeadChaCha20Poly1305},
    91  	{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, ecdheRSAKA, suiteECDHE | suiteTLS12, nil, nil, aeadAESGCM12},
    92  	{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, ecdheECDSAKA, suiteECDHE | suiteECDSA | suiteTLS12, nil, nil, aeadAESGCM12},
    93  	{TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 32, 0, 4, ecdheRSAKA, suiteECDHE | suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM12},
    94  	{TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, 32, 0, 4, ecdheECDSAKA, suiteECDHE | suiteECDSA | suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM12},
    95  	{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, 16, 32, 16, ecdheRSAKA, suiteECDHE | suiteTLS12 | suiteDefaultOff, cipherAES, macSHA256, nil},
    96  	{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, 16, 20, 16, ecdheRSAKA, suiteECDHE, cipherAES, macSHA1, nil},
    97  	{TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, 16, 32, 16, ecdheECDSAKA, suiteECDHE | suiteECDSA | suiteTLS12 | suiteDefaultOff, cipherAES, macSHA256, nil},
    98  	{TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, 16, 20, 16, ecdheECDSAKA, suiteECDHE | suiteECDSA, cipherAES, macSHA1, nil},
    99  	{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, 32, 20, 16, ecdheRSAKA, suiteECDHE, cipherAES, macSHA1, nil},
   100  	{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, 32, 20, 16, ecdheECDSAKA, suiteECDHE | suiteECDSA, cipherAES, macSHA1, nil},
   101  	{TLS_RSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, rsaKA, suiteTLS12, nil, nil, aeadAESGCM12},
   102  	{TLS_RSA_WITH_AES_256_GCM_SHA384, 32, 0, 4, rsaKA, suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM12},
   103  	{TLS_RSA_WITH_AES_128_CBC_SHA256, 16, 32, 16, rsaKA, suiteTLS12 | suiteDefaultOff, cipherAES, macSHA256, nil},
   104  	{TLS_RSA_WITH_AES_128_CBC_SHA, 16, 20, 16, rsaKA, 0, cipherAES, macSHA1, nil},
   105  	{TLS_RSA_WITH_AES_256_CBC_SHA, 32, 20, 16, rsaKA, 0, cipherAES, macSHA1, nil},
   106  	{TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, 24, 20, 8, ecdheRSAKA, suiteECDHE, cipher3DES, macSHA1, nil},
   107  	{TLS_RSA_WITH_3DES_EDE_CBC_SHA, 24, 20, 8, rsaKA, 0, cipher3DES, macSHA1, nil},
   108  
   109  	// RC4-based cipher suites are disabled by default.
   110  	{TLS_RSA_WITH_RC4_128_SHA, 16, 20, 0, rsaKA, suiteDefaultOff, cipherRC4, macSHA1, nil},
   111  	{TLS_ECDHE_RSA_WITH_RC4_128_SHA, 16, 20, 0, ecdheRSAKA, suiteECDHE | suiteDefaultOff, cipherRC4, macSHA1, nil},
   112  	{TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, 16, 20, 0, ecdheECDSAKA, suiteECDHE | suiteECDSA | suiteDefaultOff, cipherRC4, macSHA1, nil},
   113  }
   114  
   115  func cipherRC4(key, iv []byte, isRead bool) interface{} {
   116  	cipher, _ := rc4.NewCipher(key)
   117  	return cipher
   118  }
   119  
   120  func cipher3DES(key, iv []byte, isRead bool) interface{} {
   121  	block, _ := des.NewTripleDESCipher(key)
   122  	if isRead {
   123  		return cipher.NewCBCDecrypter(block, iv)
   124  	}
   125  	return cipher.NewCBCEncrypter(block, iv)
   126  }
   127  
   128  func cipherAES(key, iv []byte, isRead bool) interface{} {
   129  	block, _ := aes.NewCipher(key)
   130  	if isRead {
   131  		return cipher.NewCBCDecrypter(block, iv)
   132  	}
   133  	return cipher.NewCBCEncrypter(block, iv)
   134  }
   135  
   136  // macSHA1 returns a macFunction for the given protocol version.
   137  func macSHA1(version uint16, key []byte) macFunction {
   138  	if version == VersionSSL30 {
   139  		mac := ssl30MAC{
   140  			h:   sha1.New(),
   141  			key: make([]byte, len(key)),
   142  		}
   143  		copy(mac.key, key)
   144  		return mac
   145  	}
   146  	return tls10MAC{hmac.New(newConstantTimeHash(sha1.New), key)}
   147  }
   148  
   149  // macSHA256 returns a SHA-256 based MAC. These are only supported in TLS 1.2
   150  // so the given version is ignored.
   151  func macSHA256(version uint16, key []byte) macFunction {
   152  	return tls10MAC{hmac.New(sha256.New, key)}
   153  }
   154  
   155  type macFunction interface {
   156  	Size() int
   157  	MAC(digestBuf, seq, header, data, extra []byte) []byte
   158  }
   159  
   160  type aead interface {
   161  	cipher.AEAD
   162  
   163  	// explicitIVLen returns the number of bytes used by the explicit nonce
   164  	// that is included in the record. This is eight for older AEADs and
   165  	// zero for modern ones.
   166  	explicitNonceLen() int
   167  }
   168  
   169  // fixedNonceAEAD wraps an AEAD and prefixes a fixed portion of the nonce to
   170  // each call.
   171  type fixedNonceAEAD struct {
   172  	// nonce contains the fixed part of the nonce in the first four bytes.
   173  	nonce [12]byte
   174  	aead  cipher.AEAD
   175  }
   176  
   177  func (f *fixedNonceAEAD) NonceSize() int { return 8 }
   178  
   179  // Overhead returns the maximum difference between the lengths of a
   180  // plaintext and its ciphertext.
   181  func (f *fixedNonceAEAD) Overhead() int         { return f.aead.Overhead() }
   182  func (f *fixedNonceAEAD) explicitNonceLen() int { return 8 }
   183  
   184  func (f *fixedNonceAEAD) Seal(out, nonce, plaintext, additionalData []byte) []byte {
   185  	copy(f.nonce[4:], nonce)
   186  	return f.aead.Seal(out, f.nonce[:], plaintext, additionalData)
   187  }
   188  
   189  func (f *fixedNonceAEAD) Open(out, nonce, plaintext, additionalData []byte) ([]byte, error) {
   190  	copy(f.nonce[4:], nonce)
   191  	return f.aead.Open(out, f.nonce[:], plaintext, additionalData)
   192  }
   193  
   194  // xoredNonceAEAD wraps an AEAD by XORing in a fixed pattern to the nonce
   195  // before each call.
   196  type xorNonceAEAD struct {
   197  	nonceMask [12]byte
   198  	aead      cipher.AEAD
   199  }
   200  
   201  func (f *xorNonceAEAD) NonceSize() int        { return 8 }
   202  func (f *xorNonceAEAD) Overhead() int         { return f.aead.Overhead() }
   203  func (f *xorNonceAEAD) explicitNonceLen() int { return 0 }
   204  
   205  func (f *xorNonceAEAD) Seal(out, nonce, plaintext, additionalData []byte) []byte {
   206  	for i, b := range nonce {
   207  		f.nonceMask[4+i] ^= b
   208  	}
   209  	result := f.aead.Seal(out, f.nonceMask[:], plaintext, additionalData)
   210  	for i, b := range nonce {
   211  		f.nonceMask[4+i] ^= b
   212  	}
   213  
   214  	return result
   215  }
   216  
   217  func (f *xorNonceAEAD) Open(out, nonce, plaintext, additionalData []byte) ([]byte, error) {
   218  	for i, b := range nonce {
   219  		f.nonceMask[4+i] ^= b
   220  	}
   221  	result, err := f.aead.Open(out, f.nonceMask[:], plaintext, additionalData)
   222  	for i, b := range nonce {
   223  		f.nonceMask[4+i] ^= b
   224  	}
   225  
   226  	return result, err
   227  }
   228  
   229  func aeadAESGCM12(key, fixedNonce []byte) cipher.AEAD {
   230  	aes, err := aes.NewCipher(key)
   231  	if err != nil {
   232  		panic(err)
   233  	}
   234  	aead, err := cipher.NewGCM(aes)
   235  	if err != nil {
   236  		panic(err)
   237  	}
   238  
   239  	ret := &fixedNonceAEAD{aead: aead}
   240  	copy(ret.nonce[:], fixedNonce)
   241  	return ret
   242  }
   243  
   244  func aeadAESGCM13(key, fixedNonce []byte) cipher.AEAD {
   245  	aes, err := aes.NewCipher(key)
   246  	if err != nil {
   247  		panic(err)
   248  	}
   249  	aead, err := cipher.NewGCM(aes)
   250  	if err != nil {
   251  		panic(err)
   252  	}
   253  
   254  	ret := &xorNonceAEAD{aead: aead}
   255  	copy(ret.nonceMask[:], fixedNonce)
   256  	return ret
   257  }
   258  
   259  func aeadChaCha20Poly1305(key, fixedNonce []byte) cipher.AEAD {
   260  	aead, err := chacha20poly1305.New(key)
   261  	if err != nil {
   262  		panic(err)
   263  	}
   264  
   265  	ret := &xorNonceAEAD{aead: aead}
   266  	copy(ret.nonceMask[:], fixedNonce)
   267  	return ret
   268  }
   269  
   270  // ssl30MAC implements the SSLv3 MAC function, as defined in
   271  // www.mozilla.org/projects/security/pki/nss/ssl/draft302.txt section 5.2.3.1
   272  type ssl30MAC struct {
   273  	h   hash.Hash
   274  	key []byte
   275  }
   276  
   277  func (s ssl30MAC) Size() int {
   278  	return s.h.Size()
   279  }
   280  
   281  var ssl30Pad1 = [48]byte{0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36}
   282  
   283  var ssl30Pad2 = [48]byte{0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c}
   284  
   285  // MAC does not offer constant timing guarantees for SSL v3.0, since it's deemed
   286  // useless considering the similar, protocol-level POODLE vulnerability.
   287  func (s ssl30MAC) MAC(digestBuf, seq, header, data, extra []byte) []byte {
   288  	padLength := 48
   289  	if s.h.Size() == 20 {
   290  		padLength = 40
   291  	}
   292  
   293  	s.h.Reset()
   294  	s.h.Write(s.key)
   295  	s.h.Write(ssl30Pad1[:padLength])
   296  	s.h.Write(seq)
   297  	s.h.Write(header[:1])
   298  	s.h.Write(header[3:5])
   299  	s.h.Write(data)
   300  	digestBuf = s.h.Sum(digestBuf[:0])
   301  
   302  	s.h.Reset()
   303  	s.h.Write(s.key)
   304  	s.h.Write(ssl30Pad2[:padLength])
   305  	s.h.Write(digestBuf)
   306  	return s.h.Sum(digestBuf[:0])
   307  }
   308  
   309  type constantTimeHash interface {
   310  	hash.Hash
   311  	ConstantTimeSum(b []byte) []byte
   312  }
   313  
   314  // cthWrapper wraps any hash.Hash that implements ConstantTimeSum, and replaces
   315  // with that all calls to Sum. It's used to obtain a ConstantTimeSum-based HMAC.
   316  type cthWrapper struct {
   317  	h constantTimeHash
   318  }
   319  
   320  func (c *cthWrapper) Size() int                   { return c.h.Size() }
   321  func (c *cthWrapper) BlockSize() int              { return c.h.BlockSize() }
   322  func (c *cthWrapper) Reset()                      { c.h.Reset() }
   323  func (c *cthWrapper) Write(p []byte) (int, error) { return c.h.Write(p) }
   324  func (c *cthWrapper) Sum(b []byte) []byte         { return c.h.ConstantTimeSum(b) }
   325  
   326  func newConstantTimeHash(h func() hash.Hash) func() hash.Hash {
   327  	return func() hash.Hash {
   328  		return &cthWrapper{h().(constantTimeHash)}
   329  	}
   330  }
   331  
   332  // tls10MAC implements the TLS 1.0 MAC function. RFC 2246, section 6.2.3.
   333  type tls10MAC struct {
   334  	h hash.Hash
   335  }
   336  
   337  func (s tls10MAC) Size() int {
   338  	return s.h.Size()
   339  }
   340  
   341  // MAC is guaranteed to take constant time, as long as
   342  // len(seq)+len(header)+len(data)+len(extra) is constant. extra is not fed into
   343  // the MAC, but is only provided to make the timing profile constant.
   344  func (s tls10MAC) MAC(digestBuf, seq, header, data, extra []byte) []byte {
   345  	s.h.Reset()
   346  	s.h.Write(seq)
   347  	s.h.Write(header)
   348  	s.h.Write(data)
   349  	res := s.h.Sum(digestBuf[:0])
   350  	if extra != nil {
   351  		s.h.Write(extra)
   352  	}
   353  	return res
   354  }
   355  
   356  func rsaKA(version uint16) keyAgreement {
   357  	return rsaKeyAgreement{}
   358  }
   359  
   360  func ecdheECDSAKA(version uint16) keyAgreement {
   361  	return &ecdheKeyAgreement{
   362  		isRSA:   false,
   363  		version: version,
   364  	}
   365  }
   366  
   367  func ecdheRSAKA(version uint16) keyAgreement {
   368  	return &ecdheKeyAgreement{
   369  		isRSA:   true,
   370  		version: version,
   371  	}
   372  }
   373  
   374  // mutualCipherSuite returns a cipherSuite given a list of supported
   375  // ciphersuites and the id requested by the peer.
   376  func mutualCipherSuite(have []uint16, want uint16) *cipherSuite {
   377  	for _, id := range have {
   378  		if id == want {
   379  			for _, suite := range cipherSuites {
   380  				if suite.id == want {
   381  					return suite
   382  				}
   383  			}
   384  			return nil
   385  		}
   386  	}
   387  	return nil
   388  }
   389  
   390  // A list of cipher suite IDs that are, or have been, implemented by this
   391  // package.
   392  //
   393  // Taken from http://www.iana.org/assignments/tls-parameters/tls-parameters.xml
   394  const (
   395  	// TLS 1.0 - 1.2 cipher suites.
   396  	TLS_RSA_WITH_RC4_128_SHA                uint16 = 0x0005
   397  	TLS_RSA_WITH_3DES_EDE_CBC_SHA           uint16 = 0x000a
   398  	TLS_RSA_WITH_AES_128_CBC_SHA            uint16 = 0x002f
   399  	TLS_RSA_WITH_AES_256_CBC_SHA            uint16 = 0x0035
   400  	TLS_RSA_WITH_AES_128_CBC_SHA256         uint16 = 0x003c
   401  	TLS_RSA_WITH_AES_128_GCM_SHA256         uint16 = 0x009c
   402  	TLS_RSA_WITH_AES_256_GCM_SHA384         uint16 = 0x009d
   403  	TLS_ECDHE_ECDSA_WITH_RC4_128_SHA        uint16 = 0xc007
   404  	TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA    uint16 = 0xc009
   405  	TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA    uint16 = 0xc00a
   406  	TLS_ECDHE_RSA_WITH_RC4_128_SHA          uint16 = 0xc011
   407  	TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA     uint16 = 0xc012
   408  	TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA      uint16 = 0xc013
   409  	TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA      uint16 = 0xc014
   410  	TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 uint16 = 0xc023
   411  	TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256   uint16 = 0xc027
   412  	TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256   uint16 = 0xc02f
   413  	TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xc02b
   414  	TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384   uint16 = 0xc030
   415  	TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 uint16 = 0xc02c
   416  	TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305    uint16 = 0xcca8
   417  	TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305  uint16 = 0xcca9
   418  
   419  	// TLS 1.3+ cipher suites.
   420  	TLS_AES_128_GCM_SHA256       uint16 = 0x1301
   421  	TLS_AES_256_GCM_SHA384       uint16 = 0x1302
   422  	TLS_CHACHA20_POLY1305_SHA256 uint16 = 0x1303
   423  
   424  	// TLS_FALLBACK_SCSV isn't a standard cipher suite but an indicator
   425  	// that the client is doing version fallback. See
   426  	// https://tools.ietf.org/html/rfc7507.
   427  	TLS_FALLBACK_SCSV uint16 = 0x5600
   428  )