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