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