]> Cypherpunks.ru repositories - gostls13.git/blob - src/crypto/tls/cipher_suites.go
crypto/tls: replace custom *block with standard buffers
[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/aes"
9         "crypto/cipher"
10         "crypto/des"
11         "crypto/hmac"
12         "crypto/rc4"
13         "crypto/sha1"
14         "crypto/sha256"
15         "crypto/x509"
16         "golang_org/x/crypto/chacha20poly1305"
17         "hash"
18 )
19
20 // a keyAgreement implements the client and server side of a TLS key agreement
21 // protocol by generating and processing key exchange messages.
22 type keyAgreement interface {
23         // On the server side, the first two methods are called in order.
24
25         // In the case that the key agreement protocol doesn't use a
26         // ServerKeyExchange message, generateServerKeyExchange can return nil,
27         // nil.
28         generateServerKeyExchange(*Config, *Certificate, *clientHelloMsg, *serverHelloMsg) (*serverKeyExchangeMsg, error)
29         processClientKeyExchange(*Config, *Certificate, *clientKeyExchangeMsg, uint16) ([]byte, error)
30
31         // On the client side, the next two methods are called in order.
32
33         // This method may not be called if the server doesn't send a
34         // ServerKeyExchange message.
35         processServerKeyExchange(*Config, *clientHelloMsg, *serverHelloMsg, *x509.Certificate, *serverKeyExchangeMsg) error
36         generateClientKeyExchange(*Config, *clientHelloMsg, *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error)
37 }
38
39 const (
40         // suiteECDH indicates that the cipher suite involves elliptic curve
41         // Diffie-Hellman. This means that it should only be selected when the
42         // client indicates that it supports ECC with a curve and point format
43         // that we're happy with.
44         suiteECDHE = 1 << iota
45         // suiteECDSA indicates that the cipher suite involves an ECDSA
46         // signature and therefore may only be selected when the server's
47         // certificate is ECDSA. If this is not set then the cipher suite is
48         // RSA based.
49         suiteECDSA
50         // suiteTLS12 indicates that the cipher suite should only be advertised
51         // and accepted when using TLS 1.2.
52         suiteTLS12
53         // suiteSHA384 indicates that the cipher suite uses SHA384 as the
54         // handshake hash.
55         suiteSHA384
56         // suiteDefaultOff indicates that this cipher suite is not included by
57         // default.
58         suiteDefaultOff
59 )
60
61 // A cipherSuite is a specific combination of key agreement, cipher and MAC
62 // function. All cipher suites currently assume RSA key agreement.
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) cipher.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 | suiteECDSA | 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 | suiteECDSA | 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 | suiteECDSA | 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 | suiteECDSA | suiteTLS12 | suiteDefaultOff, cipherAES, macSHA256, nil},
89         {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, 16, 20, 16, ecdheECDSAKA, suiteECDHE | suiteECDSA, 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 | suiteECDSA, 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 | suiteECDSA | suiteDefaultOff, cipherRC4, macSHA1, nil},
104 }
105
106 func cipherRC4(key, iv []byte, isRead bool) interface{} {
107         cipher, _ := rc4.NewCipher(key)
108         return cipher
109 }
110
111 func cipher3DES(key, iv []byte, isRead bool) interface{} {
112         block, _ := des.NewTripleDESCipher(key)
113         if isRead {
114                 return cipher.NewCBCDecrypter(block, iv)
115         }
116         return cipher.NewCBCEncrypter(block, iv)
117 }
118
119 func cipherAES(key, iv []byte, isRead bool) interface{} {
120         block, _ := aes.NewCipher(key)
121         if isRead {
122                 return cipher.NewCBCDecrypter(block, iv)
123         }
124         return cipher.NewCBCEncrypter(block, iv)
125 }
126
127 // macSHA1 returns a macFunction for the given protocol version.
128 func macSHA1(version uint16, key []byte) macFunction {
129         if version == VersionSSL30 {
130                 mac := ssl30MAC{
131                         h:   sha1.New(),
132                         key: make([]byte, len(key)),
133                 }
134                 copy(mac.key, key)
135                 return mac
136         }
137         return tls10MAC{h: hmac.New(newConstantTimeHash(sha1.New), key)}
138 }
139
140 // macSHA256 returns a SHA-256 based MAC. These are only supported in TLS 1.2
141 // so the given version is ignored.
142 func macSHA256(version uint16, key []byte) macFunction {
143         return tls10MAC{h: hmac.New(sha256.New, key)}
144 }
145
146 type macFunction interface {
147         // Size returns the length of the MAC.
148         Size() int
149         // MAC appends the MAC of (seq, header, data) to out. The extra data is fed
150         // into the MAC after obtaining the result to normalize timing. The result
151         // is only valid until the next invocation of MAC as the buffer is reused.
152         MAC(seq, header, data, extra []byte) []byte
153 }
154
155 type aead interface {
156         cipher.AEAD
157
158         // explicitNonceLen returns the number of bytes of explicit nonce
159         // included in each record. This is eight for older AEADs and
160         // zero for modern ones.
161         explicitNonceLen() int
162 }
163
164 // fixedNonceAEAD wraps an AEAD and prefixes a fixed portion of the nonce to
165 // each call.
166 type fixedNonceAEAD struct {
167         // nonce contains the fixed part of the nonce in the first four bytes.
168         nonce [12]byte
169         aead  cipher.AEAD
170 }
171
172 func (f *fixedNonceAEAD) NonceSize() int        { return 8 }
173 func (f *fixedNonceAEAD) Overhead() int         { return f.aead.Overhead() }
174 func (f *fixedNonceAEAD) explicitNonceLen() int { return 8 }
175
176 func (f *fixedNonceAEAD) Seal(out, nonce, plaintext, additionalData []byte) []byte {
177         copy(f.nonce[4:], nonce)
178         return f.aead.Seal(out, f.nonce[:], plaintext, additionalData)
179 }
180
181 func (f *fixedNonceAEAD) Open(out, nonce, plaintext, additionalData []byte) ([]byte, error) {
182         copy(f.nonce[4:], nonce)
183         return f.aead.Open(out, f.nonce[:], plaintext, additionalData)
184 }
185
186 // xoredNonceAEAD wraps an AEAD by XORing in a fixed pattern to the nonce
187 // before each call.
188 type xorNonceAEAD struct {
189         nonceMask [12]byte
190         aead      cipher.AEAD
191 }
192
193 func (f *xorNonceAEAD) NonceSize() int        { return 8 }
194 func (f *xorNonceAEAD) Overhead() int         { return f.aead.Overhead() }
195 func (f *xorNonceAEAD) explicitNonceLen() int { return 0 }
196
197 func (f *xorNonceAEAD) Seal(out, nonce, plaintext, additionalData []byte) []byte {
198         for i, b := range nonce {
199                 f.nonceMask[4+i] ^= b
200         }
201         result := f.aead.Seal(out, f.nonceMask[:], plaintext, additionalData)
202         for i, b := range nonce {
203                 f.nonceMask[4+i] ^= b
204         }
205
206         return result
207 }
208
209 func (f *xorNonceAEAD) Open(out, nonce, plaintext, additionalData []byte) ([]byte, error) {
210         for i, b := range nonce {
211                 f.nonceMask[4+i] ^= b
212         }
213         result, err := f.aead.Open(out, f.nonceMask[:], plaintext, additionalData)
214         for i, b := range nonce {
215                 f.nonceMask[4+i] ^= b
216         }
217
218         return result, err
219 }
220
221 func aeadAESGCM(key, fixedNonce []byte) cipher.AEAD {
222         aes, err := aes.NewCipher(key)
223         if err != nil {
224                 panic(err)
225         }
226         aead, err := cipher.NewGCM(aes)
227         if err != nil {
228                 panic(err)
229         }
230
231         ret := &fixedNonceAEAD{aead: aead}
232         copy(ret.nonce[:], fixedNonce)
233         return ret
234 }
235
236 func aeadChaCha20Poly1305(key, fixedNonce []byte) cipher.AEAD {
237         aead, err := chacha20poly1305.New(key)
238         if err != nil {
239                 panic(err)
240         }
241
242         ret := &xorNonceAEAD{aead: aead}
243         copy(ret.nonceMask[:], fixedNonce)
244         return ret
245 }
246
247 // ssl30MAC implements the SSLv3 MAC function, as defined in
248 // www.mozilla.org/projects/security/pki/nss/ssl/draft302.txt section 5.2.3.1
249 type ssl30MAC struct {
250         h   hash.Hash
251         key []byte
252         buf []byte
253 }
254
255 func (s ssl30MAC) Size() int {
256         return s.h.Size()
257 }
258
259 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}
260
261 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}
262
263 // MAC does not offer constant timing guarantees for SSL v3.0, since it's deemed
264 // useless considering the similar, protocol-level POODLE vulnerability.
265 func (s ssl30MAC) MAC(seq, header, data, extra []byte) []byte {
266         padLength := 48
267         if s.h.Size() == 20 {
268                 padLength = 40
269         }
270
271         s.h.Reset()
272         s.h.Write(s.key)
273         s.h.Write(ssl30Pad1[:padLength])
274         s.h.Write(seq)
275         s.h.Write(header[:1])
276         s.h.Write(header[3:5])
277         s.h.Write(data)
278         s.buf = s.h.Sum(s.buf[:0])
279
280         s.h.Reset()
281         s.h.Write(s.key)
282         s.h.Write(ssl30Pad2[:padLength])
283         s.h.Write(s.buf)
284         return s.h.Sum(s.buf[:0])
285 }
286
287 type constantTimeHash interface {
288         hash.Hash
289         ConstantTimeSum(b []byte) []byte
290 }
291
292 // cthWrapper wraps any hash.Hash that implements ConstantTimeSum, and replaces
293 // with that all calls to Sum. It's used to obtain a ConstantTimeSum-based HMAC.
294 type cthWrapper struct {
295         h constantTimeHash
296 }
297
298 func (c *cthWrapper) Size() int                   { return c.h.Size() }
299 func (c *cthWrapper) BlockSize() int              { return c.h.BlockSize() }
300 func (c *cthWrapper) Reset()                      { c.h.Reset() }
301 func (c *cthWrapper) Write(p []byte) (int, error) { return c.h.Write(p) }
302 func (c *cthWrapper) Sum(b []byte) []byte         { return c.h.ConstantTimeSum(b) }
303
304 func newConstantTimeHash(h func() hash.Hash) func() hash.Hash {
305         return func() hash.Hash {
306                 return &cthWrapper{h().(constantTimeHash)}
307         }
308 }
309
310 // tls10MAC implements the TLS 1.0 MAC function. RFC 2246, Section 6.2.3.
311 type tls10MAC struct {
312         h   hash.Hash
313         buf []byte
314 }
315
316 func (s tls10MAC) Size() int {
317         return s.h.Size()
318 }
319
320 // MAC is guaranteed to take constant time, as long as
321 // len(seq)+len(header)+len(data)+len(extra) is constant. extra is not fed into
322 // the MAC, but is only provided to make the timing profile constant.
323 func (s tls10MAC) MAC(seq, header, data, extra []byte) []byte {
324         s.h.Reset()
325         s.h.Write(seq)
326         s.h.Write(header)
327         s.h.Write(data)
328         res := s.h.Sum(s.buf[:0])
329         if extra != nil {
330                 s.h.Write(extra)
331         }
332         return res
333 }
334
335 func rsaKA(version uint16) keyAgreement {
336         return rsaKeyAgreement{}
337 }
338
339 func ecdheECDSAKA(version uint16) keyAgreement {
340         return &ecdheKeyAgreement{
341                 isRSA:   false,
342                 version: version,
343         }
344 }
345
346 func ecdheRSAKA(version uint16) keyAgreement {
347         return &ecdheKeyAgreement{
348                 isRSA:   true,
349                 version: version,
350         }
351 }
352
353 // mutualCipherSuite returns a cipherSuite given a list of supported
354 // ciphersuites and the id requested by the peer.
355 func mutualCipherSuite(have []uint16, want uint16) *cipherSuite {
356         for _, id := range have {
357                 if id == want {
358                         for _, suite := range cipherSuites {
359                                 if suite.id == want {
360                                         return suite
361                                 }
362                         }
363                         return nil
364                 }
365         }
366         return nil
367 }
368
369 // A list of cipher suite IDs that are, or have been, implemented by this
370 // package.
371 //
372 // Taken from https://www.iana.org/assignments/tls-parameters/tls-parameters.xml
373 const (
374         TLS_RSA_WITH_RC4_128_SHA                uint16 = 0x0005
375         TLS_RSA_WITH_3DES_EDE_CBC_SHA           uint16 = 0x000a
376         TLS_RSA_WITH_AES_128_CBC_SHA            uint16 = 0x002f
377         TLS_RSA_WITH_AES_256_CBC_SHA            uint16 = 0x0035
378         TLS_RSA_WITH_AES_128_CBC_SHA256         uint16 = 0x003c
379         TLS_RSA_WITH_AES_128_GCM_SHA256         uint16 = 0x009c
380         TLS_RSA_WITH_AES_256_GCM_SHA384         uint16 = 0x009d
381         TLS_ECDHE_ECDSA_WITH_RC4_128_SHA        uint16 = 0xc007
382         TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA    uint16 = 0xc009
383         TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA    uint16 = 0xc00a
384         TLS_ECDHE_RSA_WITH_RC4_128_SHA          uint16 = 0xc011
385         TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA     uint16 = 0xc012
386         TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA      uint16 = 0xc013
387         TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA      uint16 = 0xc014
388         TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 uint16 = 0xc023
389         TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256   uint16 = 0xc027
390         TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256   uint16 = 0xc02f
391         TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xc02b
392         TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384   uint16 = 0xc030
393         TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 uint16 = 0xc02c
394         TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305    uint16 = 0xcca8
395         TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305  uint16 = 0xcca9
396
397         // TLS_FALLBACK_SCSV isn't a standard cipher suite but an indicator
398         // that the client is doing version fallback. See RFC 7507.
399         TLS_FALLBACK_SCSV uint16 = 0x5600
400 )