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 main
6
7import (
8	"crypto"
9	"crypto/ecdsa"
10	"crypto/elliptic"
11	"crypto/md5"
12	"crypto/rand"
13	"crypto/rsa"
14	"crypto/sha1"
15	"crypto/x509"
16	"encoding/asn1"
17	"errors"
18	"io"
19	"math/big"
20)
21
22var errClientKeyExchange = errors.New("tls: invalid ClientKeyExchange message")
23var errServerKeyExchange = errors.New("tls: invalid ServerKeyExchange message")
24
25// rsaKeyAgreement implements the standard TLS key agreement where the client
26// encrypts the pre-master secret to the server's public key.
27type rsaKeyAgreement struct {
28	version       uint16
29	clientVersion uint16
30	exportKey     *rsa.PrivateKey
31}
32
33func (ka *rsaKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
34	// Save the client version for comparison later.
35	ka.clientVersion = versionToWire(clientHello.vers, clientHello.isDTLS)
36
37	if !config.Bugs.RSAEphemeralKey {
38		return nil, nil
39	}
40
41	// Generate an ephemeral RSA key to use instead of the real
42	// one, as in RSA_EXPORT.
43	key, err := rsa.GenerateKey(config.rand(), 512)
44	if err != nil {
45		return nil, err
46	}
47	ka.exportKey = key
48
49	modulus := key.N.Bytes()
50	exponent := big.NewInt(int64(key.E)).Bytes()
51	serverRSAParams := make([]byte, 0, 2+len(modulus)+2+len(exponent))
52	serverRSAParams = append(serverRSAParams, byte(len(modulus)>>8), byte(len(modulus)))
53	serverRSAParams = append(serverRSAParams, modulus...)
54	serverRSAParams = append(serverRSAParams, byte(len(exponent)>>8), byte(len(exponent)))
55	serverRSAParams = append(serverRSAParams, exponent...)
56
57	var tls12HashId uint8
58	if ka.version >= VersionTLS12 {
59		if tls12HashId, err = pickTLS12HashForSignature(signatureRSA, clientHello.signatureAndHashes, config.signatureAndHashesForServer()); err != nil {
60			return nil, err
61		}
62	}
63
64	digest, hashFunc, err := hashForServerKeyExchange(signatureRSA, tls12HashId, ka.version, clientHello.random, hello.random, serverRSAParams)
65	if err != nil {
66		return nil, err
67	}
68	privKey, ok := cert.PrivateKey.(*rsa.PrivateKey)
69	if !ok {
70		return nil, errors.New("RSA ephemeral key requires an RSA server private key")
71	}
72	sig, err := rsa.SignPKCS1v15(config.rand(), privKey, hashFunc, digest)
73	if err != nil {
74		return nil, errors.New("failed to sign RSA parameters: " + err.Error())
75	}
76
77	skx := new(serverKeyExchangeMsg)
78	sigAndHashLen := 0
79	if ka.version >= VersionTLS12 {
80		sigAndHashLen = 2
81	}
82	skx.key = make([]byte, len(serverRSAParams)+sigAndHashLen+2+len(sig))
83	copy(skx.key, serverRSAParams)
84	k := skx.key[len(serverRSAParams):]
85	if ka.version >= VersionTLS12 {
86		k[0] = tls12HashId
87		k[1] = signatureRSA
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, errors.New("tls: invalid version in RSA premaster")
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	preMasterSecret := make([]byte, 48)
141	vers := clientHello.vers
142	if config.Bugs.RsaClientKeyExchangeVersion != 0 {
143		vers = config.Bugs.RsaClientKeyExchangeVersion
144	}
145	vers = versionToWire(vers, clientHello.isDTLS)
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	encrypted, err := rsa.EncryptPKCS1v15(config.rand(), cert.PublicKey.(*rsa.PublicKey), preMasterSecret)
154	if err != nil {
155		return nil, nil, err
156	}
157	ckx := new(clientKeyExchangeMsg)
158	if clientHello.vers != VersionSSL30 && !config.Bugs.SSL3RSAKeyExchange {
159		ckx.ciphertext = make([]byte, len(encrypted)+2)
160		ckx.ciphertext[0] = byte(len(encrypted) >> 8)
161		ckx.ciphertext[1] = byte(len(encrypted))
162		copy(ckx.ciphertext[2:], encrypted)
163	} else {
164		ckx.ciphertext = encrypted
165	}
166	return preMasterSecret, ckx, nil
167}
168
169// sha1Hash calculates a SHA1 hash over the given byte slices.
170func sha1Hash(slices [][]byte) []byte {
171	hsha1 := sha1.New()
172	for _, slice := range slices {
173		hsha1.Write(slice)
174	}
175	return hsha1.Sum(nil)
176}
177
178// md5SHA1Hash implements TLS 1.0's hybrid hash function which consists of the
179// concatenation of an MD5 and SHA1 hash.
180func md5SHA1Hash(slices [][]byte) []byte {
181	md5sha1 := make([]byte, md5.Size+sha1.Size)
182	hmd5 := md5.New()
183	for _, slice := range slices {
184		hmd5.Write(slice)
185	}
186	copy(md5sha1, hmd5.Sum(nil))
187	copy(md5sha1[md5.Size:], sha1Hash(slices))
188	return md5sha1
189}
190
191// hashForServerKeyExchange hashes the given slices and returns their digest
192// and the identifier of the hash function used. The hashFunc argument is only
193// used for >= TLS 1.2 and precisely identifies the hash function to use.
194func hashForServerKeyExchange(sigType, hashFunc uint8, version uint16, slices ...[]byte) ([]byte, crypto.Hash, error) {
195	if version >= VersionTLS12 {
196		hash, err := lookupTLSHash(hashFunc)
197		if err != nil {
198			return nil, 0, err
199		}
200		h := hash.New()
201		for _, slice := range slices {
202			h.Write(slice)
203		}
204		return h.Sum(nil), hash, nil
205	}
206	if sigType == signatureECDSA {
207		return sha1Hash(slices), crypto.SHA1, nil
208	}
209	return md5SHA1Hash(slices), crypto.MD5SHA1, nil
210}
211
212// pickTLS12HashForSignature returns a TLS 1.2 hash identifier for signing a
213// ServerKeyExchange given the signature type being used and the client's
214// advertized list of supported signature and hash combinations.
215func pickTLS12HashForSignature(sigType uint8, clientList, serverList []signatureAndHash) (uint8, error) {
216	if len(clientList) == 0 {
217		// If the client didn't specify any signature_algorithms
218		// extension then we can assume that it supports SHA1. See
219		// http://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
220		return hashSHA1, nil
221	}
222
223	for _, sigAndHash := range clientList {
224		if sigAndHash.signature != sigType {
225			continue
226		}
227		if isSupportedSignatureAndHash(sigAndHash, serverList) {
228			return sigAndHash.hash, nil
229		}
230	}
231
232	return 0, errors.New("tls: client doesn't support any common hash functions")
233}
234
235func curveForCurveID(id CurveID) (elliptic.Curve, bool) {
236	switch id {
237	case CurveP224:
238		return elliptic.P224(), true
239	case CurveP256:
240		return elliptic.P256(), true
241	case CurveP384:
242		return elliptic.P384(), true
243	case CurveP521:
244		return elliptic.P521(), true
245	default:
246		return nil, false
247	}
248
249}
250
251// keyAgreementAuthentication is a helper interface that specifies how
252// to authenticate the ServerKeyExchange parameters.
253type keyAgreementAuthentication interface {
254	signParameters(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg, params []byte) (*serverKeyExchangeMsg, error)
255	verifyParameters(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, params []byte, sig []byte) error
256}
257
258// nilKeyAgreementAuthentication does not authenticate the key
259// agreement parameters.
260type nilKeyAgreementAuthentication struct{}
261
262func (ka *nilKeyAgreementAuthentication) signParameters(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg, params []byte) (*serverKeyExchangeMsg, error) {
263	skx := new(serverKeyExchangeMsg)
264	skx.key = params
265	return skx, nil
266}
267
268func (ka *nilKeyAgreementAuthentication) verifyParameters(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, params []byte, sig []byte) error {
269	return nil
270}
271
272// signedKeyAgreement signs the ServerKeyExchange parameters with the
273// server's private key.
274type signedKeyAgreement struct {
275	version uint16
276	sigType uint8
277}
278
279func (ka *signedKeyAgreement) signParameters(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg, params []byte) (*serverKeyExchangeMsg, error) {
280	var tls12HashId uint8
281	var err error
282	if ka.version >= VersionTLS12 {
283		if tls12HashId, err = pickTLS12HashForSignature(ka.sigType, clientHello.signatureAndHashes, config.signatureAndHashesForServer()); err != nil {
284			return nil, err
285		}
286	}
287
288	digest, hashFunc, err := hashForServerKeyExchange(ka.sigType, tls12HashId, ka.version, clientHello.random, hello.random, params)
289	if err != nil {
290		return nil, err
291	}
292
293	if config.Bugs.InvalidSKXSignature {
294		digest[0] ^= 0x80
295	}
296
297	var sig []byte
298	switch ka.sigType {
299	case signatureECDSA:
300		privKey, ok := cert.PrivateKey.(*ecdsa.PrivateKey)
301		if !ok {
302			return nil, errors.New("ECDHE ECDSA requires an ECDSA server private key")
303		}
304		r, s, err := ecdsa.Sign(config.rand(), privKey, digest)
305		if err != nil {
306			return nil, errors.New("failed to sign ECDHE parameters: " + err.Error())
307		}
308		order := privKey.Curve.Params().N
309		r = maybeCorruptECDSAValue(r, config.Bugs.BadECDSAR, order)
310		s = maybeCorruptECDSAValue(s, config.Bugs.BadECDSAS, order)
311		sig, err = asn1.Marshal(ecdsaSignature{r, s})
312	case signatureRSA:
313		privKey, ok := cert.PrivateKey.(*rsa.PrivateKey)
314		if !ok {
315			return nil, errors.New("ECDHE RSA requires a RSA server private key")
316		}
317		sig, err = rsa.SignPKCS1v15(config.rand(), privKey, hashFunc, digest)
318		if err != nil {
319			return nil, errors.New("failed to sign ECDHE parameters: " + err.Error())
320		}
321	default:
322		return nil, errors.New("unknown ECDHE signature algorithm")
323	}
324
325	skx := new(serverKeyExchangeMsg)
326	if config.Bugs.UnauthenticatedECDH {
327		skx.key = params
328	} else {
329		sigAndHashLen := 0
330		if ka.version >= VersionTLS12 {
331			sigAndHashLen = 2
332		}
333		skx.key = make([]byte, len(params)+sigAndHashLen+2+len(sig))
334		copy(skx.key, params)
335		k := skx.key[len(params):]
336		if ka.version >= VersionTLS12 {
337			k[0] = tls12HashId
338			k[1] = ka.sigType
339			k = k[2:]
340		}
341		k[0] = byte(len(sig) >> 8)
342		k[1] = byte(len(sig))
343		copy(k[2:], sig)
344	}
345
346	return skx, nil
347}
348
349func (ka *signedKeyAgreement) verifyParameters(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, params []byte, sig []byte) error {
350	if len(sig) < 2 {
351		return errServerKeyExchange
352	}
353
354	var tls12HashId uint8
355	if ka.version >= VersionTLS12 {
356		// handle SignatureAndHashAlgorithm
357		var sigAndHash []uint8
358		sigAndHash, sig = sig[:2], sig[2:]
359		if sigAndHash[1] != ka.sigType {
360			return errServerKeyExchange
361		}
362		tls12HashId = sigAndHash[0]
363		if len(sig) < 2 {
364			return errServerKeyExchange
365		}
366
367		if !isSupportedSignatureAndHash(signatureAndHash{ka.sigType, tls12HashId}, config.signatureAndHashesForClient()) {
368			return errors.New("tls: unsupported hash function for ServerKeyExchange")
369		}
370	}
371	sigLen := int(sig[0])<<8 | int(sig[1])
372	if sigLen+2 != len(sig) {
373		return errServerKeyExchange
374	}
375	sig = sig[2:]
376
377	digest, hashFunc, err := hashForServerKeyExchange(ka.sigType, tls12HashId, ka.version, clientHello.random, serverHello.random, params)
378	if err != nil {
379		return err
380	}
381	switch ka.sigType {
382	case signatureECDSA:
383		pubKey, ok := cert.PublicKey.(*ecdsa.PublicKey)
384		if !ok {
385			return errors.New("ECDHE ECDSA requires a ECDSA server public key")
386		}
387		ecdsaSig := new(ecdsaSignature)
388		if _, err := asn1.Unmarshal(sig, ecdsaSig); err != nil {
389			return err
390		}
391		if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
392			return errors.New("ECDSA signature contained zero or negative values")
393		}
394		if !ecdsa.Verify(pubKey, digest, ecdsaSig.R, ecdsaSig.S) {
395			return errors.New("ECDSA verification failure")
396		}
397	case signatureRSA:
398		pubKey, ok := cert.PublicKey.(*rsa.PublicKey)
399		if !ok {
400			return errors.New("ECDHE RSA requires a RSA server public key")
401		}
402		if err := rsa.VerifyPKCS1v15(pubKey, hashFunc, digest, sig); err != nil {
403			return err
404		}
405	default:
406		return errors.New("unknown ECDHE signature algorithm")
407	}
408
409	return nil
410}
411
412// ecdheRSAKeyAgreement implements a TLS key agreement where the server
413// generates a ephemeral EC public/private key pair and signs it. The
414// pre-master secret is then calculated using ECDH. The signature may
415// either be ECDSA or RSA.
416type ecdheKeyAgreement struct {
417	auth       keyAgreementAuthentication
418	privateKey []byte
419	curve      elliptic.Curve
420	x, y       *big.Int
421}
422
423func maybeCorruptECDSAValue(n *big.Int, typeOfCorruption BadValue, limit *big.Int) *big.Int {
424	switch typeOfCorruption {
425	case BadValueNone:
426		return n
427	case BadValueNegative:
428		return new(big.Int).Neg(n)
429	case BadValueZero:
430		return big.NewInt(0)
431	case BadValueLimit:
432		return limit
433	case BadValueLarge:
434		bad := new(big.Int).Set(limit)
435		return bad.Lsh(bad, 20)
436	default:
437		panic("unknown BadValue type")
438	}
439}
440
441func (ka *ecdheKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
442	var curveid CurveID
443	preferredCurves := config.curvePreferences()
444
445NextCandidate:
446	for _, candidate := range preferredCurves {
447		for _, c := range clientHello.supportedCurves {
448			if candidate == c {
449				curveid = c
450				break NextCandidate
451			}
452		}
453	}
454
455	if curveid == 0 {
456		return nil, errors.New("tls: no supported elliptic curves offered")
457	}
458
459	var ok bool
460	if ka.curve, ok = curveForCurveID(curveid); !ok {
461		return nil, errors.New("tls: preferredCurves includes unsupported curve")
462	}
463
464	var x, y *big.Int
465	var err error
466	ka.privateKey, x, y, err = elliptic.GenerateKey(ka.curve, config.rand())
467	if err != nil {
468		return nil, err
469	}
470	ecdhePublic := elliptic.Marshal(ka.curve, x, y)
471
472	// http://tools.ietf.org/html/rfc4492#section-5.4
473	serverECDHParams := make([]byte, 1+2+1+len(ecdhePublic))
474	serverECDHParams[0] = 3 // named curve
475	serverECDHParams[1] = byte(curveid >> 8)
476	serverECDHParams[2] = byte(curveid)
477	if config.Bugs.InvalidSKXCurve {
478		serverECDHParams[2] ^= 0xff
479	}
480	serverECDHParams[3] = byte(len(ecdhePublic))
481	copy(serverECDHParams[4:], ecdhePublic)
482
483	return ka.auth.signParameters(config, cert, clientHello, hello, serverECDHParams)
484}
485
486func (ka *ecdheKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
487	if len(ckx.ciphertext) == 0 || int(ckx.ciphertext[0]) != len(ckx.ciphertext)-1 {
488		return nil, errClientKeyExchange
489	}
490	x, y := elliptic.Unmarshal(ka.curve, ckx.ciphertext[1:])
491	if x == nil {
492		return nil, errClientKeyExchange
493	}
494	x, _ = ka.curve.ScalarMult(x, y, ka.privateKey)
495	preMasterSecret := make([]byte, (ka.curve.Params().BitSize+7)>>3)
496	xBytes := x.Bytes()
497	copy(preMasterSecret[len(preMasterSecret)-len(xBytes):], xBytes)
498
499	return preMasterSecret, nil
500}
501
502func (ka *ecdheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
503	if len(skx.key) < 4 {
504		return errServerKeyExchange
505	}
506	if skx.key[0] != 3 { // named curve
507		return errors.New("tls: server selected unsupported curve")
508	}
509	curveid := CurveID(skx.key[1])<<8 | CurveID(skx.key[2])
510
511	var ok bool
512	if ka.curve, ok = curveForCurveID(curveid); !ok {
513		return errors.New("tls: server selected unsupported curve")
514	}
515
516	publicLen := int(skx.key[3])
517	if publicLen+4 > len(skx.key) {
518		return errServerKeyExchange
519	}
520	ka.x, ka.y = elliptic.Unmarshal(ka.curve, skx.key[4:4+publicLen])
521	if ka.x == nil {
522		return errServerKeyExchange
523	}
524	serverECDHParams := skx.key[:4+publicLen]
525	sig := skx.key[4+publicLen:]
526
527	return ka.auth.verifyParameters(config, clientHello, serverHello, cert, serverECDHParams, sig)
528}
529
530func (ka *ecdheKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
531	if ka.curve == nil {
532		return nil, nil, errors.New("missing ServerKeyExchange message")
533	}
534	priv, mx, my, err := elliptic.GenerateKey(ka.curve, config.rand())
535	if err != nil {
536		return nil, nil, err
537	}
538	x, _ := ka.curve.ScalarMult(ka.x, ka.y, priv)
539	preMasterSecret := make([]byte, (ka.curve.Params().BitSize+7)>>3)
540	xBytes := x.Bytes()
541	copy(preMasterSecret[len(preMasterSecret)-len(xBytes):], xBytes)
542
543	serialized := elliptic.Marshal(ka.curve, mx, my)
544
545	ckx := new(clientKeyExchangeMsg)
546	ckx.ciphertext = make([]byte, 1+len(serialized))
547	ckx.ciphertext[0] = byte(len(serialized))
548	copy(ckx.ciphertext[1:], serialized)
549
550	return preMasterSecret, ckx, nil
551}
552
553// dheRSAKeyAgreement implements a TLS key agreement where the server generates
554// an ephemeral Diffie-Hellman public/private key pair and signs it. The
555// pre-master secret is then calculated using Diffie-Hellman.
556type dheKeyAgreement struct {
557	auth    keyAgreementAuthentication
558	p, g    *big.Int
559	yTheirs *big.Int
560	xOurs   *big.Int
561}
562
563func (ka *dheKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
564	var q *big.Int
565	if p := config.Bugs.DHGroupPrime; p != nil {
566		ka.p = p
567		ka.g = big.NewInt(2)
568		q = p
569	} else {
570		// 2048-bit MODP Group with 256-bit Prime Order Subgroup (RFC
571		// 5114, Section 2.3)
572		ka.p, _ = new(big.Int).SetString("87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF4296D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4758C022E0B1EF4275BF7B6C5BFC11D45F9088B941F54EB1E59BB8BC39A0BF12307F5C4FDB70C581B23F76B63ACAE1CAA6B7902D52526735488A0EF13C6D9A51BFA4AB3AD8347796524D8EF6A167B5A41825D967E144E5140564251CCACB83E6B486F6B3CA3F7971506026C0B857F689962856DED4010ABD0BE621C3A3960A54E710C375F26375D7014103A4B54330C198AF126116D2276E11715F693877FAD7EF09CADB094AE91E1A1597", 16)
573		ka.g, _ = new(big.Int).SetString("3FB32C9B73134D0B2E77506660EDBD484CA7B18F21EF205407F4793A1A0BA12510DBC15077BE463FFF4FED4AAC0BB555BE3A6C1B0C6B47B1BC3773BF7E8C6F62901228F8C28CBB18A55AE31341000A650196F931C77A57F2DDF463E5E9EC144B777DE62AAAB8A8628AC376D282D6ED3864E67982428EBC831D14348F6F2F9193B5045AF2767164E1DFC967C1FB3F2E55A4BD1BFFE83B9C80D052B985D182EA0ADB2A3B7313D3FE14C8484B1E052588B9B7D2BBD2DF016199ECD06E1557CD0915B3353BBB64E0EC377FD028370DF92B52C7891428CDC67EB6184B523D1DB246C32F63078490F00EF8D647D148D47954515E2327CFEF98C582664B4C0F6CC41659", 16)
574		q, _ = new(big.Int).SetString("8CF83642A709A097B447997640129DA299B1A47D1EB3750BA308B0FE64F5FBD3", 16)
575	}
576
577	var err error
578	ka.xOurs, err = rand.Int(config.rand(), q)
579	if err != nil {
580		return nil, err
581	}
582	yOurs := new(big.Int).Exp(ka.g, ka.xOurs, ka.p)
583
584	// http://tools.ietf.org/html/rfc5246#section-7.4.3
585	pBytes := ka.p.Bytes()
586	gBytes := ka.g.Bytes()
587	yBytes := yOurs.Bytes()
588	serverDHParams := make([]byte, 0, 2+len(pBytes)+2+len(gBytes)+2+len(yBytes))
589	serverDHParams = append(serverDHParams, byte(len(pBytes)>>8), byte(len(pBytes)))
590	serverDHParams = append(serverDHParams, pBytes...)
591	serverDHParams = append(serverDHParams, byte(len(gBytes)>>8), byte(len(gBytes)))
592	serverDHParams = append(serverDHParams, gBytes...)
593	serverDHParams = append(serverDHParams, byte(len(yBytes)>>8), byte(len(yBytes)))
594	serverDHParams = append(serverDHParams, yBytes...)
595
596	return ka.auth.signParameters(config, cert, clientHello, hello, serverDHParams)
597}
598
599func (ka *dheKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
600	if len(ckx.ciphertext) < 2 {
601		return nil, errClientKeyExchange
602	}
603	yLen := (int(ckx.ciphertext[0]) << 8) | int(ckx.ciphertext[1])
604	if yLen != len(ckx.ciphertext)-2 {
605		return nil, errClientKeyExchange
606	}
607	yTheirs := new(big.Int).SetBytes(ckx.ciphertext[2:])
608	if yTheirs.Sign() <= 0 || yTheirs.Cmp(ka.p) >= 0 {
609		return nil, errClientKeyExchange
610	}
611	return new(big.Int).Exp(yTheirs, ka.xOurs, ka.p).Bytes(), nil
612}
613
614func (ka *dheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
615	// Read dh_p
616	k := skx.key
617	if len(k) < 2 {
618		return errServerKeyExchange
619	}
620	pLen := (int(k[0]) << 8) | int(k[1])
621	k = k[2:]
622	if len(k) < pLen {
623		return errServerKeyExchange
624	}
625	ka.p = new(big.Int).SetBytes(k[:pLen])
626	k = k[pLen:]
627
628	// Read dh_g
629	if len(k) < 2 {
630		return errServerKeyExchange
631	}
632	gLen := (int(k[0]) << 8) | int(k[1])
633	k = k[2:]
634	if len(k) < gLen {
635		return errServerKeyExchange
636	}
637	ka.g = new(big.Int).SetBytes(k[:gLen])
638	k = k[gLen:]
639
640	// Read dh_Ys
641	if len(k) < 2 {
642		return errServerKeyExchange
643	}
644	yLen := (int(k[0]) << 8) | int(k[1])
645	k = k[2:]
646	if len(k) < yLen {
647		return errServerKeyExchange
648	}
649	ka.yTheirs = new(big.Int).SetBytes(k[:yLen])
650	k = k[yLen:]
651	if ka.yTheirs.Sign() <= 0 || ka.yTheirs.Cmp(ka.p) >= 0 {
652		return errServerKeyExchange
653	}
654
655	sig := k
656	serverDHParams := skx.key[:len(skx.key)-len(sig)]
657
658	return ka.auth.verifyParameters(config, clientHello, serverHello, cert, serverDHParams, sig)
659}
660
661func (ka *dheKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
662	if ka.p == nil || ka.g == nil || ka.yTheirs == nil {
663		return nil, nil, errors.New("missing ServerKeyExchange message")
664	}
665
666	xOurs, err := rand.Int(config.rand(), ka.p)
667	if err != nil {
668		return nil, nil, err
669	}
670	preMasterSecret := new(big.Int).Exp(ka.yTheirs, xOurs, ka.p).Bytes()
671
672	yOurs := new(big.Int).Exp(ka.g, xOurs, ka.p)
673	yBytes := yOurs.Bytes()
674	ckx := new(clientKeyExchangeMsg)
675	ckx.ciphertext = make([]byte, 2+len(yBytes))
676	ckx.ciphertext[0] = byte(len(yBytes) >> 8)
677	ckx.ciphertext[1] = byte(len(yBytes))
678	copy(ckx.ciphertext[2:], yBytes)
679
680	return preMasterSecret, ckx, nil
681}
682
683// nilKeyAgreement is a fake key agreement used to implement the plain PSK key
684// exchange.
685type nilKeyAgreement struct{}
686
687func (ka *nilKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
688	return nil, nil
689}
690
691func (ka *nilKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
692	if len(ckx.ciphertext) != 0 {
693		return nil, errClientKeyExchange
694	}
695
696	// Although in plain PSK, otherSecret is all zeros, the base key
697	// agreement does not access to the length of the pre-shared
698	// key. pskKeyAgreement instead interprets nil to mean to use all zeros
699	// of the appropriate length.
700	return nil, nil
701}
702
703func (ka *nilKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
704	if len(skx.key) != 0 {
705		return errServerKeyExchange
706	}
707	return nil
708}
709
710func (ka *nilKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
711	// Although in plain PSK, otherSecret is all zeros, the base key
712	// agreement does not access to the length of the pre-shared
713	// key. pskKeyAgreement instead interprets nil to mean to use all zeros
714	// of the appropriate length.
715	return nil, &clientKeyExchangeMsg{}, nil
716}
717
718// makePSKPremaster formats a PSK pre-master secret based on otherSecret from
719// the base key exchange and psk.
720func makePSKPremaster(otherSecret, psk []byte) []byte {
721	out := make([]byte, 0, 2+len(otherSecret)+2+len(psk))
722	out = append(out, byte(len(otherSecret)>>8), byte(len(otherSecret)))
723	out = append(out, otherSecret...)
724	out = append(out, byte(len(psk)>>8), byte(len(psk)))
725	out = append(out, psk...)
726	return out
727}
728
729// pskKeyAgreement implements the PSK key agreement.
730type pskKeyAgreement struct {
731	base         keyAgreement
732	identityHint string
733}
734
735func (ka *pskKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
736	// Assemble the identity hint.
737	bytes := make([]byte, 2+len(config.PreSharedKeyIdentity))
738	bytes[0] = byte(len(config.PreSharedKeyIdentity) >> 8)
739	bytes[1] = byte(len(config.PreSharedKeyIdentity))
740	copy(bytes[2:], []byte(config.PreSharedKeyIdentity))
741
742	// If there is one, append the base key agreement's
743	// ServerKeyExchange.
744	baseSkx, err := ka.base.generateServerKeyExchange(config, cert, clientHello, hello)
745	if err != nil {
746		return nil, err
747	}
748
749	if baseSkx != nil {
750		bytes = append(bytes, baseSkx.key...)
751	} else if config.PreSharedKeyIdentity == "" {
752		// ServerKeyExchange is optional if the identity hint is empty
753		// and there would otherwise be no ServerKeyExchange.
754		return nil, nil
755	}
756
757	skx := new(serverKeyExchangeMsg)
758	skx.key = bytes
759	return skx, nil
760}
761
762func (ka *pskKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
763	// First, process the PSK identity.
764	if len(ckx.ciphertext) < 2 {
765		return nil, errClientKeyExchange
766	}
767	identityLen := (int(ckx.ciphertext[0]) << 8) | int(ckx.ciphertext[1])
768	if 2+identityLen > len(ckx.ciphertext) {
769		return nil, errClientKeyExchange
770	}
771	identity := string(ckx.ciphertext[2 : 2+identityLen])
772
773	if identity != config.PreSharedKeyIdentity {
774		return nil, errors.New("tls: unexpected identity")
775	}
776
777	if config.PreSharedKey == nil {
778		return nil, errors.New("tls: pre-shared key not configured")
779	}
780
781	// Process the remainder of the ClientKeyExchange to compute the base
782	// pre-master secret.
783	newCkx := new(clientKeyExchangeMsg)
784	newCkx.ciphertext = ckx.ciphertext[2+identityLen:]
785	otherSecret, err := ka.base.processClientKeyExchange(config, cert, newCkx, version)
786	if err != nil {
787		return nil, err
788	}
789
790	if otherSecret == nil {
791		// Special-case for the plain PSK key exchanges.
792		otherSecret = make([]byte, len(config.PreSharedKey))
793	}
794	return makePSKPremaster(otherSecret, config.PreSharedKey), nil
795}
796
797func (ka *pskKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
798	if len(skx.key) < 2 {
799		return errServerKeyExchange
800	}
801	identityLen := (int(skx.key[0]) << 8) | int(skx.key[1])
802	if 2+identityLen > len(skx.key) {
803		return errServerKeyExchange
804	}
805	ka.identityHint = string(skx.key[2 : 2+identityLen])
806
807	// Process the remainder of the ServerKeyExchange.
808	newSkx := new(serverKeyExchangeMsg)
809	newSkx.key = skx.key[2+identityLen:]
810	return ka.base.processServerKeyExchange(config, clientHello, serverHello, cert, newSkx)
811}
812
813func (ka *pskKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
814	// The server only sends an identity hint but, for purposes of
815	// test code, the server always sends the hint and it is
816	// required to match.
817	if ka.identityHint != config.PreSharedKeyIdentity {
818		return nil, nil, errors.New("tls: unexpected identity")
819	}
820
821	// Serialize the identity.
822	bytes := make([]byte, 2+len(config.PreSharedKeyIdentity))
823	bytes[0] = byte(len(config.PreSharedKeyIdentity) >> 8)
824	bytes[1] = byte(len(config.PreSharedKeyIdentity))
825	copy(bytes[2:], []byte(config.PreSharedKeyIdentity))
826
827	// Append the base key exchange's ClientKeyExchange.
828	otherSecret, baseCkx, err := ka.base.generateClientKeyExchange(config, clientHello, cert)
829	if err != nil {
830		return nil, nil, err
831	}
832	ckx := new(clientKeyExchangeMsg)
833	ckx.ciphertext = append(bytes, baseCkx.ciphertext...)
834
835	if config.PreSharedKey == nil {
836		return nil, nil, errors.New("tls: pre-shared key not configured")
837	}
838	if otherSecret == nil {
839		otherSecret = make([]byte, len(config.PreSharedKey))
840	}
841	return makePSKPremaster(otherSecret, config.PreSharedKey), ckx, nil
842}
843