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