]> Cypherpunks.ru repositories - gostls13.git/blob - src/crypto/tls/cipher_suites.go
all: gofmt main repo
[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         "fmt"
17         "hash"
18         "internal/cpu"
19         "runtime"
20
21         "golang.org/x/crypto/chacha20poly1305"
22 )
23
24 // CipherSuite is a TLS cipher suite. Note that most functions in this package
25 // accept and expose cipher suite IDs instead of this type.
26 type CipherSuite struct {
27         ID   uint16
28         Name string
29
30         // Supported versions is the list of TLS protocol versions that can
31         // negotiate this cipher suite.
32         SupportedVersions []uint16
33
34         // Insecure is true if the cipher suite has known security issues
35         // due to its primitives, design, or implementation.
36         Insecure bool
37 }
38
39 var (
40         supportedUpToTLS12 = []uint16{VersionTLS10, VersionTLS11, VersionTLS12}
41         supportedOnlyTLS12 = []uint16{VersionTLS12}
42         supportedOnlyTLS13 = []uint16{VersionTLS13}
43 )
44
45 // CipherSuites returns a list of cipher suites currently implemented by this
46 // package, excluding those with security issues, which are returned by
47 // InsecureCipherSuites.
48 //
49 // The list is sorted by ID. Note that the default cipher suites selected by
50 // this package might depend on logic that can't be captured by a static list,
51 // and might not match those returned by this function.
52 func CipherSuites() []*CipherSuite {
53         return []*CipherSuite{
54                 {TLS_RSA_WITH_AES_128_CBC_SHA, "TLS_RSA_WITH_AES_128_CBC_SHA", supportedUpToTLS12, false},
55                 {TLS_RSA_WITH_AES_256_CBC_SHA, "TLS_RSA_WITH_AES_256_CBC_SHA", supportedUpToTLS12, false},
56                 {TLS_RSA_WITH_AES_128_GCM_SHA256, "TLS_RSA_WITH_AES_128_GCM_SHA256", supportedOnlyTLS12, false},
57                 {TLS_RSA_WITH_AES_256_GCM_SHA384, "TLS_RSA_WITH_AES_256_GCM_SHA384", supportedOnlyTLS12, false},
58
59                 {TLS_AES_128_GCM_SHA256, "TLS_AES_128_GCM_SHA256", supportedOnlyTLS13, false},
60                 {TLS_AES_256_GCM_SHA384, "TLS_AES_256_GCM_SHA384", supportedOnlyTLS13, false},
61                 {TLS_CHACHA20_POLY1305_SHA256, "TLS_CHACHA20_POLY1305_SHA256", supportedOnlyTLS13, false},
62
63                 {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", supportedUpToTLS12, false},
64                 {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", supportedUpToTLS12, false},
65                 {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", supportedUpToTLS12, false},
66                 {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", supportedUpToTLS12, false},
67                 {TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", supportedOnlyTLS12, false},
68                 {TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", supportedOnlyTLS12, false},
69                 {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", supportedOnlyTLS12, false},
70                 {TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", supportedOnlyTLS12, false},
71                 {TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256", supportedOnlyTLS12, false},
72                 {TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256", supportedOnlyTLS12, false},
73         }
74 }
75
76 // InsecureCipherSuites returns a list of cipher suites currently implemented by
77 // this package and which have security issues.
78 //
79 // Most applications should not use the cipher suites in this list, and should
80 // only use those returned by CipherSuites.
81 func InsecureCipherSuites() []*CipherSuite {
82         // This list includes RC4, CBC_SHA256, and 3DES cipher suites. See
83         // cipherSuitesPreferenceOrder for details.
84         return []*CipherSuite{
85                 {TLS_RSA_WITH_RC4_128_SHA, "TLS_RSA_WITH_RC4_128_SHA", supportedUpToTLS12, true},
86                 {TLS_RSA_WITH_3DES_EDE_CBC_SHA, "TLS_RSA_WITH_3DES_EDE_CBC_SHA", supportedUpToTLS12, true},
87                 {TLS_RSA_WITH_AES_128_CBC_SHA256, "TLS_RSA_WITH_AES_128_CBC_SHA256", supportedOnlyTLS12, true},
88                 {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA", supportedUpToTLS12, true},
89                 {TLS_ECDHE_RSA_WITH_RC4_128_SHA, "TLS_ECDHE_RSA_WITH_RC4_128_SHA", supportedUpToTLS12, true},
90                 {TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA", supportedUpToTLS12, true},
91                 {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", supportedOnlyTLS12, true},
92                 {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", supportedOnlyTLS12, true},
93         }
94 }
95
96 // CipherSuiteName returns the standard name for the passed cipher suite ID
97 // (e.g. "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"), or a fallback representation
98 // of the ID value if the cipher suite is not implemented by this package.
99 func CipherSuiteName(id uint16) string {
100         for _, c := range CipherSuites() {
101                 if c.ID == id {
102                         return c.Name
103                 }
104         }
105         for _, c := range InsecureCipherSuites() {
106                 if c.ID == id {
107                         return c.Name
108                 }
109         }
110         return fmt.Sprintf("0x%04X", id)
111 }
112
113 const (
114         // suiteECDHE indicates that the cipher suite involves elliptic curve
115         // Diffie-Hellman. This means that it should only be selected when the
116         // client indicates that it supports ECC with a curve and point format
117         // that we're happy with.
118         suiteECDHE = 1 << iota
119         // suiteECSign indicates that the cipher suite involves an ECDSA or
120         // EdDSA signature and therefore may only be selected when the server's
121         // certificate is ECDSA or EdDSA. If this is not set then the cipher suite
122         // is RSA based.
123         suiteECSign
124         // suiteTLS12 indicates that the cipher suite should only be advertised
125         // and accepted when using TLS 1.2.
126         suiteTLS12
127         // suiteSHA384 indicates that the cipher suite uses SHA384 as the
128         // handshake hash.
129         suiteSHA384
130 )
131
132 // A cipherSuite is a TLS 1.0–1.2 cipher suite, and defines the key exchange
133 // mechanism, as well as the cipher+MAC pair or the AEAD.
134 type cipherSuite struct {
135         id uint16
136         // the lengths, in bytes, of the key material needed for each component.
137         keyLen int
138         macLen int
139         ivLen  int
140         ka     func(version uint16) keyAgreement
141         // flags is a bitmask of the suite* values, above.
142         flags  int
143         cipher func(key, iv []byte, isRead bool) any
144         mac    func(key []byte) hash.Hash
145         aead   func(key, fixedNonce []byte) aead
146 }
147
148 var cipherSuites = []*cipherSuite{ // TODO: replace with a map, since the order doesn't matter.
149         {TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 32, 0, 12, ecdheRSAKA, suiteECDHE | suiteTLS12, nil, nil, aeadChaCha20Poly1305},
150         {TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, 32, 0, 12, ecdheECDSAKA, suiteECDHE | suiteECSign | suiteTLS12, nil, nil, aeadChaCha20Poly1305},
151         {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, ecdheRSAKA, suiteECDHE | suiteTLS12, nil, nil, aeadAESGCM},
152         {TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, ecdheECDSAKA, suiteECDHE | suiteECSign | suiteTLS12, nil, nil, aeadAESGCM},
153         {TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 32, 0, 4, ecdheRSAKA, suiteECDHE | suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM},
154         {TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, 32, 0, 4, ecdheECDSAKA, suiteECDHE | suiteECSign | suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM},
155         {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, 16, 32, 16, ecdheRSAKA, suiteECDHE | suiteTLS12, cipherAES, macSHA256, nil},
156         {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, 16, 20, 16, ecdheRSAKA, suiteECDHE, cipherAES, macSHA1, nil},
157         {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, 16, 32, 16, ecdheECDSAKA, suiteECDHE | suiteECSign | suiteTLS12, cipherAES, macSHA256, nil},
158         {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, 16, 20, 16, ecdheECDSAKA, suiteECDHE | suiteECSign, cipherAES, macSHA1, nil},
159         {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, 32, 20, 16, ecdheRSAKA, suiteECDHE, cipherAES, macSHA1, nil},
160         {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, 32, 20, 16, ecdheECDSAKA, suiteECDHE | suiteECSign, cipherAES, macSHA1, nil},
161         {TLS_RSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, rsaKA, suiteTLS12, nil, nil, aeadAESGCM},
162         {TLS_RSA_WITH_AES_256_GCM_SHA384, 32, 0, 4, rsaKA, suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM},
163         {TLS_RSA_WITH_AES_128_CBC_SHA256, 16, 32, 16, rsaKA, suiteTLS12, cipherAES, macSHA256, nil},
164         {TLS_RSA_WITH_AES_128_CBC_SHA, 16, 20, 16, rsaKA, 0, cipherAES, macSHA1, nil},
165         {TLS_RSA_WITH_AES_256_CBC_SHA, 32, 20, 16, rsaKA, 0, cipherAES, macSHA1, nil},
166         {TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, 24, 20, 8, ecdheRSAKA, suiteECDHE, cipher3DES, macSHA1, nil},
167         {TLS_RSA_WITH_3DES_EDE_CBC_SHA, 24, 20, 8, rsaKA, 0, cipher3DES, macSHA1, nil},
168         {TLS_RSA_WITH_RC4_128_SHA, 16, 20, 0, rsaKA, 0, cipherRC4, macSHA1, nil},
169         {TLS_ECDHE_RSA_WITH_RC4_128_SHA, 16, 20, 0, ecdheRSAKA, suiteECDHE, cipherRC4, macSHA1, nil},
170         {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, 16, 20, 0, ecdheECDSAKA, suiteECDHE | suiteECSign, cipherRC4, macSHA1, nil},
171 }
172
173 // selectCipherSuite returns the first TLS 1.0–1.2 cipher suite from ids which
174 // is also in supportedIDs and passes the ok filter.
175 func selectCipherSuite(ids, supportedIDs []uint16, ok func(*cipherSuite) bool) *cipherSuite {
176         for _, id := range ids {
177                 candidate := cipherSuiteByID(id)
178                 if candidate == nil || !ok(candidate) {
179                         continue
180                 }
181
182                 for _, suppID := range supportedIDs {
183                         if id == suppID {
184                                 return candidate
185                         }
186                 }
187         }
188         return nil
189 }
190
191 // A cipherSuiteTLS13 defines only the pair of the AEAD algorithm and hash
192 // algorithm to be used with HKDF. See RFC 8446, Appendix B.4.
193 type cipherSuiteTLS13 struct {
194         id     uint16
195         keyLen int
196         aead   func(key, fixedNonce []byte) aead
197         hash   crypto.Hash
198 }
199
200 var cipherSuitesTLS13 = []*cipherSuiteTLS13{ // TODO: replace with a map.
201         {TLS_AES_128_GCM_SHA256, 16, aeadAESGCMTLS13, crypto.SHA256},
202         {TLS_CHACHA20_POLY1305_SHA256, 32, aeadChaCha20Poly1305, crypto.SHA256},
203         {TLS_AES_256_GCM_SHA384, 32, aeadAESGCMTLS13, crypto.SHA384},
204 }
205
206 // cipherSuitesPreferenceOrder is the order in which we'll select (on the
207 // server) or advertise (on the client) TLS 1.0–1.2 cipher suites.
208 //
209 // Cipher suites are filtered but not reordered based on the application and
210 // peer's preferences, meaning we'll never select a suite lower in this list if
211 // any higher one is available. This makes it more defensible to keep weaker
212 // cipher suites enabled, especially on the server side where we get the last
213 // word, since there are no known downgrade attacks on cipher suites selection.
214 //
215 // The list is sorted by applying the following priority rules, stopping at the
216 // first (most important) applicable one:
217 //
218 //   - Anything else comes before RC4
219 //
220 //     RC4 has practically exploitable biases. See https://www.rc4nomore.com.
221 //
222 //   - Anything else comes before CBC_SHA256
223 //
224 //     SHA-256 variants of the CBC ciphersuites don't implement any Lucky13
225 //     countermeasures. See http://www.isg.rhul.ac.uk/tls/Lucky13.html and
226 //     https://www.imperialviolet.org/2013/02/04/luckythirteen.html.
227 //
228 //   - Anything else comes before 3DES
229 //
230 //     3DES has 64-bit blocks, which makes it fundamentally susceptible to
231 //     birthday attacks. See https://sweet32.info.
232 //
233 //   - ECDHE comes before anything else
234 //
235 //     Once we got the broken stuff out of the way, the most important
236 //     property a cipher suite can have is forward secrecy. We don't
237 //     implement FFDHE, so that means ECDHE.
238 //
239 //   - AEADs come before CBC ciphers
240 //
241 //     Even with Lucky13 countermeasures, MAC-then-Encrypt CBC cipher suites
242 //     are fundamentally fragile, and suffered from an endless sequence of
243 //     padding oracle attacks. See https://eprint.iacr.org/2015/1129,
244 //     https://www.imperialviolet.org/2014/12/08/poodleagain.html, and
245 //     https://blog.cloudflare.com/yet-another-padding-oracle-in-openssl-cbc-ciphersuites/.
246 //
247 //   - AES comes before ChaCha20
248 //
249 //     When AES hardware is available, AES-128-GCM and AES-256-GCM are faster
250 //     than ChaCha20Poly1305.
251 //
252 //     When AES hardware is not available, AES-128-GCM is one or more of: much
253 //     slower, way more complex, and less safe (because not constant time)
254 //     than ChaCha20Poly1305.
255 //
256 //     We use this list if we think both peers have AES hardware, and
257 //     cipherSuitesPreferenceOrderNoAES otherwise.
258 //
259 //   - AES-128 comes before AES-256
260 //
261 //     The only potential advantages of AES-256 are better multi-target
262 //     margins, and hypothetical post-quantum properties. Neither apply to
263 //     TLS, and AES-256 is slower due to its four extra rounds (which don't
264 //     contribute to the advantages above).
265 //
266 //   - ECDSA comes before RSA
267 //
268 //     The relative order of ECDSA and RSA cipher suites doesn't matter,
269 //     as they depend on the certificate. Pick one to get a stable order.
270 var cipherSuitesPreferenceOrder = []uint16{
271         // AEADs w/ ECDHE
272         TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
273         TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
274         TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
275
276         // CBC w/ ECDHE
277         TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
278         TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
279
280         // AEADs w/o ECDHE
281         TLS_RSA_WITH_AES_128_GCM_SHA256,
282         TLS_RSA_WITH_AES_256_GCM_SHA384,
283
284         // CBC w/o ECDHE
285         TLS_RSA_WITH_AES_128_CBC_SHA,
286         TLS_RSA_WITH_AES_256_CBC_SHA,
287
288         // 3DES
289         TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
290         TLS_RSA_WITH_3DES_EDE_CBC_SHA,
291
292         // CBC_SHA256
293         TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
294         TLS_RSA_WITH_AES_128_CBC_SHA256,
295
296         // RC4
297         TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA,
298         TLS_RSA_WITH_RC4_128_SHA,
299 }
300
301 var cipherSuitesPreferenceOrderNoAES = []uint16{
302         // ChaCha20Poly1305
303         TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
304
305         // AES-GCM w/ ECDHE
306         TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
307         TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
308
309         // The rest of cipherSuitesPreferenceOrder.
310         TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
311         TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
312         TLS_RSA_WITH_AES_128_GCM_SHA256,
313         TLS_RSA_WITH_AES_256_GCM_SHA384,
314         TLS_RSA_WITH_AES_128_CBC_SHA,
315         TLS_RSA_WITH_AES_256_CBC_SHA,
316         TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
317         TLS_RSA_WITH_3DES_EDE_CBC_SHA,
318         TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
319         TLS_RSA_WITH_AES_128_CBC_SHA256,
320         TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA,
321         TLS_RSA_WITH_RC4_128_SHA,
322 }
323
324 // disabledCipherSuites are not used unless explicitly listed in
325 // Config.CipherSuites. They MUST be at the end of cipherSuitesPreferenceOrder.
326 var disabledCipherSuites = []uint16{
327         // CBC_SHA256
328         TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
329         TLS_RSA_WITH_AES_128_CBC_SHA256,
330
331         // RC4
332         TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA,
333         TLS_RSA_WITH_RC4_128_SHA,
334 }
335
336 var (
337         defaultCipherSuitesLen = len(cipherSuitesPreferenceOrder) - len(disabledCipherSuites)
338         defaultCipherSuites    = cipherSuitesPreferenceOrder[:defaultCipherSuitesLen]
339 )
340
341 // defaultCipherSuitesTLS13 is also the preference order, since there are no
342 // disabled by default TLS 1.3 cipher suites. The same AES vs ChaCha20 logic as
343 // cipherSuitesPreferenceOrder applies.
344 var defaultCipherSuitesTLS13 = []uint16{
345         TLS_AES_128_GCM_SHA256,
346         TLS_AES_256_GCM_SHA384,
347         TLS_CHACHA20_POLY1305_SHA256,
348 }
349
350 var defaultCipherSuitesTLS13NoAES = []uint16{
351         TLS_CHACHA20_POLY1305_SHA256,
352         TLS_AES_128_GCM_SHA256,
353         TLS_AES_256_GCM_SHA384,
354 }
355
356 var (
357         hasGCMAsmAMD64 = cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ
358         hasGCMAsmARM64 = cpu.ARM64.HasAES && cpu.ARM64.HasPMULL
359         // Keep in sync with crypto/aes/cipher_s390x.go.
360         hasGCMAsmS390X = cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR &&
361                 (cpu.S390X.HasGHASH || cpu.S390X.HasAESGCM)
362
363         hasAESGCMHardwareSupport = runtime.GOARCH == "amd64" && hasGCMAsmAMD64 ||
364                 runtime.GOARCH == "arm64" && hasGCMAsmARM64 ||
365                 runtime.GOARCH == "s390x" && hasGCMAsmS390X
366 )
367
368 var aesgcmCiphers = map[uint16]bool{
369         // TLS 1.2
370         TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:   true,
371         TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:   true,
372         TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: true,
373         TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: true,
374         // TLS 1.3
375         TLS_AES_128_GCM_SHA256: true,
376         TLS_AES_256_GCM_SHA384: true,
377 }
378
379 var nonAESGCMAEADCiphers = map[uint16]bool{
380         // TLS 1.2
381         TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305:   true,
382         TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305: true,
383         // TLS 1.3
384         TLS_CHACHA20_POLY1305_SHA256: true,
385 }
386
387 // aesgcmPreferred returns whether the first known cipher in the preference list
388 // is an AES-GCM cipher, implying the peer has hardware support for it.
389 func aesgcmPreferred(ciphers []uint16) bool {
390         for _, cID := range ciphers {
391                 if c := cipherSuiteByID(cID); c != nil {
392                         return aesgcmCiphers[cID]
393                 }
394                 if c := cipherSuiteTLS13ByID(cID); c != nil {
395                         return aesgcmCiphers[cID]
396                 }
397         }
398         return false
399 }
400
401 func cipherRC4(key, iv []byte, isRead bool) any {
402         cipher, _ := rc4.NewCipher(key)
403         return cipher
404 }
405
406 func cipher3DES(key, iv []byte, isRead bool) any {
407         block, _ := des.NewTripleDESCipher(key)
408         if isRead {
409                 return cipher.NewCBCDecrypter(block, iv)
410         }
411         return cipher.NewCBCEncrypter(block, iv)
412 }
413
414 func cipherAES(key, iv []byte, isRead bool) any {
415         block, _ := aes.NewCipher(key)
416         if isRead {
417                 return cipher.NewCBCDecrypter(block, iv)
418         }
419         return cipher.NewCBCEncrypter(block, iv)
420 }
421
422 // macSHA1 returns a SHA-1 based constant time MAC.
423 func macSHA1(key []byte) hash.Hash {
424         return hmac.New(newConstantTimeHash(sha1.New), key)
425 }
426
427 // macSHA256 returns a SHA-256 based MAC. This is only supported in TLS 1.2 and
428 // is currently only used in disabled-by-default cipher suites.
429 func macSHA256(key []byte) hash.Hash {
430         return hmac.New(sha256.New, key)
431 }
432
433 type aead interface {
434         cipher.AEAD
435
436         // explicitNonceLen returns the number of bytes of explicit nonce
437         // included in each record. This is eight for older AEADs and
438         // zero for modern ones.
439         explicitNonceLen() int
440 }
441
442 const (
443         aeadNonceLength   = 12
444         noncePrefixLength = 4
445 )
446
447 // prefixNonceAEAD wraps an AEAD and prefixes a fixed portion of the nonce to
448 // each call.
449 type prefixNonceAEAD struct {
450         // nonce contains the fixed part of the nonce in the first four bytes.
451         nonce [aeadNonceLength]byte
452         aead  cipher.AEAD
453 }
454
455 func (f *prefixNonceAEAD) NonceSize() int        { return aeadNonceLength - noncePrefixLength }
456 func (f *prefixNonceAEAD) Overhead() int         { return f.aead.Overhead() }
457 func (f *prefixNonceAEAD) explicitNonceLen() int { return f.NonceSize() }
458
459 func (f *prefixNonceAEAD) Seal(out, nonce, plaintext, additionalData []byte) []byte {
460         copy(f.nonce[4:], nonce)
461         return f.aead.Seal(out, f.nonce[:], plaintext, additionalData)
462 }
463
464 func (f *prefixNonceAEAD) Open(out, nonce, ciphertext, additionalData []byte) ([]byte, error) {
465         copy(f.nonce[4:], nonce)
466         return f.aead.Open(out, f.nonce[:], ciphertext, additionalData)
467 }
468
469 // xoredNonceAEAD wraps an AEAD by XORing in a fixed pattern to the nonce
470 // before each call.
471 type xorNonceAEAD struct {
472         nonceMask [aeadNonceLength]byte
473         aead      cipher.AEAD
474 }
475
476 func (f *xorNonceAEAD) NonceSize() int        { return 8 } // 64-bit sequence number
477 func (f *xorNonceAEAD) Overhead() int         { return f.aead.Overhead() }
478 func (f *xorNonceAEAD) explicitNonceLen() int { return 0 }
479
480 func (f *xorNonceAEAD) Seal(out, nonce, plaintext, additionalData []byte) []byte {
481         for i, b := range nonce {
482                 f.nonceMask[4+i] ^= b
483         }
484         result := f.aead.Seal(out, f.nonceMask[:], plaintext, additionalData)
485         for i, b := range nonce {
486                 f.nonceMask[4+i] ^= b
487         }
488
489         return result
490 }
491
492 func (f *xorNonceAEAD) Open(out, nonce, ciphertext, additionalData []byte) ([]byte, error) {
493         for i, b := range nonce {
494                 f.nonceMask[4+i] ^= b
495         }
496         result, err := f.aead.Open(out, f.nonceMask[:], ciphertext, additionalData)
497         for i, b := range nonce {
498                 f.nonceMask[4+i] ^= b
499         }
500
501         return result, err
502 }
503
504 func aeadAESGCM(key, noncePrefix []byte) aead {
505         if len(noncePrefix) != noncePrefixLength {
506                 panic("tls: internal error: wrong nonce length")
507         }
508         aes, err := aes.NewCipher(key)
509         if err != nil {
510                 panic(err)
511         }
512         aead, err := cipher.NewGCM(aes)
513         if err != nil {
514                 panic(err)
515         }
516
517         ret := &prefixNonceAEAD{aead: aead}
518         copy(ret.nonce[:], noncePrefix)
519         return ret
520 }
521
522 func aeadAESGCMTLS13(key, nonceMask []byte) aead {
523         if len(nonceMask) != aeadNonceLength {
524                 panic("tls: internal error: wrong nonce length")
525         }
526         aes, err := aes.NewCipher(key)
527         if err != nil {
528                 panic(err)
529         }
530         aead, err := cipher.NewGCM(aes)
531         if err != nil {
532                 panic(err)
533         }
534
535         ret := &xorNonceAEAD{aead: aead}
536         copy(ret.nonceMask[:], nonceMask)
537         return ret
538 }
539
540 func aeadChaCha20Poly1305(key, nonceMask []byte) aead {
541         if len(nonceMask) != aeadNonceLength {
542                 panic("tls: internal error: wrong nonce length")
543         }
544         aead, err := chacha20poly1305.New(key)
545         if err != nil {
546                 panic(err)
547         }
548
549         ret := &xorNonceAEAD{aead: aead}
550         copy(ret.nonceMask[:], nonceMask)
551         return ret
552 }
553
554 type constantTimeHash interface {
555         hash.Hash
556         ConstantTimeSum(b []byte) []byte
557 }
558
559 // cthWrapper wraps any hash.Hash that implements ConstantTimeSum, and replaces
560 // with that all calls to Sum. It's used to obtain a ConstantTimeSum-based HMAC.
561 type cthWrapper struct {
562         h constantTimeHash
563 }
564
565 func (c *cthWrapper) Size() int                   { return c.h.Size() }
566 func (c *cthWrapper) BlockSize() int              { return c.h.BlockSize() }
567 func (c *cthWrapper) Reset()                      { c.h.Reset() }
568 func (c *cthWrapper) Write(p []byte) (int, error) { return c.h.Write(p) }
569 func (c *cthWrapper) Sum(b []byte) []byte         { return c.h.ConstantTimeSum(b) }
570
571 func newConstantTimeHash(h func() hash.Hash) func() hash.Hash {
572         return func() hash.Hash {
573                 return &cthWrapper{h().(constantTimeHash)}
574         }
575 }
576
577 // tls10MAC implements the TLS 1.0 MAC function. RFC 2246, Section 6.2.3.
578 func tls10MAC(h hash.Hash, out, seq, header, data, extra []byte) []byte {
579         h.Reset()
580         h.Write(seq)
581         h.Write(header)
582         h.Write(data)
583         res := h.Sum(out)
584         if extra != nil {
585                 h.Write(extra)
586         }
587         return res
588 }
589
590 func rsaKA(version uint16) keyAgreement {
591         return rsaKeyAgreement{}
592 }
593
594 func ecdheECDSAKA(version uint16) keyAgreement {
595         return &ecdheKeyAgreement{
596                 isRSA:   false,
597                 version: version,
598         }
599 }
600
601 func ecdheRSAKA(version uint16) keyAgreement {
602         return &ecdheKeyAgreement{
603                 isRSA:   true,
604                 version: version,
605         }
606 }
607
608 // mutualCipherSuite returns a cipherSuite given a list of supported
609 // ciphersuites and the id requested by the peer.
610 func mutualCipherSuite(have []uint16, want uint16) *cipherSuite {
611         for _, id := range have {
612                 if id == want {
613                         return cipherSuiteByID(id)
614                 }
615         }
616         return nil
617 }
618
619 func cipherSuiteByID(id uint16) *cipherSuite {
620         for _, cipherSuite := range cipherSuites {
621                 if cipherSuite.id == id {
622                         return cipherSuite
623                 }
624         }
625         return nil
626 }
627
628 func mutualCipherSuiteTLS13(have []uint16, want uint16) *cipherSuiteTLS13 {
629         for _, id := range have {
630                 if id == want {
631                         return cipherSuiteTLS13ByID(id)
632                 }
633         }
634         return nil
635 }
636
637 func cipherSuiteTLS13ByID(id uint16) *cipherSuiteTLS13 {
638         for _, cipherSuite := range cipherSuitesTLS13 {
639                 if cipherSuite.id == id {
640                         return cipherSuite
641                 }
642         }
643         return nil
644 }
645
646 // A list of cipher suite IDs that are, or have been, implemented by this
647 // package.
648 //
649 // See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml
650 const (
651         // TLS 1.0 - 1.2 cipher suites.
652         TLS_RSA_WITH_RC4_128_SHA                      uint16 = 0x0005
653         TLS_RSA_WITH_3DES_EDE_CBC_SHA                 uint16 = 0x000a
654         TLS_RSA_WITH_AES_128_CBC_SHA                  uint16 = 0x002f
655         TLS_RSA_WITH_AES_256_CBC_SHA                  uint16 = 0x0035
656         TLS_RSA_WITH_AES_128_CBC_SHA256               uint16 = 0x003c
657         TLS_RSA_WITH_AES_128_GCM_SHA256               uint16 = 0x009c
658         TLS_RSA_WITH_AES_256_GCM_SHA384               uint16 = 0x009d
659         TLS_ECDHE_ECDSA_WITH_RC4_128_SHA              uint16 = 0xc007
660         TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA          uint16 = 0xc009
661         TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA          uint16 = 0xc00a
662         TLS_ECDHE_RSA_WITH_RC4_128_SHA                uint16 = 0xc011
663         TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA           uint16 = 0xc012
664         TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA            uint16 = 0xc013
665         TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA            uint16 = 0xc014
666         TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256       uint16 = 0xc023
667         TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256         uint16 = 0xc027
668         TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256         uint16 = 0xc02f
669         TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256       uint16 = 0xc02b
670         TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384         uint16 = 0xc030
671         TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384       uint16 = 0xc02c
672         TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256   uint16 = 0xcca8
673         TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xcca9
674
675         // TLS 1.3 cipher suites.
676         TLS_AES_128_GCM_SHA256       uint16 = 0x1301
677         TLS_AES_256_GCM_SHA384       uint16 = 0x1302
678         TLS_CHACHA20_POLY1305_SHA256 uint16 = 0x1303
679
680         // TLS_FALLBACK_SCSV isn't a standard cipher suite but an indicator
681         // that the client is doing version fallback. See RFC 7507.
682         TLS_FALLBACK_SCSV uint16 = 0x5600
683
684         // Legacy names for the corresponding cipher suites with the correct _SHA256
685         // suffix, retained for backward compatibility.
686         TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305   = TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
687         TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305 = TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
688 )