• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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		// Add TLS 1.3 padding.
575		if hc.version >= VersionTLS13 {
576			paddingLen := hc.config.Bugs.RecordPadding
577			if hc.config.Bugs.OmitRecordContents {
578				b.resize(recordHeaderLen + paddingLen)
579			} else {
580				b.resize(len(b.data) + 1 + paddingLen)
581				b.data[len(b.data)-paddingLen-1] = byte(typ)
582			}
583			for i := 0; i < paddingLen; i++ {
584				b.data[len(b.data)-paddingLen+i] = 0
585			}
586		}
587
588		switch c := hc.cipher.(type) {
589		case cipher.Stream:
590			c.XORKeyStream(payload, payload)
591		case *tlsAead:
592			payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
593			b.resize(len(b.data) + c.Overhead())
594			nonce := hc.outSeq[:]
595			if c.explicitNonce {
596				nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
597			}
598			payload := b.data[recordHeaderLen+explicitIVLen:]
599			payload = payload[:payloadLen]
600
601			var additionalData []byte
602			if hc.version < VersionTLS13 {
603				additionalData = make([]byte, 13)
604				copy(additionalData, hc.outSeq[:])
605				copy(additionalData[8:], b.data[:3])
606				additionalData[11] = byte(payloadLen >> 8)
607				additionalData[12] = byte(payloadLen)
608			} else {
609				additionalData = make([]byte, 5)
610				copy(additionalData, b.data[:3])
611				n := len(b.data) - recordHeaderLen
612				additionalData[3] = byte(n >> 8)
613				additionalData[4] = byte(n)
614			}
615
616			c.Seal(payload[:0], nonce, payload, additionalData)
617		case cbcMode:
618			blockSize := c.BlockSize()
619			if explicitIVLen > 0 {
620				c.SetIV(payload[:explicitIVLen])
621				payload = payload[explicitIVLen:]
622			}
623			prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
624			b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
625			c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
626			c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
627		case nullCipher:
628			break
629		default:
630			panic("unknown cipher type")
631		}
632	}
633
634	// update length to include MAC and any block padding needed.
635	n := len(b.data) - recordHeaderLen
636	b.data[recordHeaderLen-2] = byte(n >> 8)
637	b.data[recordHeaderLen-1] = byte(n)
638	hc.incSeq(true)
639
640	return true, 0
641}
642
643// A block is a simple data buffer.
644type block struct {
645	data []byte
646	off  int // index for Read
647	link *block
648}
649
650// resize resizes block to be n bytes, growing if necessary.
651func (b *block) resize(n int) {
652	if n > cap(b.data) {
653		b.reserve(n)
654	}
655	b.data = b.data[0:n]
656}
657
658// reserve makes sure that block contains a capacity of at least n bytes.
659func (b *block) reserve(n int) {
660	if cap(b.data) >= n {
661		return
662	}
663	m := cap(b.data)
664	if m == 0 {
665		m = 1024
666	}
667	for m < n {
668		m *= 2
669	}
670	data := make([]byte, len(b.data), m)
671	copy(data, b.data)
672	b.data = data
673}
674
675// readFromUntil reads from r into b until b contains at least n bytes
676// or else returns an error.
677func (b *block) readFromUntil(r io.Reader, n int) error {
678	// quick case
679	if len(b.data) >= n {
680		return nil
681	}
682
683	// read until have enough.
684	b.reserve(n)
685	for {
686		m, err := r.Read(b.data[len(b.data):cap(b.data)])
687		b.data = b.data[0 : len(b.data)+m]
688		if len(b.data) >= n {
689			// TODO(bradfitz,agl): slightly suspicious
690			// that we're throwing away r.Read's err here.
691			break
692		}
693		if err != nil {
694			return err
695		}
696	}
697	return nil
698}
699
700func (b *block) Read(p []byte) (n int, err error) {
701	n = copy(p, b.data[b.off:])
702	b.off += n
703	return
704}
705
706// newBlock allocates a new block, from hc's free list if possible.
707func (hc *halfConn) newBlock() *block {
708	b := hc.bfree
709	if b == nil {
710		return new(block)
711	}
712	hc.bfree = b.link
713	b.link = nil
714	b.resize(0)
715	return b
716}
717
718// freeBlock returns a block to hc's free list.
719// The protocol is such that each side only has a block or two on
720// its free list at a time, so there's no need to worry about
721// trimming the list, etc.
722func (hc *halfConn) freeBlock(b *block) {
723	b.link = hc.bfree
724	hc.bfree = b
725}
726
727// splitBlock splits a block after the first n bytes,
728// returning a block with those n bytes and a
729// block with the remainder.  the latter may be nil.
730func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
731	if len(b.data) <= n {
732		return b, nil
733	}
734	bb := hc.newBlock()
735	bb.resize(len(b.data) - n)
736	copy(bb.data, b.data[n:])
737	b.data = b.data[0:n]
738	return b, bb
739}
740
741func (c *Conn) useInTrafficSecret(level encryptionLevel, version uint16, suite *cipherSuite, secret []byte) error {
742	if c.hand.Len() != 0 {
743		return c.in.setErrorLocked(errors.New("tls: buffered handshake messages on cipher change"))
744	}
745	side := serverWrite
746	if !c.isClient {
747		side = clientWrite
748	}
749	if c.config.Bugs.MockQUICTransport != nil {
750		c.config.Bugs.MockQUICTransport.readLevel = level
751		c.config.Bugs.MockQUICTransport.readSecret = secret
752		c.config.Bugs.MockQUICTransport.readCipherSuite = suite.id
753	}
754	c.in.useTrafficSecret(version, suite, secret, side)
755	c.seenHandshakePackEnd = false
756	return nil
757}
758
759func (c *Conn) useOutTrafficSecret(level encryptionLevel, version uint16, suite *cipherSuite, secret []byte) {
760	side := serverWrite
761	if c.isClient {
762		side = clientWrite
763	}
764	if c.config.Bugs.MockQUICTransport != nil {
765		c.config.Bugs.MockQUICTransport.writeLevel = level
766		c.config.Bugs.MockQUICTransport.writeSecret = secret
767		c.config.Bugs.MockQUICTransport.writeCipherSuite = suite.id
768	}
769	c.out.useTrafficSecret(version, suite, secret, side)
770}
771
772func (c *Conn) setSkipEarlyData() {
773	if c.config.Bugs.MockQUICTransport != nil {
774		c.config.Bugs.MockQUICTransport.skipEarlyData = true
775	} else {
776		c.skipEarlyData = true
777	}
778}
779
780func (c *Conn) shouldSkipEarlyData() bool {
781	if c.config.Bugs.MockQUICTransport != nil {
782		return c.config.Bugs.MockQUICTransport.skipEarlyData
783	}
784	return c.skipEarlyData
785}
786
787func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
788RestartReadRecord:
789	if c.isDTLS {
790		return c.dtlsDoReadRecord(want)
791	}
792
793	recordHeaderLen := c.in.recordHeaderLen()
794
795	if c.rawInput == nil {
796		c.rawInput = c.in.newBlock()
797	}
798	b := c.rawInput
799
800	// Read header, payload.
801	if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
802		// RFC suggests that EOF without an alertCloseNotify is
803		// an error, but popular web sites seem to do this,
804		// so we can't make it an error, outside of tests.
805		if err == io.EOF && c.config.Bugs.ExpectCloseNotify {
806			err = io.ErrUnexpectedEOF
807		}
808		if e, ok := err.(net.Error); !ok || !e.Temporary() {
809			c.in.setErrorLocked(err)
810		}
811		return 0, nil, err
812	}
813
814	typ := recordType(b.data[0])
815
816	// No valid TLS record has a type of 0x80, however SSLv2 handshakes
817	// start with a uint16 length where the MSB is set and the first record
818	// is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
819	// an SSLv2 client.
820	if want == recordTypeHandshake && typ == 0x80 {
821		c.sendAlert(alertProtocolVersion)
822		return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
823	}
824
825	vers := uint16(b.data[1])<<8 | uint16(b.data[2])
826	n := int(b.data[3])<<8 | int(b.data[4])
827
828	// Alerts sent near version negotiation do not have a well-defined
829	// record-layer version prior to TLS 1.3. (In TLS 1.3, the record-layer
830	// version is irrelevant.)
831	if typ != recordTypeAlert {
832		var expect uint16
833		if c.haveVers {
834			expect = c.vers
835			if c.vers >= VersionTLS13 {
836				expect = VersionTLS12
837			}
838		} else {
839			expect = c.config.Bugs.ExpectInitialRecordVersion
840		}
841		if expect != 0 && vers != expect {
842			c.sendAlert(alertProtocolVersion)
843			return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
844		}
845	}
846	if n > maxCiphertext {
847		c.sendAlert(alertRecordOverflow)
848		return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
849	}
850	if !c.haveVers {
851		// First message, be extra suspicious:
852		// this might not be a TLS client.
853		// Bail out before reading a full 'body', if possible.
854		// The current max version is 3.1.
855		// If the version is >= 16.0, it's probably not real.
856		// Similarly, a clientHello message encodes in
857		// well under a kilobyte.  If the length is >= 12 kB,
858		// it's probably not real.
859		if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
860			c.sendAlert(alertUnexpectedMessage)
861			return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
862		}
863	}
864	if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
865		if err == io.EOF {
866			err = io.ErrUnexpectedEOF
867		}
868		if e, ok := err.(net.Error); !ok || !e.Temporary() {
869			c.in.setErrorLocked(err)
870		}
871		return 0, nil, err
872	}
873
874	// Process message.
875	b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
876	ok, off, encTyp, alertValue := c.in.decrypt(b)
877
878	// Handle skipping over early data.
879	if !ok && c.skipEarlyData {
880		goto RestartReadRecord
881	}
882
883	// If the server is expecting a second ClientHello (in response to
884	// a HelloRetryRequest) and the client sends early data, there
885	// won't be a decryption failure but it still needs to be skipped.
886	if c.in.cipher == nil && typ == recordTypeApplicationData && c.skipEarlyData {
887		goto RestartReadRecord
888	}
889
890	if !ok {
891		return 0, nil, c.in.setErrorLocked(c.sendAlert(alertValue))
892	}
893	b.off = off
894	c.skipEarlyData = false
895
896	if c.vers >= VersionTLS13 && c.in.cipher != nil {
897		if typ != recordTypeApplicationData {
898			return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: outer record type is not application data"))
899		}
900		typ = encTyp
901	}
902
903	length := len(b.data[b.off:])
904	if c.config.Bugs.ExpectRecordSplitting && typ == recordTypeApplicationData && length != 1 && !c.seenOneByteRecord {
905		return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: application data records were not split"))
906	}
907
908	c.seenOneByteRecord = typ == recordTypeApplicationData && length == 1
909	return typ, b, nil
910}
911
912func (c *Conn) readTLS13ChangeCipherSpec() error {
913	if c.config.Bugs.MockQUICTransport != nil {
914		return nil
915	}
916	if !c.expectTLS13ChangeCipherSpec {
917		panic("c.expectTLS13ChangeCipherSpec not set")
918	}
919
920	// Read the ChangeCipherSpec.
921	if c.rawInput == nil {
922		c.rawInput = c.in.newBlock()
923	}
924	b := c.rawInput
925	if err := b.readFromUntil(c.conn, 1); err != nil {
926		return c.in.setErrorLocked(fmt.Errorf("tls: error reading TLS 1.3 ChangeCipherSpec: %s", err))
927	}
928	if recordType(b.data[0]) == recordTypeAlert {
929		// If the client is sending an alert, allow the ChangeCipherSpec
930		// to be skipped. It may be rejecting a sufficiently malformed
931		// ServerHello that it can't parse out the version.
932		c.expectTLS13ChangeCipherSpec = false
933		return nil
934	}
935	if err := b.readFromUntil(c.conn, 6); err != nil {
936		return c.in.setErrorLocked(fmt.Errorf("tls: error reading TLS 1.3 ChangeCipherSpec: %s", err))
937	}
938
939	// Check they match that we expect.
940	expected := [6]byte{byte(recordTypeChangeCipherSpec), 3, 1, 0, 1, 1}
941	if c.vers >= VersionTLS13 {
942		expected[2] = 3
943	}
944	if !bytes.Equal(b.data[:6], expected[:]) {
945		return c.in.setErrorLocked(fmt.Errorf("tls: error invalid TLS 1.3 ChangeCipherSpec: %x", b.data[:6]))
946	}
947
948	// Discard the data.
949	b, c.rawInput = c.in.splitBlock(b, 6)
950	c.in.freeBlock(b)
951
952	c.expectTLS13ChangeCipherSpec = false
953	return nil
954}
955
956// readRecord reads the next TLS record from the connection
957// and updates the record layer state.
958// c.in.Mutex <= L; c.input == nil.
959func (c *Conn) readRecord(want recordType) error {
960	// Caller must be in sync with connection:
961	// handshake data if handshake not yet completed,
962	// else application data.
963	switch want {
964	default:
965		c.sendAlert(alertInternalError)
966		return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
967	case recordTypeChangeCipherSpec:
968		if c.handshakeComplete {
969			c.sendAlert(alertInternalError)
970			return c.in.setErrorLocked(errors.New("tls: ChangeCipherSpec requested after handshake complete"))
971		}
972	case recordTypeApplicationData, recordTypeAlert, recordTypeHandshake:
973		break
974	}
975
976	if c.expectTLS13ChangeCipherSpec {
977		if err := c.readTLS13ChangeCipherSpec(); err != nil {
978			return err
979		}
980	}
981
982Again:
983	doReadRecord := c.doReadRecord
984	if c.config.Bugs.MockQUICTransport != nil {
985		doReadRecord = c.config.Bugs.MockQUICTransport.readRecord
986	}
987	typ, b, err := doReadRecord(want)
988	if err != nil {
989		return err
990	}
991	data := b.data[b.off:]
992	max := maxPlaintext
993	if c.config.Bugs.MaxReceivePlaintext != 0 {
994		max = c.config.Bugs.MaxReceivePlaintext
995	}
996	if len(data) > max {
997		err := c.sendAlert(alertRecordOverflow)
998		c.in.freeBlock(b)
999		return c.in.setErrorLocked(err)
1000	}
1001
1002	if typ != recordTypeHandshake {
1003		c.seenHandshakePackEnd = false
1004	} else if c.seenHandshakePackEnd {
1005		c.in.freeBlock(b)
1006		return c.in.setErrorLocked(errors.New("tls: peer violated ExpectPackedEncryptedHandshake"))
1007	}
1008
1009	switch typ {
1010	default:
1011		c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1012
1013	case recordTypeAlert:
1014		if len(data) != 2 {
1015			c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1016			break
1017		}
1018		if alert(data[1]) == alertCloseNotify {
1019			c.in.setErrorLocked(io.EOF)
1020			break
1021		}
1022		switch data[0] {
1023		case alertLevelWarning:
1024			// drop on the floor
1025			c.in.freeBlock(b)
1026			goto Again
1027		case alertLevelError:
1028			c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
1029		default:
1030			c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1031		}
1032
1033	case recordTypeChangeCipherSpec:
1034		if typ != want || len(data) != 1 || data[0] != 1 {
1035			c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1036			break
1037		}
1038		if c.hand.Len() != 0 {
1039			c.in.setErrorLocked(errors.New("tls: buffered handshake messages on cipher change"))
1040			break
1041		}
1042		if err := c.in.changeCipherSpec(c.config); err != nil {
1043			c.in.setErrorLocked(c.sendAlert(err.(alert)))
1044		}
1045
1046	case recordTypeApplicationData:
1047		if typ != want {
1048			c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1049			break
1050		}
1051		c.input = b
1052		b = nil
1053
1054	case recordTypeHandshake:
1055		// Allow handshake data while reading application data to
1056		// trigger post-handshake messages.
1057		// TODO(rsc): Should at least pick off connection close.
1058		if typ != want && want != recordTypeApplicationData {
1059			return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
1060		}
1061		c.hand.Write(data)
1062		if pack := c.config.Bugs.ExpectPackedEncryptedHandshake; pack > 0 && len(data) < pack && c.out.cipher != nil {
1063			c.seenHandshakePackEnd = true
1064		}
1065	}
1066
1067	if b != nil {
1068		c.in.freeBlock(b)
1069	}
1070	return c.in.err
1071}
1072
1073// sendAlert sends a TLS alert message.
1074// c.out.Mutex <= L.
1075func (c *Conn) sendAlertLocked(level byte, err alert) error {
1076	c.tmp[0] = level
1077	c.tmp[1] = byte(err)
1078	if c.config.Bugs.FragmentAlert {
1079		c.writeRecord(recordTypeAlert, c.tmp[0:1])
1080		c.writeRecord(recordTypeAlert, c.tmp[1:2])
1081	} else if c.config.Bugs.DoubleAlert {
1082		copy(c.tmp[2:4], c.tmp[0:2])
1083		c.writeRecord(recordTypeAlert, c.tmp[0:4])
1084	} else {
1085		c.writeRecord(recordTypeAlert, c.tmp[0:2])
1086	}
1087	// Error alerts are fatal to the connection.
1088	if level == alertLevelError {
1089		return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
1090	}
1091	return nil
1092}
1093
1094// sendAlert sends a TLS alert message.
1095// L < c.out.Mutex.
1096func (c *Conn) sendAlert(err alert) error {
1097	level := byte(alertLevelError)
1098	if err == alertNoRenegotiation || err == alertCloseNotify {
1099		level = alertLevelWarning
1100	}
1101	return c.SendAlert(level, err)
1102}
1103
1104func (c *Conn) SendAlert(level byte, err alert) error {
1105	c.out.Lock()
1106	defer c.out.Unlock()
1107	return c.sendAlertLocked(level, err)
1108}
1109
1110// writeV2Record writes a record for a V2ClientHello.
1111func (c *Conn) writeV2Record(data []byte) (n int, err error) {
1112	record := make([]byte, 2+len(data))
1113	record[0] = uint8(len(data)>>8) | 0x80
1114	record[1] = uint8(len(data))
1115	copy(record[2:], data)
1116	return c.conn.Write(record)
1117}
1118
1119// writeRecord writes a TLS record with the given type and payload
1120// to the connection and updates the record layer state.
1121// c.out.Mutex <= L.
1122func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
1123	c.seenHandshakePackEnd = false
1124	if typ == recordTypeHandshake {
1125		msgType := data[0]
1126		if c.config.Bugs.SendWrongMessageType != 0 && msgType == c.config.Bugs.SendWrongMessageType {
1127			msgType += 42
1128		}
1129		if msgType != data[0] {
1130			data = append([]byte{msgType}, data[1:]...)
1131		}
1132
1133		if c.config.Bugs.SendTrailingMessageData != 0 && msgType == c.config.Bugs.SendTrailingMessageData {
1134			// Add a 0 to the body.
1135			newData := make([]byte, len(data)+1)
1136			copy(newData, data)
1137
1138			// Fix the header.
1139			newLen := len(newData) - 4
1140			newData[1] = byte(newLen >> 16)
1141			newData[2] = byte(newLen >> 8)
1142			newData[3] = byte(newLen)
1143
1144			data = newData
1145		}
1146
1147		if c.config.Bugs.TrailingDataWithFinished && msgType == typeFinished {
1148			// Add a 0 to the record. Note unused bytes in |data| may be owned by the
1149			// caller, so we force a new allocation.
1150			data = append(data[:len(data):len(data)], 0)
1151		}
1152	}
1153
1154	if c.isDTLS {
1155		return c.dtlsWriteRecord(typ, data)
1156	}
1157	if c.config.Bugs.MockQUICTransport != nil {
1158		return c.config.Bugs.MockQUICTransport.writeRecord(typ, data)
1159	}
1160
1161	if typ == recordTypeHandshake {
1162		if c.config.Bugs.SendHelloRequestBeforeEveryHandshakeMessage {
1163			newData := make([]byte, 0, 4+len(data))
1164			newData = append(newData, typeHelloRequest, 0, 0, 0)
1165			newData = append(newData, data...)
1166			data = newData
1167		}
1168
1169		if c.config.Bugs.PackHandshakeFlight {
1170			c.pendingFlight.Write(data)
1171			return len(data), nil
1172		}
1173	}
1174
1175	// Flush buffered data before writing anything.
1176	if err := c.flushHandshake(); err != nil {
1177		return 0, err
1178	}
1179
1180	if typ == recordTypeApplicationData && c.config.Bugs.SendPostHandshakeChangeCipherSpec {
1181		if _, err := c.doWriteRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
1182			return 0, err
1183		}
1184	}
1185
1186	return c.doWriteRecord(typ, data)
1187}
1188
1189func (c *Conn) doWriteRecord(typ recordType, data []byte) (n int, err error) {
1190	recordHeaderLen := c.out.recordHeaderLen()
1191	b := c.out.newBlock()
1192	first := true
1193	isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
1194	for len(data) > 0 || first {
1195		m := len(data)
1196		if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
1197			m = maxPlaintext
1198		}
1199		if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
1200			m = c.config.Bugs.MaxHandshakeRecordLength
1201			// By default, do not fragment the client_version or
1202			// server_version, which are located in the first 6
1203			// bytes.
1204			if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
1205				m = 6
1206			}
1207		}
1208		explicitIVLen := 0
1209		explicitIVIsSeq := false
1210		first = false
1211
1212		var cbc cbcMode
1213		if c.out.version >= VersionTLS11 {
1214			var ok bool
1215			if cbc, ok = c.out.cipher.(cbcMode); ok {
1216				explicitIVLen = cbc.BlockSize()
1217			}
1218		}
1219		if explicitIVLen == 0 {
1220			if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
1221				explicitIVLen = 8
1222				// The AES-GCM construction in TLS has an
1223				// explicit nonce so that the nonce can be
1224				// random. However, the nonce is only 8 bytes
1225				// which is too small for a secure, random
1226				// nonce. Therefore we use the sequence number
1227				// as the nonce.
1228				explicitIVIsSeq = true
1229			}
1230		}
1231		b.resize(recordHeaderLen + explicitIVLen + m)
1232		b.data[0] = byte(typ)
1233		if c.vers >= VersionTLS13 && c.out.cipher != nil {
1234			b.data[0] = byte(recordTypeApplicationData)
1235			if outerType := c.config.Bugs.OuterRecordType; outerType != 0 {
1236				b.data[0] = byte(outerType)
1237			}
1238		}
1239		vers := c.vers
1240		if vers == 0 {
1241			// Some TLS servers fail if the record version is
1242			// greater than TLS 1.0 for the initial ClientHello.
1243			//
1244			// TLS 1.3 fixes the version number in the record
1245			// layer to {3, 1}.
1246			vers = VersionTLS10
1247		}
1248		if c.vers >= VersionTLS13 || c.out.version >= VersionTLS13 {
1249			vers = VersionTLS12
1250		}
1251
1252		if c.config.Bugs.SendRecordVersion != 0 {
1253			vers = c.config.Bugs.SendRecordVersion
1254		}
1255		if c.vers == 0 && c.config.Bugs.SendInitialRecordVersion != 0 {
1256			vers = c.config.Bugs.SendInitialRecordVersion
1257		}
1258		b.data[1] = byte(vers >> 8)
1259		b.data[2] = byte(vers)
1260		b.data[3] = byte(m >> 8)
1261		b.data[4] = byte(m)
1262		if explicitIVLen > 0 {
1263			explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
1264			if explicitIVIsSeq {
1265				copy(explicitIV, c.out.seq[:])
1266			} else {
1267				if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
1268					break
1269				}
1270			}
1271		}
1272		copy(b.data[recordHeaderLen+explicitIVLen:], data)
1273		c.out.encrypt(b, explicitIVLen, typ)
1274		_, err = c.conn.Write(b.data)
1275		if err != nil {
1276			break
1277		}
1278		n += m
1279		data = data[m:]
1280	}
1281	c.out.freeBlock(b)
1282
1283	if typ == recordTypeChangeCipherSpec && c.vers < VersionTLS13 {
1284		err = c.out.changeCipherSpec(c.config)
1285		if err != nil {
1286			return n, c.sendAlertLocked(alertLevelError, err.(alert))
1287		}
1288	}
1289	return
1290}
1291
1292func (c *Conn) flushHandshake() error {
1293	if c.isDTLS {
1294		return c.dtlsFlushHandshake()
1295	}
1296
1297	for c.pendingFlight.Len() > 0 {
1298		var buf [maxPlaintext]byte
1299		n, _ := c.pendingFlight.Read(buf[:])
1300		if _, err := c.doWriteRecord(recordTypeHandshake, buf[:n]); err != nil {
1301			return err
1302		}
1303	}
1304
1305	c.pendingFlight.Reset()
1306	return nil
1307}
1308
1309func (c *Conn) doReadHandshake() ([]byte, error) {
1310	if c.isDTLS {
1311		return c.dtlsDoReadHandshake()
1312	}
1313
1314	for c.hand.Len() < 4 {
1315		if err := c.in.err; err != nil {
1316			return nil, err
1317		}
1318		if err := c.readRecord(recordTypeHandshake); err != nil {
1319			return nil, err
1320		}
1321	}
1322
1323	data := c.hand.Bytes()
1324	n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1325	if n > maxHandshake {
1326		return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
1327	}
1328	for c.hand.Len() < 4+n {
1329		if err := c.in.err; err != nil {
1330			return nil, err
1331		}
1332		if err := c.readRecord(recordTypeHandshake); err != nil {
1333			return nil, err
1334		}
1335	}
1336	return c.hand.Next(4 + n), nil
1337}
1338
1339// readHandshake reads the next handshake message from
1340// the record layer.
1341// c.in.Mutex < L; c.out.Mutex < L.
1342func (c *Conn) readHandshake() (any, error) {
1343	data, err := c.doReadHandshake()
1344	if err != nil {
1345		return nil, err
1346	}
1347
1348	var m handshakeMessage
1349	switch data[0] {
1350	case typeHelloRequest:
1351		m = new(helloRequestMsg)
1352	case typeClientHello:
1353		m = &clientHelloMsg{
1354			isDTLS: c.isDTLS,
1355		}
1356	case typeServerHello:
1357		m = &serverHelloMsg{
1358			isDTLS: c.isDTLS,
1359		}
1360	case typeNewSessionTicket:
1361		m = &newSessionTicketMsg{
1362			vers:   c.wireVersion,
1363			isDTLS: c.isDTLS,
1364		}
1365	case typeEncryptedExtensions:
1366		if c.isClient {
1367			m = new(encryptedExtensionsMsg)
1368		} else {
1369			m = new(clientEncryptedExtensionsMsg)
1370		}
1371	case typeCertificate:
1372		m = &certificateMsg{
1373			hasRequestContext: c.vers >= VersionTLS13,
1374		}
1375	case typeCompressedCertificate:
1376		m = new(compressedCertificateMsg)
1377	case typeCertificateRequest:
1378		m = &certificateRequestMsg{
1379			vers:                  c.wireVersion,
1380			hasSignatureAlgorithm: c.vers >= VersionTLS12,
1381			hasRequestContext:     c.vers >= VersionTLS13,
1382		}
1383	case typeCertificateStatus:
1384		m = new(certificateStatusMsg)
1385	case typeServerKeyExchange:
1386		m = new(serverKeyExchangeMsg)
1387	case typeServerHelloDone:
1388		m = new(serverHelloDoneMsg)
1389	case typeClientKeyExchange:
1390		m = new(clientKeyExchangeMsg)
1391	case typeCertificateVerify:
1392		m = &certificateVerifyMsg{
1393			hasSignatureAlgorithm: c.vers >= VersionTLS12,
1394		}
1395	case typeNextProtocol:
1396		m = new(nextProtoMsg)
1397	case typeFinished:
1398		m = new(finishedMsg)
1399	case typeHelloVerifyRequest:
1400		m = new(helloVerifyRequestMsg)
1401	case typeChannelID:
1402		m = new(channelIDMsg)
1403	case typeKeyUpdate:
1404		m = new(keyUpdateMsg)
1405	case typeEndOfEarlyData:
1406		m = new(endOfEarlyDataMsg)
1407	default:
1408		return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1409	}
1410
1411	// The handshake message unmarshallers
1412	// expect to be able to keep references to data,
1413	// so pass in a fresh copy that won't be overwritten.
1414	data = append([]byte(nil), data...)
1415
1416	if data[0] == typeServerHello && len(data) >= 38 {
1417		vers := uint16(data[4])<<8 | uint16(data[5])
1418		if vers == VersionTLS12 && bytes.Equal(data[6:38], tls13HelloRetryRequest) {
1419			m = new(helloRetryRequestMsg)
1420		}
1421	}
1422
1423	if !m.unmarshal(data) {
1424		return nil, c.in.setErrorLocked(c.sendAlert(alertDecodeError))
1425	}
1426	return m, nil
1427}
1428
1429// skipPacket processes all the DTLS records in packet. It updates
1430// sequence number expectations but otherwise ignores them.
1431func (c *Conn) skipPacket(packet []byte) error {
1432	for len(packet) > 0 {
1433		if len(packet) < 13 {
1434			return errors.New("tls: bad packet")
1435		}
1436		// Dropped packets are completely ignored save to update
1437		// expected sequence numbers for this and the next epoch. (We
1438		// don't assert on the contents of the packets both for
1439		// simplicity and because a previous test with one shorter
1440		// timeout schedule would have done so.)
1441		epoch := packet[3:5]
1442		seq := packet[5:11]
1443		length := uint16(packet[11])<<8 | uint16(packet[12])
1444		if bytes.Equal(c.in.seq[:2], epoch) {
1445			if bytes.Compare(seq, c.in.seq[2:]) < 0 {
1446				return errors.New("tls: sequence mismatch")
1447			}
1448			copy(c.in.seq[2:], seq)
1449			c.in.incSeq(false)
1450		} else {
1451			if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
1452				return errors.New("tls: sequence mismatch")
1453			}
1454			copy(c.in.nextSeq[:], seq)
1455			c.in.incNextSeq()
1456		}
1457		if len(packet) < 13+int(length) {
1458			return errors.New("tls: bad packet")
1459		}
1460		packet = packet[13+length:]
1461	}
1462	return nil
1463}
1464
1465// simulatePacketLoss simulates the loss of a handshake leg from the
1466// peer based on the schedule in c.config.Bugs. If resendFunc is
1467// non-nil, it is called after each simulated timeout to retransmit
1468// handshake messages from the local end. This is used in cases where
1469// the peer retransmits on a stale Finished rather than a timeout.
1470func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1471	if len(c.config.Bugs.TimeoutSchedule) == 0 {
1472		return nil
1473	}
1474	if !c.isDTLS {
1475		return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1476	}
1477	if c.config.Bugs.PacketAdaptor == nil {
1478		return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1479	}
1480	for _, timeout := range c.config.Bugs.TimeoutSchedule {
1481		// Simulate a timeout.
1482		packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1483		if err != nil {
1484			return err
1485		}
1486		for _, packet := range packets {
1487			if err := c.skipPacket(packet); err != nil {
1488				return err
1489			}
1490		}
1491		if resendFunc != nil {
1492			resendFunc()
1493		}
1494	}
1495	return nil
1496}
1497
1498func (c *Conn) SendHalfHelloRequest() error {
1499	if err := c.Handshake(); err != nil {
1500		return err
1501	}
1502
1503	c.out.Lock()
1504	defer c.out.Unlock()
1505
1506	if _, err := c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0}); err != nil {
1507		return err
1508	}
1509	return c.flushHandshake()
1510}
1511
1512// Write writes data to the connection.
1513func (c *Conn) Write(b []byte) (int, error) {
1514	if err := c.Handshake(); err != nil {
1515		return 0, err
1516	}
1517
1518	c.out.Lock()
1519	defer c.out.Unlock()
1520
1521	if err := c.out.err; err != nil {
1522		return 0, err
1523	}
1524
1525	if !c.handshakeComplete {
1526		return 0, alertInternalError
1527	}
1528
1529	if c.keyUpdateRequested {
1530		if err := c.sendKeyUpdateLocked(keyUpdateNotRequested); err != nil {
1531			return 0, err
1532		}
1533		c.keyUpdateRequested = false
1534	}
1535
1536	if c.config.Bugs.SendSpuriousAlert != 0 {
1537		c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
1538	}
1539
1540	if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1541		c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
1542		c.flushHandshake()
1543	}
1544
1545	// SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1546	// attack when using block mode ciphers due to predictable IVs.
1547	// This can be prevented by splitting each Application Data
1548	// record into two records, effectively randomizing the IV.
1549	//
1550	// http://www.openssl.org/~bodo/tls-cbc.txt
1551	// https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1552	// http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1553
1554	var m int
1555	if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
1556		if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1557			n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1558			if err != nil {
1559				return n, c.out.setErrorLocked(err)
1560			}
1561			m, b = 1, b[1:]
1562		}
1563	}
1564
1565	n, err := c.writeRecord(recordTypeApplicationData, b)
1566	return n + m, c.out.setErrorLocked(err)
1567}
1568
1569func (c *Conn) processTLS13NewSessionTicket(newSessionTicket *newSessionTicketMsg, cipherSuite *cipherSuite) error {
1570	if c.config.Bugs.ExpectGREASE && !newSessionTicket.hasGREASEExtension {
1571		return errors.New("tls: no GREASE ticket extension found")
1572	}
1573
1574	if c.config.Bugs.ExpectTicketEarlyData && newSessionTicket.maxEarlyDataSize == 0 {
1575		return errors.New("tls: no early_data ticket extension found")
1576	}
1577
1578	if c.config.Bugs.ExpectNoNewSessionTicket {
1579		return errors.New("tls: received unexpected NewSessionTicket")
1580	}
1581
1582	if c.config.ClientSessionCache == nil || newSessionTicket.ticketLifetime == 0 {
1583		return nil
1584	}
1585
1586	session := &ClientSessionState{
1587		sessionTicket:               newSessionTicket.ticket,
1588		vers:                        c.vers,
1589		wireVersion:                 c.wireVersion,
1590		cipherSuite:                 cipherSuite,
1591		secret:                      deriveSessionPSK(cipherSuite, c.wireVersion, c.resumptionSecret, newSessionTicket.ticketNonce),
1592		serverCertificates:          c.peerCertificates,
1593		sctList:                     c.sctList,
1594		ocspResponse:                c.ocspResponse,
1595		ticketCreationTime:          c.config.time(),
1596		ticketExpiration:            c.config.time().Add(time.Duration(newSessionTicket.ticketLifetime) * time.Second),
1597		ticketAgeAdd:                newSessionTicket.ticketAgeAdd,
1598		maxEarlyDataSize:            newSessionTicket.maxEarlyDataSize,
1599		earlyALPN:                   c.clientProtocol,
1600		hasApplicationSettings:      c.hasApplicationSettings,
1601		localApplicationSettings:    c.localApplicationSettings,
1602		peerApplicationSettings:     c.peerApplicationSettings,
1603		hasApplicationSettingsOld:   c.hasApplicationSettingsOld,
1604		localApplicationSettingsOld: c.localApplicationSettingsOld,
1605		peerApplicationSettingsOld:  c.peerApplicationSettingsOld,
1606	}
1607
1608	cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
1609	_, ok := c.config.ClientSessionCache.Get(cacheKey)
1610	if !ok || !c.config.Bugs.UseFirstSessionTicket {
1611		c.config.ClientSessionCache.Put(cacheKey, session)
1612	}
1613	return nil
1614}
1615
1616func (c *Conn) handlePostHandshakeMessage() error {
1617	msg, err := c.readHandshake()
1618	if err != nil {
1619		return err
1620	}
1621
1622	if c.vers < VersionTLS13 {
1623		if !c.isClient {
1624			c.sendAlert(alertUnexpectedMessage)
1625			return errors.New("tls: unexpected post-handshake message")
1626		}
1627
1628		_, ok := msg.(*helloRequestMsg)
1629		if !ok {
1630			c.sendAlert(alertUnexpectedMessage)
1631			return alertUnexpectedMessage
1632		}
1633
1634		c.handshakeComplete = false
1635		return c.Handshake()
1636	}
1637
1638	if c.isClient {
1639		if newSessionTicket, ok := msg.(*newSessionTicketMsg); ok {
1640			return c.processTLS13NewSessionTicket(newSessionTicket, c.cipherSuite)
1641		}
1642	}
1643
1644	if keyUpdate, ok := msg.(*keyUpdateMsg); ok {
1645		c.keyUpdateSeen = true
1646
1647		if c.config.Bugs.RejectUnsolicitedKeyUpdate {
1648			return errors.New("tls: unexpected KeyUpdate message")
1649		}
1650		if err := c.useInTrafficSecret(encryptionApplication, c.in.wireVersion, c.cipherSuite, updateTrafficSecret(c.cipherSuite.hash(), c.wireVersion, c.in.trafficSecret)); err != nil {
1651			return err
1652		}
1653		if keyUpdate.keyUpdateRequest == keyUpdateRequested {
1654			c.keyUpdateRequested = true
1655		}
1656		return nil
1657	}
1658
1659	c.sendAlert(alertUnexpectedMessage)
1660	return errors.New("tls: unexpected post-handshake message")
1661}
1662
1663// Reads a KeyUpdate acknowledgment from the peer. There may not be any
1664// application data records before the message.
1665func (c *Conn) ReadKeyUpdateACK() error {
1666	c.in.Lock()
1667	defer c.in.Unlock()
1668
1669	msg, err := c.readHandshake()
1670	if err != nil {
1671		return err
1672	}
1673
1674	keyUpdate, ok := msg.(*keyUpdateMsg)
1675	if !ok {
1676		c.sendAlert(alertUnexpectedMessage)
1677		return fmt.Errorf("tls: unexpected message (%T) when reading KeyUpdate", msg)
1678	}
1679
1680	if keyUpdate.keyUpdateRequest != keyUpdateNotRequested {
1681		return errors.New("tls: received invalid KeyUpdate message")
1682	}
1683
1684	return c.useInTrafficSecret(encryptionApplication, c.in.wireVersion, c.cipherSuite, updateTrafficSecret(c.cipherSuite.hash(), c.wireVersion, c.in.trafficSecret))
1685}
1686
1687func (c *Conn) Renegotiate() error {
1688	if !c.isClient {
1689		helloReq := new(helloRequestMsg).marshal()
1690		if c.config.Bugs.BadHelloRequest != nil {
1691			helloReq = c.config.Bugs.BadHelloRequest
1692		}
1693		c.writeRecord(recordTypeHandshake, helloReq)
1694		c.flushHandshake()
1695	}
1696
1697	c.handshakeComplete = false
1698	return c.Handshake()
1699}
1700
1701// Read can be made to time out and return a net.Error with Timeout() == true
1702// after a fixed time limit; see SetDeadline and SetReadDeadline.
1703func (c *Conn) Read(b []byte) (n int, err error) {
1704	if err = c.Handshake(); err != nil {
1705		return
1706	}
1707
1708	c.in.Lock()
1709	defer c.in.Unlock()
1710
1711	// Some OpenSSL servers send empty records in order to randomize the
1712	// CBC IV. So this loop ignores a limited number of empty records.
1713	const maxConsecutiveEmptyRecords = 100
1714	for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1715		for c.input == nil && c.in.err == nil {
1716			if err := c.readRecord(recordTypeApplicationData); err != nil {
1717				// Soft error, like EAGAIN
1718				return 0, err
1719			}
1720			for c.hand.Len() > 0 {
1721				// We received handshake bytes, indicating a
1722				// post-handshake message.
1723				if err := c.handlePostHandshakeMessage(); err != nil {
1724					return 0, err
1725				}
1726			}
1727		}
1728		if err := c.in.err; err != nil {
1729			return 0, err
1730		}
1731
1732		n, err = c.input.Read(b)
1733		if c.input.off >= len(c.input.data) || c.isDTLS {
1734			c.in.freeBlock(c.input)
1735			c.input = nil
1736		}
1737
1738		// If a close-notify alert is waiting, read it so that
1739		// we can return (n, EOF) instead of (n, nil), to signal
1740		// to the HTTP response reading goroutine that the
1741		// connection is now closed. This eliminates a race
1742		// where the HTTP response reading goroutine would
1743		// otherwise not observe the EOF until its next read,
1744		// by which time a client goroutine might have already
1745		// tried to reuse the HTTP connection for a new
1746		// request.
1747		// See https://codereview.appspot.com/76400046
1748		// and http://golang.org/issue/3514
1749		if ri := c.rawInput; ri != nil &&
1750			n != 0 && err == nil &&
1751			c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1752			if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1753				err = recErr // will be io.EOF on closeNotify
1754			}
1755		}
1756
1757		if n != 0 || err != nil {
1758			return n, err
1759		}
1760	}
1761
1762	return 0, io.ErrNoProgress
1763}
1764
1765// Close closes the connection.
1766func (c *Conn) Close() error {
1767	var alertErr error
1768
1769	c.handshakeMutex.Lock()
1770	defer c.handshakeMutex.Unlock()
1771	if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
1772		alert := alertCloseNotify
1773		if c.config.Bugs.SendAlertOnShutdown != 0 {
1774			alert = c.config.Bugs.SendAlertOnShutdown
1775		}
1776		alertErr = c.sendAlert(alert)
1777		// Clear local alerts when sending alerts so we continue to wait
1778		// for the peer rather than closing the socket early.
1779		if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1780			alertErr = nil
1781		}
1782	}
1783
1784	// Consume a close_notify from the peer if one hasn't been received
1785	// already. This avoids the peer from failing |SSL_shutdown| due to a
1786	// write failing.
1787	if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1788		for c.in.error() == nil {
1789			c.readRecord(recordTypeAlert)
1790		}
1791		if c.in.error() != io.EOF {
1792			alertErr = c.in.error()
1793		}
1794	}
1795
1796	if err := c.conn.Close(); err != nil {
1797		return err
1798	}
1799	return alertErr
1800}
1801
1802// Handshake runs the client or server handshake
1803// protocol if it has not yet been run.
1804// Most uses of this package need not call Handshake
1805// explicitly: the first Read or Write will call it automatically.
1806func (c *Conn) Handshake() error {
1807	c.handshakeMutex.Lock()
1808	defer c.handshakeMutex.Unlock()
1809	if err := c.handshakeErr; err != nil {
1810		return err
1811	}
1812	if c.handshakeComplete {
1813		return nil
1814	}
1815
1816	if c.isDTLS && c.config.Bugs.SendSplitAlert {
1817		c.conn.Write([]byte{
1818			byte(recordTypeAlert), // type
1819			0xfe, 0xff,            // version
1820			0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1821			0x0, 0x2, // length
1822		})
1823		c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1824	}
1825	if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1826		c.writeRecord(recordTypeApplicationData, data)
1827	}
1828	if c.isClient {
1829		c.handshakeErr = c.clientHandshake()
1830	} else {
1831		c.handshakeErr = c.serverHandshake()
1832	}
1833	if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1834		c.writeRecord(recordType(42), []byte("invalid record"))
1835	}
1836	return c.handshakeErr
1837}
1838
1839// ConnectionState returns basic TLS details about the connection.
1840func (c *Conn) ConnectionState() ConnectionState {
1841	c.handshakeMutex.Lock()
1842	defer c.handshakeMutex.Unlock()
1843
1844	var state ConnectionState
1845	state.HandshakeComplete = c.handshakeComplete
1846	if c.handshakeComplete {
1847		state.Version = c.vers
1848		state.NegotiatedProtocol = c.clientProtocol
1849		state.DidResume = c.didResume
1850		state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
1851		state.NegotiatedProtocolFromALPN = c.usedALPN
1852		state.CipherSuite = c.cipherSuite.id
1853		state.PeerCertificates = c.peerCertificates
1854		state.PeerDelegatedCredential = c.peerDelegatedCredential
1855		state.VerifiedChains = c.verifiedChains
1856		state.OCSPResponse = c.ocspResponse
1857		state.ServerName = c.serverName
1858		state.ChannelID = c.channelID
1859		state.SRTPProtectionProfile = c.srtpProtectionProfile
1860		state.TLSUnique = c.firstFinished[:]
1861		state.SCTList = c.sctList
1862		state.PeerSignatureAlgorithm = c.peerSignatureAlgorithm
1863		state.CurveID = c.curveID
1864		state.QUICTransportParams = c.quicTransportParams
1865		state.QUICTransportParamsLegacy = c.quicTransportParamsLegacy
1866		state.HasApplicationSettings = c.hasApplicationSettings
1867		state.PeerApplicationSettings = c.peerApplicationSettings
1868		state.HasApplicationSettingsOld = c.hasApplicationSettingsOld
1869		state.PeerApplicationSettingsOld = c.peerApplicationSettingsOld
1870		state.ECHAccepted = c.echAccepted
1871	}
1872
1873	return state
1874}
1875
1876// VerifyHostname checks that the peer certificate chain is valid for
1877// connecting to host.  If so, it returns nil; if not, it returns an error
1878// describing the problem.
1879func (c *Conn) VerifyHostname(host string) error {
1880	c.handshakeMutex.Lock()
1881	defer c.handshakeMutex.Unlock()
1882	if !c.isClient {
1883		return errors.New("tls: VerifyHostname called on TLS server connection")
1884	}
1885	if !c.handshakeComplete {
1886		return errors.New("tls: handshake has not yet been performed")
1887	}
1888	return c.peerCertificates[0].VerifyHostname(host)
1889}
1890
1891func (c *Conn) exportKeyingMaterialTLS13(length int, secret, label, context []byte) []byte {
1892	hash := c.cipherSuite.hash()
1893	exporterKeyingLabel := []byte("exporter")
1894	contextHash := hash.New()
1895	contextHash.Write(context)
1896	exporterContext := hash.New().Sum(nil)
1897	derivedSecret := hkdfExpandLabel(c.cipherSuite.hash(), secret, label, exporterContext, hash.Size())
1898	return hkdfExpandLabel(c.cipherSuite.hash(), derivedSecret, exporterKeyingLabel, contextHash.Sum(nil), length)
1899}
1900
1901// ExportKeyingMaterial exports keying material from the current connection
1902// state, as per RFC 5705.
1903func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1904	c.handshakeMutex.Lock()
1905	defer c.handshakeMutex.Unlock()
1906	if !c.handshakeComplete {
1907		return nil, errors.New("tls: handshake has not yet been performed")
1908	}
1909
1910	if c.vers >= VersionTLS13 {
1911		return c.exportKeyingMaterialTLS13(length, c.exporterSecret, label, context), nil
1912	}
1913
1914	seedLen := len(c.clientRandom) + len(c.serverRandom)
1915	if useContext {
1916		seedLen += 2 + len(context)
1917	}
1918	seed := make([]byte, 0, seedLen)
1919	seed = append(seed, c.clientRandom[:]...)
1920	seed = append(seed, c.serverRandom[:]...)
1921	if useContext {
1922		seed = append(seed, byte(len(context)>>8), byte(len(context)))
1923		seed = append(seed, context...)
1924	}
1925	result := make([]byte, length)
1926	prfForVersion(c.vers, c.cipherSuite)(result, c.exporterSecret, label, seed)
1927	return result, nil
1928}
1929
1930func (c *Conn) ExportEarlyKeyingMaterial(length int, label, context []byte) ([]byte, error) {
1931	if c.vers < VersionTLS13 {
1932		return nil, errors.New("tls: early exporters not defined before TLS 1.3")
1933	}
1934
1935	if c.earlyExporterSecret == nil {
1936		return nil, errors.New("tls: no early exporter secret")
1937	}
1938
1939	return c.exportKeyingMaterialTLS13(length, c.earlyExporterSecret, label, context), nil
1940}
1941
1942// noRenegotiationInfo returns true if the renegotiation info extension
1943// should be supported in the current handshake.
1944func (c *Conn) noRenegotiationInfo() bool {
1945	if c.config.Bugs.NoRenegotiationInfo {
1946		return true
1947	}
1948	if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1949		return true
1950	}
1951	if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1952		return true
1953	}
1954	return false
1955}
1956
1957func (c *Conn) SendNewSessionTicket(nonce []byte) error {
1958	if c.isClient || c.vers < VersionTLS13 {
1959		return errors.New("tls: cannot send post-handshake NewSessionTicket")
1960	}
1961
1962	var peerCertificatesRaw [][]byte
1963	for _, cert := range c.peerCertificates {
1964		peerCertificatesRaw = append(peerCertificatesRaw, cert.Raw)
1965	}
1966
1967	addBuffer := make([]byte, 4)
1968	_, err := io.ReadFull(c.config.rand(), addBuffer)
1969	if err != nil {
1970		c.sendAlert(alertInternalError)
1971		return errors.New("tls: short read from Rand: " + err.Error())
1972	}
1973	ticketAgeAdd := uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0])
1974
1975	// TODO(davidben): Allow configuring these values.
1976	m := &newSessionTicketMsg{
1977		vers:                        c.wireVersion,
1978		isDTLS:                      c.isDTLS,
1979		ticketLifetime:              uint32(24 * time.Hour / time.Second),
1980		duplicateEarlyDataExtension: c.config.Bugs.DuplicateTicketEarlyData,
1981		customExtension:             c.config.Bugs.CustomTicketExtension,
1982		ticketAgeAdd:                ticketAgeAdd,
1983		ticketNonce:                 nonce,
1984		maxEarlyDataSize:            c.config.MaxEarlyDataSize,
1985	}
1986	if c.config.Bugs.MockQUICTransport != nil && m.maxEarlyDataSize > 0 {
1987		m.maxEarlyDataSize = 0xffffffff
1988	}
1989
1990	if c.config.Bugs.SendTicketLifetime != 0 {
1991		m.ticketLifetime = uint32(c.config.Bugs.SendTicketLifetime / time.Second)
1992	}
1993
1994	state := sessionState{
1995		vers:                        c.vers,
1996		cipherSuite:                 c.cipherSuite.id,
1997		secret:                      deriveSessionPSK(c.cipherSuite, c.wireVersion, c.resumptionSecret, nonce),
1998		certificates:                peerCertificatesRaw,
1999		ticketCreationTime:          c.config.time(),
2000		ticketExpiration:            c.config.time().Add(time.Duration(m.ticketLifetime) * time.Second),
2001		ticketAgeAdd:                uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0]),
2002		earlyALPN:                   []byte(c.clientProtocol),
2003		hasApplicationSettings:      c.hasApplicationSettings,
2004		localApplicationSettings:    c.localApplicationSettings,
2005		peerApplicationSettings:     c.peerApplicationSettings,
2006		hasApplicationSettingsOld:   c.hasApplicationSettingsOld,
2007		localApplicationSettingsOld: c.localApplicationSettingsOld,
2008		peerApplicationSettingsOld:  c.peerApplicationSettingsOld,
2009	}
2010
2011	if !c.config.Bugs.SendEmptySessionTicket {
2012		var err error
2013		m.ticket, err = c.encryptTicket(&state)
2014		if err != nil {
2015			return err
2016		}
2017	}
2018	c.out.Lock()
2019	defer c.out.Unlock()
2020	_, err = c.writeRecord(recordTypeHandshake, m.marshal())
2021	return err
2022}
2023
2024func (c *Conn) SendKeyUpdate(keyUpdateRequest byte) error {
2025	c.out.Lock()
2026	defer c.out.Unlock()
2027	return c.sendKeyUpdateLocked(keyUpdateRequest)
2028}
2029
2030func (c *Conn) sendKeyUpdateLocked(keyUpdateRequest byte) error {
2031	if c.vers < VersionTLS13 {
2032		return errors.New("tls: attempted to send KeyUpdate before TLS 1.3")
2033	}
2034
2035	m := keyUpdateMsg{
2036		keyUpdateRequest: keyUpdateRequest,
2037	}
2038	if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
2039		return err
2040	}
2041	if err := c.flushHandshake(); err != nil {
2042		return err
2043	}
2044	c.useOutTrafficSecret(encryptionApplication, c.out.wireVersion, c.cipherSuite, updateTrafficSecret(c.cipherSuite.hash(), c.wireVersion, c.out.trafficSecret))
2045	return nil
2046}
2047
2048func (c *Conn) sendFakeEarlyData(len int) error {
2049	// Assemble a fake early data record. This does not use writeRecord
2050	// because the record layer may be using different keys at this point.
2051	payload := make([]byte, 5+len)
2052	payload[0] = byte(recordTypeApplicationData)
2053	payload[1] = 3
2054	payload[2] = 3
2055	payload[3] = byte(len >> 8)
2056	payload[4] = byte(len)
2057	_, err := c.conn.Write(payload)
2058	return err
2059}
2060