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
5package runner
6
7import (
8	"crypto"
9	"crypto/aes"
10	"crypto/cipher"
11	"crypto/des"
12	"crypto/hmac"
13	"crypto/md5"
14	"crypto/sha1"
15	"crypto/sha256"
16	"crypto/sha512"
17	"crypto/x509"
18	"hash"
19	"slices"
20
21	"golang.org/x/crypto/chacha20poly1305"
22)
23
24// a keyAgreement implements the client and server side of a TLS key agreement
25// protocol by generating and processing key exchange messages.
26type keyAgreement interface {
27	// On the server side, the first two methods are called in order.
28
29	// In the case that the key agreement protocol doesn't use a
30	// ServerKeyExchange message, generateServerKeyExchange can return nil,
31	// nil.
32	generateServerKeyExchange(*Config, *Credential, *clientHelloMsg, *serverHelloMsg, uint16) (*serverKeyExchangeMsg, error)
33	processClientKeyExchange(*Config, *Credential, *clientKeyExchangeMsg, uint16) ([]byte, error)
34
35	// On the client side, the next two methods are called in order.
36
37	// This method may not be called if the server doesn't send a
38	// ServerKeyExchange message.
39	processServerKeyExchange(*Config, *clientHelloMsg, *serverHelloMsg, crypto.PublicKey, *serverKeyExchangeMsg) error
40	generateClientKeyExchange(*Config, *clientHelloMsg, *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error)
41
42	// peerSignatureAlgorithm returns the signature algorithm used by the
43	// peer, or zero if not applicable.
44	peerSignatureAlgorithm() signatureAlgorithm
45}
46
47const (
48	// suiteECDH indicates that the cipher suite involves elliptic curve
49	// Diffie-Hellman. This means that it should only be selected when the
50	// client indicates that it supports ECC with a curve and point format
51	// that we're happy with.
52	suiteECDHE = 1 << iota
53	// suiteECDSA indicates that the cipher suite involves an ECDSA
54	// signature and therefore may only be selected when the server's
55	// certificate is ECDSA. If this is not set then the cipher suite is
56	// RSA based.
57	suiteECDSA
58	// suiteTLS12 indicates that the cipher suite should only be advertised
59	// and accepted when using TLS 1.2 or greater.
60	suiteTLS12
61	// suiteTLS13 indicates that the cipher suite can be used with TLS 1.3.
62	// Cipher suites lacking this flag may not be used with TLS 1.3.
63	suiteTLS13
64	// suiteSHA384 indicates that the cipher suite uses SHA384 as the
65	// handshake hash.
66	suiteSHA384
67	// suitePSK indicates that the cipher suite authenticates with
68	// a pre-shared key rather than a server private key.
69	suitePSK
70)
71
72type tlsAead struct {
73	cipher.AEAD
74	explicitNonce bool
75}
76
77// A cipherSuite is a specific combination of key agreement, cipher and MAC
78// function. All cipher suites currently assume RSA key agreement.
79type cipherSuite struct {
80	id uint16
81	// the lengths, in bytes, of the key material needed for each component.
82	keyLen int
83	macLen int
84	ivLen  func(version uint16) int
85	ka     func(version uint16) keyAgreement
86	// flags is a bitmask of the suite* values, above.
87	flags  int
88	cipher func(key, iv []byte, isRead bool) any
89	mac    func(version uint16, macKey []byte) macFunction
90	aead   func(version uint16, key, fixedNonce []byte) *tlsAead
91}
92
93func (cs cipherSuite) hash() crypto.Hash {
94	if cs.flags&suiteSHA384 != 0 {
95		return crypto.SHA384
96	}
97	return crypto.SHA256
98}
99
100var cipherSuites = []*cipherSuite{
101	{TLS_CHACHA20_POLY1305_SHA256, 32, 0, ivLenChaCha20Poly1305, nil, suiteTLS13, nil, nil, aeadCHACHA20POLY1305},
102	{TLS_AES_128_GCM_SHA256, 16, 0, ivLenAESGCM, nil, suiteTLS13, nil, nil, aeadAESGCM},
103	{TLS_AES_256_GCM_SHA384, 32, 0, ivLenAESGCM, nil, suiteTLS13 | suiteSHA384, nil, nil, aeadAESGCM},
104	{TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, 32, 0, ivLenChaCha20Poly1305, ecdheECDSAKA, suiteECDHE | suiteECDSA | suiteTLS12, nil, nil, aeadCHACHA20POLY1305},
105	{TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, 32, 0, ivLenChaCha20Poly1305, ecdheRSAKA, suiteECDHE | suiteTLS12, nil, nil, aeadCHACHA20POLY1305},
106	{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 16, 0, ivLenAESGCM, ecdheRSAKA, suiteECDHE | suiteTLS12, nil, nil, aeadAESGCM},
107	{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 16, 0, ivLenAESGCM, ecdheECDSAKA, suiteECDHE | suiteECDSA | suiteTLS12, nil, nil, aeadAESGCM},
108	{TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 32, 0, ivLenAESGCM, ecdheRSAKA, suiteECDHE | suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM},
109	{TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, 32, 0, ivLenAESGCM, ecdheECDSAKA, suiteECDHE | suiteECDSA | suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM},
110	{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, 16, 32, ivLenAES, ecdheRSAKA, suiteECDHE | suiteTLS12, cipherAES, macSHA256, nil},
111	{TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, 16, 32, ivLenAES, ecdheECDSAKA, suiteECDHE | suiteECDSA | suiteTLS12, cipherAES, macSHA256, nil},
112	{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, 16, 20, ivLenAES, ecdheRSAKA, suiteECDHE, cipherAES, macSHA1, nil},
113	{TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, 16, 20, ivLenAES, ecdheECDSAKA, suiteECDHE | suiteECDSA, cipherAES, macSHA1, nil},
114	{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, 32, 48, ivLenAES, ecdheRSAKA, suiteECDHE | suiteTLS12 | suiteSHA384, cipherAES, macSHA384, nil},
115	{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, 32, 48, ivLenAES, ecdheECDSAKA, suiteECDHE | suiteECDSA | suiteTLS12 | suiteSHA384, cipherAES, macSHA384, nil},
116	{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, 32, 20, ivLenAES, ecdheRSAKA, suiteECDHE, cipherAES, macSHA1, nil},
117	{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, 32, 20, ivLenAES, ecdheECDSAKA, suiteECDHE | suiteECDSA, cipherAES, macSHA1, nil},
118	{TLS_RSA_WITH_AES_128_GCM_SHA256, 16, 0, ivLenAESGCM, rsaKA, suiteTLS12, nil, nil, aeadAESGCM},
119	{TLS_RSA_WITH_AES_256_GCM_SHA384, 32, 0, ivLenAESGCM, rsaKA, suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM},
120	{TLS_RSA_WITH_AES_128_CBC_SHA256, 16, 32, ivLenAES, rsaKA, suiteTLS12, cipherAES, macSHA256, nil},
121	{TLS_RSA_WITH_AES_256_CBC_SHA256, 32, 32, ivLenAES, rsaKA, suiteTLS12, cipherAES, macSHA256, nil},
122	{TLS_RSA_WITH_AES_128_CBC_SHA, 16, 20, ivLenAES, rsaKA, 0, cipherAES, macSHA1, nil},
123	{TLS_RSA_WITH_AES_256_CBC_SHA, 32, 20, ivLenAES, rsaKA, 0, cipherAES, macSHA1, nil},
124	{TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, 24, 20, ivLen3DES, ecdheRSAKA, suiteECDHE, cipher3DES, macSHA1, nil},
125	{TLS_RSA_WITH_3DES_EDE_CBC_SHA, 24, 20, ivLen3DES, rsaKA, 0, cipher3DES, macSHA1, nil},
126	{TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256, 32, 0, ivLenChaCha20Poly1305, ecdhePSKKA, suiteECDHE | suitePSK | suiteTLS12, nil, nil, aeadCHACHA20POLY1305},
127	{TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA, 16, 20, ivLenAES, ecdhePSKKA, suiteECDHE | suitePSK, cipherAES, macSHA1, nil},
128	{TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA, 32, 20, ivLenAES, ecdhePSKKA, suiteECDHE | suitePSK, cipherAES, macSHA1, nil},
129	{TLS_PSK_WITH_AES_128_CBC_SHA, 16, 20, ivLenAES, pskKA, suitePSK, cipherAES, macSHA1, nil},
130	{TLS_PSK_WITH_AES_256_CBC_SHA, 32, 20, ivLenAES, pskKA, suitePSK, cipherAES, macSHA1, nil},
131}
132
133func ivLenChaCha20Poly1305(vers uint16) int {
134	return 12
135}
136
137func ivLenAESGCM(vers uint16) int {
138	if vers >= VersionTLS13 {
139		return 12
140	}
141	return 4
142}
143
144func ivLenAES(vers uint16) int {
145	return 16
146}
147
148func ivLen3DES(vers uint16) int {
149	return 8
150}
151
152type nullCipher struct{}
153
154func cipherNull(key, iv []byte, isRead bool) any {
155	return nullCipher{}
156}
157
158type cbcMode struct {
159	cipher.BlockMode
160	new func(iv []byte) cipher.BlockMode
161}
162
163func (c *cbcMode) SetIV(iv []byte) {
164	c.BlockMode = c.new(iv)
165}
166
167func cipher3DES(key, iv []byte, isRead bool) any {
168	c := &cbcMode{}
169	block, _ := des.NewTripleDESCipher(key)
170	if isRead {
171		c.new = func(iv []byte) cipher.BlockMode { return cipher.NewCBCDecrypter(block, iv) }
172	} else {
173		c.new = func(iv []byte) cipher.BlockMode { return cipher.NewCBCEncrypter(block, iv) }
174	}
175	c.SetIV(iv)
176	return c
177}
178
179func cipherAES(key, iv []byte, isRead bool) any {
180	c := &cbcMode{}
181	block, _ := aes.NewCipher(key)
182	if isRead {
183		c.new = func(iv []byte) cipher.BlockMode { return cipher.NewCBCDecrypter(block, iv) }
184	} else {
185		c.new = func(iv []byte) cipher.BlockMode { return cipher.NewCBCEncrypter(block, iv) }
186	}
187	c.SetIV(iv)
188	return c
189}
190
191// macSHA1 returns a macFunction for the given protocol version.
192func macSHA1(version uint16, key []byte) macFunction {
193	return tls10MAC{hmac.New(sha1.New, key)}
194}
195
196func macMD5(version uint16, key []byte) macFunction {
197	return tls10MAC{hmac.New(md5.New, key)}
198}
199
200func macSHA256(version uint16, key []byte) macFunction {
201	return tls10MAC{hmac.New(sha256.New, key)}
202}
203
204func macSHA384(version uint16, key []byte) macFunction {
205	return tls10MAC{hmac.New(sha512.New384, key)}
206}
207
208type macFunction interface {
209	Size() int
210	MAC(digestBuf, seq, header, length, data []byte) []byte
211}
212
213// fixedNonceAEAD wraps an AEAD and prefixes a fixed portion of the nonce to
214// each call.
215type fixedNonceAEAD struct {
216	// sealNonce and openNonce are buffers where the larger nonce will be
217	// constructed. Since a seal and open operation may be running
218	// concurrently, there is a separate buffer for each.
219	sealNonce, openNonce []byte
220	aead                 cipher.AEAD
221}
222
223func (f *fixedNonceAEAD) NonceSize() int { return 8 }
224func (f *fixedNonceAEAD) Overhead() int  { return f.aead.Overhead() }
225
226func (f *fixedNonceAEAD) Seal(out, nonce, plaintext, additionalData []byte) []byte {
227	copy(f.sealNonce[len(f.sealNonce)-8:], nonce)
228	return f.aead.Seal(out, f.sealNonce, plaintext, additionalData)
229}
230
231func (f *fixedNonceAEAD) Open(out, nonce, plaintext, additionalData []byte) ([]byte, error) {
232	copy(f.openNonce[len(f.openNonce)-8:], nonce)
233	return f.aead.Open(out, f.openNonce, plaintext, additionalData)
234}
235
236func aeadAESGCM(version uint16, key, fixedNonce []byte) *tlsAead {
237	aes, err := aes.NewCipher(key)
238	if err != nil {
239		panic(err)
240	}
241	aead, err := cipher.NewGCM(aes)
242	if err != nil {
243		panic(err)
244	}
245
246	nonce1, nonce2 := make([]byte, 12), make([]byte, 12)
247	copy(nonce1, fixedNonce)
248	copy(nonce2, fixedNonce)
249
250	if version >= VersionTLS13 {
251		return &tlsAead{&xorNonceAEAD{nonce1, nonce2, aead}, false}
252	}
253
254	return &tlsAead{&fixedNonceAEAD{nonce1, nonce2, aead}, true}
255}
256
257func xorSlice(out, in []byte) {
258	for i := range out {
259		out[i] ^= in[i]
260	}
261}
262
263// xorNonceAEAD wraps an AEAD and XORs a fixed portion of the nonce, left-padded
264// if necessary, each call.
265type xorNonceAEAD struct {
266	// sealNonce and openNonce are buffers where the larger nonce will be
267	// constructed. Since a seal and open operation may be running
268	// concurrently, there is a separate buffer for each.
269	sealNonce, openNonce []byte
270	aead                 cipher.AEAD
271}
272
273func (x *xorNonceAEAD) NonceSize() int { return 8 }
274func (x *xorNonceAEAD) Overhead() int  { return x.aead.Overhead() }
275
276func (x *xorNonceAEAD) Seal(out, nonce, plaintext, additionalData []byte) []byte {
277	xorSlice(x.sealNonce[len(x.sealNonce)-len(nonce):], nonce)
278	ret := x.aead.Seal(out, x.sealNonce, plaintext, additionalData)
279	xorSlice(x.sealNonce[len(x.sealNonce)-len(nonce):], nonce)
280	return ret
281}
282
283func (x *xorNonceAEAD) Open(out, nonce, plaintext, additionalData []byte) ([]byte, error) {
284	xorSlice(x.openNonce[len(x.openNonce)-len(nonce):], nonce)
285	ret, err := x.aead.Open(out, x.openNonce, plaintext, additionalData)
286	xorSlice(x.openNonce[len(x.openNonce)-len(nonce):], nonce)
287	return ret, err
288}
289
290func aeadCHACHA20POLY1305(version uint16, key, fixedNonce []byte) *tlsAead {
291	aead, err := chacha20poly1305.New(key)
292	if err != nil {
293		panic(err)
294	}
295
296	nonce1, nonce2 := make([]byte, len(fixedNonce)), make([]byte, len(fixedNonce))
297	copy(nonce1, fixedNonce)
298	copy(nonce2, fixedNonce)
299
300	return &tlsAead{&xorNonceAEAD{nonce1, nonce2, aead}, false}
301}
302
303// tls10MAC implements the TLS 1.0 MAC function. RFC 2246, section 6.2.3.
304type tls10MAC struct {
305	h hash.Hash
306}
307
308func (s tls10MAC) Size() int {
309	return s.h.Size()
310}
311
312func (s tls10MAC) MAC(digestBuf, seq, header, length, data []byte) []byte {
313	s.h.Reset()
314	s.h.Write(seq)
315	s.h.Write(header)
316	s.h.Write(length)
317	s.h.Write(data)
318	return s.h.Sum(digestBuf[:0])
319}
320
321func rsaKA(version uint16) keyAgreement {
322	return &rsaKeyAgreement{version: version}
323}
324
325func ecdheECDSAKA(version uint16) keyAgreement {
326	return &ecdheKeyAgreement{
327		auth: &signedKeyAgreement{
328			keyType: keyTypeECDSA,
329			version: version,
330		},
331	}
332}
333
334func ecdheRSAKA(version uint16) keyAgreement {
335	return &ecdheKeyAgreement{
336		auth: &signedKeyAgreement{
337			keyType: keyTypeRSA,
338			version: version,
339		},
340	}
341}
342
343func pskKA(version uint16) keyAgreement {
344	return &pskKeyAgreement{
345		base: &nilKeyAgreement{},
346	}
347}
348
349func ecdhePSKKA(version uint16) keyAgreement {
350	return &pskKeyAgreement{
351		base: &ecdheKeyAgreement{
352			auth: &nilKeyAgreementAuthentication{},
353		},
354	}
355}
356
357// mutualCipherSuite returns a cipherSuite given a list of supported
358// ciphersuites and the id requested by the peer.
359func mutualCipherSuite(have []uint16, id uint16) *cipherSuite {
360	if slices.Contains(have, id) {
361		return cipherSuiteFromID(id)
362	}
363	return nil
364}
365
366func cipherSuiteFromID(id uint16) *cipherSuite {
367	for _, suite := range cipherSuites {
368		if suite.id == id {
369			return suite
370		}
371	}
372	return nil
373}
374
375// A list of the possible cipher suite ids. Taken from
376// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml
377const (
378	TLS_RSA_WITH_3DES_EDE_CBC_SHA                 uint16 = 0x000a
379	TLS_RSA_WITH_AES_128_CBC_SHA                  uint16 = 0x002f
380	TLS_RSA_WITH_AES_256_CBC_SHA                  uint16 = 0x0035
381	TLS_RSA_WITH_AES_128_CBC_SHA256               uint16 = 0x003c
382	TLS_RSA_WITH_AES_256_CBC_SHA256               uint16 = 0x003d
383	TLS_PSK_WITH_AES_128_CBC_SHA                  uint16 = 0x008c
384	TLS_PSK_WITH_AES_256_CBC_SHA                  uint16 = 0x008d
385	TLS_RSA_WITH_AES_128_GCM_SHA256               uint16 = 0x009c
386	TLS_RSA_WITH_AES_256_GCM_SHA384               uint16 = 0x009d
387	TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA          uint16 = 0xc009
388	TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA          uint16 = 0xc00a
389	TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA           uint16 = 0xc012
390	TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA            uint16 = 0xc013
391	TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA            uint16 = 0xc014
392	TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256       uint16 = 0xc023
393	TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384       uint16 = 0xc024
394	TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256         uint16 = 0xc027
395	TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384         uint16 = 0xc028
396	TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256       uint16 = 0xc02b
397	TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384       uint16 = 0xc02c
398	TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256         uint16 = 0xc02f
399	TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384         uint16 = 0xc030
400	TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA            uint16 = 0xc035
401	TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA            uint16 = 0xc036
402	TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256   uint16 = 0xcca8
403	TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xcca9
404	TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256   uint16 = 0xccac
405	renegotiationSCSV                             uint16 = 0x00ff
406	fallbackSCSV                                  uint16 = 0x5600
407)
408
409// Additional cipher suite IDs, not IANA-assigned.
410const (
411	TLS_AES_128_GCM_SHA256       uint16 = 0x1301
412	TLS_AES_256_GCM_SHA384       uint16 = 0x1302
413	TLS_CHACHA20_POLY1305_SHA256 uint16 = 0x1303
414)
415