• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
5package runner
6
7import (
8	"crypto"
9	"crypto/ecdsa"
10	"crypto/elliptic"
11	"crypto/rsa"
12	"crypto/subtle"
13	"crypto/x509"
14	"errors"
15	"fmt"
16	"io"
17	"math/big"
18
19	"boringssl.googlesource.com/boringssl/ssl/test/runner/curve25519"
20	"boringssl.googlesource.com/boringssl/ssl/test/runner/ed25519"
21	"boringssl.googlesource.com/boringssl/ssl/test/runner/hrss"
22)
23
24type keyType int
25
26const (
27	keyTypeRSA keyType = iota + 1
28	keyTypeECDSA
29)
30
31var errClientKeyExchange = errors.New("tls: invalid ClientKeyExchange message")
32var errServerKeyExchange = errors.New("tls: invalid ServerKeyExchange message")
33
34// rsaKeyAgreement implements the standard TLS key agreement where the client
35// encrypts the pre-master secret to the server's public key.
36type rsaKeyAgreement struct {
37	version       uint16
38	clientVersion uint16
39	exportKey     *rsa.PrivateKey
40}
41
42func (ka *rsaKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg, version uint16) (*serverKeyExchangeMsg, error) {
43	// Save the client version for comparison later.
44	ka.clientVersion = clientHello.vers
45
46	if !config.Bugs.RSAEphemeralKey {
47		return nil, nil
48	}
49
50	// Generate an ephemeral RSA key to use instead of the real
51	// one, as in RSA_EXPORT.
52	key, err := rsa.GenerateKey(config.rand(), 512)
53	if err != nil {
54		return nil, err
55	}
56	ka.exportKey = key
57
58	modulus := key.N.Bytes()
59	exponent := big.NewInt(int64(key.E)).Bytes()
60	serverRSAParams := make([]byte, 0, 2+len(modulus)+2+len(exponent))
61	serverRSAParams = append(serverRSAParams, byte(len(modulus)>>8), byte(len(modulus)))
62	serverRSAParams = append(serverRSAParams, modulus...)
63	serverRSAParams = append(serverRSAParams, byte(len(exponent)>>8), byte(len(exponent)))
64	serverRSAParams = append(serverRSAParams, exponent...)
65
66	var sigAlg signatureAlgorithm
67	if ka.version >= VersionTLS12 {
68		sigAlg, err = selectSignatureAlgorithm(ka.version, cert.PrivateKey, config, clientHello.signatureAlgorithms)
69		if err != nil {
70			return nil, err
71		}
72	}
73
74	sig, err := signMessage(ka.version, cert.PrivateKey, config, sigAlg, serverRSAParams)
75	if err != nil {
76		return nil, errors.New("failed to sign RSA parameters: " + err.Error())
77	}
78
79	skx := new(serverKeyExchangeMsg)
80	sigAlgsLen := 0
81	if ka.version >= VersionTLS12 {
82		sigAlgsLen = 2
83	}
84	skx.key = make([]byte, len(serverRSAParams)+sigAlgsLen+2+len(sig))
85	copy(skx.key, serverRSAParams)
86	k := skx.key[len(serverRSAParams):]
87	if ka.version >= VersionTLS12 {
88		k[0] = byte(sigAlg >> 8)
89		k[1] = byte(sigAlg)
90		k = k[2:]
91	}
92	k[0] = byte(len(sig) >> 8)
93	k[1] = byte(len(sig))
94	copy(k[2:], sig)
95
96	return skx, nil
97}
98
99func (ka *rsaKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
100	preMasterSecret := make([]byte, 48)
101	_, err := io.ReadFull(config.rand(), preMasterSecret[2:])
102	if err != nil {
103		return nil, err
104	}
105
106	if len(ckx.ciphertext) < 2 {
107		return nil, errClientKeyExchange
108	}
109
110	ciphertext := ckx.ciphertext
111	if version != VersionSSL30 {
112		ciphertextLen := int(ckx.ciphertext[0])<<8 | int(ckx.ciphertext[1])
113		if ciphertextLen != len(ckx.ciphertext)-2 {
114			return nil, errClientKeyExchange
115		}
116		ciphertext = ckx.ciphertext[2:]
117	}
118
119	key := cert.PrivateKey.(*rsa.PrivateKey)
120	if ka.exportKey != nil {
121		key = ka.exportKey
122	}
123	err = rsa.DecryptPKCS1v15SessionKey(config.rand(), key, ciphertext, preMasterSecret)
124	if err != nil {
125		return nil, err
126	}
127	// This check should be done in constant-time, but this is a testing
128	// implementation. See the discussion at the end of section 7.4.7.1 of
129	// RFC 4346.
130	vers := uint16(preMasterSecret[0])<<8 | uint16(preMasterSecret[1])
131	if ka.clientVersion != vers {
132		return nil, fmt.Errorf("tls: invalid version in RSA premaster (got %04x, wanted %04x)", vers, ka.clientVersion)
133	}
134	return preMasterSecret, nil
135}
136
137func (ka *rsaKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, key crypto.PublicKey, skx *serverKeyExchangeMsg) error {
138	return errors.New("tls: unexpected ServerKeyExchange")
139}
140
141func rsaSize(pub *rsa.PublicKey) int {
142	return (pub.N.BitLen() + 7) / 8
143}
144
145func rsaRawEncrypt(pub *rsa.PublicKey, msg []byte) ([]byte, error) {
146	k := rsaSize(pub)
147	if len(msg) != k {
148		return nil, errors.New("tls: bad padded RSA input")
149	}
150	m := new(big.Int).SetBytes(msg)
151	e := big.NewInt(int64(pub.E))
152	m.Exp(m, e, pub.N)
153	unpadded := m.Bytes()
154	ret := make([]byte, k)
155	copy(ret[len(ret)-len(unpadded):], unpadded)
156	return ret, nil
157}
158
159// nonZeroRandomBytes fills the given slice with non-zero random octets.
160func nonZeroRandomBytes(s []byte, rand io.Reader) {
161	if _, err := io.ReadFull(rand, s); err != nil {
162		panic(err)
163	}
164
165	for i := range s {
166		for s[i] == 0 {
167			if _, err := io.ReadFull(rand, s[i:i+1]); err != nil {
168				panic(err)
169			}
170		}
171	}
172}
173
174func (ka *rsaKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
175	bad := config.Bugs.BadRSAClientKeyExchange
176	preMasterSecret := make([]byte, 48)
177	vers := clientHello.vers
178	if bad == RSABadValueWrongVersion1 {
179		vers ^= 1
180	} else if bad == RSABadValueWrongVersion2 {
181		vers ^= 0x100
182	}
183	preMasterSecret[0] = byte(vers >> 8)
184	preMasterSecret[1] = byte(vers)
185	_, err := io.ReadFull(config.rand(), preMasterSecret[2:])
186	if err != nil {
187		return nil, nil, err
188	}
189
190	sentPreMasterSecret := preMasterSecret
191	if bad == RSABadValueTooLong {
192		sentPreMasterSecret = make([]byte, 1, len(sentPreMasterSecret)+1)
193		sentPreMasterSecret = append(sentPreMasterSecret, preMasterSecret...)
194	} else if bad == RSABadValueTooShort {
195		sentPreMasterSecret = sentPreMasterSecret[:len(sentPreMasterSecret)-1]
196	}
197
198	// Pad for PKCS#1 v1.5.
199	padded := make([]byte, rsaSize(cert.PublicKey.(*rsa.PublicKey)))
200	padded[1] = 2
201	nonZeroRandomBytes(padded[2:len(padded)-len(sentPreMasterSecret)-1], config.rand())
202	copy(padded[len(padded)-len(sentPreMasterSecret):], sentPreMasterSecret)
203
204	if bad == RSABadValueWrongBlockType {
205		padded[1] = 3
206	} else if bad == RSABadValueWrongLeadingByte {
207		padded[0] = 1
208	} else if bad == RSABadValueNoZero {
209		for i := 2; i < len(padded); i++ {
210			if padded[i] == 0 {
211				padded[i]++
212			}
213		}
214	}
215
216	encrypted, err := rsaRawEncrypt(cert.PublicKey.(*rsa.PublicKey), padded)
217	if err != nil {
218		return nil, nil, err
219	}
220	if bad == RSABadValueCorrupt {
221		encrypted[len(encrypted)-1] ^= 1
222		// Clear the high byte to ensure |encrypted| is still below the RSA modulus.
223		encrypted[0] = 0
224	}
225	ckx := new(clientKeyExchangeMsg)
226	if ka.version != VersionSSL30 {
227		ckx.ciphertext = make([]byte, len(encrypted)+2)
228		ckx.ciphertext[0] = byte(len(encrypted) >> 8)
229		ckx.ciphertext[1] = byte(len(encrypted))
230		copy(ckx.ciphertext[2:], encrypted)
231	} else {
232		ckx.ciphertext = encrypted
233	}
234	return preMasterSecret, ckx, nil
235}
236
237func (ka *rsaKeyAgreement) peerSignatureAlgorithm() signatureAlgorithm {
238	return 0
239}
240
241// A ecdhCurve is an instance of ECDH-style key agreement for TLS.
242type ecdhCurve interface {
243	// offer generates a keypair using rand. It returns the encoded |publicKey|.
244	offer(rand io.Reader) (publicKey []byte, err error)
245
246	// accept responds to the |peerKey| generated by |offer| with the acceptor's
247	// |publicKey|, and returns agreed-upon |preMasterSecret| to the acceptor.
248	accept(rand io.Reader, peerKey []byte) (publicKey []byte, preMasterSecret []byte, err error)
249
250	// finish returns the computed |preMasterSecret|, given the |peerKey|
251	// generated by |accept|.
252	finish(peerKey []byte) (preMasterSecret []byte, err error)
253}
254
255// ellipticECDHCurve implements ecdhCurve with an elliptic.Curve.
256type ellipticECDHCurve struct {
257	curve          elliptic.Curve
258	privateKey     []byte
259	sendCompressed bool
260}
261
262func (e *ellipticECDHCurve) offer(rand io.Reader) (publicKey []byte, err error) {
263	var x, y *big.Int
264	e.privateKey, x, y, err = elliptic.GenerateKey(e.curve, rand)
265	if err != nil {
266		return nil, err
267	}
268	ret := elliptic.Marshal(e.curve, x, y)
269	if e.sendCompressed {
270		l := (len(ret) - 1) / 2
271		tmp := make([]byte, 1+l)
272		tmp[0] = byte(2 | y.Bit(0))
273		copy(tmp[1:], ret[1:1+l])
274		ret = tmp
275	}
276	return ret, nil
277}
278
279func (e *ellipticECDHCurve) accept(rand io.Reader, peerKey []byte) (publicKey []byte, preMasterSecret []byte, err error) {
280	publicKey, err = e.offer(rand)
281	if err != nil {
282		return nil, nil, err
283	}
284	preMasterSecret, err = e.finish(peerKey)
285	if err != nil {
286		return nil, nil, err
287	}
288	return
289}
290
291func (e *ellipticECDHCurve) finish(peerKey []byte) (preMasterSecret []byte, err error) {
292	x, y := elliptic.Unmarshal(e.curve, peerKey)
293	if x == nil {
294		return nil, errors.New("tls: invalid peer key")
295	}
296	x, _ = e.curve.ScalarMult(x, y, e.privateKey)
297	preMasterSecret = make([]byte, (e.curve.Params().BitSize+7)>>3)
298	xBytes := x.Bytes()
299	copy(preMasterSecret[len(preMasterSecret)-len(xBytes):], xBytes)
300
301	return preMasterSecret, nil
302}
303
304// x25519ECDHCurve implements ecdhCurve with X25519.
305type x25519ECDHCurve struct {
306	privateKey [32]byte
307	setHighBit bool
308}
309
310func (e *x25519ECDHCurve) offer(rand io.Reader) (publicKey []byte, err error) {
311	_, err = io.ReadFull(rand, e.privateKey[:])
312	if err != nil {
313		return
314	}
315	var out [32]byte
316	curve25519.ScalarBaseMult(&out, &e.privateKey)
317	if e.setHighBit {
318		out[31] |= 0x80
319	}
320	return out[:], nil
321}
322
323func (e *x25519ECDHCurve) accept(rand io.Reader, peerKey []byte) (publicKey []byte, preMasterSecret []byte, err error) {
324	publicKey, err = e.offer(rand)
325	if err != nil {
326		return nil, nil, err
327	}
328	preMasterSecret, err = e.finish(peerKey)
329	if err != nil {
330		return nil, nil, err
331	}
332	return
333}
334
335func (e *x25519ECDHCurve) finish(peerKey []byte) (preMasterSecret []byte, err error) {
336	if len(peerKey) != 32 {
337		return nil, errors.New("tls: invalid peer key")
338	}
339	var out, peerKeyCopy [32]byte
340	copy(peerKeyCopy[:], peerKey)
341	curve25519.ScalarMult(&out, &e.privateKey, &peerKeyCopy)
342
343	// Per RFC 7748, reject the all-zero value in constant time.
344	var zeros [32]byte
345	if subtle.ConstantTimeCompare(zeros[:], out[:]) == 1 {
346		return nil, errors.New("tls: X25519 value with wrong order")
347	}
348
349	return out[:], nil
350}
351
352// cecpq2Curve implements CECPQ2, which is HRSS+SXY combined with X25519.
353type cecpq2Curve struct {
354	x25519PrivateKey [32]byte
355	hrssPrivateKey   hrss.PrivateKey
356}
357
358func (e *cecpq2Curve) offer(rand io.Reader) (publicKey []byte, err error) {
359	if _, err := io.ReadFull(rand, e.x25519PrivateKey[:]); err != nil {
360		return nil, err
361	}
362
363	var x25519Public [32]byte
364	curve25519.ScalarBaseMult(&x25519Public, &e.x25519PrivateKey)
365
366	e.hrssPrivateKey = hrss.GenerateKey(rand)
367	hrssPublic := e.hrssPrivateKey.PublicKey.Marshal()
368
369	var ret []byte
370	ret = append(ret, x25519Public[:]...)
371	ret = append(ret, hrssPublic...)
372	return ret, nil
373}
374
375func (e *cecpq2Curve) accept(rand io.Reader, peerKey []byte) (publicKey []byte, preMasterSecret []byte, err error) {
376	if len(peerKey) != 32+hrss.PublicKeySize {
377		return nil, nil, errors.New("tls: bad length CECPQ2 offer")
378	}
379
380	if _, err := io.ReadFull(rand, e.x25519PrivateKey[:]); err != nil {
381		return nil, nil, err
382	}
383
384	var x25519Shared, x25519PeerKey, x25519Public [32]byte
385	copy(x25519PeerKey[:], peerKey)
386	curve25519.ScalarBaseMult(&x25519Public, &e.x25519PrivateKey)
387	curve25519.ScalarMult(&x25519Shared, &e.x25519PrivateKey, &x25519PeerKey)
388
389	// Per RFC 7748, reject the all-zero value in constant time.
390	var zeros [32]byte
391	if subtle.ConstantTimeCompare(zeros[:], x25519Shared[:]) == 1 {
392		return nil, nil, errors.New("tls: X25519 value with wrong order")
393	}
394
395	hrssPublicKey, ok := hrss.ParsePublicKey(peerKey[32:])
396	if !ok {
397		return nil, nil, errors.New("tls: bad CECPQ2 offer")
398	}
399
400	hrssCiphertext, hrssShared := hrssPublicKey.Encap(rand)
401
402	publicKey = append(publicKey, x25519Public[:]...)
403	publicKey = append(publicKey, hrssCiphertext...)
404	preMasterSecret = append(preMasterSecret, x25519Shared[:]...)
405	preMasterSecret = append(preMasterSecret, hrssShared...)
406
407	return publicKey, preMasterSecret, nil
408}
409
410func (e *cecpq2Curve) finish(peerKey []byte) (preMasterSecret []byte, err error) {
411	if len(peerKey) != 32+hrss.CiphertextSize {
412		return nil, errors.New("tls: bad length CECPQ2 reply")
413	}
414
415	var x25519Shared, x25519PeerKey [32]byte
416	copy(x25519PeerKey[:], peerKey)
417	curve25519.ScalarMult(&x25519Shared, &e.x25519PrivateKey, &x25519PeerKey)
418
419	// Per RFC 7748, reject the all-zero value in constant time.
420	var zeros [32]byte
421	if subtle.ConstantTimeCompare(zeros[:], x25519Shared[:]) == 1 {
422		return nil, errors.New("tls: X25519 value with wrong order")
423	}
424
425	hrssShared, ok := e.hrssPrivateKey.Decap(peerKey[32:])
426	if !ok {
427		return nil, errors.New("tls: invalid HRSS ciphertext")
428	}
429
430	preMasterSecret = append(preMasterSecret, x25519Shared[:]...)
431	preMasterSecret = append(preMasterSecret, hrssShared...)
432
433	return preMasterSecret, nil
434}
435
436func curveForCurveID(id CurveID, config *Config) (ecdhCurve, bool) {
437	switch id {
438	case CurveP224:
439		return &ellipticECDHCurve{curve: elliptic.P224(), sendCompressed: config.Bugs.SendCompressedCoordinates}, true
440	case CurveP256:
441		return &ellipticECDHCurve{curve: elliptic.P256(), sendCompressed: config.Bugs.SendCompressedCoordinates}, true
442	case CurveP384:
443		return &ellipticECDHCurve{curve: elliptic.P384(), sendCompressed: config.Bugs.SendCompressedCoordinates}, true
444	case CurveP521:
445		return &ellipticECDHCurve{curve: elliptic.P521(), sendCompressed: config.Bugs.SendCompressedCoordinates}, true
446	case CurveX25519:
447		return &x25519ECDHCurve{setHighBit: config.Bugs.SetX25519HighBit}, true
448	case CurveCECPQ2:
449		return &cecpq2Curve{}, true
450	default:
451		return nil, false
452	}
453
454}
455
456// keyAgreementAuthentication is a helper interface that specifies how
457// to authenticate the ServerKeyExchange parameters.
458type keyAgreementAuthentication interface {
459	signParameters(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg, params []byte) (*serverKeyExchangeMsg, error)
460	verifyParameters(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, key crypto.PublicKey, params []byte, sig []byte) error
461}
462
463// nilKeyAgreementAuthentication does not authenticate the key
464// agreement parameters.
465type nilKeyAgreementAuthentication struct{}
466
467func (ka *nilKeyAgreementAuthentication) signParameters(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg, params []byte) (*serverKeyExchangeMsg, error) {
468	skx := new(serverKeyExchangeMsg)
469	skx.key = params
470	return skx, nil
471}
472
473func (ka *nilKeyAgreementAuthentication) verifyParameters(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, key crypto.PublicKey, params []byte, sig []byte) error {
474	return nil
475}
476
477// signedKeyAgreement signs the ServerKeyExchange parameters with the
478// server's private key.
479type signedKeyAgreement struct {
480	keyType                keyType
481	version                uint16
482	peerSignatureAlgorithm signatureAlgorithm
483}
484
485func (ka *signedKeyAgreement) signParameters(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg, params []byte) (*serverKeyExchangeMsg, error) {
486	// The message to be signed is prepended by the randoms.
487	var msg []byte
488	msg = append(msg, clientHello.random...)
489	msg = append(msg, hello.random...)
490	msg = append(msg, params...)
491
492	var sigAlg signatureAlgorithm
493	var err error
494	if ka.version >= VersionTLS12 {
495		sigAlg, err = selectSignatureAlgorithm(ka.version, cert.PrivateKey, config, clientHello.signatureAlgorithms)
496		if err != nil {
497			return nil, err
498		}
499	}
500
501	sig, err := signMessage(ka.version, cert.PrivateKey, config, sigAlg, msg)
502	if err != nil {
503		return nil, err
504	}
505	if config.Bugs.SendSignatureAlgorithm != 0 {
506		sigAlg = config.Bugs.SendSignatureAlgorithm
507	}
508
509	skx := new(serverKeyExchangeMsg)
510	if config.Bugs.UnauthenticatedECDH {
511		skx.key = params
512	} else {
513		sigAlgsLen := 0
514		if ka.version >= VersionTLS12 {
515			sigAlgsLen = 2
516		}
517		skx.key = make([]byte, len(params)+sigAlgsLen+2+len(sig))
518		copy(skx.key, params)
519		k := skx.key[len(params):]
520		if ka.version >= VersionTLS12 {
521			k[0] = byte(sigAlg >> 8)
522			k[1] = byte(sigAlg)
523			k = k[2:]
524		}
525		k[0] = byte(len(sig) >> 8)
526		k[1] = byte(len(sig))
527		copy(k[2:], sig)
528	}
529
530	return skx, nil
531}
532
533func (ka *signedKeyAgreement) verifyParameters(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, publicKey crypto.PublicKey, params []byte, sig []byte) error {
534	// The peer's key must match the cipher type.
535	switch ka.keyType {
536	case keyTypeECDSA:
537		_, edsaOk := publicKey.(*ecdsa.PublicKey)
538		_, ed25519Ok := publicKey.(ed25519.PublicKey)
539		if !edsaOk && !ed25519Ok {
540			return errors.New("tls: ECDHE ECDSA requires a ECDSA or Ed25519 server public key")
541		}
542	case keyTypeRSA:
543		_, ok := publicKey.(*rsa.PublicKey)
544		if !ok {
545			return errors.New("tls: ECDHE RSA requires a RSA server public key")
546		}
547	default:
548		return errors.New("tls: unknown key type")
549	}
550
551	// The message to be signed is prepended by the randoms.
552	var msg []byte
553	msg = append(msg, clientHello.random...)
554	msg = append(msg, serverHello.random...)
555	msg = append(msg, params...)
556
557	var sigAlg signatureAlgorithm
558	if ka.version >= VersionTLS12 {
559		if len(sig) < 2 {
560			return errServerKeyExchange
561		}
562		sigAlg = signatureAlgorithm(sig[0])<<8 | signatureAlgorithm(sig[1])
563		sig = sig[2:]
564		// Stash the signature algorithm to be extracted by the handshake.
565		ka.peerSignatureAlgorithm = sigAlg
566	}
567
568	if len(sig) < 2 {
569		return errServerKeyExchange
570	}
571	sigLen := int(sig[0])<<8 | int(sig[1])
572	if sigLen+2 != len(sig) {
573		return errServerKeyExchange
574	}
575	sig = sig[2:]
576
577	return verifyMessage(ka.version, publicKey, config, sigAlg, msg, sig)
578}
579
580// ecdheKeyAgreement implements a TLS key agreement where the server
581// generates a ephemeral EC public/private key pair and signs it. The
582// pre-master secret is then calculated using ECDH. The signature may
583// either be ECDSA or RSA.
584type ecdheKeyAgreement struct {
585	auth    keyAgreementAuthentication
586	curve   ecdhCurve
587	curveID CurveID
588	peerKey []byte
589}
590
591func (ka *ecdheKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg, version uint16) (*serverKeyExchangeMsg, error) {
592	var curveid CurveID
593	preferredCurves := config.curvePreferences()
594
595NextCandidate:
596	for _, candidate := range preferredCurves {
597		if candidate == CurveCECPQ2 && version < VersionTLS13 {
598			// CECPQ2 is TLS 1.3-only.
599			continue
600		}
601
602		for _, c := range clientHello.supportedCurves {
603			if candidate == c {
604				curveid = c
605				break NextCandidate
606			}
607		}
608	}
609
610	if curveid == 0 {
611		return nil, errors.New("tls: no supported elliptic curves offered")
612	}
613
614	var ok bool
615	if ka.curve, ok = curveForCurveID(curveid, config); !ok {
616		return nil, errors.New("tls: preferredCurves includes unsupported curve")
617	}
618	ka.curveID = curveid
619
620	publicKey, err := ka.curve.offer(config.rand())
621	if err != nil {
622		return nil, err
623	}
624
625	// http://tools.ietf.org/html/rfc4492#section-5.4
626	serverECDHParams := make([]byte, 1+2+1+len(publicKey))
627	serverECDHParams[0] = 3 // named curve
628	if config.Bugs.SendCurve != 0 {
629		curveid = config.Bugs.SendCurve
630	}
631	serverECDHParams[1] = byte(curveid >> 8)
632	serverECDHParams[2] = byte(curveid)
633	serverECDHParams[3] = byte(len(publicKey))
634	copy(serverECDHParams[4:], publicKey)
635	if config.Bugs.InvalidECDHPoint {
636		serverECDHParams[4] ^= 0xff
637	}
638
639	return ka.auth.signParameters(config, cert, clientHello, hello, serverECDHParams)
640}
641
642func (ka *ecdheKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
643	if len(ckx.ciphertext) == 0 || int(ckx.ciphertext[0]) != len(ckx.ciphertext)-1 {
644		return nil, errClientKeyExchange
645	}
646	return ka.curve.finish(ckx.ciphertext[1:])
647}
648
649func (ka *ecdheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, key crypto.PublicKey, skx *serverKeyExchangeMsg) error {
650	if len(skx.key) < 4 {
651		return errServerKeyExchange
652	}
653	if skx.key[0] != 3 { // named curve
654		return errors.New("tls: server selected unsupported curve")
655	}
656	curveid := CurveID(skx.key[1])<<8 | CurveID(skx.key[2])
657	ka.curveID = curveid
658
659	var ok bool
660	if ka.curve, ok = curveForCurveID(curveid, config); !ok {
661		return errors.New("tls: server selected unsupported curve")
662	}
663
664	publicLen := int(skx.key[3])
665	if publicLen+4 > len(skx.key) {
666		return errServerKeyExchange
667	}
668	// Save the peer key for later.
669	ka.peerKey = skx.key[4 : 4+publicLen]
670
671	// Check the signature.
672	serverECDHParams := skx.key[:4+publicLen]
673	sig := skx.key[4+publicLen:]
674	return ka.auth.verifyParameters(config, clientHello, serverHello, key, serverECDHParams, sig)
675}
676
677func (ka *ecdheKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
678	if ka.curve == nil {
679		return nil, nil, errors.New("missing ServerKeyExchange message")
680	}
681
682	publicKey, preMasterSecret, err := ka.curve.accept(config.rand(), ka.peerKey)
683	if err != nil {
684		return nil, nil, err
685	}
686
687	ckx := new(clientKeyExchangeMsg)
688	ckx.ciphertext = make([]byte, 1+len(publicKey))
689	ckx.ciphertext[0] = byte(len(publicKey))
690	copy(ckx.ciphertext[1:], publicKey)
691	if config.Bugs.InvalidECDHPoint {
692		ckx.ciphertext[1] ^= 0xff
693	}
694
695	return preMasterSecret, ckx, nil
696}
697
698func (ka *ecdheKeyAgreement) peerSignatureAlgorithm() signatureAlgorithm {
699	if auth, ok := ka.auth.(*signedKeyAgreement); ok {
700		return auth.peerSignatureAlgorithm
701	}
702	return 0
703}
704
705// nilKeyAgreement is a fake key agreement used to implement the plain PSK key
706// exchange.
707type nilKeyAgreement struct{}
708
709func (ka *nilKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg, version uint16) (*serverKeyExchangeMsg, error) {
710	return nil, nil
711}
712
713func (ka *nilKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
714	if len(ckx.ciphertext) != 0 {
715		return nil, errClientKeyExchange
716	}
717
718	// Although in plain PSK, otherSecret is all zeros, the base key
719	// agreement does not access to the length of the pre-shared
720	// key. pskKeyAgreement instead interprets nil to mean to use all zeros
721	// of the appropriate length.
722	return nil, nil
723}
724
725func (ka *nilKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, key crypto.PublicKey, skx *serverKeyExchangeMsg) error {
726	if len(skx.key) != 0 {
727		return errServerKeyExchange
728	}
729	return nil
730}
731
732func (ka *nilKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
733	// Although in plain PSK, otherSecret is all zeros, the base key
734	// agreement does not access to the length of the pre-shared
735	// key. pskKeyAgreement instead interprets nil to mean to use all zeros
736	// of the appropriate length.
737	return nil, &clientKeyExchangeMsg{}, nil
738}
739
740func (ka *nilKeyAgreement) peerSignatureAlgorithm() signatureAlgorithm {
741	return 0
742}
743
744// makePSKPremaster formats a PSK pre-master secret based on otherSecret from
745// the base key exchange and psk.
746func makePSKPremaster(otherSecret, psk []byte) []byte {
747	out := make([]byte, 0, 2+len(otherSecret)+2+len(psk))
748	out = append(out, byte(len(otherSecret)>>8), byte(len(otherSecret)))
749	out = append(out, otherSecret...)
750	out = append(out, byte(len(psk)>>8), byte(len(psk)))
751	out = append(out, psk...)
752	return out
753}
754
755// pskKeyAgreement implements the PSK key agreement.
756type pskKeyAgreement struct {
757	base         keyAgreement
758	identityHint string
759}
760
761func (ka *pskKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg, version uint16) (*serverKeyExchangeMsg, error) {
762	// Assemble the identity hint.
763	bytes := make([]byte, 2+len(config.PreSharedKeyIdentity))
764	bytes[0] = byte(len(config.PreSharedKeyIdentity) >> 8)
765	bytes[1] = byte(len(config.PreSharedKeyIdentity))
766	copy(bytes[2:], []byte(config.PreSharedKeyIdentity))
767
768	// If there is one, append the base key agreement's
769	// ServerKeyExchange.
770	baseSkx, err := ka.base.generateServerKeyExchange(config, cert, clientHello, hello, version)
771	if err != nil {
772		return nil, err
773	}
774
775	if baseSkx != nil {
776		bytes = append(bytes, baseSkx.key...)
777	} else if config.PreSharedKeyIdentity == "" && !config.Bugs.AlwaysSendPreSharedKeyIdentityHint {
778		// ServerKeyExchange is optional if the identity hint is empty
779		// and there would otherwise be no ServerKeyExchange.
780		return nil, nil
781	}
782
783	skx := new(serverKeyExchangeMsg)
784	skx.key = bytes
785	return skx, nil
786}
787
788func (ka *pskKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
789	// First, process the PSK identity.
790	if len(ckx.ciphertext) < 2 {
791		return nil, errClientKeyExchange
792	}
793	identityLen := (int(ckx.ciphertext[0]) << 8) | int(ckx.ciphertext[1])
794	if 2+identityLen > len(ckx.ciphertext) {
795		return nil, errClientKeyExchange
796	}
797	identity := string(ckx.ciphertext[2 : 2+identityLen])
798
799	if identity != config.PreSharedKeyIdentity {
800		return nil, errors.New("tls: unexpected identity")
801	}
802
803	if config.PreSharedKey == nil {
804		return nil, errors.New("tls: pre-shared key not configured")
805	}
806
807	// Process the remainder of the ClientKeyExchange to compute the base
808	// pre-master secret.
809	newCkx := new(clientKeyExchangeMsg)
810	newCkx.ciphertext = ckx.ciphertext[2+identityLen:]
811	otherSecret, err := ka.base.processClientKeyExchange(config, cert, newCkx, version)
812	if err != nil {
813		return nil, err
814	}
815
816	if otherSecret == nil {
817		// Special-case for the plain PSK key exchanges.
818		otherSecret = make([]byte, len(config.PreSharedKey))
819	}
820	return makePSKPremaster(otherSecret, config.PreSharedKey), nil
821}
822
823func (ka *pskKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, key crypto.PublicKey, skx *serverKeyExchangeMsg) error {
824	if len(skx.key) < 2 {
825		return errServerKeyExchange
826	}
827	identityLen := (int(skx.key[0]) << 8) | int(skx.key[1])
828	if 2+identityLen > len(skx.key) {
829		return errServerKeyExchange
830	}
831	ka.identityHint = string(skx.key[2 : 2+identityLen])
832
833	// Process the remainder of the ServerKeyExchange.
834	newSkx := new(serverKeyExchangeMsg)
835	newSkx.key = skx.key[2+identityLen:]
836	return ka.base.processServerKeyExchange(config, clientHello, serverHello, key, newSkx)
837}
838
839func (ka *pskKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
840	// The server only sends an identity hint but, for purposes of
841	// test code, the server always sends the hint and it is
842	// required to match.
843	if ka.identityHint != config.PreSharedKeyIdentity {
844		return nil, nil, errors.New("tls: unexpected identity")
845	}
846
847	// Serialize the identity.
848	bytes := make([]byte, 2+len(config.PreSharedKeyIdentity))
849	bytes[0] = byte(len(config.PreSharedKeyIdentity) >> 8)
850	bytes[1] = byte(len(config.PreSharedKeyIdentity))
851	copy(bytes[2:], []byte(config.PreSharedKeyIdentity))
852
853	// Append the base key exchange's ClientKeyExchange.
854	otherSecret, baseCkx, err := ka.base.generateClientKeyExchange(config, clientHello, cert)
855	if err != nil {
856		return nil, nil, err
857	}
858	ckx := new(clientKeyExchangeMsg)
859	ckx.ciphertext = append(bytes, baseCkx.ciphertext...)
860
861	if config.PreSharedKey == nil {
862		return nil, nil, errors.New("tls: pre-shared key not configured")
863	}
864	if otherSecret == nil {
865		otherSecret = make([]byte, len(config.PreSharedKey))
866	}
867	return makePSKPremaster(otherSecret, config.PreSharedKey), ckx, nil
868}
869
870func (ka *pskKeyAgreement) peerSignatureAlgorithm() signatureAlgorithm {
871	return 0
872}
873