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