Black Lives Matter. Support the Equal Justice Initiative.

Source file src/crypto/tls/key_agreement.go

Documentation: crypto/tls

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

View as plain text