github.com/activestate/go@v0.0.0-20170614201249-0b81c023a722/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 a 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:])
   323  	if x == nil {
   324  		return nil, errClientKeyExchange
   325  	}
   326  	if !curve.IsOnCurve(x, y) {
   327  		return nil, errClientKeyExchange
   328  	}
   329  	x, _ = curve.ScalarMult(x, y, ka.privateKey)
   330  	preMasterSecret := make([]byte, (curve.Params().BitSize+7)>>3)
   331  	xBytes := x.Bytes()
   332  	copy(preMasterSecret[len(preMasterSecret)-len(xBytes):], xBytes)
   333  
   334  	return preMasterSecret, nil
   335  }
   336  
   337  func (ka *ecdheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
   338  	if len(skx.key) < 4 {
   339  		return errServerKeyExchange
   340  	}
   341  	if skx.key[0] != 3 { // named curve
   342  		return errors.New("tls: server selected unsupported curve")
   343  	}
   344  	ka.curveid = CurveID(skx.key[1])<<8 | CurveID(skx.key[2])
   345  
   346  	publicLen := int(skx.key[3])
   347  	if publicLen+4 > len(skx.key) {
   348  		return errServerKeyExchange
   349  	}
   350  	serverECDHParams := skx.key[:4+publicLen]
   351  	publicKey := serverECDHParams[4:]
   352  
   353  	sig := skx.key[4+publicLen:]
   354  	if len(sig) < 2 {
   355  		return errServerKeyExchange
   356  	}
   357  
   358  	if ka.curveid == X25519 {
   359  		if len(publicKey) != 32 {
   360  			return errors.New("tls: bad X25519 public value")
   361  		}
   362  		ka.publicKey = publicKey
   363  	} else {
   364  		curve, ok := curveForCurveID(ka.curveid)
   365  		if !ok {
   366  			return errors.New("tls: server selected unsupported curve")
   367  		}
   368  
   369  		ka.x, ka.y = elliptic.Unmarshal(curve, publicKey)
   370  		if ka.x == nil {
   371  			return errServerKeyExchange
   372  		}
   373  		if !curve.IsOnCurve(ka.x, ka.y) {
   374  			return errServerKeyExchange
   375  		}
   376  	}
   377  
   378  	sigAndHash := signatureAndHash{signature: ka.sigType}
   379  	if ka.version >= VersionTLS12 {
   380  		// handle SignatureAndHashAlgorithm
   381  		sigAndHash = signatureAndHash{hash: sig[0], signature: sig[1]}
   382  		if sigAndHash.signature != ka.sigType {
   383  			return errServerKeyExchange
   384  		}
   385  		sig = sig[2:]
   386  		if len(sig) < 2 {
   387  			return errServerKeyExchange
   388  		}
   389  	}
   390  	sigLen := int(sig[0])<<8 | int(sig[1])
   391  	if sigLen+2 != len(sig) {
   392  		return errServerKeyExchange
   393  	}
   394  	sig = sig[2:]
   395  
   396  	digest, hashFunc, err := hashForServerKeyExchange(sigAndHash, ka.version, clientHello.random, serverHello.random, serverECDHParams)
   397  	if err != nil {
   398  		return err
   399  	}
   400  	switch ka.sigType {
   401  	case signatureECDSA:
   402  		pubKey, ok := cert.PublicKey.(*ecdsa.PublicKey)
   403  		if !ok {
   404  			return errors.New("tls: ECDHE ECDSA requires a ECDSA server public key")
   405  		}
   406  		ecdsaSig := new(ecdsaSignature)
   407  		if _, err := asn1.Unmarshal(sig, ecdsaSig); err != nil {
   408  			return err
   409  		}
   410  		if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
   411  			return errors.New("tls: ECDSA signature contained zero or negative values")
   412  		}
   413  		if !ecdsa.Verify(pubKey, digest, ecdsaSig.R, ecdsaSig.S) {
   414  			return errors.New("tls: ECDSA verification failure")
   415  		}
   416  	case signatureRSA:
   417  		pubKey, ok := cert.PublicKey.(*rsa.PublicKey)
   418  		if !ok {
   419  			return errors.New("tls: ECDHE RSA requires a RSA server public key")
   420  		}
   421  		if err := rsa.VerifyPKCS1v15(pubKey, hashFunc, digest, sig); err != nil {
   422  			return err
   423  		}
   424  	default:
   425  		return errors.New("tls: unknown ECDHE signature algorithm")
   426  	}
   427  
   428  	return nil
   429  }
   430  
   431  func (ka *ecdheKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
   432  	if ka.curveid == 0 {
   433  		return nil, nil, errors.New("tls: missing ServerKeyExchange message")
   434  	}
   435  
   436  	var serialized, preMasterSecret []byte
   437  
   438  	if ka.curveid == X25519 {
   439  		var ourPublic, theirPublic, sharedKey, scalar [32]byte
   440  
   441  		if _, err := io.ReadFull(config.rand(), scalar[:]); err != nil {
   442  			return nil, nil, err
   443  		}
   444  
   445  		copy(theirPublic[:], ka.publicKey)
   446  		curve25519.ScalarBaseMult(&ourPublic, &scalar)
   447  		curve25519.ScalarMult(&sharedKey, &scalar, &theirPublic)
   448  		serialized = ourPublic[:]
   449  		preMasterSecret = sharedKey[:]
   450  	} else {
   451  		curve, ok := curveForCurveID(ka.curveid)
   452  		if !ok {
   453  			panic("internal error")
   454  		}
   455  		priv, mx, my, err := elliptic.GenerateKey(curve, config.rand())
   456  		if err != nil {
   457  			return nil, nil, err
   458  		}
   459  		x, _ := curve.ScalarMult(ka.x, ka.y, priv)
   460  		preMasterSecret = make([]byte, (curve.Params().BitSize+7)>>3)
   461  		xBytes := x.Bytes()
   462  		copy(preMasterSecret[len(preMasterSecret)-len(xBytes):], xBytes)
   463  
   464  		serialized = elliptic.Marshal(curve, mx, my)
   465  	}
   466  
   467  	ckx := new(clientKeyExchangeMsg)
   468  	ckx.ciphertext = make([]byte, 1+len(serialized))
   469  	ckx.ciphertext[0] = byte(len(serialized))
   470  	copy(ckx.ciphertext[1:], serialized)
   471  
   472  	return preMasterSecret, ckx, nil
   473  }