...
Run Format

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/elliptic"
    10  	"crypto/md5"
    11  	"crypto/rsa"
    12  	"crypto/sha1"
    13  	"crypto/x509"
    14  	"errors"
    15  	"io"
    16  	"math/big"
    17  
    18  	"golang_org/x/crypto/curve25519"
    19  )
    20  
    21  var errClientKeyExchange = errors.New("tls: invalid ClientKeyExchange message")
    22  var errServerKeyExchange = errors.New("tls: invalid ServerKeyExchange message")
    23  
    24  // rsaKeyAgreement implements the standard TLS key agreement where the client
    25  // encrypts the pre-master secret to the server's public key.
    26  type rsaKeyAgreement struct{}
    27  
    28  func (ka rsaKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
    29  	return nil, nil
    30  }
    31  
    32  func (ka rsaKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
    33  	if len(ckx.ciphertext) < 2 {
    34  		return nil, errClientKeyExchange
    35  	}
    36  
    37  	ciphertext := ckx.ciphertext
    38  	if version != VersionSSL30 {
    39  		ciphertextLen := int(ckx.ciphertext[0])<<8 | int(ckx.ciphertext[1])
    40  		if ciphertextLen != len(ckx.ciphertext)-2 {
    41  			return nil, errClientKeyExchange
    42  		}
    43  		ciphertext = ckx.ciphertext[2:]
    44  	}
    45  	priv, ok := cert.PrivateKey.(crypto.Decrypter)
    46  	if !ok {
    47  		return nil, errors.New("tls: certificate private key does not implement crypto.Decrypter")
    48  	}
    49  	// Perform constant time RSA PKCS#1 v1.5 decryption
    50  	preMasterSecret, err := priv.Decrypt(config.rand(), ciphertext, &rsa.PKCS1v15DecryptOptions{SessionKeyLen: 48})
    51  	if err != nil {
    52  		return nil, err
    53  	}
    54  	// We don't check the version number in the premaster secret. For one,
    55  	// by checking it, we would leak information about the validity of the
    56  	// encrypted pre-master secret. Secondly, it provides only a small
    57  	// benefit against a downgrade attack and some implementations send the
    58  	// wrong version anyway. See the discussion at the end of section
    59  	// 7.4.7.1 of RFC 4346.
    60  	return preMasterSecret, nil
    61  }
    62  
    63  func (ka rsaKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
    64  	return errors.New("tls: unexpected ServerKeyExchange")
    65  }
    66  
    67  func (ka rsaKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
    68  	preMasterSecret := make([]byte, 48)
    69  	preMasterSecret[0] = byte(clientHello.vers >> 8)
    70  	preMasterSecret[1] = byte(clientHello.vers)
    71  	_, err := io.ReadFull(config.rand(), preMasterSecret[2:])
    72  	if err != nil {
    73  		return nil, nil, err
    74  	}
    75  
    76  	encrypted, err := rsa.EncryptPKCS1v15(config.rand(), cert.PublicKey.(*rsa.PublicKey), preMasterSecret)
    77  	if err != nil {
    78  		return nil, nil, err
    79  	}
    80  	ckx := new(clientKeyExchangeMsg)
    81  	ckx.ciphertext = make([]byte, len(encrypted)+2)
    82  	ckx.ciphertext[0] = byte(len(encrypted) >> 8)
    83  	ckx.ciphertext[1] = byte(len(encrypted))
    84  	copy(ckx.ciphertext[2:], encrypted)
    85  	return preMasterSecret, ckx, nil
    86  }
    87  
    88  // sha1Hash calculates a SHA1 hash over the given byte slices.
    89  func sha1Hash(slices [][]byte) []byte {
    90  	hsha1 := sha1.New()
    91  	for _, slice := range slices {
    92  		hsha1.Write(slice)
    93  	}
    94  	return hsha1.Sum(nil)
    95  }
    96  
    97  // md5SHA1Hash implements TLS 1.0's hybrid hash function which consists of the
    98  // concatenation of an MD5 and SHA1 hash.
    99  func md5SHA1Hash(slices [][]byte) []byte {
   100  	md5sha1 := make([]byte, md5.Size+sha1.Size)
   101  	hmd5 := md5.New()
   102  	for _, slice := range slices {
   103  		hmd5.Write(slice)
   104  	}
   105  	copy(md5sha1, hmd5.Sum(nil))
   106  	copy(md5sha1[md5.Size:], sha1Hash(slices))
   107  	return md5sha1
   108  }
   109  
   110  // hashForServerKeyExchange hashes the given slices and returns their digest
   111  // using the given hash function (for >= TLS 1.2) or using a default based on
   112  // the sigType (for earlier TLS versions).
   113  func hashForServerKeyExchange(sigType uint8, hashFunc crypto.Hash, version uint16, slices ...[]byte) ([]byte, error) {
   114  	if version >= VersionTLS12 {
   115  		h := hashFunc.New()
   116  		for _, slice := range slices {
   117  			h.Write(slice)
   118  		}
   119  		digest := h.Sum(nil)
   120  		return digest, nil
   121  	}
   122  	if sigType == signatureECDSA {
   123  		return sha1Hash(slices), nil
   124  	}
   125  	return md5SHA1Hash(slices), nil
   126  }
   127  
   128  func curveForCurveID(id CurveID) (elliptic.Curve, bool) {
   129  	switch id {
   130  	case CurveP256:
   131  		return elliptic.P256(), true
   132  	case CurveP384:
   133  		return elliptic.P384(), true
   134  	case CurveP521:
   135  		return elliptic.P521(), true
   136  	default:
   137  		return nil, false
   138  	}
   139  
   140  }
   141  
   142  // ecdheKeyAgreement implements a TLS key agreement where the server
   143  // generates an ephemeral EC public/private key pair and signs it. The
   144  // pre-master secret is then calculated using ECDH. The signature may
   145  // either be ECDSA or RSA.
   146  type ecdheKeyAgreement struct {
   147  	version    uint16
   148  	isRSA      bool
   149  	privateKey []byte
   150  	curveid    CurveID
   151  
   152  	// publicKey is used to store the peer's public value when X25519 is
   153  	// being used.
   154  	publicKey []byte
   155  	// x and y are used to store the peer's public value when one of the
   156  	// NIST curves is being used.
   157  	x, y *big.Int
   158  }
   159  
   160  func (ka *ecdheKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
   161  	preferredCurves := config.curvePreferences()
   162  
   163  NextCandidate:
   164  	for _, candidate := range preferredCurves {
   165  		for _, c := range clientHello.supportedCurves {
   166  			if candidate == c {
   167  				ka.curveid = c
   168  				break NextCandidate
   169  			}
   170  		}
   171  	}
   172  
   173  	if ka.curveid == 0 {
   174  		return nil, errors.New("tls: no supported elliptic curves offered")
   175  	}
   176  
   177  	var ecdhePublic []byte
   178  
   179  	if ka.curveid == X25519 {
   180  		var scalar, public [32]byte
   181  		if _, err := io.ReadFull(config.rand(), scalar[:]); err != nil {
   182  			return nil, err
   183  		}
   184  
   185  		curve25519.ScalarBaseMult(&public, &scalar)
   186  		ka.privateKey = scalar[:]
   187  		ecdhePublic = public[:]
   188  	} else {
   189  		curve, ok := curveForCurveID(ka.curveid)
   190  		if !ok {
   191  			return nil, errors.New("tls: preferredCurves includes unsupported curve")
   192  		}
   193  
   194  		var x, y *big.Int
   195  		var err error
   196  		ka.privateKey, x, y, err = elliptic.GenerateKey(curve, config.rand())
   197  		if err != nil {
   198  			return nil, err
   199  		}
   200  		ecdhePublic = elliptic.Marshal(curve, x, y)
   201  	}
   202  
   203  	// https://tools.ietf.org/html/rfc4492#section-5.4
   204  	serverECDHParams := make([]byte, 1+2+1+len(ecdhePublic))
   205  	serverECDHParams[0] = 3 // named curve
   206  	serverECDHParams[1] = byte(ka.curveid >> 8)
   207  	serverECDHParams[2] = byte(ka.curveid)
   208  	serverECDHParams[3] = byte(len(ecdhePublic))
   209  	copy(serverECDHParams[4:], ecdhePublic)
   210  
   211  	priv, ok := cert.PrivateKey.(crypto.Signer)
   212  	if !ok {
   213  		return nil, errors.New("tls: certificate private key does not implement crypto.Signer")
   214  	}
   215  
   216  	signatureAlgorithm, sigType, hashFunc, err := pickSignatureAlgorithm(priv.Public(), clientHello.supportedSignatureAlgorithms, supportedSignatureAlgorithms, ka.version)
   217  	if err != nil {
   218  		return nil, err
   219  	}
   220  	if (sigType == signaturePKCS1v15 || sigType == signatureRSAPSS) != ka.isRSA {
   221  		return nil, errors.New("tls: certificate cannot be used with the selected cipher suite")
   222  	}
   223  
   224  	digest, err := hashForServerKeyExchange(sigType, hashFunc, ka.version, clientHello.random, hello.random, serverECDHParams)
   225  	if err != nil {
   226  		return nil, err
   227  	}
   228  
   229  	signOpts := crypto.SignerOpts(hashFunc)
   230  	if sigType == signatureRSAPSS {
   231  		signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: hashFunc}
   232  	}
   233  	sig, err := priv.Sign(config.rand(), digest, signOpts)
   234  	if err != nil {
   235  		return nil, errors.New("tls: failed to sign ECDHE parameters: " + err.Error())
   236  	}
   237  
   238  	skx := new(serverKeyExchangeMsg)
   239  	sigAndHashLen := 0
   240  	if ka.version >= VersionTLS12 {
   241  		sigAndHashLen = 2
   242  	}
   243  	skx.key = make([]byte, len(serverECDHParams)+sigAndHashLen+2+len(sig))
   244  	copy(skx.key, serverECDHParams)
   245  	k := skx.key[len(serverECDHParams):]
   246  	if ka.version >= VersionTLS12 {
   247  		k[0] = byte(signatureAlgorithm >> 8)
   248  		k[1] = byte(signatureAlgorithm)
   249  		k = k[2:]
   250  	}
   251  	k[0] = byte(len(sig) >> 8)
   252  	k[1] = byte(len(sig))
   253  	copy(k[2:], sig)
   254  
   255  	return skx, nil
   256  }
   257  
   258  func (ka *ecdheKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
   259  	if len(ckx.ciphertext) == 0 || int(ckx.ciphertext[0]) != len(ckx.ciphertext)-1 {
   260  		return nil, errClientKeyExchange
   261  	}
   262  
   263  	if ka.curveid == X25519 {
   264  		if len(ckx.ciphertext) != 1+32 {
   265  			return nil, errClientKeyExchange
   266  		}
   267  
   268  		var theirPublic, sharedKey, scalar [32]byte
   269  		copy(theirPublic[:], ckx.ciphertext[1:])
   270  		copy(scalar[:], ka.privateKey)
   271  		curve25519.ScalarMult(&sharedKey, &scalar, &theirPublic)
   272  		return sharedKey[:], nil
   273  	}
   274  
   275  	curve, ok := curveForCurveID(ka.curveid)
   276  	if !ok {
   277  		panic("internal error")
   278  	}
   279  	x, y := elliptic.Unmarshal(curve, ckx.ciphertext[1:]) // Unmarshal also checks whether the given point is on the curve
   280  	if x == nil {
   281  		return nil, errClientKeyExchange
   282  	}
   283  	x, _ = curve.ScalarMult(x, y, ka.privateKey)
   284  	preMasterSecret := make([]byte, (curve.Params().BitSize+7)>>3)
   285  	xBytes := x.Bytes()
   286  	copy(preMasterSecret[len(preMasterSecret)-len(xBytes):], xBytes)
   287  
   288  	return preMasterSecret, nil
   289  }
   290  
   291  func (ka *ecdheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
   292  	if len(skx.key) < 4 {
   293  		return errServerKeyExchange
   294  	}
   295  	if skx.key[0] != 3 { // named curve
   296  		return errors.New("tls: server selected unsupported curve")
   297  	}
   298  	ka.curveid = CurveID(skx.key[1])<<8 | CurveID(skx.key[2])
   299  
   300  	publicLen := int(skx.key[3])
   301  	if publicLen+4 > len(skx.key) {
   302  		return errServerKeyExchange
   303  	}
   304  	serverECDHParams := skx.key[:4+publicLen]
   305  	publicKey := serverECDHParams[4:]
   306  
   307  	sig := skx.key[4+publicLen:]
   308  	if len(sig) < 2 {
   309  		return errServerKeyExchange
   310  	}
   311  
   312  	if ka.curveid == X25519 {
   313  		if len(publicKey) != 32 {
   314  			return errors.New("tls: bad X25519 public value")
   315  		}
   316  		ka.publicKey = publicKey
   317  	} else {
   318  		curve, ok := curveForCurveID(ka.curveid)
   319  		if !ok {
   320  			return errors.New("tls: server selected unsupported curve")
   321  		}
   322  		ka.x, ka.y = elliptic.Unmarshal(curve, publicKey) // Unmarshal also checks whether the given point is on the curve
   323  		if ka.x == nil {
   324  			return errServerKeyExchange
   325  		}
   326  	}
   327  
   328  	var signatureAlgorithm SignatureScheme
   329  	if ka.version >= VersionTLS12 {
   330  		// handle SignatureAndHashAlgorithm
   331  		signatureAlgorithm = SignatureScheme(sig[0])<<8 | SignatureScheme(sig[1])
   332  		sig = sig[2:]
   333  		if len(sig) < 2 {
   334  			return errServerKeyExchange
   335  		}
   336  	}
   337  	_, sigType, hashFunc, err := pickSignatureAlgorithm(cert.PublicKey, []SignatureScheme{signatureAlgorithm}, clientHello.supportedSignatureAlgorithms, ka.version)
   338  	if err != nil {
   339  		return err
   340  	}
   341  	if (sigType == signaturePKCS1v15 || sigType == signatureRSAPSS) != ka.isRSA {
   342  		return errServerKeyExchange
   343  	}
   344  
   345  	sigLen := int(sig[0])<<8 | int(sig[1])
   346  	if sigLen+2 != len(sig) {
   347  		return errServerKeyExchange
   348  	}
   349  	sig = sig[2:]
   350  
   351  	digest, err := hashForServerKeyExchange(sigType, hashFunc, ka.version, clientHello.random, serverHello.random, serverECDHParams)
   352  	if err != nil {
   353  		return err
   354  	}
   355  	return verifyHandshakeSignature(sigType, cert.PublicKey, hashFunc, digest, sig)
   356  }
   357  
   358  func (ka *ecdheKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
   359  	if ka.curveid == 0 {
   360  		return nil, nil, errors.New("tls: missing ServerKeyExchange message")
   361  	}
   362  
   363  	var serialized, preMasterSecret []byte
   364  
   365  	if ka.curveid == X25519 {
   366  		var ourPublic, theirPublic, sharedKey, scalar [32]byte
   367  
   368  		if _, err := io.ReadFull(config.rand(), scalar[:]); err != nil {
   369  			return nil, nil, err
   370  		}
   371  
   372  		copy(theirPublic[:], ka.publicKey)
   373  		curve25519.ScalarBaseMult(&ourPublic, &scalar)
   374  		curve25519.ScalarMult(&sharedKey, &scalar, &theirPublic)
   375  		serialized = ourPublic[:]
   376  		preMasterSecret = sharedKey[:]
   377  	} else {
   378  		curve, ok := curveForCurveID(ka.curveid)
   379  		if !ok {
   380  			panic("internal error")
   381  		}
   382  		priv, mx, my, err := elliptic.GenerateKey(curve, config.rand())
   383  		if err != nil {
   384  			return nil, nil, err
   385  		}
   386  		x, _ := curve.ScalarMult(ka.x, ka.y, priv)
   387  		preMasterSecret = make([]byte, (curve.Params().BitSize+7)>>3)
   388  		xBytes := x.Bytes()
   389  		copy(preMasterSecret[len(preMasterSecret)-len(xBytes):], xBytes)
   390  
   391  		serialized = elliptic.Marshal(curve, mx, my)
   392  	}
   393  
   394  	ckx := new(clientKeyExchangeMsg)
   395  	ckx.ciphertext = make([]byte, 1+len(serialized))
   396  	ckx.ciphertext[0] = byte(len(serialized))
   397  	copy(ckx.ciphertext[1:], serialized)
   398  
   399  	return preMasterSecret, ckx, nil
   400  }
   401  

View as plain text