• 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/ecdsa"
9	"crypto/elliptic"
10	"crypto/rsa"
11	"crypto/subtle"
12	"crypto/x509"
13	"errors"
14	"fmt"
15	"io"
16	"math/big"
17
18	"./curve25519"
19	"./ed25519"
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	publicKey := getCertificatePublicKey(cert)
382	switch ka.keyType {
383	case keyTypeECDSA:
384		_, edsaOk := publicKey.(*ecdsa.PublicKey)
385		_, ed25519Ok := publicKey.(ed25519.PublicKey)
386		if !edsaOk && !ed25519Ok {
387			return errors.New("tls: ECDHE ECDSA requires a ECDSA or Ed25519 server public key")
388		}
389	case keyTypeRSA:
390		_, ok := publicKey.(*rsa.PublicKey)
391		if !ok {
392			return errors.New("tls: ECDHE RSA requires a RSA server public key")
393		}
394	default:
395		return errors.New("tls: unknown key type")
396	}
397
398	// The message to be signed is prepended by the randoms.
399	var msg []byte
400	msg = append(msg, clientHello.random...)
401	msg = append(msg, serverHello.random...)
402	msg = append(msg, params...)
403
404	var sigAlg signatureAlgorithm
405	if ka.version >= VersionTLS12 {
406		if len(sig) < 2 {
407			return errServerKeyExchange
408		}
409		sigAlg = signatureAlgorithm(sig[0])<<8 | signatureAlgorithm(sig[1])
410		sig = sig[2:]
411		// Stash the signature algorithm to be extracted by the handshake.
412		ka.peerSignatureAlgorithm = sigAlg
413	}
414
415	if len(sig) < 2 {
416		return errServerKeyExchange
417	}
418	sigLen := int(sig[0])<<8 | int(sig[1])
419	if sigLen+2 != len(sig) {
420		return errServerKeyExchange
421	}
422	sig = sig[2:]
423
424	return verifyMessage(ka.version, publicKey, config, sigAlg, msg, sig)
425}
426
427// ecdheKeyAgreement implements a TLS key agreement where the server
428// generates a ephemeral EC public/private key pair and signs it. The
429// pre-master secret is then calculated using ECDH. The signature may
430// either be ECDSA or RSA.
431type ecdheKeyAgreement struct {
432	auth    keyAgreementAuthentication
433	curve   ecdhCurve
434	curveID CurveID
435	peerKey []byte
436}
437
438func (ka *ecdheKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
439	var curveid CurveID
440	preferredCurves := config.curvePreferences()
441
442NextCandidate:
443	for _, candidate := range preferredCurves {
444		for _, c := range clientHello.supportedCurves {
445			if candidate == c {
446				curveid = c
447				break NextCandidate
448			}
449		}
450	}
451
452	if curveid == 0 {
453		return nil, errors.New("tls: no supported elliptic curves offered")
454	}
455
456	var ok bool
457	if ka.curve, ok = curveForCurveID(curveid); !ok {
458		return nil, errors.New("tls: preferredCurves includes unsupported curve")
459	}
460	ka.curveID = curveid
461
462	publicKey, err := ka.curve.offer(config.rand())
463	if err != nil {
464		return nil, err
465	}
466
467	// http://tools.ietf.org/html/rfc4492#section-5.4
468	serverECDHParams := make([]byte, 1+2+1+len(publicKey))
469	serverECDHParams[0] = 3 // named curve
470	if config.Bugs.SendCurve != 0 {
471		curveid = config.Bugs.SendCurve
472	}
473	serverECDHParams[1] = byte(curveid >> 8)
474	serverECDHParams[2] = byte(curveid)
475	serverECDHParams[3] = byte(len(publicKey))
476	copy(serverECDHParams[4:], publicKey)
477	if config.Bugs.InvalidECDHPoint {
478		serverECDHParams[4] ^= 0xff
479	}
480
481	return ka.auth.signParameters(config, cert, clientHello, hello, serverECDHParams)
482}
483
484func (ka *ecdheKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
485	if len(ckx.ciphertext) == 0 || int(ckx.ciphertext[0]) != len(ckx.ciphertext)-1 {
486		return nil, errClientKeyExchange
487	}
488	return ka.curve.finish(ckx.ciphertext[1:])
489}
490
491func (ka *ecdheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
492	if len(skx.key) < 4 {
493		return errServerKeyExchange
494	}
495	if skx.key[0] != 3 { // named curve
496		return errors.New("tls: server selected unsupported curve")
497	}
498	curveid := CurveID(skx.key[1])<<8 | CurveID(skx.key[2])
499	ka.curveID = curveid
500
501	var ok bool
502	if ka.curve, ok = curveForCurveID(curveid); !ok {
503		return errors.New("tls: server selected unsupported curve")
504	}
505
506	publicLen := int(skx.key[3])
507	if publicLen+4 > len(skx.key) {
508		return errServerKeyExchange
509	}
510	// Save the peer key for later.
511	ka.peerKey = skx.key[4 : 4+publicLen]
512
513	// Check the signature.
514	serverECDHParams := skx.key[:4+publicLen]
515	sig := skx.key[4+publicLen:]
516	return ka.auth.verifyParameters(config, clientHello, serverHello, cert, serverECDHParams, sig)
517}
518
519func (ka *ecdheKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
520	if ka.curve == nil {
521		return nil, nil, errors.New("missing ServerKeyExchange message")
522	}
523
524	publicKey, preMasterSecret, err := ka.curve.accept(config.rand(), ka.peerKey)
525	if err != nil {
526		return nil, nil, err
527	}
528
529	ckx := new(clientKeyExchangeMsg)
530	ckx.ciphertext = make([]byte, 1+len(publicKey))
531	ckx.ciphertext[0] = byte(len(publicKey))
532	copy(ckx.ciphertext[1:], publicKey)
533	if config.Bugs.InvalidECDHPoint {
534		ckx.ciphertext[1] ^= 0xff
535	}
536
537	return preMasterSecret, ckx, nil
538}
539
540func (ka *ecdheKeyAgreement) peerSignatureAlgorithm() signatureAlgorithm {
541	if auth, ok := ka.auth.(*signedKeyAgreement); ok {
542		return auth.peerSignatureAlgorithm
543	}
544	return 0
545}
546
547// nilKeyAgreement is a fake key agreement used to implement the plain PSK key
548// exchange.
549type nilKeyAgreement struct{}
550
551func (ka *nilKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
552	return nil, nil
553}
554
555func (ka *nilKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
556	if len(ckx.ciphertext) != 0 {
557		return nil, errClientKeyExchange
558	}
559
560	// Although in plain PSK, otherSecret is all zeros, the base key
561	// agreement does not access to the length of the pre-shared
562	// key. pskKeyAgreement instead interprets nil to mean to use all zeros
563	// of the appropriate length.
564	return nil, nil
565}
566
567func (ka *nilKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
568	if len(skx.key) != 0 {
569		return errServerKeyExchange
570	}
571	return nil
572}
573
574func (ka *nilKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
575	// Although in plain PSK, otherSecret is all zeros, the base key
576	// agreement does not access to the length of the pre-shared
577	// key. pskKeyAgreement instead interprets nil to mean to use all zeros
578	// of the appropriate length.
579	return nil, &clientKeyExchangeMsg{}, nil
580}
581
582func (ka *nilKeyAgreement) peerSignatureAlgorithm() signatureAlgorithm {
583	return 0
584}
585
586// makePSKPremaster formats a PSK pre-master secret based on otherSecret from
587// the base key exchange and psk.
588func makePSKPremaster(otherSecret, psk []byte) []byte {
589	out := make([]byte, 0, 2+len(otherSecret)+2+len(psk))
590	out = append(out, byte(len(otherSecret)>>8), byte(len(otherSecret)))
591	out = append(out, otherSecret...)
592	out = append(out, byte(len(psk)>>8), byte(len(psk)))
593	out = append(out, psk...)
594	return out
595}
596
597// pskKeyAgreement implements the PSK key agreement.
598type pskKeyAgreement struct {
599	base         keyAgreement
600	identityHint string
601}
602
603func (ka *pskKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
604	// Assemble the identity hint.
605	bytes := make([]byte, 2+len(config.PreSharedKeyIdentity))
606	bytes[0] = byte(len(config.PreSharedKeyIdentity) >> 8)
607	bytes[1] = byte(len(config.PreSharedKeyIdentity))
608	copy(bytes[2:], []byte(config.PreSharedKeyIdentity))
609
610	// If there is one, append the base key agreement's
611	// ServerKeyExchange.
612	baseSkx, err := ka.base.generateServerKeyExchange(config, cert, clientHello, hello)
613	if err != nil {
614		return nil, err
615	}
616
617	if baseSkx != nil {
618		bytes = append(bytes, baseSkx.key...)
619	} else if config.PreSharedKeyIdentity == "" && !config.Bugs.AlwaysSendPreSharedKeyIdentityHint {
620		// ServerKeyExchange is optional if the identity hint is empty
621		// and there would otherwise be no ServerKeyExchange.
622		return nil, nil
623	}
624
625	skx := new(serverKeyExchangeMsg)
626	skx.key = bytes
627	return skx, nil
628}
629
630func (ka *pskKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
631	// First, process the PSK identity.
632	if len(ckx.ciphertext) < 2 {
633		return nil, errClientKeyExchange
634	}
635	identityLen := (int(ckx.ciphertext[0]) << 8) | int(ckx.ciphertext[1])
636	if 2+identityLen > len(ckx.ciphertext) {
637		return nil, errClientKeyExchange
638	}
639	identity := string(ckx.ciphertext[2 : 2+identityLen])
640
641	if identity != config.PreSharedKeyIdentity {
642		return nil, errors.New("tls: unexpected identity")
643	}
644
645	if config.PreSharedKey == nil {
646		return nil, errors.New("tls: pre-shared key not configured")
647	}
648
649	// Process the remainder of the ClientKeyExchange to compute the base
650	// pre-master secret.
651	newCkx := new(clientKeyExchangeMsg)
652	newCkx.ciphertext = ckx.ciphertext[2+identityLen:]
653	otherSecret, err := ka.base.processClientKeyExchange(config, cert, newCkx, version)
654	if err != nil {
655		return nil, err
656	}
657
658	if otherSecret == nil {
659		// Special-case for the plain PSK key exchanges.
660		otherSecret = make([]byte, len(config.PreSharedKey))
661	}
662	return makePSKPremaster(otherSecret, config.PreSharedKey), nil
663}
664
665func (ka *pskKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
666	if len(skx.key) < 2 {
667		return errServerKeyExchange
668	}
669	identityLen := (int(skx.key[0]) << 8) | int(skx.key[1])
670	if 2+identityLen > len(skx.key) {
671		return errServerKeyExchange
672	}
673	ka.identityHint = string(skx.key[2 : 2+identityLen])
674
675	// Process the remainder of the ServerKeyExchange.
676	newSkx := new(serverKeyExchangeMsg)
677	newSkx.key = skx.key[2+identityLen:]
678	return ka.base.processServerKeyExchange(config, clientHello, serverHello, cert, newSkx)
679}
680
681func (ka *pskKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
682	// The server only sends an identity hint but, for purposes of
683	// test code, the server always sends the hint and it is
684	// required to match.
685	if ka.identityHint != config.PreSharedKeyIdentity {
686		return nil, nil, errors.New("tls: unexpected identity")
687	}
688
689	// Serialize the identity.
690	bytes := make([]byte, 2+len(config.PreSharedKeyIdentity))
691	bytes[0] = byte(len(config.PreSharedKeyIdentity) >> 8)
692	bytes[1] = byte(len(config.PreSharedKeyIdentity))
693	copy(bytes[2:], []byte(config.PreSharedKeyIdentity))
694
695	// Append the base key exchange's ClientKeyExchange.
696	otherSecret, baseCkx, err := ka.base.generateClientKeyExchange(config, clientHello, cert)
697	if err != nil {
698		return nil, nil, err
699	}
700	ckx := new(clientKeyExchangeMsg)
701	ckx.ciphertext = append(bytes, baseCkx.ciphertext...)
702
703	if config.PreSharedKey == nil {
704		return nil, nil, errors.New("tls: pre-shared key not configured")
705	}
706	if otherSecret == nil {
707		otherSecret = make([]byte, len(config.PreSharedKey))
708	}
709	return makePSKPremaster(otherSecret, config.PreSharedKey), ckx, nil
710}
711
712func (ka *pskKeyAgreement) peerSignatureAlgorithm() signatureAlgorithm {
713	return 0
714}
715