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