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// TLS low level connection and record layer
6
7package runner
8
9import (
10	"bytes"
11	"crypto/aes"
12	"crypto/cipher"
13	"crypto/ecdsa"
14	"crypto/subtle"
15	"crypto/x509"
16	"encoding/binary"
17	"errors"
18	"fmt"
19	"io"
20	"net"
21	"slices"
22	"sync"
23	"time"
24
25	"golang.org/x/crypto/chacha20"
26	"golang.org/x/crypto/cryptobyte"
27)
28
29type dtlsRecordInfo struct {
30	typ   recordType
31	epoch uint16
32	// bytesAvailable is the number of additional bytes of plaintext that could
33	// have been added to this record without exceeding the packet limit.
34	bytesAvailable int
35}
36
37// A Conn represents a secured connection.
38// It implements the net.Conn interface.
39type Conn struct {
40	// constant
41	conn     net.Conn
42	isDTLS   bool
43	isClient bool
44
45	// constant after handshake; protected by handshakeMutex
46	handshakeMutex          sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
47	handshakeErr            error      // error resulting from handshake
48	wireVersion             uint16     // TLS wire version
49	vers                    uint16     // TLS version
50	haveVers                bool       // version has been negotiated
51	config                  *Config    // configuration passed to constructor
52	handshakeComplete       bool
53	skipEarlyData           bool // On a server, indicates that the client is sending early data that must be skipped over.
54	didResume               bool // whether this connection was a session resumption
55	extendedMasterSecret    bool // whether this session used an extended master secret
56	cipherSuite             *cipherSuite
57	ocspResponse            []byte // stapled OCSP response
58	sctList                 []byte // signed certificate timestamp list
59	peerCertificates        []*x509.Certificate
60	peerDelegatedCredential []byte
61	// verifiedChains contains the certificate chains that we built, as
62	// opposed to the ones presented by the server.
63	verifiedChains [][]*x509.Certificate
64	// serverName contains the server name indicated by the client, if any.
65	serverName    string
66	serverNameAck bool
67	// firstFinished contains the first Finished hash sent during the
68	// handshake. This is the "tls-unique" channel binding value.
69	firstFinished [12]byte
70	// peerSignatureAlgorithm contains the signature algorithm that was used
71	// by the peer in the handshake, or zero if not applicable.
72	peerSignatureAlgorithm signatureAlgorithm
73	// curveID contains the curve that was used in the handshake, or zero if
74	// not applicable.
75	curveID CurveID
76	// quicTransportParams contains the QUIC transport params received
77	// by the peer using codepoint 57.
78	quicTransportParams []byte
79	// quicTransportParams contains the QUIC transport params received
80	// by the peer using legacy codepoint 0xffa5.
81	quicTransportParamsLegacy []byte
82
83	clientRandom, serverRandom [32]byte
84	earlyExporterSecret        []byte
85	exporterSecret             []byte
86	resumptionSecret           []byte
87
88	clientProtocol         string
89	clientProtocolFallback bool
90	usedALPN               bool
91
92	localApplicationSettings, peerApplicationSettings       []byte
93	hasApplicationSettings                                  bool
94	localApplicationSettingsOld, peerApplicationSettingsOld []byte
95	hasApplicationSettingsOld                               bool
96
97	// verify_data values for the renegotiation extension.
98	clientVerify []byte
99	serverVerify []byte
100
101	channelID *ecdsa.PublicKey
102
103	srtpProtectionProfile uint16
104
105	clientVersion uint16
106
107	// input/output
108	in, out  halfConn     // in.Mutex < out.Mutex
109	rawInput bytes.Buffer // raw input, right off the wire
110	input    bytes.Buffer // application record waiting to be read
111	hand     bytes.Buffer // handshake record waiting to be read
112
113	// pendingFlight, if PackHandshakeFlight is enabled, is the buffer of
114	// handshake data to be split into records at the end of the flight.
115	pendingFlight bytes.Buffer
116
117	// DTLS state
118	sendHandshakeSeq uint16
119	recvHandshakeSeq uint16
120	handMsg          []byte // pending assembled handshake message
121	handMsgLen       int    // handshake message length, not including the header
122	pendingPacket    []byte // pending outgoing packet.
123	maxPacketLen     int
124
125	previousFlight        []DTLSMessage
126	receivedFlight        []DTLSMessage
127	receivedFlightRecords []DTLSRecordNumberInfo
128	nextFlight            []DTLSMessage
129	expectedACK           []DTLSRecordNumber
130
131	keyUpdateSeen      bool
132	keyUpdateRequested bool
133	seenOneByteRecord  bool
134
135	expectTLS13ChangeCipherSpec bool
136
137	// seenHandshakePackEnd is whether the most recent handshake record was
138	// not full for ExpectPackedEncryptedHandshake. If true, no more
139	// handshake data may be received until the next flight or epoch change.
140	seenHandshakePackEnd bool
141
142	// lastRecordInFlight contains information about the previous handshake or
143	// ChangeCipherSpec record from the current flight, or nil if we are not in
144	// the middle of reading a flight from the peer.
145	lastRecordInFlight *dtlsRecordInfo
146
147	// bytesAvailableInPacket is the number of bytes that were still available
148	// in the current DTLS packet, up to a budget of maxPacketLen.
149	bytesAvailableInPacket int
150
151	// skipRecordVersionCheck, if true, causes the DTLS record layer to skip the
152	// record version check, even if the version is known. This is used when
153	// simulating retransmits.
154	skipRecordVersionCheck bool
155
156	// echAccepted indicates whether ECH was accepted for this connection.
157	echAccepted bool
158
159	tmp [16]byte
160}
161
162func (c *Conn) init() {
163	c.in.isDTLS = c.isDTLS
164	c.out.isDTLS = c.isDTLS
165	c.in.config = c.config
166	c.out.config = c.config
167	c.in.conn = c
168	c.out.conn = c
169	c.maxPacketLen = c.config.Bugs.MaxPacketLength
170}
171
172// Access to net.Conn methods.
173// Cannot just embed net.Conn because that would
174// export the struct field too.
175
176// LocalAddr returns the local network address.
177func (c *Conn) LocalAddr() net.Addr {
178	return c.conn.LocalAddr()
179}
180
181// RemoteAddr returns the remote network address.
182func (c *Conn) RemoteAddr() net.Addr {
183	return c.conn.RemoteAddr()
184}
185
186// SetDeadline sets the read and write deadlines associated with the connection.
187// A zero value for t means Read and Write will not time out.
188// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
189func (c *Conn) SetDeadline(t time.Time) error {
190	return c.conn.SetDeadline(t)
191}
192
193// SetReadDeadline sets the read deadline on the underlying connection.
194// A zero value for t means Read will not time out.
195func (c *Conn) SetReadDeadline(t time.Time) error {
196	return c.conn.SetReadDeadline(t)
197}
198
199// SetWriteDeadline sets the write deadline on the underlying conneciton.
200// A zero value for t means Write will not time out.
201// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
202func (c *Conn) SetWriteDeadline(t time.Time) error {
203	return c.conn.SetWriteDeadline(t)
204}
205
206// Arbitrarily cap the number of past epochs to 4. This is far more than is
207// necessary. We set a limit only so tests can freely trigger unboundedly many
208// KeyUpdates.
209const maxEpochs = 4
210
211type epochState struct {
212	epoch                 uint16
213	cipher                any // cipher algorithm
214	recordNumberEncrypter recordNumberEncrypter
215	mac                   macFunction
216	seq                   [8]byte
217}
218
219// A halfConn represents one direction of the record layer
220// connection, either sending or receiving.
221type halfConn struct {
222	sync.Mutex
223
224	err         error  // first permanent error
225	version     uint16 // protocol version
226	wireVersion uint16 // wire version
227	isDTLS      bool
228	epoch       epochState
229	pastEpochs  []epochState
230
231	nextEpoch epochState
232
233	// used to save allocating a new buffer for each MAC.
234	macBuf []byte
235
236	trafficSecret []byte
237
238	config *Config
239	conn   *Conn
240}
241
242func (hc *halfConn) setErrorLocked(err error) error {
243	hc.err = err
244	return err
245}
246
247func (hc *halfConn) error() error {
248	// This should be locked, but I've removed it for the renegotiation
249	// tests since we don't concurrently read and write the same tls.Conn
250	// in any case during testing.
251	err := hc.err
252	return err
253}
254
255func (hc *halfConn) getEpoch(epochValue uint16) (*epochState, bool) {
256	if hc.epoch.epoch == epochValue {
257		return &hc.epoch, true
258	}
259	for i := range hc.pastEpochs {
260		if hc.pastEpochs[i].epoch == epochValue {
261			return &hc.pastEpochs[i], true
262		}
263	}
264	return nil, false
265}
266
267func (hc *halfConn) changeEpoch(epoch epochState) {
268	if len(hc.pastEpochs) < maxEpochs {
269		hc.pastEpochs = append(hc.pastEpochs, hc.epoch)
270	} else {
271		for i := 1; i < len(hc.pastEpochs); i++ {
272			hc.pastEpochs[i-1] = hc.pastEpochs[i]
273		}
274		hc.pastEpochs[len(hc.pastEpochs)-1] = hc.epoch
275	}
276	hc.epoch = epoch
277}
278
279func (hc *halfConn) newEpochState(epoch uint16, cipher any, mac macFunction) epochState {
280	ret := epochState{epoch: epoch, cipher: cipher, mac: mac}
281	if hc.isDTLS {
282		binary.BigEndian.PutUint16(ret.seq[:2], epoch)
283	}
284	return ret
285}
286
287// prepareCipherSpec sets the encryption and MAC states
288// that a subsequent changeCipherSpec will use.
289func (hc *halfConn) prepareCipherSpec(version uint16, cipher any, mac macFunction) {
290	hc.wireVersion = version
291	protocolVersion, ok := wireToVersion(version, hc.isDTLS)
292	if !ok {
293		panic("TLS: unknown version")
294	}
295	hc.version = protocolVersion
296	epoch := hc.epoch.epoch + 1
297	if epoch == 0 {
298		panic("TLS: epoch overflow")
299	}
300	hc.nextEpoch = hc.newEpochState(epoch, cipher, mac)
301}
302
303// changeCipherSpec changes the encryption and MAC states
304// to the ones previously passed to prepareCipherSpec.
305func (hc *halfConn) changeCipherSpec() error {
306	if hc.nextEpoch.cipher == nil {
307		return alertInternalError
308	}
309	hc.changeEpoch(hc.nextEpoch)
310	hc.nextEpoch = epochState{}
311
312	if hc.config.Bugs.NullAllCiphers {
313		hc.epoch.cipher = nullCipher{}
314		hc.epoch.mac = nil
315	}
316	return nil
317}
318
319// useTrafficSecret sets the current cipher state for TLS 1.3.
320func (hc *halfConn) useTrafficSecret(version uint16, suite *cipherSuite, secret []byte, side trafficDirection, epoch uint16) {
321	hc.wireVersion = version
322	protocolVersion, ok := wireToVersion(version, hc.isDTLS)
323	if !ok {
324		panic("TLS: unknown version")
325	}
326	hc.version = protocolVersion
327	newEpoch := hc.newEpochState(epoch, deriveTrafficAEAD(version, suite, secret, side, hc.isDTLS), nil)
328	if hc.isDTLS && !hc.config.Bugs.NullAllCiphers {
329		sn_key := hkdfExpandLabel(suite.hash(), secret, []byte("sn"), nil, suite.keyLen, hc.isDTLS)
330		switch suite.id {
331		case TLS_CHACHA20_POLY1305_SHA256:
332			newEpoch.recordNumberEncrypter = newChachaRecordNumberEncrypter(sn_key)
333		case TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384:
334			newEpoch.recordNumberEncrypter = newAESRecordNumberEncrypter(sn_key)
335		default:
336			panic("Cipher suite does not support TLS 1.3")
337		}
338	}
339	if hc.config.Bugs.NullAllCiphers {
340		newEpoch.cipher = nullCipher{}
341	}
342	hc.trafficSecret = secret
343	hc.changeEpoch(newEpoch)
344}
345
346// resetCipher resets the cipher state back to no encryption to be able
347// to send an unencrypted ClientHello in response to HelloRetryRequest
348// after 0-RTT data was rejected.
349func (hc *halfConn) resetCipher() {
350	initialEpoch, ok := hc.getEpoch(0)
351	if !ok {
352		panic("tls: could not find initial epoch")
353	}
354	hc.epoch = *initialEpoch
355	hc.pastEpochs = nil
356}
357
358// incSeq increments the sequence number.
359func (hc *halfConn) incSeq(epoch *epochState) {
360	limit := 0
361	increment := uint64(1)
362	if hc.isDTLS {
363		// Increment up to the epoch in DTLS.
364		limit = 2
365	}
366	for i := 7; i >= limit; i-- {
367		increment += uint64(epoch.seq[i])
368		epoch.seq[i] = byte(increment)
369		increment >>= 8
370	}
371
372	// Not allowed to let sequence number wrap.
373	// Instead, must renegotiate before it does.
374	// Not likely enough to bother.
375	if increment != 0 {
376		panic("TLS: sequence number wraparound")
377	}
378}
379
380// lastRecordNumber returns the most recent record number decrypted or encrypted
381// on a halfConn.
382//
383// TODO(crbug.com/376641666): This function is a bit hacky. It needs to rewind
384// the state back to what the last call actually used. Fix the TLS/DTLS
385// abstractions so we can return this value out directly.
386func (hc *halfConn) lastRecordNumber(epoch *epochState, isOut bool) DTLSRecordNumber {
387	seq := binary.BigEndian.Uint64(epoch.seq[:])
388	// We maintain the next record number, so undo the increment.
389	if seq&(1<<48-1) == 0 {
390		panic("tls: epoch has never been used")
391	}
392	seq--
393	if hc.isDTLS {
394		if isOut && hc.config.Bugs.SequenceNumberMapping != nil {
395			seq = hc.config.Bugs.SequenceNumberMapping(seq)
396		}
397		// Remove the embedded epoch number.
398		seq &= 1<<48 - 1
399	}
400	return DTLSRecordNumber{Epoch: uint64(epoch.epoch), Sequence: seq}
401}
402
403func (hc *halfConn) sequenceNumberForOutput(epoch *epochState) []byte {
404	if !hc.isDTLS || hc.config.Bugs.SequenceNumberMapping == nil {
405		return epoch.seq[:]
406	}
407
408	var seq [8]byte
409	seqU64 := binary.BigEndian.Uint64(epoch.seq[:])
410	seqU64 = hc.config.Bugs.SequenceNumberMapping(seqU64)
411	binary.BigEndian.PutUint64(seq[:], seqU64)
412	// The DTLS epoch cannot be changed.
413	copy(seq[:2], epoch.seq[:2])
414	return seq[:]
415}
416
417func (hc *halfConn) explicitIVLen(epoch *epochState) int {
418	if epoch.cipher == nil {
419		return 0
420	}
421	switch c := epoch.cipher.(type) {
422	case cipher.Stream:
423		return 0
424	case *tlsAead:
425		if c.explicitNonce {
426			return 8
427		}
428		return 0
429	case *cbcMode:
430		if hc.version >= VersionTLS11 || hc.isDTLS {
431			return c.BlockSize()
432		}
433		return 0
434	case nullCipher:
435		return 0
436	default:
437		panic("unknown cipher type")
438	}
439}
440
441func (hc *halfConn) computeMAC(epoch *epochState, seq, header, data []byte) []byte {
442	hc.macBuf = epoch.mac.MAC(hc.macBuf[:0], seq, header[:3], header[len(header)-2:], data)
443	return hc.macBuf
444}
445
446// removePadding returns an unpadded slice, in constant time, which is a prefix
447// of the input. It also returns a byte which is equal to 255 if the padding
448// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
449func removePadding(payload []byte) ([]byte, byte) {
450	if len(payload) < 1 {
451		return payload, 0
452	}
453
454	paddingLen := payload[len(payload)-1]
455	t := uint(len(payload)-1) - uint(paddingLen)
456	// if len(payload) >= (paddingLen - 1) then the MSB of t is zero
457	good := byte(int32(^t) >> 31)
458
459	toCheck := 255 // the maximum possible padding length
460	// The length of the padded data is public, so we can use an if here
461	if toCheck+1 > len(payload) {
462		toCheck = len(payload) - 1
463	}
464
465	for i := 0; i < toCheck; i++ {
466		t := uint(paddingLen) - uint(i)
467		// if i <= paddingLen then the MSB of t is zero
468		mask := byte(int32(^t) >> 31)
469		b := payload[len(payload)-1-i]
470		good &^= mask&paddingLen ^ mask&b
471	}
472
473	// We AND together the bits of good and replicate the result across
474	// all the bits.
475	good &= good << 4
476	good &= good << 2
477	good &= good << 1
478	good = uint8(int8(good) >> 7)
479
480	toRemove := good&paddingLen + 1
481	return payload[:len(payload)-int(toRemove)], good
482}
483
484func roundUp(a, b int) int {
485	return a + (b-a%b)%b
486}
487
488// decrypt checks and strips the mac and decrypts the data in record. Returns a
489// success boolean, the application payload, the encrypted record type (or 0
490// if there is none), and an optional alert value. Decryption occurs in-place,
491// so the contents of record will be overwritten as part of this process.
492func (hc *halfConn) decrypt(epoch *epochState, recordHeaderLen int, record []byte) (ok bool, contentType recordType, data []byte, alertValue alert) {
493	// pull out payload
494	payload := record[recordHeaderLen:]
495
496	macSize := 0
497	if epoch.mac != nil {
498		macSize = epoch.mac.Size()
499	}
500
501	paddingGood := byte(255)
502	explicitIVLen := hc.explicitIVLen(epoch)
503
504	// decrypt
505	if epoch.cipher != nil {
506		switch c := epoch.cipher.(type) {
507		case cipher.Stream:
508			c.XORKeyStream(payload, payload)
509		case *tlsAead:
510			nonce := epoch.seq[:]
511			if hc.isDTLS && hc.version >= VersionTLS13 && !hc.conn.useDTLSPlaintextHeader() {
512				// Unlike DTLS 1.2, DTLS 1.3's nonce construction does not use
513				// the epoch number. We store the epoch and nonce numbers
514				// together, so make a copy without the epoch.
515				nonce = make([]byte, 8)
516				copy(nonce[2:], epoch.seq[2:])
517			}
518
519			if explicitIVLen != 0 {
520				if len(payload) < explicitIVLen {
521					return false, 0, nil, alertBadRecordMAC
522				}
523				nonce = payload[:explicitIVLen]
524				payload = payload[explicitIVLen:]
525			}
526
527			var additionalData []byte
528			if hc.version < VersionTLS13 {
529				additionalData = make([]byte, 13)
530				copy(additionalData, epoch.seq[:])
531				copy(additionalData[8:], record[:3])
532				n := len(payload) - c.Overhead()
533				additionalData[11] = byte(n >> 8)
534				additionalData[12] = byte(n)
535			} else {
536				additionalData = record[:recordHeaderLen]
537			}
538			var err error
539			payload, err = c.Open(payload[:0], nonce, payload, additionalData)
540			if err != nil {
541				return false, 0, nil, alertBadRecordMAC
542			}
543		case *cbcMode:
544			blockSize := c.BlockSize()
545			if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
546				return false, 0, nil, alertBadRecordMAC
547			}
548
549			if explicitIVLen > 0 {
550				c.SetIV(payload[:explicitIVLen])
551				payload = payload[explicitIVLen:]
552			}
553			c.CryptBlocks(payload, payload)
554			payload, paddingGood = removePadding(payload)
555
556			// note that we still have a timing side-channel in the
557			// MAC check, below. An attacker can align the record
558			// so that a correct padding will cause one less hash
559			// block to be calculated. Then they can iteratively
560			// decrypt a record by breaking each byte. See
561			// "Password Interception in a SSL/TLS Channel", Brice
562			// Canvel et al.
563			//
564			// However, our behavior matches OpenSSL, so we leak
565			// only as much as they do.
566		case nullCipher:
567			break
568		default:
569			panic("unknown cipher type")
570		}
571
572		if hc.version >= VersionTLS13 {
573			i := len(payload)
574			for i > 0 && payload[i-1] == 0 {
575				i--
576			}
577			payload = payload[:i]
578			if len(payload) == 0 {
579				return false, 0, nil, alertUnexpectedMessage
580			}
581			contentType = recordType(payload[len(payload)-1])
582			payload = payload[:len(payload)-1]
583		}
584	}
585
586	// check, strip mac
587	if epoch.mac != nil {
588		if len(payload) < macSize {
589			return false, 0, nil, alertBadRecordMAC
590		}
591
592		// strip mac off payload
593		n := len(payload) - macSize
594		remoteMAC := payload[n:]
595		payload = payload[:n]
596		record[recordHeaderLen-2] = byte(n >> 8)
597		record[recordHeaderLen-1] = byte(n)
598		localMAC := hc.computeMAC(epoch, epoch.seq[:], record[:recordHeaderLen], payload)
599		if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
600			return false, 0, nil, alertBadRecordMAC
601		}
602	}
603	hc.incSeq(epoch)
604
605	return true, contentType, payload, 0
606}
607
608// extendSlice updates *data to contain n more bytes and returns a slice
609// containing the bytes that were added.
610func extendSlice(data *[]byte, n int) []byte {
611	// Reallocate the slice if needed.
612	*data = slices.Grow(*data, n)
613	// Extend data into the capacity and return the newly added slice.
614	oldLen := len(*data)
615	newLen := oldLen + n
616	*data = (*data)[:newLen]
617	return (*data)[oldLen:newLen]
618}
619
620// computingCBCPaddingLength returns the number of bytes of CBC padding to use
621// for a payload (plaintext + MAC) of length payloadLen.
622func computingCBCPaddingLength(payloadLen, blockSize int, config *Config) int {
623	paddingLen := blockSize - payloadLen%blockSize
624	if config.Bugs.MaxPadding {
625		for paddingLen+blockSize <= 256 {
626			paddingLen += blockSize
627		}
628	}
629	return paddingLen
630}
631
632// appendCBCPadding computes paddingLen bytes of padding data, appends it to b,
633// and returns the result.
634func appendCBCPadding(b []byte, paddingLen int, config *Config) []byte {
635	padding := extendSlice(&b, paddingLen)
636	for i := range padding {
637		padding[i] = byte(paddingLen - 1)
638	}
639	if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
640		padding[0] ^= 0xff
641	}
642	return b
643}
644
645func (hc *halfConn) maxEncryptOverhead(epoch *epochState, payloadLen int) int {
646	var macSize int
647	if epoch.mac != nil {
648		macSize = epoch.mac.Size()
649	}
650	overhead := macSize + hc.explicitIVLen(epoch)
651	if hc.version >= VersionTLS13 {
652		overhead += 1 + hc.config.Bugs.RecordPadding // type + padding
653	}
654	if epoch.cipher != nil {
655		switch c := epoch.cipher.(type) {
656		case cipher.Stream, *nullCipher:
657		case *tlsAead:
658			overhead += c.Overhead()
659		case *cbcMode:
660			overhead += computingCBCPaddingLength(payloadLen+macSize, c.BlockSize(), hc.config)
661		case nullCipher:
662			break
663		default:
664			panic("unknown cipher type")
665		}
666	}
667	return overhead
668}
669
670func (c *Conn) useDTLSPlaintextHeader() bool {
671	return c.config.Bugs.DTLSUsePlaintextRecordHeader && c.handshakeComplete
672}
673
674// encrypt encrypts and MACs the data in payload, appending it record. On
675// entry, the last headerLen bytes of record must be the header. The length
676// (which must be in the last two bytes of the header) should be computed for
677// the unencrypted, unpadded payload. It will be updated, potentially in-place,
678// with the final length.
679func (hc *halfConn) encrypt(epoch *epochState, record, payload []byte, typ recordType, headerLen int, headerHasLength bool) ([]byte, error) {
680	seq := hc.sequenceNumberForOutput(epoch)
681	prefixLen := len(record)
682	header := record[prefixLen-headerLen:]
683	explicitIVLen := hc.explicitIVLen(epoch)
684
685	// Reserve some space for the explicit IV. The slice may get reallocated
686	// after this, so don't use the return value.
687	extendSlice(&record, explicitIVLen)
688
689	// Stage the plaintext, TLS 1.3 padding, and TLS 1.2 MAC in the record, to
690	// be encrypted in-place.
691	record = append(record, payload...)
692
693	if hc.version >= VersionTLS13 && epoch.cipher != nil {
694		if hc.config.Bugs.OmitRecordContents {
695			record = record[:len(record)-len(payload)]
696		} else {
697			record = append(record, byte(typ))
698		}
699		padding := extendSlice(&record, hc.config.Bugs.RecordPadding)
700		clear(padding)
701	}
702
703	if epoch.mac != nil {
704		record = append(record, hc.computeMAC(epoch, seq, header, payload)...)
705	}
706
707	explicitIV := record[prefixLen : prefixLen+explicitIVLen]
708	if epoch.cipher != nil {
709		switch c := epoch.cipher.(type) {
710		case cipher.Stream:
711			if explicitIVLen != 0 {
712				panic("tls: unexpected explicit IV length")
713			}
714			c.XORKeyStream(record[prefixLen:], record[prefixLen:])
715		case *tlsAead:
716			nonce := seq
717			if hc.isDTLS && hc.version >= VersionTLS13 && !hc.conn.useDTLSPlaintextHeader() {
718				// Unlike DTLS 1.2, DTLS 1.3's nonce construction does not use
719				// the epoch number. We store the epoch and nonce numbers
720				// together, so make a copy without the epoch.
721				nonce = make([]byte, 8)
722				copy(nonce[2:], seq[2:])
723			}
724
725			// Save the explicit IV, if not empty.
726			if len(explicitIV) != 0 {
727				if explicitIVLen != len(nonce) {
728					panic("tls: unexpected explicit IV length")
729				}
730				copy(explicitIV, nonce)
731			}
732
733			var additionalData []byte
734			if hc.version < VersionTLS13 {
735				// (D)TLS 1.2's AD is seq_num || type || version || plaintext length
736				additionalData = make([]byte, 13)
737				copy(additionalData, seq)
738				copy(additionalData[8:], header[:3])
739				additionalData[11] = byte(len(payload) >> 8)
740				additionalData[12] = byte(len(payload))
741			} else {
742				// (D)TLS 1.3's AD is the ciphertext record header, so update the
743				// length now.
744				if headerHasLength {
745					n := len(record) - prefixLen + c.Overhead()
746					record[prefixLen-2] = byte(n >> 8)
747					record[prefixLen-1] = byte(n)
748				}
749				additionalData = record[prefixLen-headerLen : prefixLen]
750			}
751
752			record = c.Seal(record[:prefixLen+explicitIVLen], nonce, record[prefixLen+explicitIVLen:], additionalData)
753		case *cbcMode:
754			if explicitIVLen > 0 {
755				if _, err := io.ReadFull(hc.config.rand(), explicitIV); err != nil {
756					return nil, err
757				}
758				c.SetIV(explicitIV)
759			}
760
761			blockSize := c.BlockSize()
762			paddingLen := computingCBCPaddingLength(len(record)-prefixLen, blockSize, hc.config)
763			record = appendCBCPadding(record, paddingLen, hc.config)
764			c.CryptBlocks(record[prefixLen:], record[prefixLen:])
765		case nullCipher:
766			break
767		default:
768			panic("unknown cipher type")
769		}
770	}
771
772	// Update the record header to include the encryption overhead.
773	if headerHasLength {
774		n := len(record) - prefixLen
775		record[prefixLen-2] = byte(n >> 8)
776		record[prefixLen-1] = byte(n)
777	}
778	hc.incSeq(epoch)
779
780	return record, nil
781}
782
783type recordNumberEncrypter interface {
784	// GenerateMask takes a sample of the encrypted record and returns the
785	// mask used to encrypt and decrypt record numbers.
786	generateMask(sample []byte) []byte
787}
788
789type aesRecordNumberEncrypter struct {
790	aesCipher cipher.Block
791}
792
793func newAESRecordNumberEncrypter(key []byte) *aesRecordNumberEncrypter {
794	aesCipher, err := aes.NewCipher(key)
795	if err != nil {
796		panic("Incorrect usage of newAESRecordNumberEncrypter")
797	}
798	return &aesRecordNumberEncrypter{
799		aesCipher: aesCipher,
800	}
801}
802
803func (a *aesRecordNumberEncrypter) generateMask(sample []byte) []byte {
804	out := make([]byte, len(sample))
805	a.aesCipher.Encrypt(out, sample)
806	return out
807}
808
809type chachaRecordNumberEncrypter struct {
810	key []byte
811}
812
813func newChachaRecordNumberEncrypter(key []byte) *chachaRecordNumberEncrypter {
814	out := &chachaRecordNumberEncrypter{
815		key: key,
816	}
817	return out
818}
819
820func (c *chachaRecordNumberEncrypter) generateMask(sample []byte) []byte {
821	var counter, nonce []byte
822	sampleReader := cryptobyte.String(sample)
823	if !sampleReader.ReadBytes(&counter, 4) || !sampleReader.ReadBytes(&nonce, 12) {
824		panic("chachaRecordNumberEncrypter.GenerateMask called with wrong size sample")
825	}
826	cipher, err := chacha20.NewUnauthenticatedCipher(c.key, nonce)
827	if err != nil {
828		panic("Failed to create chacha20 cipher for record number encryption")
829	}
830	cipher.SetCounter(binary.LittleEndian.Uint32(counter))
831	out := make([]byte, 2)
832	cipher.XORKeyStream(out, out)
833	return out
834}
835
836func (c *Conn) useInTrafficSecret(epoch uint16, version uint16, suite *cipherSuite, secret []byte) error {
837	if c.hand.Len() != 0 {
838		return c.in.setErrorLocked(errors.New("tls: buffered handshake messages on cipher change"))
839	}
840	side := serverWrite
841	if !c.isClient {
842		side = clientWrite
843	}
844	if c.config.Bugs.MockQUICTransport != nil {
845		if epoch > uint16(encryptionApplication) {
846			panic("tls: KeyUpdate processed in QUIC")
847		}
848		c.config.Bugs.MockQUICTransport.readLevel = encryptionLevel(epoch)
849		c.config.Bugs.MockQUICTransport.readSecret = secret
850		c.config.Bugs.MockQUICTransport.readCipherSuite = suite.id
851	}
852	c.in.useTrafficSecret(version, suite, secret, side, epoch)
853	c.seenHandshakePackEnd = false
854	return nil
855}
856
857func (c *Conn) useOutTrafficSecret(epoch uint16, version uint16, suite *cipherSuite, secret []byte) {
858	if !c.isDTLS {
859		// The TLS logic relies on flushHandshake to write out packed handshake
860		// data on key changes. The DTLS logic handles key changes directly.
861		c.flushHandshake()
862	}
863	side := serverWrite
864	if c.isClient {
865		side = clientWrite
866	}
867	if c.config.Bugs.MockQUICTransport != nil {
868		if epoch > uint16(encryptionApplication) {
869			panic("tls: KeyUpdate processed in QUIC")
870		}
871		c.config.Bugs.MockQUICTransport.writeLevel = encryptionLevel(epoch)
872		c.config.Bugs.MockQUICTransport.writeSecret = secret
873		c.config.Bugs.MockQUICTransport.writeCipherSuite = suite.id
874	}
875	c.out.useTrafficSecret(version, suite, secret, side, epoch)
876}
877
878func (c *Conn) setSkipEarlyData() {
879	if c.config.Bugs.MockQUICTransport != nil {
880		c.config.Bugs.MockQUICTransport.skipEarlyData = true
881	} else {
882		c.skipEarlyData = true
883	}
884}
885
886func (c *Conn) shouldSkipEarlyData() bool {
887	if c.config.Bugs.MockQUICTransport != nil {
888		return c.config.Bugs.MockQUICTransport.skipEarlyData
889	}
890	return c.skipEarlyData
891}
892
893func (c *Conn) readRawInputUntil(n int) error {
894	if c.rawInput.Len() >= n {
895		return nil
896	}
897
898	n -= c.rawInput.Len()
899	c.rawInput.Grow(n)
900	buf := c.rawInput.AvailableBuffer()
901	nread, err := io.ReadAtLeast(c.conn, buf[:cap(buf)], n)
902	c.rawInput.Write(buf[:nread])
903	return err
904}
905
906func (c *Conn) doReadRecord(want recordType) (recordType, []byte, error) {
907RestartReadRecord:
908	if c.isDTLS {
909		return c.dtlsDoReadRecord(&c.in.epoch, want)
910	}
911
912	recordHeaderLen := tlsRecordHeaderLen
913
914	// Read header, payload.
915	if err := c.readRawInputUntil(recordHeaderLen); err != nil {
916		// RFC suggests that EOF without an alertCloseNotify is
917		// an error, but popular web sites seem to do this,
918		// so we can't make it an error, outside of tests.
919		if err == io.EOF && c.config.Bugs.ExpectCloseNotify {
920			err = io.ErrUnexpectedEOF
921		}
922		if e, ok := err.(net.Error); !ok || !e.Temporary() {
923			c.in.setErrorLocked(err)
924		}
925		return 0, nil, err
926	}
927
928	header := c.rawInput.Bytes()[:recordHeaderLen]
929	typ := recordType(header[0])
930
931	// No valid TLS record has a type of 0x80, however SSLv2 handshakes
932	// start with a uint16 length where the MSB is set and the first record
933	// is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
934	// an SSLv2 client.
935	if want == recordTypeHandshake && typ == 0x80 {
936		c.sendAlert(alertProtocolVersion)
937		return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
938	}
939
940	vers := uint16(header[1])<<8 | uint16(header[2])
941	n := int(header[3])<<8 | int(header[4])
942
943	// Alerts sent near version negotiation do not have a well-defined
944	// record-layer version prior to TLS 1.3. (In TLS 1.3, the record-layer
945	// version is irrelevant.)
946	if typ != recordTypeAlert {
947		var expect uint16
948		if c.haveVers {
949			expect = c.vers
950			if c.vers >= VersionTLS13 {
951				expect = VersionTLS12
952			}
953		} else {
954			expect = c.config.Bugs.ExpectInitialRecordVersion
955		}
956		if expect != 0 && vers != expect {
957			c.sendAlert(alertProtocolVersion)
958			return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
959		}
960	}
961	if n > maxCiphertext {
962		c.sendAlert(alertRecordOverflow)
963		return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
964	}
965	if !c.haveVers {
966		// First message, be extra suspicious:
967		// this might not be a TLS client.
968		// Bail out before reading a full 'body', if possible.
969		// The current max version is 3.1.
970		// If the version is >= 16.0, it's probably not real.
971		// Similarly, a clientHello message encodes in
972		// well under a kilobyte.  If the length is >= 12 kB,
973		// it's probably not real.
974		if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
975			c.sendAlert(alertUnexpectedMessage)
976			return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
977		}
978	}
979	if err := c.readRawInputUntil(recordHeaderLen + n); err != nil {
980		if err == io.EOF {
981			err = io.ErrUnexpectedEOF
982		}
983		if e, ok := err.(net.Error); !ok || !e.Temporary() {
984			c.in.setErrorLocked(err)
985		}
986		return 0, nil, err
987	}
988
989	// Process message.
990	b := c.rawInput.Next(recordHeaderLen + n)
991	epoch := &c.in.epoch
992	ok, encTyp, data, alertValue := c.in.decrypt(epoch, recordHeaderLen, b)
993	if !ok {
994		// TLS 1.3 early data uses trial decryption.
995		if c.skipEarlyData {
996			goto RestartReadRecord
997		}
998		return 0, nil, c.in.setErrorLocked(c.sendAlert(alertValue))
999	}
1000
1001	// If the server is expecting a second ClientHello (in response to
1002	// a HelloRetryRequest) and the client sends early data, there
1003	// won't be a decryption failure (we will interpret the ciphertext
1004	// as plaintext application data) but it still needs to be skipped.
1005	if epoch.cipher == nil && typ == recordTypeApplicationData && c.skipEarlyData {
1006		goto RestartReadRecord
1007	}
1008
1009	c.skipEarlyData = false
1010
1011	if c.vers >= VersionTLS13 && epoch.cipher != nil {
1012		if typ != recordTypeApplicationData {
1013			return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: outer record type is not application data"))
1014		}
1015		typ = encTyp
1016	}
1017
1018	if c.config.Bugs.ExpectRecordSplitting && typ == recordTypeApplicationData && len(data) != 1 && !c.seenOneByteRecord {
1019		return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: application data records were not split"))
1020	}
1021
1022	c.seenOneByteRecord = typ == recordTypeApplicationData && len(data) == 1
1023	return typ, data, nil
1024}
1025
1026func (c *Conn) readTLS13ChangeCipherSpec() error {
1027	if c.config.Bugs.MockQUICTransport != nil {
1028		return nil
1029	}
1030	if c.isDTLS {
1031		// ChangeCipherSpec in DTLS 1.3 is handled within dtlsDoReadRecord.
1032		return nil
1033	}
1034	if !c.expectTLS13ChangeCipherSpec {
1035		panic("c.expectTLS13ChangeCipherSpec not set")
1036	}
1037
1038	// Read the ChangeCipherSpec.
1039	if err := c.readRawInputUntil(6); err != nil {
1040		return c.in.setErrorLocked(fmt.Errorf("tls: error reading TLS 1.3 ChangeCipherSpec: %s", err))
1041	}
1042	if recordType(c.rawInput.Bytes()[0]) == recordTypeAlert {
1043		// If the client is sending an alert, allow the ChangeCipherSpec
1044		// to be skipped. It may be rejecting a sufficiently malformed
1045		// ServerHello that it can't parse out the version.
1046		c.expectTLS13ChangeCipherSpec = false
1047		return nil
1048	}
1049
1050	// Check they match that we expect.
1051	expected := [6]byte{byte(recordTypeChangeCipherSpec), 3, 1, 0, 1, 1}
1052	if c.vers >= VersionTLS13 {
1053		expected[2] = 3
1054	}
1055	if data := c.rawInput.Bytes()[:6]; !bytes.Equal(data, expected[:]) {
1056		return c.in.setErrorLocked(fmt.Errorf("tls: error invalid TLS 1.3 ChangeCipherSpec: %x", data))
1057	}
1058
1059	// Discard the data.
1060	c.rawInput.Next(6)
1061
1062	c.expectTLS13ChangeCipherSpec = false
1063	return nil
1064}
1065
1066// readRecord reads the next TLS record from the connection
1067// and updates the record layer state.
1068// c.in.Mutex <= L; c.input == nil.
1069func (c *Conn) readRecord(want recordType) error {
1070	// Caller must be in sync with connection:
1071	// handshake data if handshake not yet completed,
1072	// else application data.
1073	switch want {
1074	default:
1075		c.sendAlert(alertInternalError)
1076		return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
1077	case recordTypeChangeCipherSpec:
1078		if c.handshakeComplete {
1079			c.sendAlert(alertInternalError)
1080			return c.in.setErrorLocked(errors.New("tls: ChangeCipherSpec requested after handshake complete"))
1081		}
1082	case recordTypeApplicationData, recordTypeAlert, recordTypeHandshake, recordTypeACK:
1083		break
1084	}
1085
1086	if c.expectTLS13ChangeCipherSpec {
1087		if err := c.readTLS13ChangeCipherSpec(); err != nil {
1088			return err
1089		}
1090	}
1091
1092Again:
1093	doReadRecord := c.doReadRecord
1094	if c.config.Bugs.MockQUICTransport != nil {
1095		doReadRecord = c.config.Bugs.MockQUICTransport.readRecord
1096	}
1097	typ, data, err := doReadRecord(want)
1098	if err != nil {
1099		return err
1100	}
1101	max := maxPlaintext
1102	if c.config.Bugs.MaxReceivePlaintext != 0 {
1103		max = c.config.Bugs.MaxReceivePlaintext
1104	}
1105	if len(data) > max {
1106		err := c.sendAlert(alertRecordOverflow)
1107		return c.in.setErrorLocked(err)
1108	}
1109
1110	if typ != recordTypeHandshake {
1111		c.seenHandshakePackEnd = false
1112	} else if c.seenHandshakePackEnd {
1113		return c.in.setErrorLocked(errors.New("tls: peer violated ExpectPackedEncryptedHandshake"))
1114	}
1115
1116	switch typ {
1117	default:
1118		c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1119
1120	case recordTypeAlert:
1121		if len(data) != 2 {
1122			c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1123			break
1124		}
1125		if alert(data[1]) == alertCloseNotify {
1126			c.in.setErrorLocked(io.EOF)
1127			break
1128		}
1129		switch data[0] {
1130		case alertLevelWarning:
1131			// drop on the floor
1132			goto Again
1133		case alertLevelError:
1134			c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
1135		default:
1136			c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1137		}
1138
1139	case recordTypeChangeCipherSpec:
1140		if typ != want || len(data) != 1 || data[0] != 1 {
1141			c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1142			break
1143		}
1144		if c.hand.Len() != 0 {
1145			c.in.setErrorLocked(errors.New("tls: buffered handshake messages on cipher change"))
1146			break
1147		}
1148		if c.isDTLS {
1149			// Track the ChangeCipherSpec record in the current flight.
1150			c.receivedFlight = append(c.receivedFlight, DTLSMessage{
1151				Epoch:              c.in.epoch.epoch,
1152				IsChangeCipherSpec: true,
1153				Data:               slices.Clone(data),
1154			})
1155		}
1156		if err := c.in.changeCipherSpec(); err != nil {
1157			c.in.setErrorLocked(c.sendAlert(err.(alert)))
1158		}
1159
1160	case recordTypeApplicationData:
1161		if typ != want {
1162			c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1163			break
1164		}
1165		c.input.Write(data)
1166
1167	case recordTypeHandshake:
1168		// Allow handshake data while reading application data to
1169		// trigger post-handshake messages.
1170		// TODO(rsc): Should at least pick off connection close.
1171		if typ != want && want != recordTypeApplicationData {
1172			return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
1173		}
1174		c.hand.Write(data)
1175		if pack := c.config.Bugs.ExpectPackedEncryptedHandshake; pack > 0 && len(data) < pack && c.out.epoch.cipher != nil {
1176			c.seenHandshakePackEnd = true
1177		}
1178		if c.isDTLS {
1179			record, err := c.makeDTLSRecordNumberInfo(&c.in.epoch, c.hand.Bytes())
1180			if err != nil {
1181				return err
1182			}
1183			c.receivedFlightRecords = append(c.receivedFlightRecords, record)
1184		}
1185
1186	case recordTypeACK:
1187		if typ != want || !c.isDTLS {
1188			c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1189			break
1190		}
1191
1192		if err := c.checkACK(data); err != nil {
1193			c.in.setErrorLocked(err)
1194			break
1195		}
1196	}
1197
1198	return c.in.err
1199}
1200
1201// sendAlert sends a TLS alert message.
1202// c.out.Mutex <= L.
1203func (c *Conn) sendAlertLocked(level byte, err alert) error {
1204	c.tmp[0] = level
1205	c.tmp[1] = byte(err)
1206	if c.config.Bugs.FragmentAlert {
1207		c.writeRecord(recordTypeAlert, c.tmp[0:1])
1208		c.writeRecord(recordTypeAlert, c.tmp[1:2])
1209	} else if c.config.Bugs.DoubleAlert {
1210		copy(c.tmp[2:4], c.tmp[0:2])
1211		c.writeRecord(recordTypeAlert, c.tmp[0:4])
1212	} else {
1213		c.writeRecord(recordTypeAlert, c.tmp[0:2])
1214	}
1215	// Error alerts are fatal to the connection.
1216	if level == alertLevelError {
1217		return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
1218	}
1219	return nil
1220}
1221
1222// sendAlert sends a TLS alert message.
1223// L < c.out.Mutex.
1224func (c *Conn) sendAlert(err alert) error {
1225	level := byte(alertLevelError)
1226	if err == alertNoRenegotiation || err == alertCloseNotify {
1227		level = alertLevelWarning
1228	}
1229	return c.SendAlert(level, err)
1230}
1231
1232func (c *Conn) SendAlert(level byte, err alert) error {
1233	c.out.Lock()
1234	defer c.out.Unlock()
1235	return c.sendAlertLocked(level, err)
1236}
1237
1238// writeV2Record writes a record for a V2ClientHello.
1239func (c *Conn) writeV2Record(data []byte) (n int, err error) {
1240	record := make([]byte, 2+len(data))
1241	record[0] = uint8(len(data)>>8) | 0x80
1242	record[1] = uint8(len(data))
1243	copy(record[2:], data)
1244	return c.conn.Write(record)
1245}
1246
1247// writeRecord writes a TLS record with the given type and payload
1248// to the connection and updates the record layer state.
1249// c.out.Mutex <= L.
1250func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
1251	c.seenHandshakePackEnd = false
1252	if c.hand.Len() == 0 {
1253		c.lastRecordInFlight = nil
1254	}
1255	if typ == recordTypeHandshake {
1256		msgType := data[0]
1257		if c.config.Bugs.SendWrongMessageType != 0 && msgType == c.config.Bugs.SendWrongMessageType {
1258			msgType += 42
1259		}
1260		if msgType != data[0] {
1261			data = append([]byte{msgType}, data[1:]...)
1262		}
1263
1264		if c.config.Bugs.SendTrailingMessageData != 0 && msgType == c.config.Bugs.SendTrailingMessageData {
1265			// Add a 0 to the body.
1266			newData := make([]byte, len(data)+1)
1267			copy(newData, data)
1268
1269			// Fix the header.
1270			newLen := len(newData) - 4
1271			newData[1] = byte(newLen >> 16)
1272			newData[2] = byte(newLen >> 8)
1273			newData[3] = byte(newLen)
1274
1275			data = newData
1276		}
1277
1278		if c.config.Bugs.TrailingDataWithFinished && msgType == typeFinished {
1279			// Add a 0 to the record. Note unused bytes in |data| may be owned by the
1280			// caller, so we force a new allocation.
1281			data = append(data[:len(data):len(data)], 0)
1282		}
1283	}
1284
1285	if c.isDTLS {
1286		return c.dtlsWriteRecord(typ, data)
1287	}
1288	if c.config.Bugs.MockQUICTransport != nil {
1289		return c.config.Bugs.MockQUICTransport.writeRecord(typ, data)
1290	}
1291
1292	if typ == recordTypeHandshake {
1293		if c.config.Bugs.SendHelloRequestBeforeEveryHandshakeMessage {
1294			newData := make([]byte, 0, 4+len(data))
1295			newData = append(newData, typeHelloRequest, 0, 0, 0)
1296			newData = append(newData, data...)
1297			data = newData
1298		}
1299
1300		if c.config.Bugs.PackHandshakeFlight {
1301			c.pendingFlight.Write(data)
1302			return len(data), nil
1303		}
1304	}
1305
1306	// Flush buffered data before writing anything.
1307	if err := c.flushHandshake(); err != nil {
1308		return 0, err
1309	}
1310
1311	if typ == recordTypeApplicationData && c.config.Bugs.SendPostHandshakeChangeCipherSpec {
1312		if _, err := c.doWriteRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
1313			return 0, err
1314		}
1315	}
1316
1317	return c.doWriteRecord(typ, data)
1318}
1319
1320func (c *Conn) doWriteRecord(typ recordType, data []byte) (n int, err error) {
1321	first := true
1322	for len(data) > 0 || first {
1323		m := len(data)
1324		if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
1325			m = maxPlaintext
1326		}
1327		if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
1328			m = c.config.Bugs.MaxHandshakeRecordLength
1329		}
1330		first = false
1331
1332		// Determine record version.
1333		vers := c.vers
1334		if vers == 0 {
1335			// Some TLS servers fail if the record version is
1336			// greater than TLS 1.0 for the initial ClientHello.
1337			//
1338			// TLS 1.3 fixes the version number in the record
1339			// layer to {3, 1}.
1340			vers = VersionTLS10
1341		}
1342		if c.vers >= VersionTLS13 || c.out.version >= VersionTLS13 {
1343			vers = VersionTLS12
1344		}
1345		if c.config.Bugs.SendRecordVersion != 0 {
1346			vers = c.config.Bugs.SendRecordVersion
1347		}
1348		if c.vers == 0 && c.config.Bugs.SendInitialRecordVersion != 0 {
1349			vers = c.config.Bugs.SendInitialRecordVersion
1350		}
1351
1352		// Assemble the record header.
1353		epoch := &c.out.epoch
1354		record := make([]byte, tlsRecordHeaderLen, tlsRecordHeaderLen+m+c.out.maxEncryptOverhead(epoch, m))
1355		record[0] = byte(typ)
1356		if c.vers >= VersionTLS13 && epoch.cipher != nil {
1357			record[0] = byte(recordTypeApplicationData)
1358			if outerType := c.config.Bugs.OuterRecordType; outerType != 0 {
1359				record[0] = byte(outerType)
1360			}
1361		}
1362		record[1] = byte(vers >> 8)
1363		record[2] = byte(vers)
1364		record[3] = byte(m >> 8) // encrypt will update this
1365		record[4] = byte(m)
1366
1367		record, err = c.out.encrypt(epoch, record, data[:m], typ, tlsRecordHeaderLen, true /* header has length */)
1368		if err != nil {
1369			return
1370		}
1371		_, err = c.conn.Write(record)
1372		if err != nil {
1373			break
1374		}
1375		n += m
1376		data = data[m:]
1377	}
1378
1379	if typ == recordTypeChangeCipherSpec && c.vers < VersionTLS13 {
1380		err = c.out.changeCipherSpec()
1381		if err != nil {
1382			return n, c.sendAlertLocked(alertLevelError, err.(alert))
1383		}
1384	}
1385	return
1386}
1387
1388func (c *Conn) flushHandshake() error {
1389	if c.isDTLS {
1390		return c.dtlsFlushHandshake()
1391	}
1392
1393	for c.pendingFlight.Len() > 0 {
1394		var buf [maxPlaintext]byte
1395		n, _ := c.pendingFlight.Read(buf[:])
1396		if _, err := c.doWriteRecord(recordTypeHandshake, buf[:n]); err != nil {
1397			return err
1398		}
1399	}
1400
1401	c.pendingFlight.Reset()
1402	return nil
1403}
1404
1405func (c *Conn) ackHandshake() error {
1406	if c.isDTLS {
1407		return c.dtlsACKHandshake()
1408	}
1409	return nil
1410}
1411
1412func (c *Conn) doReadHandshake() ([]byte, error) {
1413	if c.isDTLS {
1414		return c.dtlsDoReadHandshake()
1415	}
1416
1417	for c.hand.Len() < 4 {
1418		if err := c.in.err; err != nil {
1419			return nil, err
1420		}
1421		if err := c.readRecord(recordTypeHandshake); err != nil {
1422			return nil, err
1423		}
1424	}
1425
1426	data := c.hand.Bytes()
1427	n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1428	if n > maxHandshake {
1429		return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
1430	}
1431	for c.hand.Len() < 4+n {
1432		if err := c.in.err; err != nil {
1433			return nil, err
1434		}
1435		if err := c.readRecord(recordTypeHandshake); err != nil {
1436			return nil, err
1437		}
1438	}
1439	return c.hand.Next(4 + n), nil
1440}
1441
1442// readHandshake reads the next handshake message from
1443// the record layer.
1444// c.in.Mutex < L; c.out.Mutex < L.
1445func (c *Conn) readHandshake() (any, error) {
1446	data, err := c.doReadHandshake()
1447	if err != nil {
1448		return nil, err
1449	}
1450
1451	typ := data[0]
1452	var m handshakeMessage
1453	switch typ {
1454	case typeHelloRequest:
1455		m = new(helloRequestMsg)
1456	case typeClientHello:
1457		m = &clientHelloMsg{
1458			isDTLS: c.isDTLS,
1459		}
1460	case typeServerHello:
1461		m = &serverHelloMsg{
1462			isDTLS: c.isDTLS,
1463		}
1464	case typeNewSessionTicket:
1465		m = &newSessionTicketMsg{
1466			vers:   c.wireVersion,
1467			isDTLS: c.isDTLS,
1468		}
1469	case typeEncryptedExtensions:
1470		if c.isClient {
1471			m = new(encryptedExtensionsMsg)
1472		} else {
1473			m = new(clientEncryptedExtensionsMsg)
1474		}
1475	case typeCertificate:
1476		m = &certificateMsg{
1477			hasRequestContext: c.vers >= VersionTLS13,
1478		}
1479	case typeCompressedCertificate:
1480		m = new(compressedCertificateMsg)
1481	case typeCertificateRequest:
1482		m = &certificateRequestMsg{
1483			vers:                  c.wireVersion,
1484			hasSignatureAlgorithm: c.vers >= VersionTLS12,
1485			hasRequestContext:     c.vers >= VersionTLS13,
1486		}
1487	case typeCertificateStatus:
1488		m = new(certificateStatusMsg)
1489	case typeServerKeyExchange:
1490		m = new(serverKeyExchangeMsg)
1491	case typeServerHelloDone:
1492		m = new(serverHelloDoneMsg)
1493	case typeClientKeyExchange:
1494		m = new(clientKeyExchangeMsg)
1495	case typeCertificateVerify:
1496		m = &certificateVerifyMsg{
1497			hasSignatureAlgorithm: c.vers >= VersionTLS12,
1498		}
1499	case typeNextProtocol:
1500		m = new(nextProtoMsg)
1501	case typeFinished:
1502		m = new(finishedMsg)
1503	case typeHelloVerifyRequest:
1504		m = new(helloVerifyRequestMsg)
1505	case typeChannelID:
1506		m = new(channelIDMsg)
1507	case typeKeyUpdate:
1508		m = new(keyUpdateMsg)
1509	case typeEndOfEarlyData:
1510		m = new(endOfEarlyDataMsg)
1511	default:
1512		return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1513	}
1514
1515	// The handshake message unmarshallers
1516	// expect to be able to keep references to data,
1517	// so pass in a fresh copy that won't be overwritten.
1518	data = slices.Clone(data)
1519
1520	if data[0] == typeServerHello && len(data) >= 38 {
1521		vers := uint16(data[4])<<8 | uint16(data[5])
1522		if (vers == VersionDTLS12 || vers == VersionTLS12) && bytes.Equal(data[6:38], tls13HelloRetryRequest) {
1523			m = &helloRetryRequestMsg{isDTLS: c.isDTLS}
1524		}
1525	}
1526
1527	if !m.unmarshal(data) {
1528		c.sendAlert(alertDecodeError)
1529		return nil, c.in.setErrorLocked(fmt.Errorf("tls: error decoding %s message", messageTypeToString(typ)))
1530	}
1531	return m, nil
1532}
1533
1534func readHandshakeType[T any](c *Conn) (*T, error) {
1535	m, err := c.readHandshake()
1536	if err != nil {
1537		return nil, err
1538	}
1539	mType, ok := m.(*T)
1540	if !ok {
1541		c.sendAlert(alertUnexpectedMessage)
1542		return nil, unexpectedMessageError(mType, m)
1543	}
1544	return mType, nil
1545}
1546
1547func (c *Conn) SendHalfHelloRequest() error {
1548	if err := c.Handshake(); err != nil {
1549		return err
1550	}
1551
1552	c.out.Lock()
1553	defer c.out.Unlock()
1554
1555	if _, err := c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0}); err != nil {
1556		return err
1557	}
1558	return c.flushHandshake()
1559}
1560
1561// Write writes data to the connection.
1562func (c *Conn) Write(b []byte) (int, error) {
1563	if err := c.Handshake(); err != nil {
1564		return 0, err
1565	}
1566
1567	c.out.Lock()
1568	defer c.out.Unlock()
1569
1570	if err := c.out.err; err != nil {
1571		return 0, err
1572	}
1573
1574	if !c.handshakeComplete {
1575		return 0, alertInternalError
1576	}
1577
1578	if c.keyUpdateRequested {
1579		if err := c.sendKeyUpdateLocked(keyUpdateNotRequested); err != nil {
1580			return 0, err
1581		}
1582		c.keyUpdateRequested = false
1583	}
1584
1585	if c.config.Bugs.SendSpuriousAlert != 0 {
1586		c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
1587	}
1588
1589	if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1590		c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
1591		c.flushHandshake()
1592	}
1593
1594	// SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1595	// attack when using block mode ciphers due to predictable IVs.
1596	// This can be prevented by splitting each Application Data
1597	// record into two records, effectively randomizing the IV.
1598	//
1599	// http://www.openssl.org/~bodo/tls-cbc.txt
1600	// https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1601	// http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1602
1603	var m int
1604	if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
1605		if _, ok := c.out.epoch.cipher.(*cbcMode); ok {
1606			n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1607			if err != nil {
1608				return n, c.out.setErrorLocked(err)
1609			}
1610			m, b = 1, b[1:]
1611		}
1612	}
1613
1614	n, err := c.writeRecord(recordTypeApplicationData, b)
1615	return n + m, c.out.setErrorLocked(err)
1616}
1617
1618func (c *Conn) processTLS13NewSessionTicket(newSessionTicket *newSessionTicketMsg, cipherSuite *cipherSuite) error {
1619	session := &ClientSessionState{
1620		sessionTicket:               newSessionTicket.ticket,
1621		vers:                        c.vers,
1622		wireVersion:                 c.wireVersion,
1623		cipherSuite:                 cipherSuite,
1624		secret:                      deriveSessionPSK(cipherSuite, c.wireVersion, c.resumptionSecret, newSessionTicket.ticketNonce, c.isDTLS),
1625		serverCertificates:          c.peerCertificates,
1626		sctList:                     c.sctList,
1627		ocspResponse:                c.ocspResponse,
1628		ticketCreationTime:          c.config.time(),
1629		ticketExpiration:            c.config.time().Add(time.Duration(newSessionTicket.ticketLifetime) * time.Second),
1630		ticketAgeAdd:                newSessionTicket.ticketAgeAdd,
1631		maxEarlyDataSize:            newSessionTicket.maxEarlyDataSize,
1632		earlyALPN:                   c.clientProtocol,
1633		hasApplicationSettings:      c.hasApplicationSettings,
1634		localApplicationSettings:    c.localApplicationSettings,
1635		peerApplicationSettings:     c.peerApplicationSettings,
1636		hasApplicationSettingsOld:   c.hasApplicationSettingsOld,
1637		localApplicationSettingsOld: c.localApplicationSettingsOld,
1638		peerApplicationSettingsOld:  c.peerApplicationSettingsOld,
1639		resumptionAcrossNames:       newSessionTicket.flags.hasFlag(flagResumptionAcrossNames),
1640	}
1641
1642	if c.config.Bugs.ExpectGREASE && !newSessionTicket.hasGREASEExtension {
1643		return errors.New("tls: no GREASE ticket extension found")
1644	}
1645
1646	if c.config.Bugs.ExpectTicketEarlyData && newSessionTicket.maxEarlyDataSize == 0 {
1647		return errors.New("tls: no early_data ticket extension found")
1648	}
1649
1650	if c.config.Bugs.ExpectNoNewSessionTicket || c.config.Bugs.ExpectNoNonEmptyNewSessionTicket {
1651		return errors.New("tls: received unexpected NewSessionTicket")
1652	}
1653
1654	if expect := c.config.Bugs.ExpectResumptionAcrossNames; expect != nil && session.resumptionAcrossNames != *expect {
1655		return errors.New("tls: resumption_across_names status of ticket did not match expectation")
1656	}
1657
1658	if c.config.ClientSessionCache == nil || newSessionTicket.ticketLifetime == 0 {
1659		return nil
1660	}
1661
1662	cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
1663	_, ok := c.config.ClientSessionCache.Get(cacheKey)
1664	if !ok || !c.config.Bugs.UseFirstSessionTicket {
1665		c.config.ClientSessionCache.Put(cacheKey, session)
1666	}
1667
1668	return c.ackHandshake()
1669}
1670
1671func (c *Conn) processKeyUpdate(keyUpdate *keyUpdateMsg) error {
1672	epoch := c.in.epoch.epoch + 1
1673	if epoch == 0 && !c.config.Bugs.AllowEpochOverflow {
1674		return errors.New("tls: too many KeyUpdates")
1675	}
1676	if err := c.useInTrafficSecret(epoch, c.in.wireVersion, c.cipherSuite, updateTrafficSecret(c.cipherSuite.hash(), c.wireVersion, c.in.trafficSecret, c.isDTLS)); err != nil {
1677		return err
1678	}
1679	if keyUpdate.keyUpdateRequest == keyUpdateRequested {
1680		c.keyUpdateRequested = true
1681	}
1682	return c.ackHandshake()
1683}
1684
1685func (c *Conn) handlePostHandshakeMessage() error {
1686	msg, err := c.readHandshake()
1687	if err != nil {
1688		return err
1689	}
1690
1691	if c.vers < VersionTLS13 {
1692		if !c.isClient {
1693			c.sendAlert(alertUnexpectedMessage)
1694			return errors.New("tls: unexpected post-handshake message")
1695		}
1696
1697		_, ok := msg.(*helloRequestMsg)
1698		if !ok {
1699			c.sendAlert(alertUnexpectedMessage)
1700			return alertUnexpectedMessage
1701		}
1702
1703		c.handshakeComplete = false
1704		return c.Handshake()
1705	}
1706
1707	if c.isClient {
1708		if newSessionTicket, ok := msg.(*newSessionTicketMsg); ok {
1709			return c.processTLS13NewSessionTicket(newSessionTicket, c.cipherSuite)
1710		}
1711	}
1712
1713	if keyUpdate, ok := msg.(*keyUpdateMsg); ok {
1714		c.keyUpdateSeen = true
1715		if c.config.Bugs.RejectUnsolicitedKeyUpdate {
1716			return errors.New("tls: unexpected KeyUpdate message")
1717		}
1718		return c.processKeyUpdate(keyUpdate)
1719	}
1720
1721	c.sendAlert(alertUnexpectedMessage)
1722	return errors.New("tls: unexpected post-handshake message")
1723}
1724
1725// Reads a KeyUpdate from the peer, with type key_update_not_requested. There
1726// may not be any application data records before the message.
1727func (c *Conn) ReadKeyUpdate() error {
1728	c.in.Lock()
1729	defer c.in.Unlock()
1730
1731	keyUpdate, err := readHandshakeType[keyUpdateMsg](c)
1732	if err != nil {
1733		return err
1734	}
1735
1736	if keyUpdate.keyUpdateRequest != keyUpdateNotRequested {
1737		return errors.New("tls: received invalid KeyUpdate message")
1738	}
1739
1740	return c.processKeyUpdate(keyUpdate)
1741}
1742
1743func (c *Conn) Renegotiate() error {
1744	if !c.isClient {
1745		helloReq := new(helloRequestMsg).marshal()
1746		if c.config.Bugs.BadHelloRequest != nil {
1747			helloReq = c.config.Bugs.BadHelloRequest
1748		}
1749		c.writeRecord(recordTypeHandshake, helloReq)
1750		c.flushHandshake()
1751	}
1752
1753	c.handshakeComplete = false
1754	return c.Handshake()
1755}
1756
1757// Read can be made to time out and return a net.Error with Timeout() == true
1758// after a fixed time limit; see SetDeadline and SetReadDeadline.
1759func (c *Conn) Read(b []byte) (n int, err error) {
1760	if err = c.Handshake(); err != nil {
1761		return
1762	}
1763
1764	c.in.Lock()
1765	defer c.in.Unlock()
1766
1767	// Some OpenSSL servers send empty records in order to randomize the
1768	// CBC IV. So this loop ignores a limited number of empty records.
1769	const maxConsecutiveEmptyRecords = 100
1770	for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1771		for c.input.Len() == 0 && c.in.err == nil {
1772			if err := c.readRecord(recordTypeApplicationData); err != nil {
1773				// Soft error, like EAGAIN
1774				return 0, err
1775			}
1776			for c.hand.Len() > 0 {
1777				// We received handshake bytes, indicating a
1778				// post-handshake message.
1779				if err := c.handlePostHandshakeMessage(); err != nil {
1780					return 0, err
1781				}
1782			}
1783		}
1784		if err := c.in.err; err != nil {
1785			return 0, err
1786		}
1787
1788		n, err = c.input.Read(b)
1789		if c.input.Len() == 0 || c.isDTLS {
1790			c.input.Reset()
1791		}
1792
1793		// If a close-notify alert is waiting, read it so that
1794		// we can return (n, EOF) instead of (n, nil), to signal
1795		// to the HTTP response reading goroutine that the
1796		// connection is now closed. This eliminates a race
1797		// where the HTTP response reading goroutine would
1798		// otherwise not observe the EOF until its next read,
1799		// by which time a client goroutine might have already
1800		// tried to reuse the HTTP connection for a new
1801		// request.
1802		// See https://codereview.appspot.com/76400046
1803		// and http://golang.org/issue/3514
1804		if ri := c.rawInput.Bytes(); !c.isDTLS && n != 0 && err == nil &&
1805			c.input.Len() == 0 && len(ri) > 0 && recordType(ri[0]) == recordTypeAlert {
1806			if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1807				err = recErr // will be io.EOF on closeNotify
1808			}
1809		}
1810
1811		if n != 0 || err != nil {
1812			return n, err
1813		}
1814	}
1815
1816	return 0, io.ErrNoProgress
1817}
1818
1819// Close closes the connection.
1820func (c *Conn) Close() error {
1821	var alertErr error
1822
1823	c.handshakeMutex.Lock()
1824	defer c.handshakeMutex.Unlock()
1825	if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
1826		alert := alertCloseNotify
1827		if c.config.Bugs.SendAlertOnShutdown != 0 {
1828			alert = c.config.Bugs.SendAlertOnShutdown
1829		}
1830		alertErr = c.sendAlert(alert)
1831		// Clear local alerts when sending alerts so we continue to wait
1832		// for the peer rather than closing the socket early.
1833		if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1834			alertErr = nil
1835		}
1836	}
1837
1838	// Consume a close_notify from the peer if one hasn't been received
1839	// already. This avoids the peer from failing |SSL_shutdown| due to a
1840	// write failing.
1841	if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1842		for c.in.error() == nil {
1843			c.readRecord(recordTypeAlert)
1844		}
1845		if c.in.error() != io.EOF {
1846			alertErr = c.in.error()
1847		}
1848	}
1849
1850	if err := c.conn.Close(); err != nil {
1851		return err
1852	}
1853	return alertErr
1854}
1855
1856// Handshake runs the client or server handshake
1857// protocol if it has not yet been run.
1858// Most uses of this package need not call Handshake
1859// explicitly: the first Read or Write will call it automatically.
1860func (c *Conn) Handshake() error {
1861	c.handshakeMutex.Lock()
1862	defer c.handshakeMutex.Unlock()
1863	if err := c.handshakeErr; err != nil {
1864		return err
1865	}
1866	if c.handshakeComplete {
1867		return nil
1868	}
1869
1870	if c.isDTLS && c.config.Bugs.SendSplitAlert {
1871		c.conn.Write([]byte{
1872			byte(recordTypeAlert), // type
1873			0xfe, 0xff,            // version
1874			0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1875			0x0, 0x2, // length
1876		})
1877		c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1878	}
1879	if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1880		c.writeRecord(recordTypeApplicationData, data)
1881	}
1882	if c.isClient {
1883		c.handshakeErr = c.clientHandshake()
1884	} else {
1885		c.handshakeErr = c.serverHandshake()
1886	}
1887	if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1888		c.writeRecord(recordType(42), []byte("invalid record"))
1889	}
1890	return c.handshakeErr
1891}
1892
1893// ConnectionState returns basic TLS details about the connection.
1894func (c *Conn) ConnectionState() ConnectionState {
1895	c.handshakeMutex.Lock()
1896	defer c.handshakeMutex.Unlock()
1897
1898	var state ConnectionState
1899	state.HandshakeComplete = c.handshakeComplete
1900	if c.handshakeComplete {
1901		state.Version = c.vers
1902		state.NegotiatedProtocol = c.clientProtocol
1903		state.DidResume = c.didResume
1904		state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
1905		state.NegotiatedProtocolFromALPN = c.usedALPN
1906		state.CipherSuite = c.cipherSuite.id
1907		state.PeerCertificates = c.peerCertificates
1908		state.PeerDelegatedCredential = c.peerDelegatedCredential
1909		state.VerifiedChains = c.verifiedChains
1910		state.OCSPResponse = c.ocspResponse
1911		state.ServerName = c.serverName
1912		state.ServerNameAck = c.serverNameAck
1913		state.ChannelID = c.channelID
1914		state.SRTPProtectionProfile = c.srtpProtectionProfile
1915		state.TLSUnique = c.firstFinished[:]
1916		state.SCTList = c.sctList
1917		state.PeerSignatureAlgorithm = c.peerSignatureAlgorithm
1918		state.CurveID = c.curveID
1919		state.QUICTransportParams = c.quicTransportParams
1920		state.QUICTransportParamsLegacy = c.quicTransportParamsLegacy
1921		state.HasApplicationSettings = c.hasApplicationSettings
1922		state.PeerApplicationSettings = c.peerApplicationSettings
1923		state.HasApplicationSettingsOld = c.hasApplicationSettingsOld
1924		state.PeerApplicationSettingsOld = c.peerApplicationSettingsOld
1925		state.ECHAccepted = c.echAccepted
1926	}
1927
1928	return state
1929}
1930
1931// VerifyHostname checks that the peer certificate chain is valid for
1932// connecting to host.  If so, it returns nil; if not, it returns an error
1933// describing the problem.
1934func (c *Conn) VerifyHostname(host string) error {
1935	c.handshakeMutex.Lock()
1936	defer c.handshakeMutex.Unlock()
1937	if !c.isClient {
1938		return errors.New("tls: VerifyHostname called on TLS server connection")
1939	}
1940	if !c.handshakeComplete {
1941		return errors.New("tls: handshake has not yet been performed")
1942	}
1943	return c.peerCertificates[0].VerifyHostname(host)
1944}
1945
1946func (c *Conn) exportKeyingMaterialTLS13(length int, secret, label, context []byte) []byte {
1947	hash := c.cipherSuite.hash()
1948	exporterKeyingLabel := []byte("exporter")
1949	contextHash := hash.New()
1950	contextHash.Write(context)
1951	exporterContext := hash.New().Sum(nil)
1952	derivedSecret := hkdfExpandLabel(c.cipherSuite.hash(), secret, label, exporterContext, hash.Size(), c.isDTLS)
1953	return hkdfExpandLabel(c.cipherSuite.hash(), derivedSecret, exporterKeyingLabel, contextHash.Sum(nil), length, c.isDTLS)
1954}
1955
1956// ExportKeyingMaterial exports keying material from the current connection
1957// state, as per RFC 5705.
1958func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1959	c.handshakeMutex.Lock()
1960	defer c.handshakeMutex.Unlock()
1961	if !c.handshakeComplete {
1962		return nil, errors.New("tls: handshake has not yet been performed")
1963	}
1964
1965	if c.vers >= VersionTLS13 {
1966		return c.exportKeyingMaterialTLS13(length, c.exporterSecret, label, context), nil
1967	}
1968
1969	seedLen := len(c.clientRandom) + len(c.serverRandom)
1970	if useContext {
1971		seedLen += 2 + len(context)
1972	}
1973	seed := make([]byte, 0, seedLen)
1974	seed = append(seed, c.clientRandom[:]...)
1975	seed = append(seed, c.serverRandom[:]...)
1976	if useContext {
1977		seed = append(seed, byte(len(context)>>8), byte(len(context)))
1978		seed = append(seed, context...)
1979	}
1980	result := make([]byte, length)
1981	prfForVersion(c.vers, c.cipherSuite)(result, c.exporterSecret, label, seed)
1982	return result, nil
1983}
1984
1985func (c *Conn) ExportEarlyKeyingMaterial(length int, label, context []byte) ([]byte, error) {
1986	if c.vers < VersionTLS13 {
1987		return nil, errors.New("tls: early exporters not defined before TLS 1.3")
1988	}
1989
1990	if c.earlyExporterSecret == nil {
1991		return nil, errors.New("tls: no early exporter secret")
1992	}
1993
1994	return c.exportKeyingMaterialTLS13(length, c.earlyExporterSecret, label, context), nil
1995}
1996
1997// noRenegotiationInfo returns true if the renegotiation info extension
1998// should be supported in the current handshake.
1999func (c *Conn) noRenegotiationInfo() bool {
2000	if c.config.Bugs.NoRenegotiationInfo {
2001		return true
2002	}
2003	if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
2004		return true
2005	}
2006	if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
2007		return true
2008	}
2009	return false
2010}
2011
2012func (c *Conn) SendNewSessionTicket(nonce []byte) error {
2013	if c.isClient || c.vers < VersionTLS13 {
2014		return errors.New("tls: cannot send post-handshake NewSessionTicket")
2015	}
2016
2017	var peerCertificatesRaw [][]byte
2018	for _, cert := range c.peerCertificates {
2019		peerCertificatesRaw = append(peerCertificatesRaw, cert.Raw)
2020	}
2021
2022	addBuffer := make([]byte, 4)
2023	_, err := io.ReadFull(c.config.rand(), addBuffer)
2024	if err != nil {
2025		c.sendAlert(alertInternalError)
2026		return errors.New("tls: short read from Rand: " + err.Error())
2027	}
2028	ticketAgeAdd := uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0])
2029
2030	// TODO(davidben): Allow configuring these values.
2031	m := &newSessionTicketMsg{
2032		vers:                        c.wireVersion,
2033		isDTLS:                      c.isDTLS,
2034		ticketLifetime:              uint32(24 * time.Hour / time.Second),
2035		duplicateEarlyDataExtension: c.config.Bugs.DuplicateTicketEarlyData,
2036		customExtension:             c.config.Bugs.CustomTicketExtension,
2037		ticketAgeAdd:                ticketAgeAdd,
2038		ticketNonce:                 nonce,
2039		maxEarlyDataSize:            c.config.MaxEarlyDataSize,
2040		flags: flagSet{
2041			mustInclude: c.config.Bugs.AlwaysSendTicketFlags,
2042			padding:     c.config.Bugs.TicketFlagPadding,
2043		},
2044	}
2045	if c.config.Bugs.MockQUICTransport != nil && m.maxEarlyDataSize > 0 {
2046		m.maxEarlyDataSize = 0xffffffff
2047	}
2048
2049	if c.config.Bugs.SendTicketLifetime != 0 {
2050		m.ticketLifetime = uint32(c.config.Bugs.SendTicketLifetime / time.Second)
2051	}
2052	if c.config.ResumptionAcrossNames {
2053		m.flags.setFlag(flagResumptionAcrossNames)
2054	}
2055	for _, flag := range c.config.Bugs.SendTicketFlags {
2056		m.flags.setFlag(flag)
2057	}
2058
2059	state := sessionState{
2060		vers:                        c.vers,
2061		cipherSuite:                 c.cipherSuite.id,
2062		secret:                      deriveSessionPSK(c.cipherSuite, c.wireVersion, c.resumptionSecret, nonce, c.isDTLS),
2063		certificates:                peerCertificatesRaw,
2064		ticketCreationTime:          c.config.time(),
2065		ticketExpiration:            c.config.time().Add(time.Duration(m.ticketLifetime) * time.Second),
2066		ticketAgeAdd:                uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0]),
2067		earlyALPN:                   []byte(c.clientProtocol),
2068		hasApplicationSettings:      c.hasApplicationSettings,
2069		localApplicationSettings:    c.localApplicationSettings,
2070		peerApplicationSettings:     c.peerApplicationSettings,
2071		hasApplicationSettingsOld:   c.hasApplicationSettingsOld,
2072		localApplicationSettingsOld: c.localApplicationSettingsOld,
2073		peerApplicationSettingsOld:  c.peerApplicationSettingsOld,
2074	}
2075
2076	if !c.config.Bugs.SendEmptySessionTicket {
2077		var err error
2078		m.ticket, err = c.encryptTicket(&state)
2079		if err != nil {
2080			return err
2081		}
2082	}
2083	c.out.Lock()
2084	defer c.out.Unlock()
2085	_, err = c.writeRecord(recordTypeHandshake, m.marshal())
2086	return err
2087}
2088
2089func (c *Conn) SendKeyUpdate(keyUpdateRequest byte) error {
2090	c.out.Lock()
2091	defer c.out.Unlock()
2092	return c.sendKeyUpdateLocked(keyUpdateRequest)
2093}
2094
2095func (c *Conn) sendKeyUpdateLocked(keyUpdateRequest byte) error {
2096	if c.vers < VersionTLS13 {
2097		return errors.New("tls: attempted to send KeyUpdate before TLS 1.3")
2098	}
2099	epoch := c.out.epoch.epoch + 1
2100	if epoch == 0 && !c.config.Bugs.AllowEpochOverflow {
2101		return errors.New("tls: too many KeyUpdates")
2102	}
2103
2104	m := keyUpdateMsg{
2105		keyUpdateRequest: keyUpdateRequest,
2106	}
2107	if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
2108		return err
2109	}
2110	// In DTLS 1.3, a real implementation would not install the new epoch until
2111	// receiving an ACK. Our test transport is ordered and reliable, so this is
2112	// not necessary. ACK effects will be simulated in tests by the WriteFlight
2113	// callback.
2114	c.useOutTrafficSecret(epoch, c.out.wireVersion, c.cipherSuite, updateTrafficSecret(c.cipherSuite.hash(), c.wireVersion, c.out.trafficSecret, c.isDTLS))
2115	return c.flushHandshake()
2116}
2117
2118func (c *Conn) sendFakeEarlyData(len int) error {
2119	// Assemble a fake early data record. This does not use writeRecord
2120	// because the record layer may be using different keys at this point.
2121	payload := make([]byte, 5+len)
2122	payload[0] = byte(recordTypeApplicationData)
2123	payload[1] = 3
2124	payload[2] = 3
2125	payload[3] = byte(len >> 8)
2126	payload[4] = byte(len)
2127	_, err := c.conn.Write(payload)
2128	return err
2129}
2130
2131func (c *Conn) usesEndOfEarlyData() bool {
2132	if c.isClient && c.config.Bugs.SendEndOfEarlyDataInQUICAndDTLS {
2133		return true
2134	}
2135	return c.config.Bugs.MockQUICTransport == nil && !c.isDTLS
2136}
2137