gitee.com/zhaochuninhefei/gmgo@v0.0.31-0.20240209061119-069254a02979/gmtls/cipher_suites.go (about)

     1  // Copyright (c) 2022 zhaochun
     2  // gmgo 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/zhaochuninhefei/gmgo/internal/cpu"
    29  	"gitee.com/zhaochuninhefei/gmgo/sm4"
    30  	"gitee.com/zhaochuninhefei/gmgo/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  //
   312  var cipherSuitesPreferenceOrder = []uint16{
   313  	// AEADs w/ ECDHE
   314  	TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
   315  	TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
   316  	TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
   317  
   318  	// CBC w/ ECDHE
   319  	TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
   320  	TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
   321  
   322  	// AEADs w/o ECDHE
   323  	TLS_RSA_WITH_AES_128_GCM_SHA256,
   324  	TLS_RSA_WITH_AES_256_GCM_SHA384,
   325  
   326  	// CBC w/o ECDHE
   327  	TLS_RSA_WITH_AES_128_CBC_SHA,
   328  	TLS_RSA_WITH_AES_256_CBC_SHA,
   329  
   330  	// 3DES
   331  	TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
   332  	TLS_RSA_WITH_3DES_EDE_CBC_SHA,
   333  
   334  	// CBC_SHA256
   335  	TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
   336  	TLS_RSA_WITH_AES_128_CBC_SHA256,
   337  
   338  	// RC4
   339  	TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA,
   340  	TLS_RSA_WITH_RC4_128_SHA,
   341  }
   342  
   343  var cipherSuitesPreferenceOrderNoAES = []uint16{
   344  	// ChaCha20Poly1305
   345  	TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
   346  
   347  	// AES-GCM w/ ECDHE
   348  	TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
   349  	TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
   350  
   351  	// The rest of cipherSuitesPreferenceOrder.
   352  	TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
   353  	TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
   354  	TLS_RSA_WITH_AES_128_GCM_SHA256,
   355  	TLS_RSA_WITH_AES_256_GCM_SHA384,
   356  	TLS_RSA_WITH_AES_128_CBC_SHA,
   357  	TLS_RSA_WITH_AES_256_CBC_SHA,
   358  	TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
   359  	TLS_RSA_WITH_3DES_EDE_CBC_SHA,
   360  	TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
   361  	TLS_RSA_WITH_AES_128_CBC_SHA256,
   362  	TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA,
   363  	TLS_RSA_WITH_RC4_128_SHA,
   364  }
   365  
   366  // disabledCipherSuites are not used unless explicitly listed in
   367  // Config.CipherSuites. They MUST be at the end of cipherSuitesPreferenceOrder.
   368  var disabledCipherSuites = []uint16{
   369  	// CBC_SHA256
   370  	TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
   371  	TLS_RSA_WITH_AES_128_CBC_SHA256,
   372  
   373  	// RC4
   374  	TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA,
   375  	TLS_RSA_WITH_RC4_128_SHA,
   376  }
   377  
   378  var (
   379  	defaultCipherSuitesLen = len(cipherSuitesPreferenceOrder) - len(disabledCipherSuites)
   380  	defaultCipherSuites    = cipherSuitesPreferenceOrder[:defaultCipherSuitesLen]
   381  )
   382  
   383  // tls1.3的默认密码学套件选择顺序,已将对应的国密密码学套件作为首选。
   384  // defaultCipherSuitesTLS13 is also the preference order, since there are no
   385  // disabled by default TLS 1.3 cipher suites. The same AES vs ChaCha20 logic as
   386  // cipherSuitesPreferenceOrder applies.
   387  var defaultCipherSuitesTLS13 = []uint16{
   388  	TLS_SM4_GCM_SM3,
   389  	TLS_AES_128_GCM_SHA256,
   390  	TLS_AES_256_GCM_SHA384,
   391  	TLS_CHACHA20_POLY1305_SHA256,
   392  }
   393  
   394  var defaultCipherSuitesTLS13NoAES = []uint16{
   395  	TLS_SM4_GCM_SM3,
   396  	TLS_CHACHA20_POLY1305_SHA256,
   397  	TLS_AES_128_GCM_SHA256,
   398  	TLS_AES_256_GCM_SHA384,
   399  }
   400  
   401  var (
   402  	hasGCMAsmAMD64 = cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ
   403  	hasGCMAsmARM64 = cpu.ARM64.HasAES && cpu.ARM64.HasPMULL
   404  	// Keep in sync with crypto/aes/cipher_s390x.go.
   405  	hasGCMAsmS390X = cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR &&
   406  		(cpu.S390X.HasGHASH || cpu.S390X.HasAESGCM)
   407  
   408  	hasAESGCMHardwareSupport = runtime.GOARCH == "amd64" && hasGCMAsmAMD64 ||
   409  		runtime.GOARCH == "arm64" && hasGCMAsmARM64 ||
   410  		runtime.GOARCH == "s390x" && hasGCMAsmS390X
   411  )
   412  
   413  var aesgcmCiphers = map[uint16]bool{
   414  	// TLS 1.2
   415  	TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:   true,
   416  	TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:   true,
   417  	TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: true,
   418  	TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: true,
   419  	// TLS 1.3
   420  	TLS_SM4_GCM_SM3:        true,
   421  	TLS_AES_128_GCM_SHA256: true,
   422  	TLS_AES_256_GCM_SHA384: true,
   423  }
   424  
   425  // var nonAESGCMAEADCiphers = map[uint16]bool{
   426  // 	// TLS 1.2
   427  // 	TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305:   true,
   428  // 	TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305: true,
   429  // 	// TLS 1.3
   430  // 	TLS_SM4_GCM_SM3:          true,
   431  // 	TLS_CHACHA20_POLY1305_SHA256: true,
   432  // }
   433  
   434  // aesgcmPreferred returns whether the first known cipher in the preference list
   435  // is an AES-GCM cipher, implying the peer has hardware support for it.
   436  func aesgcmPreferred(ciphers []uint16) bool {
   437  	for _, cID := range ciphers {
   438  		if c := cipherSuiteByID(cID); c != nil {
   439  			return aesgcmCiphers[cID]
   440  		}
   441  		if c := cipherSuiteTLS13ByID(cID); c != nil {
   442  			return aesgcmCiphers[cID]
   443  		}
   444  	}
   445  	return false
   446  }
   447  
   448  //goland:noinspection GoUnusedParameter
   449  func cipherRC4(key, iv []byte, isRead bool) interface{} {
   450  	newCipher, _ := rc4.NewCipher(key)
   451  	return newCipher
   452  }
   453  
   454  func cipher3DES(key, iv []byte, isRead bool) interface{} {
   455  	block, _ := des.NewTripleDESCipher(key)
   456  	if isRead {
   457  		return cipher.NewCBCDecrypter(block, iv)
   458  	}
   459  	return cipher.NewCBCEncrypter(block, iv)
   460  }
   461  
   462  func cipherAES(key, iv []byte, isRead bool) interface{} {
   463  	block, _ := aes.NewCipher(key)
   464  	if isRead {
   465  		return cipher.NewCBCDecrypter(block, iv)
   466  	}
   467  	return cipher.NewCBCEncrypter(block, iv)
   468  }
   469  
   470  // 暂时没有为tls1.2准备国密套件,因此不需要对照 cipherAES 实现 cipherSM4。
   471  // 基于相同原因,下面的 macSHA1 与 macSHA256 同样没有准备对应的 macSM3。
   472  
   473  // macSHA1 returns a SHA-1 based constant time MAC.
   474  func macSHA1(key []byte) hash.Hash {
   475  	return hmac.New(newConstantTimeHash(sha1.New), key)
   476  }
   477  
   478  // macSHA256 returns a SHA-256 based MAC. This is only supported in TLS 1.2 and
   479  // is currently only used in disabled-by-default cipher suites.
   480  func macSHA256(key []byte) hash.Hash {
   481  	return hmac.New(sha256.New, key)
   482  }
   483  
   484  type aead interface {
   485  	cipher.AEAD
   486  
   487  	// explicitNonceLen returns the number of bytes of explicit nonce
   488  	// included in each record. This is eight for older AEADs and
   489  	// zero for modern ones.
   490  	explicitNonceLen() int
   491  }
   492  
   493  const (
   494  	aeadNonceLength   = 12
   495  	noncePrefixLength = 4
   496  )
   497  
   498  // prefixNonceAEAD wraps an AEAD and prefixes a fixed portion of the nonce to
   499  // each call.
   500  type prefixNonceAEAD struct {
   501  	// nonce contains the fixed part of the nonce in the first four bytes.
   502  	nonce [aeadNonceLength]byte
   503  	aead  cipher.AEAD
   504  }
   505  
   506  func (f *prefixNonceAEAD) NonceSize() int        { return aeadNonceLength - noncePrefixLength }
   507  func (f *prefixNonceAEAD) Overhead() int         { return f.aead.Overhead() }
   508  func (f *prefixNonceAEAD) explicitNonceLen() int { return f.NonceSize() }
   509  
   510  func (f *prefixNonceAEAD) Seal(out, nonce, plaintext, additionalData []byte) []byte {
   511  	copy(f.nonce[4:], nonce)
   512  	return f.aead.Seal(out, f.nonce[:], plaintext, additionalData)
   513  }
   514  
   515  func (f *prefixNonceAEAD) Open(out, nonce, ciphertext, additionalData []byte) ([]byte, error) {
   516  	copy(f.nonce[4:], nonce)
   517  	return f.aead.Open(out, f.nonce[:], ciphertext, additionalData)
   518  }
   519  
   520  // xoredNonceAEAD wraps an AEAD by XORing in a fixed pattern to the nonce
   521  // before each call.
   522  type xorNonceAEAD struct {
   523  	nonceMask [aeadNonceLength]byte
   524  	aead      cipher.AEAD
   525  }
   526  
   527  func (f *xorNonceAEAD) NonceSize() int        { return 8 } // 64-bit sequence number
   528  func (f *xorNonceAEAD) Overhead() int         { return f.aead.Overhead() }
   529  func (f *xorNonceAEAD) explicitNonceLen() int { return 0 }
   530  
   531  func (f *xorNonceAEAD) Seal(out, nonce, plaintext, additionalData []byte) []byte {
   532  	for i, b := range nonce {
   533  		f.nonceMask[4+i] ^= b
   534  	}
   535  	result := f.aead.Seal(out, f.nonceMask[:], plaintext, additionalData)
   536  	for i, b := range nonce {
   537  		f.nonceMask[4+i] ^= b
   538  	}
   539  
   540  	return result
   541  }
   542  
   543  func (f *xorNonceAEAD) Open(out, nonce, ciphertext, additionalData []byte) ([]byte, error) {
   544  	for i, b := range nonce {
   545  		f.nonceMask[4+i] ^= b
   546  	}
   547  	result, err := f.aead.Open(out, f.nonceMask[:], ciphertext, additionalData)
   548  	for i, b := range nonce {
   549  		f.nonceMask[4+i] ^= b
   550  	}
   551  
   552  	return result, err
   553  }
   554  
   555  func aeadAESGCM(key, noncePrefix []byte) aead {
   556  	if len(noncePrefix) != noncePrefixLength {
   557  		panic("gmtls: internal error: wrong nonce length")
   558  	}
   559  	newCipher, err := aes.NewCipher(key)
   560  	if err != nil {
   561  		panic(err)
   562  	}
   563  	aead, err := cipher.NewGCM(newCipher)
   564  	if err != nil {
   565  		panic(err)
   566  	}
   567  
   568  	ret := &prefixNonceAEAD{aead: aead}
   569  	copy(ret.nonce[:], noncePrefix)
   570  	return ret
   571  }
   572  
   573  func aeadAESGCMTLS13(key, nonceMask []byte) aead {
   574  	if len(nonceMask) != aeadNonceLength {
   575  		panic("gmtls: internal error: wrong nonce length")
   576  	}
   577  	newCipher, err := aes.NewCipher(key)
   578  	if err != nil {
   579  		panic(err)
   580  	}
   581  	aead, err := cipher.NewGCM(newCipher)
   582  	if err != nil {
   583  		panic(err)
   584  	}
   585  
   586  	ret := &xorNonceAEAD{aead: aead}
   587  	copy(ret.nonceMask[:], nonceMask)
   588  	return ret
   589  }
   590  
   591  // sm4实现AEAD,需要验证
   592  // 只实现 aeadSM4GCMTLS13 没有实现 aeadSM4GCM 同样是因为目前没有为tls1.2准备国密密码套件
   593  func aeadSM4GCMTLS13(key, nonceMask []byte) aead {
   594  	if len(nonceMask) != aeadNonceLength {
   595  		panic("gmtls: internal error: wrong nonce length")
   596  	}
   597  	sm4Cipher, err := sm4.NewCipher(key)
   598  	if err != nil {
   599  		panic(err)
   600  	}
   601  	aead, err := cipher.NewGCM(sm4Cipher)
   602  	if err != nil {
   603  		panic(err)
   604  	}
   605  
   606  	ret := &xorNonceAEAD{aead: aead}
   607  	copy(ret.nonceMask[:], nonceMask)
   608  	return ret
   609  }
   610  
   611  func aeadChaCha20Poly1305(key, nonceMask []byte) aead {
   612  	if len(nonceMask) != aeadNonceLength {
   613  		panic("gmtls: internal error: wrong nonce length")
   614  	}
   615  	aead, err := chacha20poly1305.New(key)
   616  	if err != nil {
   617  		panic(err)
   618  	}
   619  
   620  	ret := &xorNonceAEAD{aead: aead}
   621  	copy(ret.nonceMask[:], nonceMask)
   622  	return ret
   623  }
   624  
   625  type constantTimeHash interface {
   626  	hash.Hash
   627  	ConstantTimeSum(b []byte) []byte
   628  }
   629  
   630  // cthWrapper wraps any hash.Hash that implements ConstantTimeSum, and replaces
   631  // with that all calls to Sum. It's used to obtain a ConstantTimeSum-based HMAC.
   632  type cthWrapper struct {
   633  	h constantTimeHash
   634  }
   635  
   636  func (c *cthWrapper) Size() int                   { return c.h.Size() }
   637  func (c *cthWrapper) BlockSize() int              { return c.h.BlockSize() }
   638  func (c *cthWrapper) Reset()                      { c.h.Reset() }
   639  func (c *cthWrapper) Write(p []byte) (int, error) { return c.h.Write(p) }
   640  func (c *cthWrapper) Sum(b []byte) []byte         { return c.h.ConstantTimeSum(b) }
   641  
   642  func newConstantTimeHash(h func() hash.Hash) func() hash.Hash {
   643  	return func() hash.Hash {
   644  		return &cthWrapper{h().(constantTimeHash)}
   645  	}
   646  }
   647  
   648  // tls10MAC implements the TLS 1.0 MAC function. RFC 2246, Section 6.2.3.
   649  func tls10MAC(h hash.Hash, out, seq, header, data, extra []byte) []byte {
   650  	h.Reset()
   651  	h.Write(seq)
   652  	h.Write(header)
   653  	h.Write(data)
   654  	res := h.Sum(out)
   655  	if extra != nil {
   656  		h.Write(extra)
   657  	}
   658  	return res
   659  }
   660  
   661  //goland:noinspection GoUnusedParameter
   662  func rsaKA(version uint16) keyAgreement {
   663  	return rsaKeyAgreement{}
   664  }
   665  
   666  func ecdheECDSAKA(version uint16) keyAgreement {
   667  	return &ecdheKeyAgreement{
   668  		isRSA:   false,
   669  		version: version,
   670  	}
   671  }
   672  
   673  func ecdheRSAKA(version uint16) keyAgreement {
   674  	return &ecdheKeyAgreement{
   675  		isRSA:   true,
   676  		version: version,
   677  	}
   678  }
   679  
   680  // 从给定的have密码套件列表中匹配want密码套件。
   681  // mutualCipherSuite returns a cipherSuite given a list of supported
   682  // ciphersuites and the id requested by the peer.
   683  func mutualCipherSuite(have []uint16, want uint16) *cipherSuite {
   684  	for _, id := range have {
   685  		if id == want {
   686  			return cipherSuiteByID(id)
   687  		}
   688  	}
   689  	return nil
   690  }
   691  
   692  // 从tls1.0~1.2的密码学套件中根据ID获取对应的密码学套件
   693  func cipherSuiteByID(id uint16) *cipherSuite {
   694  	for _, cipherSuite := range cipherSuites {
   695  		if cipherSuite.id == id {
   696  			return cipherSuite
   697  		}
   698  	}
   699  	return nil
   700  }
   701  
   702  // 协商tls1.3的密码套件
   703  //  - have 己方拥有的密码套件
   704  //  - want 对方需求的密码套件
   705  func mutualCipherSuiteTLS13(have []uint16, want uint16) *cipherSuiteTLS13 {
   706  	for _, id := range have {
   707  		if id == want {
   708  			return cipherSuiteTLS13ByID(id)
   709  		}
   710  	}
   711  	return nil
   712  }
   713  
   714  // 根据id获取tls1.3对应的密码套件
   715  func cipherSuiteTLS13ByID(id uint16) *cipherSuiteTLS13 {
   716  	for _, cipherSuite := range cipherSuitesTLS13 {
   717  		if cipherSuite.id == id {
   718  			return cipherSuite
   719  		}
   720  	}
   721  	return nil
   722  }
   723  
   724  // A list of cipher suite IDs that are, or have been, implemented by this
   725  // package.
   726  //
   727  // See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml
   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  )