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