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

View as plain text