github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/gmtls/key_agreement.go (about)

     1  // Copyright 2022 s1ren@github.com/hxx258456.
     2  
     3  /*
     4  gmtls是基于`golang/go`的`tls`包实现的国密改造版本。
     5  对应版权声明: thrid_licenses/github.com/golang/go/LICENSE
     6  */
     7  
     8  package gmtls
     9  
    10  import (
    11  	"crypto"
    12  	"crypto/md5"
    13  	"crypto/rsa"
    14  	"crypto/sha1"
    15  	"errors"
    16  	"fmt"
    17  	"io"
    18  
    19  	"github.com/hxx258456/ccgo/x509"
    20  )
    21  
    22  // a keyAgreement implements the client and server side of a TLS key agreement
    23  // protocol by generating and processing key exchange messages.
    24  type keyAgreement interface {
    25  	// On the server side, the first two methods are called in order.
    26  
    27  	// In the case that the key agreement protocol doesn't use a
    28  	// ServerKeyExchange message, generateServerKeyExchange can return nil,
    29  	// nil.
    30  	generateServerKeyExchange(*Config, *Certificate, *clientHelloMsg, *serverHelloMsg) (*serverKeyExchangeMsg, error)
    31  	processClientKeyExchange(*Config, *Certificate, *clientKeyExchangeMsg, uint16) ([]byte, error)
    32  
    33  	// On the client side, the next two methods are called in order.
    34  
    35  	// This method may not be called if the server doesn't send a
    36  	// ServerKeyExchange message.
    37  	processServerKeyExchange(*Config, *clientHelloMsg, *serverHelloMsg, *x509.Certificate, *serverKeyExchangeMsg) error
    38  	generateClientKeyExchange(*Config, *clientHelloMsg, *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error)
    39  }
    40  
    41  var errClientKeyExchange = errors.New("gmtls: invalid ClientKeyExchange message")
    42  var errServerKeyExchange = errors.New("gmtls: invalid ServerKeyExchange message")
    43  
    44  // rsaKeyAgreement implements the standard TLS key agreement where the client
    45  // encrypts the pre-master secret to the server's public key.
    46  type rsaKeyAgreement struct{}
    47  
    48  //goland:noinspection GoUnusedParameter
    49  func (ka rsaKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
    50  	return nil, nil
    51  }
    52  
    53  // 处理客户端密钥交换参数(rsa, tls1.2及更老版本)
    54  //
    55  //goland:noinspection GoUnusedParameter
    56  func (ka rsaKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
    57  	if len(ckx.ciphertext) < 2 {
    58  		return nil, errClientKeyExchange
    59  	}
    60  	ciphertextLen := int(ckx.ciphertext[0])<<8 | int(ckx.ciphertext[1])
    61  	if ciphertextLen != len(ckx.ciphertext)-2 {
    62  		return nil, errClientKeyExchange
    63  	}
    64  	ciphertext := ckx.ciphertext[2:]
    65  
    66  	priv, ok := cert.PrivateKey.(crypto.Decrypter)
    67  	if !ok {
    68  		return nil, errors.New("gmtls: certificate private key does not implement crypto.Decrypter")
    69  	}
    70  	// Perform constant time RSA PKCS #1 v1.5 decryption
    71  	preMasterSecret, err := priv.Decrypt(config.rand(), ciphertext, &rsa.PKCS1v15DecryptOptions{SessionKeyLen: 48})
    72  	if err != nil {
    73  		return nil, err
    74  	}
    75  	// We don't check the version number in the premaster secret. For one,
    76  	// by checking it, we would leak information about the validity of the
    77  	// encrypted pre-master secret. Secondly, it provides only a small
    78  	// benefit against a downgrade attack and some implementations send the
    79  	// wrong version anyway. See the discussion at the end of section
    80  	// 7.4.7.1 of RFC 4346.
    81  	return preMasterSecret, nil
    82  }
    83  
    84  // 处理服务端密钥交换参数(rsa, tls1.2及更老版本)
    85  //
    86  //goland:noinspection GoUnusedParameter
    87  func (ka rsaKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
    88  	return errors.New("gmtls: unexpected ServerKeyExchange")
    89  }
    90  
    91  //goland:noinspection GoUnusedParameter
    92  func (ka rsaKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
    93  	preMasterSecret := make([]byte, 48)
    94  	preMasterSecret[0] = byte(clientHello.vers >> 8)
    95  	preMasterSecret[1] = byte(clientHello.vers)
    96  	_, err := io.ReadFull(config.rand(), preMasterSecret[2:])
    97  	if err != nil {
    98  		return nil, nil, err
    99  	}
   100  
   101  	rsaKey, ok := cert.PublicKey.(*rsa.PublicKey)
   102  	if !ok {
   103  		return nil, nil, errors.New("gmtls: server certificate contains incorrect key type for selected ciphersuite")
   104  	}
   105  	encrypted, err := rsa.EncryptPKCS1v15(config.rand(), rsaKey, preMasterSecret)
   106  	if err != nil {
   107  		return nil, nil, err
   108  	}
   109  	ckx := new(clientKeyExchangeMsg)
   110  	ckx.ciphertext = make([]byte, len(encrypted)+2)
   111  	ckx.ciphertext[0] = byte(len(encrypted) >> 8)
   112  	ckx.ciphertext[1] = byte(len(encrypted))
   113  	copy(ckx.ciphertext[2:], encrypted)
   114  	return preMasterSecret, ckx, nil
   115  }
   116  
   117  // sha1Hash calculates a SHA1 hash over the given byte slices.
   118  func sha1Hash(slices [][]byte) []byte {
   119  	hsha1 := sha1.New()
   120  	for _, slice := range slices {
   121  		hsha1.Write(slice)
   122  	}
   123  	return hsha1.Sum(nil)
   124  }
   125  
   126  // md5SHA1Hash implements TLS 1.0's hybrid hash function which consists of the
   127  // concatenation of an MD5 and SHA1 hash.
   128  func md5SHA1Hash(slices [][]byte) []byte {
   129  	md5sha1 := make([]byte, md5.Size+sha1.Size)
   130  	hmd5 := md5.New()
   131  	for _, slice := range slices {
   132  		hmd5.Write(slice)
   133  	}
   134  	copy(md5sha1, hmd5.Sum(nil))
   135  	copy(md5sha1[md5.Size:], sha1Hash(slices))
   136  	return md5sha1
   137  }
   138  
   139  // hashForServerKeyExchange hashes the given slices and returns their digest
   140  // using the given hash function (for >= TLS 1.2) or using a default based on
   141  // the sigType (for earlier TLS versions). For Ed25519 signatures, which don't
   142  // do pre-hashing, it returns the concatenation of the slices.
   143  func hashForServerKeyExchange(sigType uint8, hashFunc x509.Hash, version uint16, slices ...[]byte) []byte {
   144  	if sigType == signatureEd25519 {
   145  		var signed []byte
   146  		for _, slice := range slices {
   147  			signed = append(signed, slice...)
   148  		}
   149  		return signed
   150  	}
   151  	// 添加国密分支
   152  	if version >= VersionTLS12 || version == VersionGMSSL {
   153  		h := hashFunc.New()
   154  		for _, slice := range slices {
   155  			h.Write(slice)
   156  		}
   157  		digest := h.Sum(nil)
   158  		return digest
   159  	}
   160  	if sigType == signatureECDSA {
   161  		return sha1Hash(slices)
   162  	}
   163  	return md5SHA1Hash(slices)
   164  }
   165  
   166  // ecdheKeyAgreement implements a TLS key agreement where the server
   167  // generates an ephemeral EC public/private key pair and signs it. The
   168  // pre-master secret is then calculated using ECDH. The signature may
   169  // be ECDSA, Ed25519 or RSA.
   170  type ecdheKeyAgreement struct {
   171  	version uint16
   172  	isRSA   bool
   173  	// TODO: 需要先改造 gmtls/key_schedule.go
   174  	params ecdheParameters
   175  
   176  	// ckx and preMasterSecret are generated in processServerKeyExchange
   177  	// and returned in generateClientKeyExchange.
   178  	ckx             *clientKeyExchangeMsg
   179  	preMasterSecret []byte
   180  }
   181  
   182  func (ka *ecdheKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
   183  	var curveID CurveID
   184  	for _, c := range clientHello.supportedCurves {
   185  		if config.supportsCurve(c) {
   186  			curveID = c
   187  			break
   188  		}
   189  	}
   190  
   191  	if curveID == 0 {
   192  		return nil, errors.New("gmtls: no supported elliptic curves offered")
   193  	}
   194  	if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok {
   195  		return nil, errors.New("gmtls: CurvePreferences includes unsupported curve")
   196  	}
   197  
   198  	params, err := generateECDHEParameters(config.rand(), curveID)
   199  	if err != nil {
   200  		return nil, err
   201  	}
   202  	ka.params = params
   203  
   204  	// See RFC 4492, Section 5.4.
   205  	ecdhePublic := params.PublicKey()
   206  	serverECDHEParams := make([]byte, 1+2+1+len(ecdhePublic))
   207  	serverECDHEParams[0] = 3 // named curve
   208  	serverECDHEParams[1] = byte(curveID >> 8)
   209  	serverECDHEParams[2] = byte(curveID)
   210  	serverECDHEParams[3] = byte(len(ecdhePublic))
   211  	copy(serverECDHEParams[4:], ecdhePublic)
   212  
   213  	priv, ok := cert.PrivateKey.(crypto.Signer)
   214  	if !ok {
   215  		return nil, fmt.Errorf("gmtls: certificate private key of type %T does not implement crypto.Signer", cert.PrivateKey)
   216  	}
   217  
   218  	var signatureAlgorithm SignatureScheme
   219  	var sigType uint8
   220  	var sigHash x509.Hash
   221  	if ka.version >= VersionTLS12 {
   222  		signatureAlgorithm, err = selectSignatureScheme(ka.version, cert, clientHello.supportedSignatureAlgorithms)
   223  		if err != nil {
   224  			return nil, err
   225  		}
   226  		sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm)
   227  		if err != nil {
   228  			return nil, err
   229  		}
   230  	} else {
   231  		sigType, sigHash, err = legacyTypeAndHashFromPublicKey(priv.Public())
   232  		if err != nil {
   233  			return nil, err
   234  		}
   235  	}
   236  	if (sigType == signaturePKCS1v15 || sigType == signatureRSAPSS) != ka.isRSA {
   237  		return nil, errors.New("gmtls: certificate cannot be used with the selected cipher suite")
   238  	}
   239  
   240  	signed := hashForServerKeyExchange(sigType, sigHash, ka.version, clientHello.random, hello.random, serverECDHEParams)
   241  
   242  	signOpts := crypto.SignerOpts(sigHash)
   243  	if sigType == signatureRSAPSS {
   244  		signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash.HashFunc()}
   245  	}
   246  	sig, err := priv.Sign(config.rand(), signed, signOpts)
   247  	if err != nil {
   248  		return nil, errors.New("gmtls: failed to sign ECDHE parameters: " + err.Error())
   249  	}
   250  
   251  	skx := new(serverKeyExchangeMsg)
   252  	sigAndHashLen := 0
   253  	if ka.version >= VersionTLS12 {
   254  		sigAndHashLen = 2
   255  	}
   256  	skx.key = make([]byte, len(serverECDHEParams)+sigAndHashLen+2+len(sig))
   257  	copy(skx.key, serverECDHEParams)
   258  	k := skx.key[len(serverECDHEParams):]
   259  	if ka.version >= VersionTLS12 {
   260  		k[0] = byte(signatureAlgorithm >> 8)
   261  		k[1] = byte(signatureAlgorithm)
   262  		k = k[2:]
   263  	}
   264  	k[0] = byte(len(sig) >> 8)
   265  	k[1] = byte(len(sig))
   266  	copy(k[2:], sig)
   267  
   268  	return skx, nil
   269  }
   270  
   271  // 处理客户端密钥交换参数(ecdhe, tls1.2)
   272  //
   273  //goland:noinspection GoUnusedParameter
   274  func (ka *ecdheKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
   275  	if len(ckx.ciphertext) == 0 || int(ckx.ciphertext[0]) != len(ckx.ciphertext)-1 {
   276  		return nil, errClientKeyExchange
   277  	}
   278  
   279  	preMasterSecret := ka.params.SharedKey(ckx.ciphertext[1:])
   280  	if preMasterSecret == nil {
   281  		return nil, errClientKeyExchange
   282  	}
   283  
   284  	return preMasterSecret, nil
   285  }
   286  
   287  // 处理服务端密钥交换参数(ecdhe, tls1.2)
   288  //
   289  //goland:noinspection GoUnusedParameter
   290  func (ka *ecdheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
   291  	if len(skx.key) < 4 {
   292  		return errServerKeyExchange
   293  	}
   294  	if skx.key[0] != 3 { // named curve
   295  		return errors.New("gmtls: server selected unsupported curve")
   296  	}
   297  	curveID := CurveID(skx.key[1])<<8 | CurveID(skx.key[2])
   298  
   299  	publicLen := int(skx.key[3])
   300  	if publicLen+4 > len(skx.key) {
   301  		return errServerKeyExchange
   302  	}
   303  	serverECDHEParams := skx.key[:4+publicLen]
   304  	publicKey := serverECDHEParams[4:]
   305  
   306  	sig := skx.key[4+publicLen:]
   307  	if len(sig) < 2 {
   308  		return errServerKeyExchange
   309  	}
   310  
   311  	if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok {
   312  		return errors.New("gmtls: server selected unsupported curve")
   313  	}
   314  
   315  	params, err := generateECDHEParameters(config.rand(), curveID)
   316  	if err != nil {
   317  		return err
   318  	}
   319  	ka.params = params
   320  
   321  	ka.preMasterSecret = params.SharedKey(publicKey)
   322  	if ka.preMasterSecret == nil {
   323  		return errServerKeyExchange
   324  	}
   325  
   326  	ourPublicKey := params.PublicKey()
   327  	ka.ckx = new(clientKeyExchangeMsg)
   328  	ka.ckx.ciphertext = make([]byte, 1+len(ourPublicKey))
   329  	ka.ckx.ciphertext[0] = byte(len(ourPublicKey))
   330  	copy(ka.ckx.ciphertext[1:], ourPublicKey)
   331  
   332  	var sigType uint8
   333  	var sigHash x509.Hash
   334  	if ka.version >= VersionTLS12 {
   335  		signatureAlgorithm := SignatureScheme(sig[0])<<8 | SignatureScheme(sig[1])
   336  		sig = sig[2:]
   337  		if len(sig) < 2 {
   338  			return errServerKeyExchange
   339  		}
   340  
   341  		if !isSupportedSignatureAlgorithm(signatureAlgorithm, clientHello.supportedSignatureAlgorithms) {
   342  			return errors.New("gmtls: certificate used with invalid signature algorithm")
   343  		}
   344  		sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm)
   345  		if err != nil {
   346  			return err
   347  		}
   348  	} else {
   349  		sigType, sigHash, err = legacyTypeAndHashFromPublicKey(cert.PublicKey)
   350  		if err != nil {
   351  			return err
   352  		}
   353  	}
   354  	if (sigType == signaturePKCS1v15 || sigType == signatureRSAPSS) != ka.isRSA {
   355  		return errServerKeyExchange
   356  	}
   357  
   358  	sigLen := int(sig[0])<<8 | int(sig[1])
   359  	if sigLen+2 != len(sig) {
   360  		return errServerKeyExchange
   361  	}
   362  	sig = sig[2:]
   363  
   364  	signed := hashForServerKeyExchange(sigType, sigHash, ka.version, clientHello.random, serverHello.random, serverECDHEParams)
   365  	if err := verifyHandshakeSignature(sigType, cert.PublicKey, sigHash, signed, sig); err != nil {
   366  		return errors.New("gmtls: invalid signature by the server certificate: " + err.Error())
   367  	}
   368  	return nil
   369  }
   370  
   371  func (ka *ecdheKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
   372  	if ka.ckx == nil {
   373  		return nil, nil, errors.New("gmtls: missing ServerKeyExchange message")
   374  	}
   375  
   376  	return ka.preMasterSecret, ka.ckx, nil
   377  }