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