gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/gmtls/cipher_suites.go (about)

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