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