...

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/md5"
		10  	"crypto/rsa"
		11  	"crypto/sha1"
		12  	"crypto/x509"
		13  	"errors"
		14  	"fmt"
		15  	"io"
		16  )
		17  
		18  // a keyAgreement implements the client and server side of a TLS key agreement
		19  // protocol by generating and processing key exchange messages.
		20  type keyAgreement interface {
		21  	// On the server side, the first two methods are called in order.
		22  
		23  	// In the case that the key agreement protocol doesn't use a
		24  	// ServerKeyExchange message, generateServerKeyExchange can return nil,
		25  	// nil.
		26  	generateServerKeyExchange(*Config, *Certificate, *clientHelloMsg, *serverHelloMsg) (*serverKeyExchangeMsg, error)
		27  	processClientKeyExchange(*Config, *Certificate, *clientKeyExchangeMsg, uint16) ([]byte, error)
		28  
		29  	// On the client side, the next two methods are called in order.
		30  
		31  	// This method may not be called if the server doesn't send a
		32  	// ServerKeyExchange message.
		33  	processServerKeyExchange(*Config, *clientHelloMsg, *serverHelloMsg, *x509.Certificate, *serverKeyExchangeMsg) error
		34  	generateClientKeyExchange(*Config, *clientHelloMsg, *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error)
		35  }
		36  
		37  var errClientKeyExchange = errors.New("tls: invalid ClientKeyExchange message")
		38  var errServerKeyExchange = errors.New("tls: invalid ServerKeyExchange message")
		39  
		40  // rsaKeyAgreement implements the standard TLS key agreement where the client
		41  // encrypts the pre-master secret to the server's public key.
		42  type rsaKeyAgreement struct{}
		43  
		44  func (ka rsaKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
		45  	return nil, nil
		46  }
		47  
		48  func (ka rsaKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
		49  	if len(ckx.ciphertext) < 2 {
		50  		return nil, errClientKeyExchange
		51  	}
		52  	ciphertextLen := int(ckx.ciphertext[0])<<8 | int(ckx.ciphertext[1])
		53  	if ciphertextLen != len(ckx.ciphertext)-2 {
		54  		return nil, errClientKeyExchange
		55  	}
		56  	ciphertext := ckx.ciphertext[2:]
		57  
		58  	priv, ok := cert.PrivateKey.(crypto.Decrypter)
		59  	if !ok {
		60  		return nil, errors.New("tls: certificate private key does not implement crypto.Decrypter")
		61  	}
		62  	// Perform constant time RSA PKCS #1 v1.5 decryption
		63  	preMasterSecret, err := priv.Decrypt(config.rand(), ciphertext, &rsa.PKCS1v15DecryptOptions{SessionKeyLen: 48})
		64  	if err != nil {
		65  		return nil, err
		66  	}
		67  	// We don't check the version number in the premaster secret. For one,
		68  	// by checking it, we would leak information about the validity of the
		69  	// encrypted pre-master secret. Secondly, it provides only a small
		70  	// benefit against a downgrade attack and some implementations send the
		71  	// wrong version anyway. See the discussion at the end of section
		72  	// 7.4.7.1 of RFC 4346.
		73  	return preMasterSecret, nil
		74  }
		75  
		76  func (ka rsaKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
		77  	return errors.New("tls: unexpected ServerKeyExchange")
		78  }
		79  
		80  func (ka rsaKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
		81  	preMasterSecret := make([]byte, 48)
		82  	preMasterSecret[0] = byte(clientHello.vers >> 8)
		83  	preMasterSecret[1] = byte(clientHello.vers)
		84  	_, err := io.ReadFull(config.rand(), preMasterSecret[2:])
		85  	if err != nil {
		86  		return nil, nil, err
		87  	}
		88  
		89  	rsaKey, ok := cert.PublicKey.(*rsa.PublicKey)
		90  	if !ok {
		91  		return nil, nil, errors.New("tls: server certificate contains incorrect key type for selected ciphersuite")
		92  	}
		93  	encrypted, err := rsa.EncryptPKCS1v15(config.rand(), rsaKey, preMasterSecret)
		94  	if err != nil {
		95  		return nil, nil, err
		96  	}
		97  	ckx := new(clientKeyExchangeMsg)
		98  	ckx.ciphertext = make([]byte, len(encrypted)+2)
		99  	ckx.ciphertext[0] = byte(len(encrypted) >> 8)
	 100  	ckx.ciphertext[1] = byte(len(encrypted))
	 101  	copy(ckx.ciphertext[2:], encrypted)
	 102  	return preMasterSecret, ckx, nil
	 103  }
	 104  
	 105  // sha1Hash calculates a SHA1 hash over the given byte slices.
	 106  func sha1Hash(slices [][]byte) []byte {
	 107  	hsha1 := sha1.New()
	 108  	for _, slice := range slices {
	 109  		hsha1.Write(slice)
	 110  	}
	 111  	return hsha1.Sum(nil)
	 112  }
	 113  
	 114  // md5SHA1Hash implements TLS 1.0's hybrid hash function which consists of the
	 115  // concatenation of an MD5 and SHA1 hash.
	 116  func md5SHA1Hash(slices [][]byte) []byte {
	 117  	md5sha1 := make([]byte, md5.Size+sha1.Size)
	 118  	hmd5 := md5.New()
	 119  	for _, slice := range slices {
	 120  		hmd5.Write(slice)
	 121  	}
	 122  	copy(md5sha1, hmd5.Sum(nil))
	 123  	copy(md5sha1[md5.Size:], sha1Hash(slices))
	 124  	return md5sha1
	 125  }
	 126  
	 127  // hashForServerKeyExchange hashes the given slices and returns their digest
	 128  // using the given hash function (for >= TLS 1.2) or using a default based on
	 129  // the sigType (for earlier TLS versions). For Ed25519 signatures, which don't
	 130  // do pre-hashing, it returns the concatenation of the slices.
	 131  func hashForServerKeyExchange(sigType uint8, hashFunc crypto.Hash, version uint16, slices ...[]byte) []byte {
	 132  	if sigType == signatureEd25519 {
	 133  		var signed []byte
	 134  		for _, slice := range slices {
	 135  			signed = append(signed, slice...)
	 136  		}
	 137  		return signed
	 138  	}
	 139  	if version >= VersionTLS12 {
	 140  		h := hashFunc.New()
	 141  		for _, slice := range slices {
	 142  			h.Write(slice)
	 143  		}
	 144  		digest := h.Sum(nil)
	 145  		return digest
	 146  	}
	 147  	if sigType == signatureECDSA {
	 148  		return sha1Hash(slices)
	 149  	}
	 150  	return md5SHA1Hash(slices)
	 151  }
	 152  
	 153  // ecdheKeyAgreement implements a TLS key agreement where the server
	 154  // generates an ephemeral EC public/private key pair and signs it. The
	 155  // pre-master secret is then calculated using ECDH. The signature may
	 156  // be ECDSA, Ed25519 or RSA.
	 157  type ecdheKeyAgreement struct {
	 158  	version uint16
	 159  	isRSA	 bool
	 160  	params	ecdheParameters
	 161  
	 162  	// ckx and preMasterSecret are generated in processServerKeyExchange
	 163  	// and returned in generateClientKeyExchange.
	 164  	ckx						 *clientKeyExchangeMsg
	 165  	preMasterSecret []byte
	 166  }
	 167  
	 168  func (ka *ecdheKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
	 169  	var curveID CurveID
	 170  	for _, c := range clientHello.supportedCurves {
	 171  		if config.supportsCurve(c) {
	 172  			curveID = c
	 173  			break
	 174  		}
	 175  	}
	 176  
	 177  	if curveID == 0 {
	 178  		return nil, errors.New("tls: no supported elliptic curves offered")
	 179  	}
	 180  	if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok {
	 181  		return nil, errors.New("tls: CurvePreferences includes unsupported curve")
	 182  	}
	 183  
	 184  	params, err := generateECDHEParameters(config.rand(), curveID)
	 185  	if err != nil {
	 186  		return nil, err
	 187  	}
	 188  	ka.params = params
	 189  
	 190  	// See RFC 4492, Section 5.4.
	 191  	ecdhePublic := params.PublicKey()
	 192  	serverECDHEParams := make([]byte, 1+2+1+len(ecdhePublic))
	 193  	serverECDHEParams[0] = 3 // named curve
	 194  	serverECDHEParams[1] = byte(curveID >> 8)
	 195  	serverECDHEParams[2] = byte(curveID)
	 196  	serverECDHEParams[3] = byte(len(ecdhePublic))
	 197  	copy(serverECDHEParams[4:], ecdhePublic)
	 198  
	 199  	priv, ok := cert.PrivateKey.(crypto.Signer)
	 200  	if !ok {
	 201  		return nil, fmt.Errorf("tls: certificate private key of type %T does not implement crypto.Signer", cert.PrivateKey)
	 202  	}
	 203  
	 204  	var signatureAlgorithm SignatureScheme
	 205  	var sigType uint8
	 206  	var sigHash crypto.Hash
	 207  	if ka.version >= VersionTLS12 {
	 208  		signatureAlgorithm, err = selectSignatureScheme(ka.version, cert, clientHello.supportedSignatureAlgorithms)
	 209  		if err != nil {
	 210  			return nil, err
	 211  		}
	 212  		sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm)
	 213  		if err != nil {
	 214  			return nil, err
	 215  		}
	 216  	} else {
	 217  		sigType, sigHash, err = legacyTypeAndHashFromPublicKey(priv.Public())
	 218  		if err != nil {
	 219  			return nil, err
	 220  		}
	 221  	}
	 222  	if (sigType == signaturePKCS1v15 || sigType == signatureRSAPSS) != ka.isRSA {
	 223  		return nil, errors.New("tls: certificate cannot be used with the selected cipher suite")
	 224  	}
	 225  
	 226  	signed := hashForServerKeyExchange(sigType, sigHash, ka.version, clientHello.random, hello.random, serverECDHEParams)
	 227  
	 228  	signOpts := crypto.SignerOpts(sigHash)
	 229  	if sigType == signatureRSAPSS {
	 230  		signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
	 231  	}
	 232  	sig, err := priv.Sign(config.rand(), signed, signOpts)
	 233  	if err != nil {
	 234  		return nil, errors.New("tls: failed to sign ECDHE parameters: " + err.Error())
	 235  	}
	 236  
	 237  	skx := new(serverKeyExchangeMsg)
	 238  	sigAndHashLen := 0
	 239  	if ka.version >= VersionTLS12 {
	 240  		sigAndHashLen = 2
	 241  	}
	 242  	skx.key = make([]byte, len(serverECDHEParams)+sigAndHashLen+2+len(sig))
	 243  	copy(skx.key, serverECDHEParams)
	 244  	k := skx.key[len(serverECDHEParams):]
	 245  	if ka.version >= VersionTLS12 {
	 246  		k[0] = byte(signatureAlgorithm >> 8)
	 247  		k[1] = byte(signatureAlgorithm)
	 248  		k = k[2:]
	 249  	}
	 250  	k[0] = byte(len(sig) >> 8)
	 251  	k[1] = byte(len(sig))
	 252  	copy(k[2:], sig)
	 253  
	 254  	return skx, nil
	 255  }
	 256  
	 257  func (ka *ecdheKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
	 258  	if len(ckx.ciphertext) == 0 || int(ckx.ciphertext[0]) != len(ckx.ciphertext)-1 {
	 259  		return nil, errClientKeyExchange
	 260  	}
	 261  
	 262  	preMasterSecret := ka.params.SharedKey(ckx.ciphertext[1:])
	 263  	if preMasterSecret == nil {
	 264  		return nil, errClientKeyExchange
	 265  	}
	 266  
	 267  	return preMasterSecret, nil
	 268  }
	 269  
	 270  func (ka *ecdheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
	 271  	if len(skx.key) < 4 {
	 272  		return errServerKeyExchange
	 273  	}
	 274  	if skx.key[0] != 3 { // named curve
	 275  		return errors.New("tls: server selected unsupported curve")
	 276  	}
	 277  	curveID := CurveID(skx.key[1])<<8 | CurveID(skx.key[2])
	 278  
	 279  	publicLen := int(skx.key[3])
	 280  	if publicLen+4 > len(skx.key) {
	 281  		return errServerKeyExchange
	 282  	}
	 283  	serverECDHEParams := skx.key[:4+publicLen]
	 284  	publicKey := serverECDHEParams[4:]
	 285  
	 286  	sig := skx.key[4+publicLen:]
	 287  	if len(sig) < 2 {
	 288  		return errServerKeyExchange
	 289  	}
	 290  
	 291  	if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok {
	 292  		return errors.New("tls: server selected unsupported curve")
	 293  	}
	 294  
	 295  	params, err := generateECDHEParameters(config.rand(), curveID)
	 296  	if err != nil {
	 297  		return err
	 298  	}
	 299  	ka.params = params
	 300  
	 301  	ka.preMasterSecret = params.SharedKey(publicKey)
	 302  	if ka.preMasterSecret == nil {
	 303  		return errServerKeyExchange
	 304  	}
	 305  
	 306  	ourPublicKey := params.PublicKey()
	 307  	ka.ckx = new(clientKeyExchangeMsg)
	 308  	ka.ckx.ciphertext = make([]byte, 1+len(ourPublicKey))
	 309  	ka.ckx.ciphertext[0] = byte(len(ourPublicKey))
	 310  	copy(ka.ckx.ciphertext[1:], ourPublicKey)
	 311  
	 312  	var sigType uint8
	 313  	var sigHash crypto.Hash
	 314  	if ka.version >= VersionTLS12 {
	 315  		signatureAlgorithm := SignatureScheme(sig[0])<<8 | SignatureScheme(sig[1])
	 316  		sig = sig[2:]
	 317  		if len(sig) < 2 {
	 318  			return errServerKeyExchange
	 319  		}
	 320  
	 321  		if !isSupportedSignatureAlgorithm(signatureAlgorithm, clientHello.supportedSignatureAlgorithms) {
	 322  			return errors.New("tls: certificate used with invalid signature algorithm")
	 323  		}
	 324  		sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm)
	 325  		if err != nil {
	 326  			return err
	 327  		}
	 328  	} else {
	 329  		sigType, sigHash, err = legacyTypeAndHashFromPublicKey(cert.PublicKey)
	 330  		if err != nil {
	 331  			return err
	 332  		}
	 333  	}
	 334  	if (sigType == signaturePKCS1v15 || sigType == signatureRSAPSS) != ka.isRSA {
	 335  		return errServerKeyExchange
	 336  	}
	 337  
	 338  	sigLen := int(sig[0])<<8 | int(sig[1])
	 339  	if sigLen+2 != len(sig) {
	 340  		return errServerKeyExchange
	 341  	}
	 342  	sig = sig[2:]
	 343  
	 344  	signed := hashForServerKeyExchange(sigType, sigHash, ka.version, clientHello.random, serverHello.random, serverECDHEParams)
	 345  	if err := verifyHandshakeSignature(sigType, cert.PublicKey, sigHash, signed, sig); err != nil {
	 346  		return errors.New("tls: invalid signature by the server certificate: " + err.Error())
	 347  	}
	 348  	return nil
	 349  }
	 350  
	 351  func (ka *ecdheKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
	 352  	if ka.ckx == nil {
	 353  		return nil, nil, errors.New("tls: missing ServerKeyExchange message")
	 354  	}
	 355  
	 356  	return ka.preMasterSecret, ka.ckx, nil
	 357  }
	 358  

View as plain text