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