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