github.com/icodeface/tls@v0.0.0-20230910023335-34df9250cd12/key_agreement.go (about)

     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/md5"
    10  	"crypto/rsa"
    11  	"crypto/sha1"
    12  	"crypto/x509"
    13  	"errors"
    14  	"io"
    15  )
    16  
    17  var errClientKeyExchange = errors.New("tls: invalid ClientKeyExchange message")
    18  var errServerKeyExchange = errors.New("tls: invalid ServerKeyExchange message")
    19  
    20  // rsaKeyAgreement implements the standard TLS key agreement where the client
    21  // encrypts the pre-master secret to the server's public key.
    22  type rsaKeyAgreement struct{}
    23  
    24  func (ka rsaKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
    25  	return nil, nil
    26  }
    27  
    28  func (ka rsaKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
    29  	if len(ckx.ciphertext) < 2 {
    30  		return nil, errClientKeyExchange
    31  	}
    32  
    33  	ciphertext := ckx.ciphertext
    34  	if version != VersionSSL30 {
    35  		ciphertextLen := int(ckx.ciphertext[0])<<8 | int(ckx.ciphertext[1])
    36  		if ciphertextLen != len(ckx.ciphertext)-2 {
    37  			return nil, errClientKeyExchange
    38  		}
    39  		ciphertext = ckx.ciphertext[2:]
    40  	}
    41  	priv, ok := cert.PrivateKey.(crypto.Decrypter)
    42  	if !ok {
    43  		return nil, errors.New("tls: certificate private key does not implement crypto.Decrypter")
    44  	}
    45  	// Perform constant time RSA PKCS#1 v1.5 decryption
    46  	preMasterSecret, err := priv.Decrypt(config.rand(), ciphertext, &rsa.PKCS1v15DecryptOptions{SessionKeyLen: 48})
    47  	if err != nil {
    48  		return nil, err
    49  	}
    50  	// We don't check the version number in the premaster secret. For one,
    51  	// by checking it, we would leak information about the validity of the
    52  	// encrypted pre-master secret. Secondly, it provides only a small
    53  	// benefit against a downgrade attack and some implementations send the
    54  	// wrong version anyway. See the discussion at the end of section
    55  	// 7.4.7.1 of RFC 4346.
    56  	return preMasterSecret, nil
    57  }
    58  
    59  func (ka rsaKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
    60  	return errors.New("tls: unexpected ServerKeyExchange")
    61  }
    62  
    63  func (ka rsaKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
    64  	preMasterSecret := make([]byte, 48)
    65  	preMasterSecret[0] = byte(clientHello.vers >> 8)
    66  	preMasterSecret[1] = byte(clientHello.vers)
    67  	_, err := io.ReadFull(config.rand(), preMasterSecret[2:])
    68  	if err != nil {
    69  		return nil, nil, err
    70  	}
    71  
    72  	encrypted, err := rsa.EncryptPKCS1v15(config.rand(), cert.PublicKey.(*rsa.PublicKey), preMasterSecret)
    73  	if err != nil {
    74  		return nil, nil, err
    75  	}
    76  	ckx := new(clientKeyExchangeMsg)
    77  	ckx.ciphertext = make([]byte, len(encrypted)+2)
    78  	ckx.ciphertext[0] = byte(len(encrypted) >> 8)
    79  	ckx.ciphertext[1] = byte(len(encrypted))
    80  	copy(ckx.ciphertext[2:], encrypted)
    81  	return preMasterSecret, ckx, nil
    82  }
    83  
    84  // sha1Hash calculates a SHA1 hash over the given byte slices.
    85  func sha1Hash(slices [][]byte) []byte {
    86  	hsha1 := sha1.New()
    87  	for _, slice := range slices {
    88  		hsha1.Write(slice)
    89  	}
    90  	return hsha1.Sum(nil)
    91  }
    92  
    93  // md5SHA1Hash implements TLS 1.0's hybrid hash function which consists of the
    94  // concatenation of an MD5 and SHA1 hash.
    95  func md5SHA1Hash(slices [][]byte) []byte {
    96  	md5sha1 := make([]byte, md5.Size+sha1.Size)
    97  	hmd5 := md5.New()
    98  	for _, slice := range slices {
    99  		hmd5.Write(slice)
   100  	}
   101  	copy(md5sha1, hmd5.Sum(nil))
   102  	copy(md5sha1[md5.Size:], sha1Hash(slices))
   103  	return md5sha1
   104  }
   105  
   106  // hashForServerKeyExchange hashes the given slices and returns their digest
   107  // using the given hash function (for >= TLS 1.2) or using a default based on
   108  // the sigType (for earlier TLS versions).
   109  func hashForServerKeyExchange(sigType uint8, hashFunc crypto.Hash, version uint16, slices ...[]byte) ([]byte, error) {
   110  	if version >= VersionTLS12 {
   111  		h := hashFunc.New()
   112  		for _, slice := range slices {
   113  			h.Write(slice)
   114  		}
   115  		digest := h.Sum(nil)
   116  		return digest, nil
   117  	}
   118  	if sigType == signatureECDSA {
   119  		return sha1Hash(slices), nil
   120  	}
   121  	return md5SHA1Hash(slices), nil
   122  }
   123  
   124  // ecdheKeyAgreement implements a TLS key agreement where the server
   125  // generates an ephemeral EC public/private key pair and signs it. The
   126  // pre-master secret is then calculated using ECDH. The signature may
   127  // either be ECDSA or RSA.
   128  type ecdheKeyAgreement struct {
   129  	version uint16
   130  	isRSA   bool
   131  	params  ecdheParameters
   132  
   133  	// ckx and preMasterSecret are generated in processServerKeyExchange
   134  	// and returned in generateClientKeyExchange.
   135  	ckx             *clientKeyExchangeMsg
   136  	preMasterSecret []byte
   137  }
   138  
   139  func (ka *ecdheKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
   140  	preferredCurves := config.curvePreferences()
   141  
   142  	var curveID CurveID
   143  NextCandidate:
   144  	for _, candidate := range preferredCurves {
   145  		for _, c := range clientHello.supportedCurves {
   146  			if candidate == c {
   147  				curveID = c
   148  				break NextCandidate
   149  			}
   150  		}
   151  	}
   152  
   153  	if curveID == 0 {
   154  		return nil, errors.New("tls: no supported elliptic curves offered")
   155  	}
   156  	if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok {
   157  		return nil, errors.New("tls: CurvePreferences includes unsupported curve")
   158  	}
   159  
   160  	params, err := generateECDHEParameters(config.rand(), curveID)
   161  	if err != nil {
   162  		return nil, err
   163  	}
   164  	ka.params = params
   165  
   166  	// See RFC 4492, Section 5.4.
   167  	ecdhePublic := params.PublicKey()
   168  	serverECDHParams := make([]byte, 1+2+1+len(ecdhePublic))
   169  	serverECDHParams[0] = 3 // named curve
   170  	serverECDHParams[1] = byte(curveID >> 8)
   171  	serverECDHParams[2] = byte(curveID)
   172  	serverECDHParams[3] = byte(len(ecdhePublic))
   173  	copy(serverECDHParams[4:], ecdhePublic)
   174  
   175  	priv, ok := cert.PrivateKey.(crypto.Signer)
   176  	if !ok {
   177  		return nil, errors.New("tls: certificate private key does not implement crypto.Signer")
   178  	}
   179  
   180  	signatureAlgorithm, sigType, hashFunc, err := pickSignatureAlgorithm(priv.Public(), clientHello.supportedSignatureAlgorithms, supportedSignatureAlgorithmsTLS12, ka.version)
   181  	if err != nil {
   182  		return nil, err
   183  	}
   184  	if (sigType == signaturePKCS1v15 || sigType == signatureRSAPSS) != ka.isRSA {
   185  		return nil, errors.New("tls: certificate cannot be used with the selected cipher suite")
   186  	}
   187  
   188  	digest, err := hashForServerKeyExchange(sigType, hashFunc, ka.version, clientHello.random, hello.random, serverECDHParams)
   189  	if err != nil {
   190  		return nil, err
   191  	}
   192  
   193  	signOpts := crypto.SignerOpts(hashFunc)
   194  	if sigType == signatureRSAPSS {
   195  		signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: hashFunc}
   196  	}
   197  	sig, err := priv.Sign(config.rand(), digest, signOpts)
   198  	if err != nil {
   199  		return nil, errors.New("tls: failed to sign ECDHE parameters: " + err.Error())
   200  	}
   201  
   202  	skx := new(serverKeyExchangeMsg)
   203  	sigAndHashLen := 0
   204  	if ka.version >= VersionTLS12 {
   205  		sigAndHashLen = 2
   206  	}
   207  	skx.key = make([]byte, len(serverECDHParams)+sigAndHashLen+2+len(sig))
   208  	copy(skx.key, serverECDHParams)
   209  	k := skx.key[len(serverECDHParams):]
   210  	if ka.version >= VersionTLS12 {
   211  		k[0] = byte(signatureAlgorithm >> 8)
   212  		k[1] = byte(signatureAlgorithm)
   213  		k = k[2:]
   214  	}
   215  	k[0] = byte(len(sig) >> 8)
   216  	k[1] = byte(len(sig))
   217  	copy(k[2:], sig)
   218  
   219  	return skx, nil
   220  }
   221  
   222  func (ka *ecdheKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
   223  	if len(ckx.ciphertext) == 0 || int(ckx.ciphertext[0]) != len(ckx.ciphertext)-1 {
   224  		return nil, errClientKeyExchange
   225  	}
   226  
   227  	preMasterSecret := ka.params.SharedKey(ckx.ciphertext[1:])
   228  	if preMasterSecret == nil {
   229  		return nil, errClientKeyExchange
   230  	}
   231  
   232  	return preMasterSecret, nil
   233  }
   234  
   235  func (ka *ecdheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
   236  	if len(skx.key) < 4 {
   237  		return errServerKeyExchange
   238  	}
   239  	if skx.key[0] != 3 { // named curve
   240  		return errors.New("tls: server selected unsupported curve")
   241  	}
   242  	curveID := CurveID(skx.key[1])<<8 | CurveID(skx.key[2])
   243  
   244  	publicLen := int(skx.key[3])
   245  	if publicLen+4 > len(skx.key) {
   246  		return errServerKeyExchange
   247  	}
   248  	serverECDHParams := skx.key[:4+publicLen]
   249  	publicKey := serverECDHParams[4:]
   250  
   251  	sig := skx.key[4+publicLen:]
   252  	if len(sig) < 2 {
   253  		return errServerKeyExchange
   254  	}
   255  
   256  	if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok {
   257  		return errors.New("tls: server selected unsupported curve")
   258  	}
   259  
   260  	params, err := generateECDHEParameters(config.rand(), curveID)
   261  	if err != nil {
   262  		return err
   263  	}
   264  	ka.params = params
   265  
   266  	ka.preMasterSecret = params.SharedKey(publicKey)
   267  	if ka.preMasterSecret == nil {
   268  		return errServerKeyExchange
   269  	}
   270  
   271  	ourPublicKey := params.PublicKey()
   272  	ka.ckx = new(clientKeyExchangeMsg)
   273  	ka.ckx.ciphertext = make([]byte, 1+len(ourPublicKey))
   274  	ka.ckx.ciphertext[0] = byte(len(ourPublicKey))
   275  	copy(ka.ckx.ciphertext[1:], ourPublicKey)
   276  
   277  	var signatureAlgorithm SignatureScheme
   278  	if ka.version >= VersionTLS12 {
   279  		// handle SignatureAndHashAlgorithm
   280  		signatureAlgorithm = SignatureScheme(sig[0])<<8 | SignatureScheme(sig[1])
   281  		sig = sig[2:]
   282  		if len(sig) < 2 {
   283  			return errServerKeyExchange
   284  		}
   285  	}
   286  	_, sigType, hashFunc, err := pickSignatureAlgorithm(cert.PublicKey, []SignatureScheme{signatureAlgorithm}, clientHello.supportedSignatureAlgorithms, ka.version)
   287  	if err != nil {
   288  		return err
   289  	}
   290  	if (sigType == signaturePKCS1v15 || sigType == signatureRSAPSS) != ka.isRSA {
   291  		return errServerKeyExchange
   292  	}
   293  
   294  	sigLen := int(sig[0])<<8 | int(sig[1])
   295  	if sigLen+2 != len(sig) {
   296  		return errServerKeyExchange
   297  	}
   298  	sig = sig[2:]
   299  
   300  	digest, err := hashForServerKeyExchange(sigType, hashFunc, ka.version, clientHello.random, serverHello.random, serverECDHParams)
   301  	if err != nil {
   302  		return err
   303  	}
   304  	return verifyHandshakeSignature(sigType, cert.PublicKey, hashFunc, digest, sig)
   305  }
   306  
   307  func (ka *ecdheKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
   308  	if ka.ckx == nil {
   309  		return nil, nil, errors.New("tls: missing ServerKeyExchange message")
   310  	}
   311  
   312  	return ka.preMasterSecret, ka.ckx, nil
   313  }