Source file src/crypto/tls/cipher_suites.go

     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/internal/boring"
    14  	fipsaes "crypto/internal/fips140/aes"
    15  	"crypto/internal/fips140/aes/gcm"
    16  	"crypto/rc4"
    17  	"crypto/sha1"
    18  	"crypto/sha256"
    19  	_ "crypto/sha512" // for crypto.SHA384
    20  	"fmt"
    21  	"hash"
    22  	"internal/cpu"
    23  	"runtime"
    24  	_ "unsafe" // for linkname
    25  
    26  	"golang.org/x/crypto/chacha20poly1305"
    27  )
    28  
    29  // CipherSuite is a TLS cipher suite. Note that most functions in this package
    30  // accept and expose cipher suite IDs instead of this type.
    31  type CipherSuite struct {
    32  	ID   uint16
    33  	Name string
    34  
    35  	// Supported versions is the list of TLS protocol versions that can
    36  	// negotiate this cipher suite.
    37  	SupportedVersions []uint16
    38  
    39  	// Insecure is true if the cipher suite has known security issues
    40  	// due to its primitives, design, or implementation.
    41  	Insecure bool
    42  }
    43  
    44  var (
    45  	supportedUpToTLS12 = []uint16{VersionTLS10, VersionTLS11, VersionTLS12}
    46  	supportedOnlyTLS12 = []uint16{VersionTLS12}
    47  	supportedOnlyTLS13 = []uint16{VersionTLS13}
    48  )
    49  
    50  // CipherSuites returns a list of cipher suites currently implemented by this
    51  // package, excluding those with security issues, which are returned by
    52  // [InsecureCipherSuites].
    53  //
    54  // The list is sorted by ID. Note that the default cipher suites selected by
    55  // this package might depend on logic that can't be captured by a static list,
    56  // and might not match those returned by this function.
    57  func CipherSuites() []*CipherSuite {
    58  	return []*CipherSuite{
    59  		{TLS_AES_128_GCM_SHA256, "TLS_AES_128_GCM_SHA256", supportedOnlyTLS13, false},
    60  		{TLS_AES_256_GCM_SHA384, "TLS_AES_256_GCM_SHA384", supportedOnlyTLS13, false},
    61  		{TLS_CHACHA20_POLY1305_SHA256, "TLS_CHACHA20_POLY1305_SHA256", supportedOnlyTLS13, false},
    62  
    63  		{TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", supportedUpToTLS12, false},
    64  		{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", supportedUpToTLS12, false},
    65  		{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", supportedUpToTLS12, false},
    66  		{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", supportedUpToTLS12, false},
    67  		{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", supportedOnlyTLS12, false},
    68  		{TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", supportedOnlyTLS12, false},
    69  		{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", supportedOnlyTLS12, false},
    70  		{TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", supportedOnlyTLS12, false},
    71  		{TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256", supportedOnlyTLS12, false},
    72  		{TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256", supportedOnlyTLS12, false},
    73  	}
    74  }
    75  
    76  // InsecureCipherSuites returns a list of cipher suites currently implemented by
    77  // this package and which have security issues.
    78  //
    79  // Most applications should not use the cipher suites in this list, and should
    80  // only use those returned by [CipherSuites].
    81  func InsecureCipherSuites() []*CipherSuite {
    82  	// This list includes legacy RSA kex, RC4, CBC_SHA256, and 3DES cipher
    83  	// suites. See cipherSuitesPreferenceOrder for details.
    84  	return []*CipherSuite{
    85  		{TLS_RSA_WITH_RC4_128_SHA, "TLS_RSA_WITH_RC4_128_SHA", supportedUpToTLS12, true},
    86  		{TLS_RSA_WITH_3DES_EDE_CBC_SHA, "TLS_RSA_WITH_3DES_EDE_CBC_SHA", supportedUpToTLS12, true},
    87  		{TLS_RSA_WITH_AES_128_CBC_SHA, "TLS_RSA_WITH_AES_128_CBC_SHA", supportedUpToTLS12, true},
    88  		{TLS_RSA_WITH_AES_256_CBC_SHA, "TLS_RSA_WITH_AES_256_CBC_SHA", supportedUpToTLS12, true},
    89  		{TLS_RSA_WITH_AES_128_CBC_SHA256, "TLS_RSA_WITH_AES_128_CBC_SHA256", supportedOnlyTLS12, true},
    90  		{TLS_RSA_WITH_AES_128_GCM_SHA256, "TLS_RSA_WITH_AES_128_GCM_SHA256", supportedOnlyTLS12, true},
    91  		{TLS_RSA_WITH_AES_256_GCM_SHA384, "TLS_RSA_WITH_AES_256_GCM_SHA384", supportedOnlyTLS12, true},
    92  		{TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA", supportedUpToTLS12, true},
    93  		{TLS_ECDHE_RSA_WITH_RC4_128_SHA, "TLS_ECDHE_RSA_WITH_RC4_128_SHA", supportedUpToTLS12, true},
    94  		{TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA", supportedUpToTLS12, true},
    95  		{TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", supportedOnlyTLS12, true},
    96  		{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", supportedOnlyTLS12, true},
    97  	}
    98  }
    99  
   100  // CipherSuiteName returns the standard name for the passed cipher suite ID
   101  // (e.g. "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"), or a fallback representation
   102  // of the ID value if the cipher suite is not implemented by this package.
   103  func CipherSuiteName(id uint16) string {
   104  	for _, c := range CipherSuites() {
   105  		if c.ID == id {
   106  			return c.Name
   107  		}
   108  	}
   109  	for _, c := range InsecureCipherSuites() {
   110  		if c.ID == id {
   111  			return c.Name
   112  		}
   113  	}
   114  	return fmt.Sprintf("0x%04X", id)
   115  }
   116  
   117  const (
   118  	// suiteECDHE indicates that the cipher suite involves elliptic curve
   119  	// Diffie-Hellman. This means that it should only be selected when the
   120  	// client indicates that it supports ECC with a curve and point format
   121  	// that we're happy with.
   122  	suiteECDHE = 1 << iota
   123  	// suiteECSign indicates that the cipher suite involves an ECDSA or
   124  	// EdDSA signature and therefore may only be selected when the server's
   125  	// certificate is ECDSA or EdDSA. If this is not set then the cipher suite
   126  	// is RSA based.
   127  	suiteECSign
   128  	// suiteTLS12 indicates that the cipher suite should only be advertised
   129  	// and accepted when using TLS 1.2.
   130  	suiteTLS12
   131  	// suiteSHA384 indicates that the cipher suite uses SHA384 as the
   132  	// handshake hash.
   133  	suiteSHA384
   134  )
   135  
   136  // A cipherSuite is a TLS 1.0–1.2 cipher suite, and defines the key exchange
   137  // mechanism, as well as the cipher+MAC pair or the AEAD.
   138  type cipherSuite struct {
   139  	id uint16
   140  	// the lengths, in bytes, of the key material needed for each component.
   141  	keyLen int
   142  	macLen int
   143  	ivLen  int
   144  	ka     func(version uint16) keyAgreement
   145  	// flags is a bitmask of the suite* values, above.
   146  	flags  int
   147  	cipher func(key, iv []byte, isRead bool) any
   148  	mac    func(key []byte) hash.Hash
   149  	aead   func(key, fixedNonce []byte) aead
   150  }
   151  
   152  var cipherSuites = []*cipherSuite{ // TODO: replace with a map, since the order doesn't matter.
   153  	{TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, 32, 0, 12, ecdheRSAKA, suiteECDHE | suiteTLS12, nil, nil, aeadChaCha20Poly1305},
   154  	{TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, 32, 0, 12, ecdheECDSAKA, suiteECDHE | suiteECSign | suiteTLS12, nil, nil, aeadChaCha20Poly1305},
   155  	{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, ecdheRSAKA, suiteECDHE | suiteTLS12, nil, nil, aeadAESGCM},
   156  	{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, ecdheECDSAKA, suiteECDHE | suiteECSign | suiteTLS12, nil, nil, aeadAESGCM},
   157  	{TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 32, 0, 4, ecdheRSAKA, suiteECDHE | suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM},
   158  	{TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, 32, 0, 4, ecdheECDSAKA, suiteECDHE | suiteECSign | suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM},
   159  	{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, 16, 32, 16, ecdheRSAKA, suiteECDHE | suiteTLS12, cipherAES, macSHA256, nil},
   160  	{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, 16, 20, 16, ecdheRSAKA, suiteECDHE, cipherAES, macSHA1, nil},
   161  	{TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, 16, 32, 16, ecdheECDSAKA, suiteECDHE | suiteECSign | suiteTLS12, cipherAES, macSHA256, nil},
   162  	{TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, 16, 20, 16, ecdheECDSAKA, suiteECDHE | suiteECSign, cipherAES, macSHA1, nil},
   163  	{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, 32, 20, 16, ecdheRSAKA, suiteECDHE, cipherAES, macSHA1, nil},
   164  	{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, 32, 20, 16, ecdheECDSAKA, suiteECDHE | suiteECSign, cipherAES, macSHA1, nil},
   165  	{TLS_RSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, rsaKA, suiteTLS12, nil, nil, aeadAESGCM},
   166  	{TLS_RSA_WITH_AES_256_GCM_SHA384, 32, 0, 4, rsaKA, suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM},
   167  	{TLS_RSA_WITH_AES_128_CBC_SHA256, 16, 32, 16, rsaKA, suiteTLS12, cipherAES, macSHA256, nil},
   168  	{TLS_RSA_WITH_AES_128_CBC_SHA, 16, 20, 16, rsaKA, 0, cipherAES, macSHA1, nil},
   169  	{TLS_RSA_WITH_AES_256_CBC_SHA, 32, 20, 16, rsaKA, 0, cipherAES, macSHA1, nil},
   170  	{TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, 24, 20, 8, ecdheRSAKA, suiteECDHE, cipher3DES, macSHA1, nil},
   171  	{TLS_RSA_WITH_3DES_EDE_CBC_SHA, 24, 20, 8, rsaKA, 0, cipher3DES, macSHA1, nil},
   172  	{TLS_RSA_WITH_RC4_128_SHA, 16, 20, 0, rsaKA, 0, cipherRC4, macSHA1, nil},
   173  	{TLS_ECDHE_RSA_WITH_RC4_128_SHA, 16, 20, 0, ecdheRSAKA, suiteECDHE, cipherRC4, macSHA1, nil},
   174  	{TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, 16, 20, 0, ecdheECDSAKA, suiteECDHE | suiteECSign, cipherRC4, macSHA1, nil},
   175  }
   176  
   177  // selectCipherSuite returns the first TLS 1.0–1.2 cipher suite from ids which
   178  // is also in supportedIDs and passes the ok filter.
   179  func selectCipherSuite(ids, supportedIDs []uint16, ok func(*cipherSuite) bool) *cipherSuite {
   180  	for _, id := range ids {
   181  		candidate := cipherSuiteByID(id)
   182  		if candidate == nil || !ok(candidate) {
   183  			continue
   184  		}
   185  
   186  		for _, suppID := range supportedIDs {
   187  			if id == suppID {
   188  				return candidate
   189  			}
   190  		}
   191  	}
   192  	return nil
   193  }
   194  
   195  // A cipherSuiteTLS13 defines only the pair of the AEAD algorithm and hash
   196  // algorithm to be used with HKDF. See RFC 8446, Appendix B.4.
   197  type cipherSuiteTLS13 struct {
   198  	id     uint16
   199  	keyLen int
   200  	aead   func(key, fixedNonce []byte) aead
   201  	hash   crypto.Hash
   202  }
   203  
   204  // cipherSuitesTLS13 should be an internal detail,
   205  // but widely used packages access it using linkname.
   206  // Notable members of the hall of shame include:
   207  //   - github.com/quic-go/quic-go
   208  //   - github.com/sagernet/quic-go
   209  //
   210  // Do not remove or change the type signature.
   211  // See go.dev/issue/67401.
   212  //
   213  //go:linkname cipherSuitesTLS13
   214  var cipherSuitesTLS13 = []*cipherSuiteTLS13{ // TODO: replace with a map.
   215  	{TLS_AES_128_GCM_SHA256, 16, aeadAESGCMTLS13, crypto.SHA256},
   216  	{TLS_CHACHA20_POLY1305_SHA256, 32, aeadChaCha20Poly1305, crypto.SHA256},
   217  	{TLS_AES_256_GCM_SHA384, 32, aeadAESGCMTLS13, crypto.SHA384},
   218  }
   219  
   220  // cipherSuitesPreferenceOrder is the order in which we'll select (on the
   221  // server) or advertise (on the client) TLS 1.0–1.2 cipher suites.
   222  //
   223  // Cipher suites are filtered but not reordered based on the application and
   224  // peer's preferences, meaning we'll never select a suite lower in this list if
   225  // any higher one is available. This makes it more defensible to keep weaker
   226  // cipher suites enabled, especially on the server side where we get the last
   227  // word, since there are no known downgrade attacks on cipher suites selection.
   228  //
   229  // The list is sorted by applying the following priority rules, stopping at the
   230  // first (most important) applicable one:
   231  //
   232  //   - Anything else comes before RC4
   233  //
   234  //     RC4 has practically exploitable biases. See https://www.rc4nomore.com.
   235  //
   236  //   - Anything else comes before CBC_SHA256
   237  //
   238  //     SHA-256 variants of the CBC ciphersuites don't implement any Lucky13
   239  //     countermeasures. See https://www.isg.rhul.ac.uk/tls/Lucky13.html and
   240  //     https://www.imperialviolet.org/2013/02/04/luckythirteen.html.
   241  //
   242  //   - Anything else comes before 3DES
   243  //
   244  //     3DES has 64-bit blocks, which makes it fundamentally susceptible to
   245  //     birthday attacks. See https://sweet32.info.
   246  //
   247  //   - ECDHE comes before anything else
   248  //
   249  //     Once we got the broken stuff out of the way, the most important
   250  //     property a cipher suite can have is forward secrecy. We don't
   251  //     implement FFDHE, so that means ECDHE.
   252  //
   253  //   - AEADs come before CBC ciphers
   254  //
   255  //     Even with Lucky13 countermeasures, MAC-then-Encrypt CBC cipher suites
   256  //     are fundamentally fragile, and suffered from an endless sequence of
   257  //     padding oracle attacks. See https://eprint.iacr.org/2015/1129,
   258  //     https://www.imperialviolet.org/2014/12/08/poodleagain.html, and
   259  //     https://blog.cloudflare.com/yet-another-padding-oracle-in-openssl-cbc-ciphersuites/.
   260  //
   261  //   - AES comes before ChaCha20
   262  //
   263  //     When AES hardware is available, AES-128-GCM and AES-256-GCM are faster
   264  //     than ChaCha20Poly1305.
   265  //
   266  //     When AES hardware is not available, AES-128-GCM is one or more of: much
   267  //     slower, way more complex, and less safe (because not constant time)
   268  //     than ChaCha20Poly1305.
   269  //
   270  //     We use this list if we think both peers have AES hardware, and
   271  //     cipherSuitesPreferenceOrderNoAES otherwise.
   272  //
   273  //   - AES-128 comes before AES-256
   274  //
   275  //     The only potential advantages of AES-256 are better multi-target
   276  //     margins, and hypothetical post-quantum properties. Neither apply to
   277  //     TLS, and AES-256 is slower due to its four extra rounds (which don't
   278  //     contribute to the advantages above).
   279  //
   280  //   - ECDSA comes before RSA
   281  //
   282  //     The relative order of ECDSA and RSA cipher suites doesn't matter,
   283  //     as they depend on the certificate. Pick one to get a stable order.
   284  var cipherSuitesPreferenceOrder = []uint16{
   285  	// AEADs w/ ECDHE
   286  	TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
   287  	TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
   288  	TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
   289  
   290  	// CBC w/ ECDHE
   291  	TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
   292  	TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
   293  
   294  	// AEADs w/o ECDHE
   295  	TLS_RSA_WITH_AES_128_GCM_SHA256,
   296  	TLS_RSA_WITH_AES_256_GCM_SHA384,
   297  
   298  	// CBC w/o ECDHE
   299  	TLS_RSA_WITH_AES_128_CBC_SHA,
   300  	TLS_RSA_WITH_AES_256_CBC_SHA,
   301  
   302  	// 3DES
   303  	TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
   304  	TLS_RSA_WITH_3DES_EDE_CBC_SHA,
   305  
   306  	// CBC_SHA256
   307  	TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
   308  	TLS_RSA_WITH_AES_128_CBC_SHA256,
   309  
   310  	// RC4
   311  	TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA,
   312  	TLS_RSA_WITH_RC4_128_SHA,
   313  }
   314  
   315  var cipherSuitesPreferenceOrderNoAES = []uint16{
   316  	// ChaCha20Poly1305
   317  	TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
   318  
   319  	// AES-GCM w/ ECDHE
   320  	TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
   321  	TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
   322  
   323  	// The rest of cipherSuitesPreferenceOrder.
   324  	TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
   325  	TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
   326  	TLS_RSA_WITH_AES_128_GCM_SHA256,
   327  	TLS_RSA_WITH_AES_256_GCM_SHA384,
   328  	TLS_RSA_WITH_AES_128_CBC_SHA,
   329  	TLS_RSA_WITH_AES_256_CBC_SHA,
   330  	TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
   331  	TLS_RSA_WITH_3DES_EDE_CBC_SHA,
   332  	TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
   333  	TLS_RSA_WITH_AES_128_CBC_SHA256,
   334  	TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA,
   335  	TLS_RSA_WITH_RC4_128_SHA,
   336  }
   337  
   338  // disabledCipherSuites are not used unless explicitly listed in Config.CipherSuites.
   339  var disabledCipherSuites = map[uint16]bool{
   340  	// CBC_SHA256
   341  	TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: true,
   342  	TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:   true,
   343  	TLS_RSA_WITH_AES_128_CBC_SHA256:         true,
   344  
   345  	// RC4
   346  	TLS_ECDHE_ECDSA_WITH_RC4_128_SHA: true,
   347  	TLS_ECDHE_RSA_WITH_RC4_128_SHA:   true,
   348  	TLS_RSA_WITH_RC4_128_SHA:         true,
   349  
   350  	// RSA key exchange
   351  	TLS_RSA_WITH_3DES_EDE_CBC_SHA:   true,
   352  	TLS_RSA_WITH_AES_128_CBC_SHA:    true,
   353  	TLS_RSA_WITH_AES_256_CBC_SHA:    true,
   354  	TLS_RSA_WITH_AES_128_GCM_SHA256: true,
   355  	TLS_RSA_WITH_AES_256_GCM_SHA384: true,
   356  
   357  	// 3DES
   358  	TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA: true,
   359  }
   360  
   361  var (
   362  	// Keep in sync with crypto/internal/fips140/aes/gcm.supportsAESGCM.
   363  	hasGCMAsmAMD64 = cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ && cpu.X86.HasSSE41 && cpu.X86.HasSSSE3
   364  	hasGCMAsmARM64 = cpu.ARM64.HasAES && cpu.ARM64.HasPMULL
   365  	hasGCMAsmS390X = cpu.S390X.HasAES && cpu.S390X.HasAESCTR && cpu.S390X.HasGHASH
   366  	hasGCMAsmPPC64 = runtime.GOARCH == "ppc64" || runtime.GOARCH == "ppc64le"
   367  
   368  	hasAESGCMHardwareSupport = hasGCMAsmAMD64 || hasGCMAsmARM64 || hasGCMAsmS390X || hasGCMAsmPPC64
   369  )
   370  
   371  var aesgcmCiphers = map[uint16]bool{
   372  	// TLS 1.2
   373  	TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:   true,
   374  	TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:   true,
   375  	TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: true,
   376  	TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: true,
   377  	// TLS 1.3
   378  	TLS_AES_128_GCM_SHA256: true,
   379  	TLS_AES_256_GCM_SHA384: true,
   380  }
   381  
   382  // isAESGCMPreferred returns whether we have hardware support for AES-GCM, and the
   383  // first known cipher in the peer's preference list is an AES-GCM cipher,
   384  // implying the peer also has hardware support for it.
   385  func isAESGCMPreferred(ciphers []uint16) bool {
   386  	if !hasAESGCMHardwareSupport {
   387  		return false
   388  	}
   389  	for _, cID := range ciphers {
   390  		if c := cipherSuiteByID(cID); c != nil {
   391  			return aesgcmCiphers[cID]
   392  		}
   393  		if c := cipherSuiteTLS13ByID(cID); c != nil {
   394  			return aesgcmCiphers[cID]
   395  		}
   396  	}
   397  	return false
   398  }
   399  
   400  func cipherRC4(key, iv []byte, isRead bool) any {
   401  	cipher, _ := rc4.NewCipher(key)
   402  	return cipher
   403  }
   404  
   405  func cipher3DES(key, iv []byte, isRead bool) any {
   406  	block, _ := des.NewTripleDESCipher(key)
   407  	if isRead {
   408  		return cipher.NewCBCDecrypter(block, iv)
   409  	}
   410  	return cipher.NewCBCEncrypter(block, iv)
   411  }
   412  
   413  func cipherAES(key, iv []byte, isRead bool) any {
   414  	block, _ := aes.NewCipher(key)
   415  	if isRead {
   416  		return cipher.NewCBCDecrypter(block, iv)
   417  	}
   418  	return cipher.NewCBCEncrypter(block, iv)
   419  }
   420  
   421  // macSHA1 returns a SHA-1 based constant time MAC.
   422  func macSHA1(key []byte) hash.Hash {
   423  	h := sha1.New
   424  	// The BoringCrypto SHA1 does not have a constant-time
   425  	// checksum function, so don't try to use it.
   426  	if !boring.Enabled {
   427  		h = newConstantTimeHash(h)
   428  	}
   429  	return hmac.New(h, key)
   430  }
   431  
   432  // macSHA256 returns a SHA-256 based MAC. This is only supported in TLS 1.2 and
   433  // is currently only used in disabled-by-default cipher suites.
   434  func macSHA256(key []byte) hash.Hash {
   435  	return hmac.New(sha256.New, key)
   436  }
   437  
   438  type aead interface {
   439  	cipher.AEAD
   440  
   441  	// explicitNonceLen returns the number of bytes of explicit nonce
   442  	// included in each record. This is eight for older AEADs and
   443  	// zero for modern ones.
   444  	explicitNonceLen() int
   445  }
   446  
   447  const (
   448  	aeadNonceLength   = 12
   449  	noncePrefixLength = 4
   450  )
   451  
   452  // prefixNonceAEAD wraps an AEAD and prefixes a fixed portion of the nonce to
   453  // each call.
   454  type prefixNonceAEAD struct {
   455  	// nonce contains the fixed part of the nonce in the first four bytes.
   456  	nonce [aeadNonceLength]byte
   457  	aead  cipher.AEAD
   458  }
   459  
   460  func (f *prefixNonceAEAD) NonceSize() int        { return aeadNonceLength - noncePrefixLength }
   461  func (f *prefixNonceAEAD) Overhead() int         { return f.aead.Overhead() }
   462  func (f *prefixNonceAEAD) explicitNonceLen() int { return f.NonceSize() }
   463  
   464  func (f *prefixNonceAEAD) Seal(out, nonce, plaintext, additionalData []byte) []byte {
   465  	copy(f.nonce[4:], nonce)
   466  	return f.aead.Seal(out, f.nonce[:], plaintext, additionalData)
   467  }
   468  
   469  func (f *prefixNonceAEAD) Open(out, nonce, ciphertext, additionalData []byte) ([]byte, error) {
   470  	copy(f.nonce[4:], nonce)
   471  	return f.aead.Open(out, f.nonce[:], ciphertext, additionalData)
   472  }
   473  
   474  // xorNonceAEAD wraps an AEAD by XORing in a fixed pattern to the nonce
   475  // before each call.
   476  type xorNonceAEAD struct {
   477  	nonceMask [aeadNonceLength]byte
   478  	aead      cipher.AEAD
   479  }
   480  
   481  func (f *xorNonceAEAD) NonceSize() int        { return 8 } // 64-bit sequence number
   482  func (f *xorNonceAEAD) Overhead() int         { return f.aead.Overhead() }
   483  func (f *xorNonceAEAD) explicitNonceLen() int { return 0 }
   484  
   485  func (f *xorNonceAEAD) Seal(out, nonce, plaintext, additionalData []byte) []byte {
   486  	for i, b := range nonce {
   487  		f.nonceMask[4+i] ^= b
   488  	}
   489  	result := f.aead.Seal(out, f.nonceMask[:], plaintext, additionalData)
   490  	for i, b := range nonce {
   491  		f.nonceMask[4+i] ^= b
   492  	}
   493  
   494  	return result
   495  }
   496  
   497  func (f *xorNonceAEAD) Open(out, nonce, ciphertext, additionalData []byte) ([]byte, error) {
   498  	for i, b := range nonce {
   499  		f.nonceMask[4+i] ^= b
   500  	}
   501  	result, err := f.aead.Open(out, f.nonceMask[:], ciphertext, additionalData)
   502  	for i, b := range nonce {
   503  		f.nonceMask[4+i] ^= b
   504  	}
   505  
   506  	return result, err
   507  }
   508  
   509  func aeadAESGCM(key, noncePrefix []byte) aead {
   510  	if len(noncePrefix) != noncePrefixLength {
   511  		panic("tls: internal error: wrong nonce length")
   512  	}
   513  	aes, err := aes.NewCipher(key)
   514  	if err != nil {
   515  		panic(err)
   516  	}
   517  	var aead cipher.AEAD
   518  	if boring.Enabled {
   519  		aead, err = boring.NewGCMTLS(aes)
   520  	} else {
   521  		boring.Unreachable()
   522  		aead, err = gcm.NewGCMForTLS12(aes.(*fipsaes.Block))
   523  	}
   524  	if err != nil {
   525  		panic(err)
   526  	}
   527  
   528  	ret := &prefixNonceAEAD{aead: aead}
   529  	copy(ret.nonce[:], noncePrefix)
   530  	return ret
   531  }
   532  
   533  // aeadAESGCMTLS13 should be an internal detail,
   534  // but widely used packages access it using linkname.
   535  // Notable members of the hall of shame include:
   536  //   - github.com/xtls/xray-core
   537  //   - github.com/v2fly/v2ray-core
   538  //
   539  // Do not remove or change the type signature.
   540  // See go.dev/issue/67401.
   541  //
   542  //go:linkname aeadAESGCMTLS13
   543  func aeadAESGCMTLS13(key, nonceMask []byte) aead {
   544  	if len(nonceMask) != aeadNonceLength {
   545  		panic("tls: internal error: wrong nonce length")
   546  	}
   547  	aes, err := aes.NewCipher(key)
   548  	if err != nil {
   549  		panic(err)
   550  	}
   551  	var aead cipher.AEAD
   552  	if boring.Enabled {
   553  		aead, err = boring.NewGCMTLS13(aes)
   554  	} else {
   555  		boring.Unreachable()
   556  		aead, err = gcm.NewGCMForTLS13(aes.(*fipsaes.Block))
   557  	}
   558  	if err != nil {
   559  		panic(err)
   560  	}
   561  
   562  	ret := &xorNonceAEAD{aead: aead}
   563  	copy(ret.nonceMask[:], nonceMask)
   564  	return ret
   565  }
   566  
   567  func aeadChaCha20Poly1305(key, nonceMask []byte) aead {
   568  	if len(nonceMask) != aeadNonceLength {
   569  		panic("tls: internal error: wrong nonce length")
   570  	}
   571  	aead, err := chacha20poly1305.New(key)
   572  	if err != nil {
   573  		panic(err)
   574  	}
   575  
   576  	ret := &xorNonceAEAD{aead: aead}
   577  	copy(ret.nonceMask[:], nonceMask)
   578  	return ret
   579  }
   580  
   581  type constantTimeHash interface {
   582  	hash.Hash
   583  	ConstantTimeSum(b []byte) []byte
   584  }
   585  
   586  // cthWrapper wraps any hash.Hash that implements ConstantTimeSum, and replaces
   587  // with that all calls to Sum. It's used to obtain a ConstantTimeSum-based HMAC.
   588  type cthWrapper struct {
   589  	h constantTimeHash
   590  }
   591  
   592  func (c *cthWrapper) Size() int                   { return c.h.Size() }
   593  func (c *cthWrapper) BlockSize() int              { return c.h.BlockSize() }
   594  func (c *cthWrapper) Reset()                      { c.h.Reset() }
   595  func (c *cthWrapper) Write(p []byte) (int, error) { return c.h.Write(p) }
   596  func (c *cthWrapper) Sum(b []byte) []byte         { return c.h.ConstantTimeSum(b) }
   597  
   598  func newConstantTimeHash(h func() hash.Hash) func() hash.Hash {
   599  	boring.Unreachable()
   600  	return func() hash.Hash {
   601  		return &cthWrapper{h().(constantTimeHash)}
   602  	}
   603  }
   604  
   605  // tls10MAC implements the TLS 1.0 MAC function. RFC 2246, Section 6.2.3.
   606  func tls10MAC(h hash.Hash, out, seq, header, data, extra []byte) []byte {
   607  	h.Reset()
   608  	h.Write(seq)
   609  	h.Write(header)
   610  	h.Write(data)
   611  	res := h.Sum(out)
   612  	if extra != nil {
   613  		h.Write(extra)
   614  	}
   615  	return res
   616  }
   617  
   618  func rsaKA(version uint16) keyAgreement {
   619  	return rsaKeyAgreement{}
   620  }
   621  
   622  func ecdheECDSAKA(version uint16) keyAgreement {
   623  	return &ecdheKeyAgreement{
   624  		isRSA:   false,
   625  		version: version,
   626  	}
   627  }
   628  
   629  func ecdheRSAKA(version uint16) keyAgreement {
   630  	return &ecdheKeyAgreement{
   631  		isRSA:   true,
   632  		version: version,
   633  	}
   634  }
   635  
   636  // mutualCipherSuite returns a cipherSuite given a list of supported
   637  // ciphersuites and the id requested by the peer.
   638  func mutualCipherSuite(have []uint16, want uint16) *cipherSuite {
   639  	for _, id := range have {
   640  		if id == want {
   641  			return cipherSuiteByID(id)
   642  		}
   643  	}
   644  	return nil
   645  }
   646  
   647  func cipherSuiteByID(id uint16) *cipherSuite {
   648  	for _, cipherSuite := range cipherSuites {
   649  		if cipherSuite.id == id {
   650  			return cipherSuite
   651  		}
   652  	}
   653  	return nil
   654  }
   655  
   656  func mutualCipherSuiteTLS13(have []uint16, want uint16) *cipherSuiteTLS13 {
   657  	for _, id := range have {
   658  		if id == want {
   659  			return cipherSuiteTLS13ByID(id)
   660  		}
   661  	}
   662  	return nil
   663  }
   664  
   665  func cipherSuiteTLS13ByID(id uint16) *cipherSuiteTLS13 {
   666  	for _, cipherSuite := range cipherSuitesTLS13 {
   667  		if cipherSuite.id == id {
   668  			return cipherSuite
   669  		}
   670  	}
   671  	return nil
   672  }
   673  
   674  // A list of cipher suite IDs that are, or have been, implemented by this
   675  // package.
   676  //
   677  // See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml
   678  const (
   679  	// TLS 1.0 - 1.2 cipher suites.
   680  	TLS_RSA_WITH_RC4_128_SHA                      uint16 = 0x0005
   681  	TLS_RSA_WITH_3DES_EDE_CBC_SHA                 uint16 = 0x000a
   682  	TLS_RSA_WITH_AES_128_CBC_SHA                  uint16 = 0x002f
   683  	TLS_RSA_WITH_AES_256_CBC_SHA                  uint16 = 0x0035
   684  	TLS_RSA_WITH_AES_128_CBC_SHA256               uint16 = 0x003c
   685  	TLS_RSA_WITH_AES_128_GCM_SHA256               uint16 = 0x009c
   686  	TLS_RSA_WITH_AES_256_GCM_SHA384               uint16 = 0x009d
   687  	TLS_ECDHE_ECDSA_WITH_RC4_128_SHA              uint16 = 0xc007
   688  	TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA          uint16 = 0xc009
   689  	TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA          uint16 = 0xc00a
   690  	TLS_ECDHE_RSA_WITH_RC4_128_SHA                uint16 = 0xc011
   691  	TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA           uint16 = 0xc012
   692  	TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA            uint16 = 0xc013
   693  	TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA            uint16 = 0xc014
   694  	TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256       uint16 = 0xc023
   695  	TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256         uint16 = 0xc027
   696  	TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256         uint16 = 0xc02f
   697  	TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256       uint16 = 0xc02b
   698  	TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384         uint16 = 0xc030
   699  	TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384       uint16 = 0xc02c
   700  	TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256   uint16 = 0xcca8
   701  	TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xcca9
   702  
   703  	// TLS 1.3 cipher suites.
   704  	TLS_AES_128_GCM_SHA256       uint16 = 0x1301
   705  	TLS_AES_256_GCM_SHA384       uint16 = 0x1302
   706  	TLS_CHACHA20_POLY1305_SHA256 uint16 = 0x1303
   707  
   708  	// TLS_FALLBACK_SCSV isn't a standard cipher suite but an indicator
   709  	// that the client is doing version fallback. See RFC 7507.
   710  	TLS_FALLBACK_SCSV uint16 = 0x5600
   711  
   712  	// Legacy names for the corresponding cipher suites with the correct _SHA256
   713  	// suffix, retained for backward compatibility.
   714  	TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305   = TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
   715  	TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305 = TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
   716  )
   717  

View as plain text