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