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/aes"
9	"crypto/cipher"
10	"crypto/des"
11	"crypto/hmac"
12	"crypto/md5"
13	"crypto/rc4"
14	"crypto/sha1"
15	"crypto/sha256"
16	"crypto/sha512"
17	"crypto/x509"
18	"hash"
19)
20
21// a keyAgreement implements the client and server side of a TLS key agreement
22// protocol by generating and processing key exchange messages.
23type keyAgreement interface {
24	// On the server side, the first two methods are called in order.
25
26	// In the case that the key agreement protocol doesn't use a
27	// ServerKeyExchange message, generateServerKeyExchange can return nil,
28	// nil.
29	generateServerKeyExchange(*Config, *Certificate, *clientHelloMsg, *serverHelloMsg) (*serverKeyExchangeMsg, error)
30	processClientKeyExchange(*Config, *Certificate, *clientKeyExchangeMsg, uint16) ([]byte, error)
31
32	// On the client side, the next two methods are called in order.
33
34	// This method may not be called if the server doesn't send a
35	// ServerKeyExchange message.
36	processServerKeyExchange(*Config, *clientHelloMsg, *serverHelloMsg, *x509.Certificate, *serverKeyExchangeMsg) error
37	generateClientKeyExchange(*Config, *clientHelloMsg, *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error)
38}
39
40const (
41	// suiteECDH indicates that the cipher suite involves elliptic curve
42	// Diffie-Hellman. This means that it should only be selected when the
43	// client indicates that it supports ECC with a curve and point format
44	// that we're happy with.
45	suiteECDHE = 1 << iota
46	// suiteECDSA indicates that the cipher suite involves an ECDSA
47	// signature and therefore may only be selected when the server's
48	// certificate is ECDSA. If this is not set then the cipher suite is
49	// RSA based.
50	suiteECDSA
51	// suiteTLS12 indicates that the cipher suite should only be advertised
52	// and accepted when using TLS 1.2.
53	suiteTLS12
54	// suiteSHA384 indicates that the cipher suite uses SHA384 as the
55	// handshake hash.
56	suiteSHA384
57	// suiteNoDTLS indicates that the cipher suite cannot be used
58	// in DTLS.
59	suiteNoDTLS
60	// suitePSK indicates that the cipher suite authenticates with
61	// a pre-shared key rather than a server private key.
62	suitePSK
63)
64
65type tlsAead struct {
66	cipher.AEAD
67	explicitNonce bool
68}
69
70// A cipherSuite is a specific combination of key agreement, cipher and MAC
71// function. All cipher suites currently assume RSA key agreement.
72type cipherSuite struct {
73	id uint16
74	// the lengths, in bytes, of the key material needed for each component.
75	keyLen int
76	macLen int
77	ivLen  int
78	ka     func(version uint16) keyAgreement
79	// flags is a bitmask of the suite* values, above.
80	flags  int
81	cipher func(key, iv []byte, isRead bool) interface{}
82	mac    func(version uint16, macKey []byte) macFunction
83	aead   func(key, fixedNonce []byte) *tlsAead
84}
85
86var cipherSuites = []*cipherSuite{
87	// Ciphersuite order is chosen so that ECDHE comes before plain RSA
88	// and RC4 comes before AES (because of the Lucky13 attack).
89	{TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, 32, 0, 0, ecdheECDSAKA, suiteECDHE | suiteECDSA | suiteTLS12, nil, nil, aeadCHACHA20POLY1305},
90	{TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, 32, 0, 0, ecdheRSAKA, suiteECDHE | suiteTLS12, nil, nil, aeadCHACHA20POLY1305},
91	{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, ecdheRSAKA, suiteECDHE | suiteTLS12, nil, nil, aeadAESGCM},
92	{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, ecdheECDSAKA, suiteECDHE | suiteECDSA | suiteTLS12, nil, nil, aeadAESGCM},
93	{TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 32, 0, 4, ecdheRSAKA, suiteECDHE | suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM},
94	{TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, 32, 0, 4, ecdheECDSAKA, suiteECDHE | suiteECDSA | suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM},
95	{TLS_ECDHE_RSA_WITH_RC4_128_SHA, 16, 20, 0, ecdheRSAKA, suiteECDHE | suiteNoDTLS, cipherRC4, macSHA1, nil},
96	{TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, 16, 20, 0, ecdheECDSAKA, suiteECDHE | suiteECDSA | suiteNoDTLS, cipherRC4, macSHA1, nil},
97	{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, 16, 32, 16, ecdheRSAKA, suiteECDHE | suiteTLS12, cipherAES, macSHA256, nil},
98	{TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, 16, 32, 16, ecdheECDSAKA, suiteECDHE | suiteECDSA | suiteTLS12, cipherAES, macSHA256, nil},
99	{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, 16, 20, 16, ecdheRSAKA, suiteECDHE, cipherAES, macSHA1, nil},
100	{TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, 16, 20, 16, ecdheECDSAKA, suiteECDHE | suiteECDSA, cipherAES, macSHA1, nil},
101	{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, 32, 48, 16, ecdheRSAKA, suiteECDHE | suiteTLS12 | suiteSHA384, cipherAES, macSHA384, nil},
102	{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, 32, 48, 16, ecdheECDSAKA, suiteECDHE | suiteECDSA | suiteTLS12 | suiteSHA384, cipherAES, macSHA384, nil},
103	{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, 32, 20, 16, ecdheRSAKA, suiteECDHE, cipherAES, macSHA1, nil},
104	{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, 32, 20, 16, ecdheECDSAKA, suiteECDHE | suiteECDSA, cipherAES, macSHA1, nil},
105	{TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, 32, 0, 0, dheRSAKA, suiteTLS12, nil, nil, aeadCHACHA20POLY1305},
106	{TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, dheRSAKA, suiteTLS12, nil, nil, aeadAESGCM},
107	{TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, 32, 0, 4, dheRSAKA, suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM},
108	{TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, 16, 32, 16, dheRSAKA, suiteTLS12, cipherAES, macSHA256, nil},
109	{TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, 32, 32, 16, dheRSAKA, suiteTLS12, cipherAES, macSHA256, nil},
110	{TLS_DHE_RSA_WITH_AES_128_CBC_SHA, 16, 20, 16, dheRSAKA, 0, cipherAES, macSHA1, nil},
111	{TLS_DHE_RSA_WITH_AES_256_CBC_SHA, 32, 20, 16, dheRSAKA, 0, cipherAES, macSHA1, nil},
112	{TLS_RSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, rsaKA, suiteTLS12, nil, nil, aeadAESGCM},
113	{TLS_RSA_WITH_AES_256_GCM_SHA384, 32, 0, 4, rsaKA, suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM},
114	{TLS_RSA_WITH_RC4_128_SHA, 16, 20, 0, rsaKA, suiteNoDTLS, cipherRC4, macSHA1, nil},
115	{TLS_RSA_WITH_RC4_128_MD5, 16, 16, 0, rsaKA, suiteNoDTLS, cipherRC4, macMD5, nil},
116	{TLS_RSA_WITH_AES_128_CBC_SHA256, 16, 32, 16, rsaKA, suiteTLS12, cipherAES, macSHA256, nil},
117	{TLS_RSA_WITH_AES_256_CBC_SHA256, 32, 32, 16, rsaKA, suiteTLS12, cipherAES, macSHA256, nil},
118	{TLS_RSA_WITH_AES_128_CBC_SHA, 16, 20, 16, rsaKA, 0, cipherAES, macSHA1, nil},
119	{TLS_RSA_WITH_AES_256_CBC_SHA, 32, 20, 16, rsaKA, 0, cipherAES, macSHA1, nil},
120	{TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, 24, 20, 8, ecdheRSAKA, suiteECDHE, cipher3DES, macSHA1, nil},
121	{TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, 24, 20, 8, dheRSAKA, 0, cipher3DES, macSHA1, nil},
122	{TLS_RSA_WITH_3DES_EDE_CBC_SHA, 24, 20, 8, rsaKA, 0, cipher3DES, macSHA1, nil},
123	{TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256, 16, 0, 4, ecdhePSKKA, suiteECDHE | suiteTLS12 | suitePSK, nil, nil, aeadAESGCM},
124	{TLS_PSK_WITH_RC4_128_SHA, 16, 20, 0, pskKA, suiteNoDTLS | suitePSK, cipherRC4, macSHA1, nil},
125	{TLS_PSK_WITH_AES_128_CBC_SHA, 16, 20, 16, pskKA, suitePSK, cipherAES, macSHA1, nil},
126	{TLS_PSK_WITH_AES_256_CBC_SHA, 32, 20, 16, pskKA, suitePSK, cipherAES, macSHA1, nil},
127	{TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA, 16, 20, 16, ecdhePSKKA, suiteECDHE | suitePSK, cipherAES, macSHA1, nil},
128	{TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA, 32, 20, 16, ecdhePSKKA, suiteECDHE | suitePSK, cipherAES, macSHA1, nil},
129}
130
131func cipherRC4(key, iv []byte, isRead bool) interface{} {
132	cipher, _ := rc4.NewCipher(key)
133	return cipher
134}
135
136func cipher3DES(key, iv []byte, isRead bool) interface{} {
137	block, _ := des.NewTripleDESCipher(key)
138	if isRead {
139		return cipher.NewCBCDecrypter(block, iv)
140	}
141	return cipher.NewCBCEncrypter(block, iv)
142}
143
144func cipherAES(key, iv []byte, isRead bool) interface{} {
145	block, _ := aes.NewCipher(key)
146	if isRead {
147		return cipher.NewCBCDecrypter(block, iv)
148	}
149	return cipher.NewCBCEncrypter(block, iv)
150}
151
152// macSHA1 returns a macFunction for the given protocol version.
153func macSHA1(version uint16, key []byte) macFunction {
154	if version == VersionSSL30 {
155		mac := ssl30MAC{
156			h:   sha1.New(),
157			key: make([]byte, len(key)),
158		}
159		copy(mac.key, key)
160		return mac
161	}
162	return tls10MAC{hmac.New(sha1.New, key)}
163}
164
165func macMD5(version uint16, key []byte) macFunction {
166	if version == VersionSSL30 {
167		mac := ssl30MAC{
168			h:   md5.New(),
169			key: make([]byte, len(key)),
170		}
171		copy(mac.key, key)
172		return mac
173	}
174	return tls10MAC{hmac.New(md5.New, key)}
175}
176
177func macSHA256(version uint16, key []byte) macFunction {
178	if version == VersionSSL30 {
179		mac := ssl30MAC{
180			h:   sha256.New(),
181			key: make([]byte, len(key)),
182		}
183		copy(mac.key, key)
184		return mac
185	}
186	return tls10MAC{hmac.New(sha256.New, key)}
187}
188
189func macSHA384(version uint16, key []byte) macFunction {
190	if version == VersionSSL30 {
191		mac := ssl30MAC{
192			h:   sha512.New384(),
193			key: make([]byte, len(key)),
194		}
195		copy(mac.key, key)
196		return mac
197	}
198	return tls10MAC{hmac.New(sha512.New384, key)}
199}
200
201type macFunction interface {
202	Size() int
203	MAC(digestBuf, seq, header, length, data []byte) []byte
204}
205
206// fixedNonceAEAD wraps an AEAD and prefixes a fixed portion of the nonce to
207// each call.
208type fixedNonceAEAD struct {
209	// sealNonce and openNonce are buffers where the larger nonce will be
210	// constructed. Since a seal and open operation may be running
211	// concurrently, there is a separate buffer for each.
212	sealNonce, openNonce []byte
213	aead                 cipher.AEAD
214}
215
216func (f *fixedNonceAEAD) NonceSize() int { return 8 }
217func (f *fixedNonceAEAD) Overhead() int  { return f.aead.Overhead() }
218
219func (f *fixedNonceAEAD) Seal(out, nonce, plaintext, additionalData []byte) []byte {
220	copy(f.sealNonce[len(f.sealNonce)-8:], nonce)
221	return f.aead.Seal(out, f.sealNonce, plaintext, additionalData)
222}
223
224func (f *fixedNonceAEAD) Open(out, nonce, plaintext, additionalData []byte) ([]byte, error) {
225	copy(f.openNonce[len(f.openNonce)-8:], nonce)
226	return f.aead.Open(out, f.openNonce, plaintext, additionalData)
227}
228
229func aeadAESGCM(key, fixedNonce []byte) *tlsAead {
230	aes, err := aes.NewCipher(key)
231	if err != nil {
232		panic(err)
233	}
234	aead, err := cipher.NewGCM(aes)
235	if err != nil {
236		panic(err)
237	}
238
239	nonce1, nonce2 := make([]byte, 12), make([]byte, 12)
240	copy(nonce1, fixedNonce)
241	copy(nonce2, fixedNonce)
242
243	return &tlsAead{&fixedNonceAEAD{nonce1, nonce2, aead}, true}
244}
245
246func aeadCHACHA20POLY1305(key, fixedNonce []byte) *tlsAead {
247	aead, err := newChaCha20Poly1305(key)
248	if err != nil {
249		panic(err)
250	}
251	return &tlsAead{aead, false}
252}
253
254// ssl30MAC implements the SSLv3 MAC function, as defined in
255// www.mozilla.org/projects/security/pki/nss/ssl/draft302.txt section 5.2.3.1
256type ssl30MAC struct {
257	h   hash.Hash
258	key []byte
259}
260
261func (s ssl30MAC) Size() int {
262	return s.h.Size()
263}
264
265var ssl30Pad1 = [48]byte{0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36}
266
267var ssl30Pad2 = [48]byte{0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c}
268
269func (s ssl30MAC) MAC(digestBuf, seq, header, length, data []byte) []byte {
270	padLength := 48
271	if s.h.Size() == 20 {
272		padLength = 40
273	}
274
275	s.h.Reset()
276	s.h.Write(s.key)
277	s.h.Write(ssl30Pad1[:padLength])
278	s.h.Write(seq)
279	s.h.Write(header[:1])
280	s.h.Write(length)
281	s.h.Write(data)
282	digestBuf = s.h.Sum(digestBuf[:0])
283
284	s.h.Reset()
285	s.h.Write(s.key)
286	s.h.Write(ssl30Pad2[:padLength])
287	s.h.Write(digestBuf)
288	return s.h.Sum(digestBuf[:0])
289}
290
291// tls10MAC implements the TLS 1.0 MAC function. RFC 2246, section 6.2.3.
292type tls10MAC struct {
293	h hash.Hash
294}
295
296func (s tls10MAC) Size() int {
297	return s.h.Size()
298}
299
300func (s tls10MAC) MAC(digestBuf, seq, header, length, data []byte) []byte {
301	s.h.Reset()
302	s.h.Write(seq)
303	s.h.Write(header)
304	s.h.Write(length)
305	s.h.Write(data)
306	return s.h.Sum(digestBuf[:0])
307}
308
309func rsaKA(version uint16) keyAgreement {
310	return &rsaKeyAgreement{version: version}
311}
312
313func ecdheECDSAKA(version uint16) keyAgreement {
314	return &ecdheKeyAgreement{
315		auth: &signedKeyAgreement{
316			sigType: signatureECDSA,
317			version: version,
318		},
319	}
320}
321
322func ecdheRSAKA(version uint16) keyAgreement {
323	return &ecdheKeyAgreement{
324		auth: &signedKeyAgreement{
325			sigType: signatureRSA,
326			version: version,
327		},
328	}
329}
330
331func dheRSAKA(version uint16) keyAgreement {
332	return &dheKeyAgreement{
333		auth: &signedKeyAgreement{
334			sigType: signatureRSA,
335			version: version,
336		},
337	}
338}
339
340func pskKA(version uint16) keyAgreement {
341	return &pskKeyAgreement{
342		base: &nilKeyAgreement{},
343	}
344}
345
346func ecdhePSKKA(version uint16) keyAgreement {
347	return &pskKeyAgreement{
348		base: &ecdheKeyAgreement{
349			auth: &nilKeyAgreementAuthentication{},
350		},
351	}
352}
353
354// mutualCipherSuite returns a cipherSuite given a list of supported
355// ciphersuites and the id requested by the peer.
356func mutualCipherSuite(have []uint16, want uint16) *cipherSuite {
357	for _, id := range have {
358		if id == want {
359			for _, suite := range cipherSuites {
360				if suite.id == want {
361					return suite
362				}
363			}
364			return nil
365		}
366	}
367	return nil
368}
369
370// A list of the possible cipher suite ids. Taken from
371// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml
372const (
373	TLS_RSA_WITH_RC4_128_MD5                uint16 = 0x0004
374	TLS_RSA_WITH_RC4_128_SHA                uint16 = 0x0005
375	TLS_RSA_WITH_3DES_EDE_CBC_SHA           uint16 = 0x000a
376	TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA       uint16 = 0x0016
377	TLS_RSA_WITH_AES_128_CBC_SHA            uint16 = 0x002f
378	TLS_DHE_RSA_WITH_AES_128_CBC_SHA        uint16 = 0x0033
379	TLS_RSA_WITH_AES_256_CBC_SHA            uint16 = 0x0035
380	TLS_DHE_RSA_WITH_AES_256_CBC_SHA        uint16 = 0x0039
381	TLS_RSA_WITH_AES_128_CBC_SHA256         uint16 = 0x003c
382	TLS_RSA_WITH_AES_256_CBC_SHA256         uint16 = 0x003d
383	TLS_DHE_RSA_WITH_AES_128_CBC_SHA256     uint16 = 0x0067
384	TLS_DHE_RSA_WITH_AES_256_CBC_SHA256     uint16 = 0x006b
385	TLS_PSK_WITH_RC4_128_SHA                uint16 = 0x008a
386	TLS_PSK_WITH_AES_128_CBC_SHA            uint16 = 0x008c
387	TLS_PSK_WITH_AES_256_CBC_SHA            uint16 = 0x008d
388	TLS_RSA_WITH_AES_128_GCM_SHA256         uint16 = 0x009c
389	TLS_RSA_WITH_AES_256_GCM_SHA384         uint16 = 0x009d
390	TLS_DHE_RSA_WITH_AES_128_GCM_SHA256     uint16 = 0x009e
391	TLS_DHE_RSA_WITH_AES_256_GCM_SHA384     uint16 = 0x009f
392	TLS_ECDHE_ECDSA_WITH_RC4_128_SHA        uint16 = 0xc007
393	TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA    uint16 = 0xc009
394	TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA    uint16 = 0xc00a
395	TLS_ECDHE_RSA_WITH_RC4_128_SHA          uint16 = 0xc011
396	TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA     uint16 = 0xc012
397	TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA      uint16 = 0xc013
398	TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA      uint16 = 0xc014
399	TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 uint16 = 0xc023
400	TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 uint16 = 0xc024
401	TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256   uint16 = 0xc027
402	TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384   uint16 = 0xc028
403	TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xc02b
404	TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 uint16 = 0xc02c
405	TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256   uint16 = 0xc02f
406	TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384   uint16 = 0xc030
407	TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA      uint16 = 0xc035
408	TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA      uint16 = 0xc036
409	fallbackSCSV                            uint16 = 0x5600
410)
411
412// Additional cipher suite IDs, not IANA-assigned.
413const (
414	TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256         uint16 = 0xcafe
415	TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256   uint16 = 0xcc13
416	TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xcc14
417	TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256     uint16 = 0xcc15
418)
419