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