]> Cypherpunks.ru repositories - gostls13.git/blob - src/crypto/tls/cipher_suites.go
crypto/tls: add correct names for CHACHA20_POLY1305 cipher suite constants
[gostls13.git] / src / crypto / tls / cipher_suites.go
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
5 package tls
6
7 import (
8         "crypto"
9         "crypto/aes"
10         "crypto/cipher"
11         "crypto/des"
12         "crypto/hmac"
13         "crypto/rc4"
14         "crypto/sha1"
15         "crypto/sha256"
16         "crypto/x509"
17         "golang.org/x/crypto/chacha20poly1305"
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.
23 type 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
40 const (
41         // suiteECDHE 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         // suiteECSign indicates that the cipher suite involves an ECDSA or
47         // EdDSA signature and therefore may only be selected when the server's
48         // certificate is ECDSA or EdDSA. If this is not set then the cipher suite
49         // is RSA based.
50         suiteECSign
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         // suiteDefaultOff indicates that this cipher suite is not included by
58         // default.
59         suiteDefaultOff
60 )
61
62 // A cipherSuite is a specific combination of key agreement, cipher and MAC function.
63 type cipherSuite struct {
64         id uint16
65         // the lengths, in bytes, of the key material needed for each component.
66         keyLen int
67         macLen int
68         ivLen  int
69         ka     func(version uint16) keyAgreement
70         // flags is a bitmask of the suite* values, above.
71         flags  int
72         cipher func(key, iv []byte, isRead bool) interface{}
73         mac    func(version uint16, macKey []byte) macFunction
74         aead   func(key, fixedNonce []byte) aead
75 }
76
77 var cipherSuites = []*cipherSuite{
78         // Ciphersuite order is chosen so that ECDHE comes before plain RSA and
79         // AEADs are the top preference.
80         {TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 32, 0, 12, ecdheRSAKA, suiteECDHE | suiteTLS12, nil, nil, aeadChaCha20Poly1305},
81         {TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, 32, 0, 12, ecdheECDSAKA, suiteECDHE | suiteECSign | suiteTLS12, nil, nil, aeadChaCha20Poly1305},
82         {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, ecdheRSAKA, suiteECDHE | suiteTLS12, nil, nil, aeadAESGCM},
83         {TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, ecdheECDSAKA, suiteECDHE | suiteECSign | suiteTLS12, nil, nil, aeadAESGCM},
84         {TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 32, 0, 4, ecdheRSAKA, suiteECDHE | suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM},
85         {TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, 32, 0, 4, ecdheECDSAKA, suiteECDHE | suiteECSign | suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM},
86         {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, 16, 32, 16, ecdheRSAKA, suiteECDHE | suiteTLS12 | suiteDefaultOff, cipherAES, macSHA256, nil},
87         {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, 16, 20, 16, ecdheRSAKA, suiteECDHE, cipherAES, macSHA1, nil},
88         {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, 16, 32, 16, ecdheECDSAKA, suiteECDHE | suiteECSign | suiteTLS12 | suiteDefaultOff, cipherAES, macSHA256, nil},
89         {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, 16, 20, 16, ecdheECDSAKA, suiteECDHE | suiteECSign, cipherAES, macSHA1, nil},
90         {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, 32, 20, 16, ecdheRSAKA, suiteECDHE, cipherAES, macSHA1, nil},
91         {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, 32, 20, 16, ecdheECDSAKA, suiteECDHE | suiteECSign, cipherAES, macSHA1, nil},
92         {TLS_RSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, rsaKA, suiteTLS12, nil, nil, aeadAESGCM},
93         {TLS_RSA_WITH_AES_256_GCM_SHA384, 32, 0, 4, rsaKA, suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM},
94         {TLS_RSA_WITH_AES_128_CBC_SHA256, 16, 32, 16, rsaKA, suiteTLS12 | suiteDefaultOff, cipherAES, macSHA256, nil},
95         {TLS_RSA_WITH_AES_128_CBC_SHA, 16, 20, 16, rsaKA, 0, cipherAES, macSHA1, nil},
96         {TLS_RSA_WITH_AES_256_CBC_SHA, 32, 20, 16, rsaKA, 0, cipherAES, macSHA1, nil},
97         {TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, 24, 20, 8, ecdheRSAKA, suiteECDHE, cipher3DES, macSHA1, nil},
98         {TLS_RSA_WITH_3DES_EDE_CBC_SHA, 24, 20, 8, rsaKA, 0, cipher3DES, macSHA1, nil},
99
100         // RC4-based cipher suites are disabled by default.
101         {TLS_RSA_WITH_RC4_128_SHA, 16, 20, 0, rsaKA, suiteDefaultOff, cipherRC4, macSHA1, nil},
102         {TLS_ECDHE_RSA_WITH_RC4_128_SHA, 16, 20, 0, ecdheRSAKA, suiteECDHE | suiteDefaultOff, cipherRC4, macSHA1, nil},
103         {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, 16, 20, 0, ecdheECDSAKA, suiteECDHE | suiteECSign | suiteDefaultOff, cipherRC4, macSHA1, nil},
104 }
105
106 // selectCipherSuite returns the first cipher suite from ids which is also in
107 // supportedIDs and passes the ok filter.
108 func selectCipherSuite(ids, supportedIDs []uint16, ok func(*cipherSuite) bool) *cipherSuite {
109         for _, id := range ids {
110                 candidate := cipherSuiteByID(id)
111                 if candidate == nil || !ok(candidate) {
112                         continue
113                 }
114
115                 for _, suppID := range supportedIDs {
116                         if id == suppID {
117                                 return candidate
118                         }
119                 }
120         }
121         return nil
122 }
123
124 // A cipherSuiteTLS13 defines only the pair of the AEAD algorithm and hash
125 // algorithm to be used with HKDF. See RFC 8446, Appendix B.4.
126 type cipherSuiteTLS13 struct {
127         id     uint16
128         keyLen int
129         aead   func(key, fixedNonce []byte) aead
130         hash   crypto.Hash
131 }
132
133 var cipherSuitesTLS13 = []*cipherSuiteTLS13{
134         {TLS_AES_128_GCM_SHA256, 16, aeadAESGCMTLS13, crypto.SHA256},
135         {TLS_CHACHA20_POLY1305_SHA256, 32, aeadChaCha20Poly1305, crypto.SHA256},
136         {TLS_AES_256_GCM_SHA384, 32, aeadAESGCMTLS13, crypto.SHA384},
137 }
138
139 func cipherRC4(key, iv []byte, isRead bool) interface{} {
140         cipher, _ := rc4.NewCipher(key)
141         return cipher
142 }
143
144 func cipher3DES(key, iv []byte, isRead bool) interface{} {
145         block, _ := des.NewTripleDESCipher(key)
146         if isRead {
147                 return cipher.NewCBCDecrypter(block, iv)
148         }
149         return cipher.NewCBCEncrypter(block, iv)
150 }
151
152 func cipherAES(key, iv []byte, isRead bool) interface{} {
153         block, _ := aes.NewCipher(key)
154         if isRead {
155                 return cipher.NewCBCDecrypter(block, iv)
156         }
157         return cipher.NewCBCEncrypter(block, iv)
158 }
159
160 // macSHA1 returns a macFunction for the given protocol version.
161 func macSHA1(version uint16, key []byte) macFunction {
162         return tls10MAC{h: hmac.New(newConstantTimeHash(sha1.New), key)}
163 }
164
165 // macSHA256 returns a SHA-256 based MAC. These are only supported in TLS 1.2
166 // so the given version is ignored.
167 func macSHA256(version uint16, key []byte) macFunction {
168         return tls10MAC{h: hmac.New(sha256.New, key)}
169 }
170
171 type macFunction interface {
172         // Size returns the length of the MAC.
173         Size() int
174         // MAC appends the MAC of (seq, header, data) to out. The extra data is fed
175         // into the MAC after obtaining the result to normalize timing. The result
176         // is only valid until the next invocation of MAC as the buffer is reused.
177         MAC(seq, header, data, extra []byte) []byte
178 }
179
180 type aead interface {
181         cipher.AEAD
182
183         // explicitNonceLen returns the number of bytes of explicit nonce
184         // included in each record. This is eight for older AEADs and
185         // zero for modern ones.
186         explicitNonceLen() int
187 }
188
189 const (
190         aeadNonceLength   = 12
191         noncePrefixLength = 4
192 )
193
194 // prefixNonceAEAD wraps an AEAD and prefixes a fixed portion of the nonce to
195 // each call.
196 type prefixNonceAEAD struct {
197         // nonce contains the fixed part of the nonce in the first four bytes.
198         nonce [aeadNonceLength]byte
199         aead  cipher.AEAD
200 }
201
202 func (f *prefixNonceAEAD) NonceSize() int        { return aeadNonceLength - noncePrefixLength }
203 func (f *prefixNonceAEAD) Overhead() int         { return f.aead.Overhead() }
204 func (f *prefixNonceAEAD) explicitNonceLen() int { return f.NonceSize() }
205
206 func (f *prefixNonceAEAD) Seal(out, nonce, plaintext, additionalData []byte) []byte {
207         copy(f.nonce[4:], nonce)
208         return f.aead.Seal(out, f.nonce[:], plaintext, additionalData)
209 }
210
211 func (f *prefixNonceAEAD) Open(out, nonce, ciphertext, additionalData []byte) ([]byte, error) {
212         copy(f.nonce[4:], nonce)
213         return f.aead.Open(out, f.nonce[:], ciphertext, additionalData)
214 }
215
216 // xoredNonceAEAD wraps an AEAD by XORing in a fixed pattern to the nonce
217 // before each call.
218 type xorNonceAEAD struct {
219         nonceMask [aeadNonceLength]byte
220         aead      cipher.AEAD
221 }
222
223 func (f *xorNonceAEAD) NonceSize() int        { return 8 } // 64-bit sequence number
224 func (f *xorNonceAEAD) Overhead() int         { return f.aead.Overhead() }
225 func (f *xorNonceAEAD) explicitNonceLen() int { return 0 }
226
227 func (f *xorNonceAEAD) Seal(out, nonce, plaintext, additionalData []byte) []byte {
228         for i, b := range nonce {
229                 f.nonceMask[4+i] ^= b
230         }
231         result := f.aead.Seal(out, f.nonceMask[:], plaintext, additionalData)
232         for i, b := range nonce {
233                 f.nonceMask[4+i] ^= b
234         }
235
236         return result
237 }
238
239 func (f *xorNonceAEAD) Open(out, nonce, ciphertext, additionalData []byte) ([]byte, error) {
240         for i, b := range nonce {
241                 f.nonceMask[4+i] ^= b
242         }
243         result, err := f.aead.Open(out, f.nonceMask[:], ciphertext, additionalData)
244         for i, b := range nonce {
245                 f.nonceMask[4+i] ^= b
246         }
247
248         return result, err
249 }
250
251 func aeadAESGCM(key, noncePrefix []byte) aead {
252         if len(noncePrefix) != noncePrefixLength {
253                 panic("tls: internal error: wrong nonce length")
254         }
255         aes, err := aes.NewCipher(key)
256         if err != nil {
257                 panic(err)
258         }
259         aead, err := cipher.NewGCM(aes)
260         if err != nil {
261                 panic(err)
262         }
263
264         ret := &prefixNonceAEAD{aead: aead}
265         copy(ret.nonce[:], noncePrefix)
266         return ret
267 }
268
269 func aeadAESGCMTLS13(key, nonceMask []byte) aead {
270         if len(nonceMask) != aeadNonceLength {
271                 panic("tls: internal error: wrong nonce length")
272         }
273         aes, err := aes.NewCipher(key)
274         if err != nil {
275                 panic(err)
276         }
277         aead, err := cipher.NewGCM(aes)
278         if err != nil {
279                 panic(err)
280         }
281
282         ret := &xorNonceAEAD{aead: aead}
283         copy(ret.nonceMask[:], nonceMask)
284         return ret
285 }
286
287 func aeadChaCha20Poly1305(key, nonceMask []byte) aead {
288         if len(nonceMask) != aeadNonceLength {
289                 panic("tls: internal error: wrong nonce length")
290         }
291         aead, err := chacha20poly1305.New(key)
292         if err != nil {
293                 panic(err)
294         }
295
296         ret := &xorNonceAEAD{aead: aead}
297         copy(ret.nonceMask[:], nonceMask)
298         return ret
299 }
300
301 type constantTimeHash interface {
302         hash.Hash
303         ConstantTimeSum(b []byte) []byte
304 }
305
306 // cthWrapper wraps any hash.Hash that implements ConstantTimeSum, and replaces
307 // with that all calls to Sum. It's used to obtain a ConstantTimeSum-based HMAC.
308 type cthWrapper struct {
309         h constantTimeHash
310 }
311
312 func (c *cthWrapper) Size() int                   { return c.h.Size() }
313 func (c *cthWrapper) BlockSize() int              { return c.h.BlockSize() }
314 func (c *cthWrapper) Reset()                      { c.h.Reset() }
315 func (c *cthWrapper) Write(p []byte) (int, error) { return c.h.Write(p) }
316 func (c *cthWrapper) Sum(b []byte) []byte         { return c.h.ConstantTimeSum(b) }
317
318 func newConstantTimeHash(h func() hash.Hash) func() hash.Hash {
319         return func() hash.Hash {
320                 return &cthWrapper{h().(constantTimeHash)}
321         }
322 }
323
324 // tls10MAC implements the TLS 1.0 MAC function. RFC 2246, Section 6.2.3.
325 type tls10MAC struct {
326         h   hash.Hash
327         buf []byte
328 }
329
330 func (s tls10MAC) Size() int {
331         return s.h.Size()
332 }
333
334 // MAC is guaranteed to take constant time, as long as
335 // len(seq)+len(header)+len(data)+len(extra) is constant. extra is not fed into
336 // the MAC, but is only provided to make the timing profile constant.
337 func (s tls10MAC) MAC(seq, header, data, extra []byte) []byte {
338         s.h.Reset()
339         s.h.Write(seq)
340         s.h.Write(header)
341         s.h.Write(data)
342         res := s.h.Sum(s.buf[:0])
343         if extra != nil {
344                 s.h.Write(extra)
345         }
346         return res
347 }
348
349 func rsaKA(version uint16) keyAgreement {
350         return rsaKeyAgreement{}
351 }
352
353 func ecdheECDSAKA(version uint16) keyAgreement {
354         return &ecdheKeyAgreement{
355                 isRSA:   false,
356                 version: version,
357         }
358 }
359
360 func ecdheRSAKA(version uint16) keyAgreement {
361         return &ecdheKeyAgreement{
362                 isRSA:   true,
363                 version: version,
364         }
365 }
366
367 // mutualCipherSuite returns a cipherSuite given a list of supported
368 // ciphersuites and the id requested by the peer.
369 func mutualCipherSuite(have []uint16, want uint16) *cipherSuite {
370         for _, id := range have {
371                 if id == want {
372                         return cipherSuiteByID(id)
373                 }
374         }
375         return nil
376 }
377
378 func cipherSuiteByID(id uint16) *cipherSuite {
379         for _, cipherSuite := range cipherSuites {
380                 if cipherSuite.id == id {
381                         return cipherSuite
382                 }
383         }
384         return nil
385 }
386
387 func mutualCipherSuiteTLS13(have []uint16, want uint16) *cipherSuiteTLS13 {
388         for _, id := range have {
389                 if id == want {
390                         return cipherSuiteTLS13ByID(id)
391                 }
392         }
393         return nil
394 }
395
396 func cipherSuiteTLS13ByID(id uint16) *cipherSuiteTLS13 {
397         for _, cipherSuite := range cipherSuitesTLS13 {
398                 if cipherSuite.id == id {
399                         return cipherSuite
400                 }
401         }
402         return nil
403 }
404
405 // A list of cipher suite IDs that are, or have been, implemented by this
406 // package.
407 //
408 // See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml
409 const (
410         // TLS 1.0 - 1.2 cipher suites.
411         TLS_RSA_WITH_RC4_128_SHA                      uint16 = 0x0005
412         TLS_RSA_WITH_3DES_EDE_CBC_SHA                 uint16 = 0x000a
413         TLS_RSA_WITH_AES_128_CBC_SHA                  uint16 = 0x002f
414         TLS_RSA_WITH_AES_256_CBC_SHA                  uint16 = 0x0035
415         TLS_RSA_WITH_AES_128_CBC_SHA256               uint16 = 0x003c
416         TLS_RSA_WITH_AES_128_GCM_SHA256               uint16 = 0x009c
417         TLS_RSA_WITH_AES_256_GCM_SHA384               uint16 = 0x009d
418         TLS_ECDHE_ECDSA_WITH_RC4_128_SHA              uint16 = 0xc007
419         TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA          uint16 = 0xc009
420         TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA          uint16 = 0xc00a
421         TLS_ECDHE_RSA_WITH_RC4_128_SHA                uint16 = 0xc011
422         TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA           uint16 = 0xc012
423         TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA            uint16 = 0xc013
424         TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA            uint16 = 0xc014
425         TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256       uint16 = 0xc023
426         TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256         uint16 = 0xc027
427         TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256         uint16 = 0xc02f
428         TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256       uint16 = 0xc02b
429         TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384         uint16 = 0xc030
430         TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384       uint16 = 0xc02c
431         TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256   uint16 = 0xcca8
432         TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xcca9
433
434         // TLS 1.3 cipher suites.
435         TLS_AES_128_GCM_SHA256       uint16 = 0x1301
436         TLS_AES_256_GCM_SHA384       uint16 = 0x1302
437         TLS_CHACHA20_POLY1305_SHA256 uint16 = 0x1303
438
439         // TLS_FALLBACK_SCSV isn't a standard cipher suite but an indicator
440         // that the client is doing version fallback. See RFC 7507.
441         TLS_FALLBACK_SCSV uint16 = 0x5600
442
443         // Legacy names for the corresponding cipher suites with the correct _SHA256
444         // suffix, retained for backward compatibility.
445         TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305   = TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
446         TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305 = TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
447 )