github.com/mattn/go@v0.0.0-20171011075504-07f7db3ea99f/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 sigAndHash argument is
   114  // only used for >= TLS 1.2 and precisely identifies the hash function to use.
   115  func hashForServerKeyExchange(sigAndHash signatureAndHash, version uint16, slices ...[]byte) ([]byte, crypto.Hash, error) {
   116  	if version >= VersionTLS12 {
   117  		if !isSupportedSignatureAndHash(sigAndHash, supportedSignatureAlgorithms) {
   118  			return nil, crypto.Hash(0), errors.New("tls: unsupported hash function used by peer")
   119  		}
   120  		hashFunc, err := lookupTLSHash(sigAndHash.hash)
   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 sigAndHash.signature == 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 []signatureAndHash) (uint8, 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  		return hashSHA1, nil
   146  	}
   147  
   148  	for _, sigAndHash := range clientList {
   149  		if sigAndHash.signature != sigType {
   150  			continue
   151  		}
   152  		if isSupportedSignatureAndHash(sigAndHash, supportedSignatureAlgorithms) {
   153  			return sigAndHash.hash, nil
   154  		}
   155  	}
   156  
   157  	return 0, errors.New("tls: client doesn't support any common hash functions")
   158  }
   159  
   160  func curveForCurveID(id CurveID) (elliptic.Curve, bool) {
   161  	switch id {
   162  	case CurveP256:
   163  		return elliptic.P256(), true
   164  	case CurveP384:
   165  		return elliptic.P384(), true
   166  	case CurveP521:
   167  		return elliptic.P521(), true
   168  	default:
   169  		return nil, false
   170  	}
   171  
   172  }
   173  
   174  // ecdheRSAKeyAgreement implements a TLS key agreement where the server
   175  // generates an ephemeral EC public/private key pair and signs it. The
   176  // pre-master secret is then calculated using ECDH. The signature may
   177  // either be ECDSA or RSA.
   178  type ecdheKeyAgreement struct {
   179  	version    uint16
   180  	sigType    uint8
   181  	privateKey []byte
   182  	curveid    CurveID
   183  
   184  	// publicKey is used to store the peer's public value when X25519 is
   185  	// being used.
   186  	publicKey []byte
   187  	// x and y are used to store the peer's public value when one of the
   188  	// NIST curves is being used.
   189  	x, y *big.Int
   190  }
   191  
   192  func (ka *ecdheKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
   193  	preferredCurves := config.curvePreferences()
   194  
   195  NextCandidate:
   196  	for _, candidate := range preferredCurves {
   197  		for _, c := range clientHello.supportedCurves {
   198  			if candidate == c {
   199  				ka.curveid = c
   200  				break NextCandidate
   201  			}
   202  		}
   203  	}
   204  
   205  	if ka.curveid == 0 {
   206  		return nil, errors.New("tls: no supported elliptic curves offered")
   207  	}
   208  
   209  	var ecdhePublic []byte
   210  
   211  	if ka.curveid == X25519 {
   212  		var scalar, public [32]byte
   213  		if _, err := io.ReadFull(config.rand(), scalar[:]); err != nil {
   214  			return nil, err
   215  		}
   216  
   217  		curve25519.ScalarBaseMult(&public, &scalar)
   218  		ka.privateKey = scalar[:]
   219  		ecdhePublic = public[:]
   220  	} else {
   221  		curve, ok := curveForCurveID(ka.curveid)
   222  		if !ok {
   223  			return nil, errors.New("tls: preferredCurves includes unsupported curve")
   224  		}
   225  
   226  		var x, y *big.Int
   227  		var err error
   228  		ka.privateKey, x, y, err = elliptic.GenerateKey(curve, config.rand())
   229  		if err != nil {
   230  			return nil, err
   231  		}
   232  		ecdhePublic = elliptic.Marshal(curve, x, y)
   233  	}
   234  
   235  	// http://tools.ietf.org/html/rfc4492#section-5.4
   236  	serverECDHParams := make([]byte, 1+2+1+len(ecdhePublic))
   237  	serverECDHParams[0] = 3 // named curve
   238  	serverECDHParams[1] = byte(ka.curveid >> 8)
   239  	serverECDHParams[2] = byte(ka.curveid)
   240  	serverECDHParams[3] = byte(len(ecdhePublic))
   241  	copy(serverECDHParams[4:], ecdhePublic)
   242  
   243  	sigAndHash := signatureAndHash{signature: ka.sigType}
   244  
   245  	if ka.version >= VersionTLS12 {
   246  		var err error
   247  		if sigAndHash.hash, err = pickTLS12HashForSignature(ka.sigType, clientHello.signatureAndHashes); err != nil {
   248  			return nil, err
   249  		}
   250  	}
   251  
   252  	digest, hashFunc, err := hashForServerKeyExchange(sigAndHash, ka.version, clientHello.random, hello.random, serverECDHParams)
   253  	if err != nil {
   254  		return nil, err
   255  	}
   256  
   257  	priv, ok := cert.PrivateKey.(crypto.Signer)
   258  	if !ok {
   259  		return nil, errors.New("tls: certificate private key does not implement crypto.Signer")
   260  	}
   261  	var sig []byte
   262  	switch ka.sigType {
   263  	case signatureECDSA:
   264  		_, ok := priv.Public().(*ecdsa.PublicKey)
   265  		if !ok {
   266  			return nil, errors.New("tls: ECDHE ECDSA requires an ECDSA server key")
   267  		}
   268  	case signatureRSA:
   269  		_, ok := priv.Public().(*rsa.PublicKey)
   270  		if !ok {
   271  			return nil, errors.New("tls: ECDHE RSA requires a RSA server key")
   272  		}
   273  	default:
   274  		return nil, errors.New("tls: unknown ECDHE signature algorithm")
   275  	}
   276  	sig, err = priv.Sign(config.rand(), digest, hashFunc)
   277  	if err != nil {
   278  		return nil, errors.New("tls: failed to sign ECDHE parameters: " + err.Error())
   279  	}
   280  
   281  	skx := new(serverKeyExchangeMsg)
   282  	sigAndHashLen := 0
   283  	if ka.version >= VersionTLS12 {
   284  		sigAndHashLen = 2
   285  	}
   286  	skx.key = make([]byte, len(serverECDHParams)+sigAndHashLen+2+len(sig))
   287  	copy(skx.key, serverECDHParams)
   288  	k := skx.key[len(serverECDHParams):]
   289  	if ka.version >= VersionTLS12 {
   290  		k[0] = sigAndHash.hash
   291  		k[1] = sigAndHash.signature
   292  		k = k[2:]
   293  	}
   294  	k[0] = byte(len(sig) >> 8)
   295  	k[1] = byte(len(sig))
   296  	copy(k[2:], sig)
   297  
   298  	return skx, nil
   299  }
   300  
   301  func (ka *ecdheKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
   302  	if len(ckx.ciphertext) == 0 || int(ckx.ciphertext[0]) != len(ckx.ciphertext)-1 {
   303  		return nil, errClientKeyExchange
   304  	}
   305  
   306  	if ka.curveid == X25519 {
   307  		if len(ckx.ciphertext) != 1+32 {
   308  			return nil, errClientKeyExchange
   309  		}
   310  
   311  		var theirPublic, sharedKey, scalar [32]byte
   312  		copy(theirPublic[:], ckx.ciphertext[1:])
   313  		copy(scalar[:], ka.privateKey)
   314  		curve25519.ScalarMult(&sharedKey, &scalar, &theirPublic)
   315  		return sharedKey[:], nil
   316  	}
   317  
   318  	curve, ok := curveForCurveID(ka.curveid)
   319  	if !ok {
   320  		panic("internal error")
   321  	}
   322  	x, y := elliptic.Unmarshal(curve, ckx.ciphertext[1:]) // Unmarshal also checks whether the given point is on the curve
   323  	if x == nil {
   324  		return nil, errClientKeyExchange
   325  	}
   326  	x, _ = curve.ScalarMult(x, y, ka.privateKey)
   327  	preMasterSecret := make([]byte, (curve.Params().BitSize+7)>>3)
   328  	xBytes := x.Bytes()
   329  	copy(preMasterSecret[len(preMasterSecret)-len(xBytes):], xBytes)
   330  
   331  	return preMasterSecret, nil
   332  }
   333  
   334  func (ka *ecdheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
   335  	if len(skx.key) < 4 {
   336  		return errServerKeyExchange
   337  	}
   338  	if skx.key[0] != 3 { // named curve
   339  		return errors.New("tls: server selected unsupported curve")
   340  	}
   341  	ka.curveid = CurveID(skx.key[1])<<8 | CurveID(skx.key[2])
   342  
   343  	publicLen := int(skx.key[3])
   344  	if publicLen+4 > len(skx.key) {
   345  		return errServerKeyExchange
   346  	}
   347  	serverECDHParams := skx.key[:4+publicLen]
   348  	publicKey := serverECDHParams[4:]
   349  
   350  	sig := skx.key[4+publicLen:]
   351  	if len(sig) < 2 {
   352  		return errServerKeyExchange
   353  	}
   354  
   355  	if ka.curveid == X25519 {
   356  		if len(publicKey) != 32 {
   357  			return errors.New("tls: bad X25519 public value")
   358  		}
   359  		ka.publicKey = publicKey
   360  	} else {
   361  		curve, ok := curveForCurveID(ka.curveid)
   362  		if !ok {
   363  			return errors.New("tls: server selected unsupported curve")
   364  		}
   365  		ka.x, ka.y = elliptic.Unmarshal(curve, publicKey) // Unmarshal also checks whether the given point is on the curve
   366  		if ka.x == nil {
   367  			return errServerKeyExchange
   368  		}
   369  	}
   370  
   371  	sigAndHash := signatureAndHash{signature: ka.sigType}
   372  	if ka.version >= VersionTLS12 {
   373  		// handle SignatureAndHashAlgorithm
   374  		sigAndHash = signatureAndHash{hash: sig[0], signature: sig[1]}
   375  		if sigAndHash.signature != ka.sigType {
   376  			return errServerKeyExchange
   377  		}
   378  		sig = sig[2:]
   379  		if len(sig) < 2 {
   380  			return errServerKeyExchange
   381  		}
   382  	}
   383  	sigLen := int(sig[0])<<8 | int(sig[1])
   384  	if sigLen+2 != len(sig) {
   385  		return errServerKeyExchange
   386  	}
   387  	sig = sig[2:]
   388  
   389  	digest, hashFunc, err := hashForServerKeyExchange(sigAndHash, ka.version, clientHello.random, serverHello.random, serverECDHParams)
   390  	if err != nil {
   391  		return err
   392  	}
   393  	switch ka.sigType {
   394  	case signatureECDSA:
   395  		pubKey, ok := cert.PublicKey.(*ecdsa.PublicKey)
   396  		if !ok {
   397  			return errors.New("tls: ECDHE ECDSA requires a ECDSA server public key")
   398  		}
   399  		ecdsaSig := new(ecdsaSignature)
   400  		if _, err := asn1.Unmarshal(sig, ecdsaSig); err != nil {
   401  			return err
   402  		}
   403  		if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
   404  			return errors.New("tls: ECDSA signature contained zero or negative values")
   405  		}
   406  		if !ecdsa.Verify(pubKey, digest, ecdsaSig.R, ecdsaSig.S) {
   407  			return errors.New("tls: ECDSA verification failure")
   408  		}
   409  	case signatureRSA:
   410  		pubKey, ok := cert.PublicKey.(*rsa.PublicKey)
   411  		if !ok {
   412  			return errors.New("tls: ECDHE RSA requires a RSA server public key")
   413  		}
   414  		if err := rsa.VerifyPKCS1v15(pubKey, hashFunc, digest, sig); err != nil {
   415  			return err
   416  		}
   417  	default:
   418  		return errors.New("tls: unknown ECDHE signature algorithm")
   419  	}
   420  
   421  	return nil
   422  }
   423  
   424  func (ka *ecdheKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
   425  	if ka.curveid == 0 {
   426  		return nil, nil, errors.New("tls: missing ServerKeyExchange message")
   427  	}
   428  
   429  	var serialized, preMasterSecret []byte
   430  
   431  	if ka.curveid == X25519 {
   432  		var ourPublic, theirPublic, sharedKey, scalar [32]byte
   433  
   434  		if _, err := io.ReadFull(config.rand(), scalar[:]); err != nil {
   435  			return nil, nil, err
   436  		}
   437  
   438  		copy(theirPublic[:], ka.publicKey)
   439  		curve25519.ScalarBaseMult(&ourPublic, &scalar)
   440  		curve25519.ScalarMult(&sharedKey, &scalar, &theirPublic)
   441  		serialized = ourPublic[:]
   442  		preMasterSecret = sharedKey[:]
   443  	} else {
   444  		curve, ok := curveForCurveID(ka.curveid)
   445  		if !ok {
   446  			panic("internal error")
   447  		}
   448  		priv, mx, my, err := elliptic.GenerateKey(curve, config.rand())
   449  		if err != nil {
   450  			return nil, nil, err
   451  		}
   452  		x, _ := curve.ScalarMult(ka.x, ka.y, priv)
   453  		preMasterSecret = make([]byte, (curve.Params().BitSize+7)>>3)
   454  		xBytes := x.Bytes()
   455  		copy(preMasterSecret[len(preMasterSecret)-len(xBytes):], xBytes)
   456  
   457  		serialized = elliptic.Marshal(curve, mx, my)
   458  	}
   459  
   460  	ckx := new(clientKeyExchangeMsg)
   461  	ckx.ciphertext = make([]byte, 1+len(serialized))
   462  	ckx.ciphertext[0] = byte(len(serialized))
   463  	copy(ckx.ciphertext[1:], serialized)
   464  
   465  	return preMasterSecret, ckx, nil
   466  }