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 qtls
8
9import (
10	"bytes"
11	"crypto/cipher"
12	"crypto/subtle"
13	"crypto/x509"
14	"errors"
15	"fmt"
16	"hash"
17	"io"
18	"net"
19	"sync"
20	"sync/atomic"
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	isClient    bool
30	handshakeFn func() error // (*Conn).clientHandshake or serverHandshake
31
32	// handshakeStatus is 1 if the connection is currently transferring
33	// application data (i.e. is not currently processing a handshake).
34	// This field is only to be accessed with sync/atomic.
35	handshakeStatus uint32
36	// constant after handshake; protected by handshakeMutex
37	handshakeMutex sync.Mutex
38	handshakeErr   error   // error resulting from handshake
39	vers           uint16  // TLS version
40	haveVers       bool    // version has been negotiated
41	config         *config // configuration passed to constructor
42	// handshakes counts the number of handshakes performed on the
43	// connection so far. If renegotiation is disabled then this is either
44	// zero or one.
45	extraConfig *ExtraConfig
46
47	handshakes       int
48	didResume        bool // whether this connection was a session resumption
49	cipherSuite      uint16
50	ocspResponse     []byte   // stapled OCSP response
51	scts             [][]byte // signed certificate timestamps from server
52	peerCertificates []*x509.Certificate
53	// verifiedChains contains the certificate chains that we built, as
54	// opposed to the ones presented by the server.
55	verifiedChains [][]*x509.Certificate
56	// serverName contains the server name indicated by the client, if any.
57	serverName string
58	// secureRenegotiation is true if the server echoed the secure
59	// renegotiation extension. (This is meaningless as a server because
60	// renegotiation is not supported in that case.)
61	secureRenegotiation bool
62	// ekm is a closure for exporting keying material.
63	ekm func(label string, context []byte, length int) ([]byte, error)
64	// For the client:
65	// resumptionSecret is the resumption_master_secret for handling
66	// NewSessionTicket messages. nil if config.SessionTicketsDisabled.
67	// For the server:
68	// resumptionSecret is the resumption_master_secret for generating
69	// NewSessionTicket messages. Only used when the alternative record
70	// layer is set. nil if config.SessionTicketsDisabled.
71	resumptionSecret []byte
72
73	// ticketKeys is the set of active session ticket keys for this
74	// connection. The first one is used to encrypt new tickets and
75	// all are tried to decrypt tickets.
76	ticketKeys []ticketKey
77
78	// clientFinishedIsFirst is true if the client sent the first Finished
79	// message during the most recent handshake. This is recorded because
80	// the first transmitted Finished message is the tls-unique
81	// channel-binding value.
82	clientFinishedIsFirst bool
83
84	// closeNotifyErr is any error from sending the alertCloseNotify record.
85	closeNotifyErr error
86	// closeNotifySent is true if the Conn attempted to send an
87	// alertCloseNotify record.
88	closeNotifySent bool
89
90	// clientFinished and serverFinished contain the Finished message sent
91	// by the client or server in the most recent handshake. This is
92	// retained to support the renegotiation extension and tls-unique
93	// channel-binding.
94	clientFinished [12]byte
95	serverFinished [12]byte
96
97	// clientProtocol is the negotiated ALPN protocol.
98	clientProtocol string
99
100	// input/output
101	in, out   halfConn
102	rawInput  bytes.Buffer // raw input, starting with a record header
103	input     bytes.Reader // application data waiting to be read, from rawInput.Next
104	hand      bytes.Buffer // handshake data waiting to be read
105	buffering bool         // whether records are buffered in sendBuf
106	sendBuf   []byte       // a buffer of records waiting to be sent
107
108	// bytesSent counts the bytes of application data sent.
109	// packetsSent counts packets.
110	bytesSent   int64
111	packetsSent int64
112
113	// retryCount counts the number of consecutive non-advancing records
114	// received by Conn.readRecord. That is, records that neither advance the
115	// handshake, nor deliver application data. Protected by in.Mutex.
116	retryCount int
117
118	// activeCall is an atomic int32; the low bit is whether Close has
119	// been called. the rest of the bits are the number of goroutines
120	// in Conn.Write.
121	activeCall int32
122
123	used0RTT bool
124
125	tmp [16]byte
126}
127
128// Access to net.Conn methods.
129// Cannot just embed net.Conn because that would
130// export the struct field too.
131
132// LocalAddr returns the local network address.
133func (c *Conn) LocalAddr() net.Addr {
134	return c.conn.LocalAddr()
135}
136
137// RemoteAddr returns the remote network address.
138func (c *Conn) RemoteAddr() net.Addr {
139	return c.conn.RemoteAddr()
140}
141
142// SetDeadline sets the read and write deadlines associated with the connection.
143// A zero value for t means Read and Write will not time out.
144// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
145func (c *Conn) SetDeadline(t time.Time) error {
146	return c.conn.SetDeadline(t)
147}
148
149// SetReadDeadline sets the read deadline on the underlying connection.
150// A zero value for t means Read will not time out.
151func (c *Conn) SetReadDeadline(t time.Time) error {
152	return c.conn.SetReadDeadline(t)
153}
154
155// SetWriteDeadline sets the write deadline on the underlying connection.
156// A zero value for t means Write will not time out.
157// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
158func (c *Conn) SetWriteDeadline(t time.Time) error {
159	return c.conn.SetWriteDeadline(t)
160}
161
162// A halfConn represents one direction of the record layer
163// connection, either sending or receiving.
164type halfConn struct {
165	sync.Mutex
166
167	err     error       // first permanent error
168	version uint16      // protocol version
169	cipher  interface{} // cipher algorithm
170	mac     hash.Hash
171	seq     [8]byte // 64-bit sequence number
172
173	scratchBuf [13]byte // to avoid allocs; interface method args escape
174
175	nextCipher interface{} // next encryption state
176	nextMac    hash.Hash   // next MAC algorithm
177
178	trafficSecret []byte // current TLS 1.3 traffic secret
179
180	setKeyCallback func(encLevel EncryptionLevel, suite *CipherSuiteTLS13, trafficSecret []byte)
181}
182
183type permanentError struct {
184	err net.Error
185}
186
187func (e *permanentError) Error() string   { return e.err.Error() }
188func (e *permanentError) Unwrap() error   { return e.err }
189func (e *permanentError) Timeout() bool   { return e.err.Timeout() }
190func (e *permanentError) Temporary() bool { return false }
191
192func (hc *halfConn) setErrorLocked(err error) error {
193	if e, ok := err.(net.Error); ok {
194		hc.err = &permanentError{err: e}
195	} else {
196		hc.err = err
197	}
198	return hc.err
199}
200
201// prepareCipherSpec sets the encryption and MAC states
202// that a subsequent changeCipherSpec will use.
203func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac hash.Hash) {
204	hc.version = version
205	hc.nextCipher = cipher
206	hc.nextMac = mac
207}
208
209// changeCipherSpec changes the encryption and MAC states
210// to the ones previously passed to prepareCipherSpec.
211func (hc *halfConn) changeCipherSpec() error {
212	if hc.nextCipher == nil || hc.version == VersionTLS13 {
213		return alertInternalError
214	}
215	hc.cipher = hc.nextCipher
216	hc.mac = hc.nextMac
217	hc.nextCipher = nil
218	hc.nextMac = nil
219	for i := range hc.seq {
220		hc.seq[i] = 0
221	}
222	return nil
223}
224
225func (hc *halfConn) exportKey(encLevel EncryptionLevel, suite *cipherSuiteTLS13, trafficSecret []byte) {
226	if hc.setKeyCallback != nil {
227		s := &CipherSuiteTLS13{
228			ID:     suite.id,
229			KeyLen: suite.keyLen,
230			Hash:   suite.hash,
231			AEAD:   func(key, fixedNonce []byte) cipher.AEAD { return suite.aead(key, fixedNonce) },
232		}
233		hc.setKeyCallback(encLevel, s, trafficSecret)
234	}
235}
236
237func (hc *halfConn) setTrafficSecret(suite *cipherSuiteTLS13, secret []byte) {
238	hc.trafficSecret = secret
239	key, iv := suite.trafficKey(secret)
240	hc.cipher = suite.aead(key, iv)
241	for i := range hc.seq {
242		hc.seq[i] = 0
243	}
244}
245
246// incSeq increments the sequence number.
247func (hc *halfConn) incSeq() {
248	for i := 7; i >= 0; i-- {
249		hc.seq[i]++
250		if hc.seq[i] != 0 {
251			return
252		}
253	}
254
255	// Not allowed to let sequence number wrap.
256	// Instead, must renegotiate before it does.
257	// Not likely enough to bother.
258	panic("TLS: sequence number wraparound")
259}
260
261// explicitNonceLen returns the number of bytes of explicit nonce or IV included
262// in each record. Explicit nonces are present only in CBC modes after TLS 1.0
263// and in certain AEAD modes in TLS 1.2.
264func (hc *halfConn) explicitNonceLen() int {
265	if hc.cipher == nil {
266		return 0
267	}
268
269	switch c := hc.cipher.(type) {
270	case cipher.Stream:
271		return 0
272	case aead:
273		return c.explicitNonceLen()
274	case cbcMode:
275		// TLS 1.1 introduced a per-record explicit IV to fix the BEAST attack.
276		if hc.version >= VersionTLS11 {
277			return c.BlockSize()
278		}
279		return 0
280	default:
281		panic("unknown cipher type")
282	}
283}
284
285// extractPadding returns, in constant time, the length of the padding to remove
286// from the end of payload. It also returns a byte which is equal to 255 if the
287// padding was valid and 0 otherwise. See RFC 2246, Section 6.2.3.2.
288func extractPadding(payload []byte) (toRemove int, good byte) {
289	if len(payload) < 1 {
290		return 0, 0
291	}
292
293	paddingLen := payload[len(payload)-1]
294	t := uint(len(payload)-1) - uint(paddingLen)
295	// if len(payload) >= (paddingLen - 1) then the MSB of t is zero
296	good = byte(int32(^t) >> 31)
297
298	// The maximum possible padding length plus the actual length field
299	toCheck := 256
300	// The length of the padded data is public, so we can use an if here
301	if toCheck > len(payload) {
302		toCheck = len(payload)
303	}
304
305	for i := 0; i < toCheck; i++ {
306		t := uint(paddingLen) - uint(i)
307		// if i <= paddingLen then the MSB of t is zero
308		mask := byte(int32(^t) >> 31)
309		b := payload[len(payload)-1-i]
310		good &^= mask&paddingLen ^ mask&b
311	}
312
313	// We AND together the bits of good and replicate the result across
314	// all the bits.
315	good &= good << 4
316	good &= good << 2
317	good &= good << 1
318	good = uint8(int8(good) >> 7)
319
320	// Zero the padding length on error. This ensures any unchecked bytes
321	// are included in the MAC. Otherwise, an attacker that could
322	// distinguish MAC failures from padding failures could mount an attack
323	// similar to POODLE in SSL 3.0: given a good ciphertext that uses a
324	// full block's worth of padding, replace the final block with another
325	// block. If the MAC check passed but the padding check failed, the
326	// last byte of that block decrypted to the block size.
327	//
328	// See also macAndPaddingGood logic below.
329	paddingLen &= good
330
331	toRemove = int(paddingLen) + 1
332	return
333}
334
335func roundUp(a, b int) int {
336	return a + (b-a%b)%b
337}
338
339// cbcMode is an interface for block ciphers using cipher block chaining.
340type cbcMode interface {
341	cipher.BlockMode
342	SetIV([]byte)
343}
344
345// decrypt authenticates and decrypts the record if protection is active at
346// this stage. The returned plaintext might overlap with the input.
347func (hc *halfConn) decrypt(record []byte) ([]byte, recordType, error) {
348	var plaintext []byte
349	typ := recordType(record[0])
350	payload := record[recordHeaderLen:]
351
352	// In TLS 1.3, change_cipher_spec messages are to be ignored without being
353	// decrypted. See RFC 8446, Appendix D.4.
354	if hc.version == VersionTLS13 && typ == recordTypeChangeCipherSpec {
355		return payload, typ, nil
356	}
357
358	paddingGood := byte(255)
359	paddingLen := 0
360
361	explicitNonceLen := hc.explicitNonceLen()
362
363	if hc.cipher != nil {
364		switch c := hc.cipher.(type) {
365		case cipher.Stream:
366			c.XORKeyStream(payload, payload)
367		case aead:
368			if len(payload) < explicitNonceLen {
369				return nil, 0, alertBadRecordMAC
370			}
371			nonce := payload[:explicitNonceLen]
372			if len(nonce) == 0 {
373				nonce = hc.seq[:]
374			}
375			payload = payload[explicitNonceLen:]
376
377			var additionalData []byte
378			if hc.version == VersionTLS13 {
379				additionalData = record[:recordHeaderLen]
380			} else {
381				additionalData = append(hc.scratchBuf[:0], hc.seq[:]...)
382				additionalData = append(additionalData, record[:3]...)
383				n := len(payload) - c.Overhead()
384				additionalData = append(additionalData, byte(n>>8), byte(n))
385			}
386
387			var err error
388			plaintext, err = c.Open(payload[:0], nonce, payload, additionalData)
389			if err != nil {
390				return nil, 0, alertBadRecordMAC
391			}
392		case cbcMode:
393			blockSize := c.BlockSize()
394			minPayload := explicitNonceLen + roundUp(hc.mac.Size()+1, blockSize)
395			if len(payload)%blockSize != 0 || len(payload) < minPayload {
396				return nil, 0, alertBadRecordMAC
397			}
398
399			if explicitNonceLen > 0 {
400				c.SetIV(payload[:explicitNonceLen])
401				payload = payload[explicitNonceLen:]
402			}
403			c.CryptBlocks(payload, payload)
404
405			// In a limited attempt to protect against CBC padding oracles like
406			// Lucky13, the data past paddingLen (which is secret) is passed to
407			// the MAC function as extra data, to be fed into the HMAC after
408			// computing the digest. This makes the MAC roughly constant time as
409			// long as the digest computation is constant time and does not
410			// affect the subsequent write, modulo cache effects.
411			paddingLen, paddingGood = extractPadding(payload)
412		default:
413			panic("unknown cipher type")
414		}
415
416		if hc.version == VersionTLS13 {
417			if typ != recordTypeApplicationData {
418				return nil, 0, alertUnexpectedMessage
419			}
420			if len(plaintext) > maxPlaintext+1 {
421				return nil, 0, alertRecordOverflow
422			}
423			// Remove padding and find the ContentType scanning from the end.
424			for i := len(plaintext) - 1; i >= 0; i-- {
425				if plaintext[i] != 0 {
426					typ = recordType(plaintext[i])
427					plaintext = plaintext[:i]
428					break
429				}
430				if i == 0 {
431					return nil, 0, alertUnexpectedMessage
432				}
433			}
434		}
435	} else {
436		plaintext = payload
437	}
438
439	if hc.mac != nil {
440		macSize := hc.mac.Size()
441		if len(payload) < macSize {
442			return nil, 0, alertBadRecordMAC
443		}
444
445		n := len(payload) - macSize - paddingLen
446		n = subtle.ConstantTimeSelect(int(uint32(n)>>31), 0, n) // if n < 0 { n = 0 }
447		record[3] = byte(n >> 8)
448		record[4] = byte(n)
449		remoteMAC := payload[n : n+macSize]
450		localMAC := tls10MAC(hc.mac, hc.scratchBuf[:0], hc.seq[:], record[:recordHeaderLen], payload[:n], payload[n+macSize:])
451
452		// This is equivalent to checking the MACs and paddingGood
453		// separately, but in constant-time to prevent distinguishing
454		// padding failures from MAC failures. Depending on what value
455		// of paddingLen was returned on bad padding, distinguishing
456		// bad MAC from bad padding can lead to an attack.
457		//
458		// See also the logic at the end of extractPadding.
459		macAndPaddingGood := subtle.ConstantTimeCompare(localMAC, remoteMAC) & int(paddingGood)
460		if macAndPaddingGood != 1 {
461			return nil, 0, alertBadRecordMAC
462		}
463
464		plaintext = payload[:n]
465	}
466
467	hc.incSeq()
468	return plaintext, typ, nil
469}
470
471func (c *Conn) setAlternativeRecordLayer() {
472	if c.extraConfig != nil && c.extraConfig.AlternativeRecordLayer != nil {
473		c.in.setKeyCallback = c.extraConfig.AlternativeRecordLayer.SetReadKey
474		c.out.setKeyCallback = c.extraConfig.AlternativeRecordLayer.SetWriteKey
475	}
476}
477
478// sliceForAppend extends the input slice by n bytes. head is the full extended
479// slice, while tail is the appended part. If the original slice has sufficient
480// capacity no allocation is performed.
481func sliceForAppend(in []byte, n int) (head, tail []byte) {
482	if total := len(in) + n; cap(in) >= total {
483		head = in[:total]
484	} else {
485		head = make([]byte, total)
486		copy(head, in)
487	}
488	tail = head[len(in):]
489	return
490}
491
492// encrypt encrypts payload, adding the appropriate nonce and/or MAC, and
493// appends it to record, which must already contain the record header.
494func (hc *halfConn) encrypt(record, payload []byte, rand io.Reader) ([]byte, error) {
495	if hc.cipher == nil {
496		return append(record, payload...), nil
497	}
498
499	var explicitNonce []byte
500	if explicitNonceLen := hc.explicitNonceLen(); explicitNonceLen > 0 {
501		record, explicitNonce = sliceForAppend(record, explicitNonceLen)
502		if _, isCBC := hc.cipher.(cbcMode); !isCBC && explicitNonceLen < 16 {
503			// The AES-GCM construction in TLS has an explicit nonce so that the
504			// nonce can be random. However, the nonce is only 8 bytes which is
505			// too small for a secure, random nonce. Therefore we use the
506			// sequence number as the nonce. The 3DES-CBC construction also has
507			// an 8 bytes nonce but its nonces must be unpredictable (see RFC
508			// 5246, Appendix F.3), forcing us to use randomness. That's not
509			// 3DES' biggest problem anyway because the birthday bound on block
510			// collision is reached first due to its similarly small block size
511			// (see the Sweet32 attack).
512			copy(explicitNonce, hc.seq[:])
513		} else {
514			if _, err := io.ReadFull(rand, explicitNonce); err != nil {
515				return nil, err
516			}
517		}
518	}
519
520	var dst []byte
521	switch c := hc.cipher.(type) {
522	case cipher.Stream:
523		mac := tls10MAC(hc.mac, hc.scratchBuf[:0], hc.seq[:], record[:recordHeaderLen], payload, nil)
524		record, dst = sliceForAppend(record, len(payload)+len(mac))
525		c.XORKeyStream(dst[:len(payload)], payload)
526		c.XORKeyStream(dst[len(payload):], mac)
527	case aead:
528		nonce := explicitNonce
529		if len(nonce) == 0 {
530			nonce = hc.seq[:]
531		}
532
533		if hc.version == VersionTLS13 {
534			record = append(record, payload...)
535
536			// Encrypt the actual ContentType and replace the plaintext one.
537			record = append(record, record[0])
538			record[0] = byte(recordTypeApplicationData)
539
540			n := len(payload) + 1 + c.Overhead()
541			record[3] = byte(n >> 8)
542			record[4] = byte(n)
543
544			record = c.Seal(record[:recordHeaderLen],
545				nonce, record[recordHeaderLen:], record[:recordHeaderLen])
546		} else {
547			additionalData := append(hc.scratchBuf[:0], hc.seq[:]...)
548			additionalData = append(additionalData, record[:recordHeaderLen]...)
549			record = c.Seal(record, nonce, payload, additionalData)
550		}
551	case cbcMode:
552		mac := tls10MAC(hc.mac, hc.scratchBuf[:0], hc.seq[:], record[:recordHeaderLen], payload, nil)
553		blockSize := c.BlockSize()
554		plaintextLen := len(payload) + len(mac)
555		paddingLen := blockSize - plaintextLen%blockSize
556		record, dst = sliceForAppend(record, plaintextLen+paddingLen)
557		copy(dst, payload)
558		copy(dst[len(payload):], mac)
559		for i := plaintextLen; i < len(dst); i++ {
560			dst[i] = byte(paddingLen - 1)
561		}
562		if len(explicitNonce) > 0 {
563			c.SetIV(explicitNonce)
564		}
565		c.CryptBlocks(dst, dst)
566	default:
567		panic("unknown cipher type")
568	}
569
570	// Update length to include nonce, MAC and any block padding needed.
571	n := len(record) - recordHeaderLen
572	record[3] = byte(n >> 8)
573	record[4] = byte(n)
574	hc.incSeq()
575
576	return record, nil
577}
578
579// RecordHeaderError is returned when a TLS record header is invalid.
580type RecordHeaderError struct {
581	// Msg contains a human readable string that describes the error.
582	Msg string
583	// RecordHeader contains the five bytes of TLS record header that
584	// triggered the error.
585	RecordHeader [5]byte
586	// Conn provides the underlying net.Conn in the case that a client
587	// sent an initial handshake that didn't look like TLS.
588	// It is nil if there's already been a handshake or a TLS alert has
589	// been written to the connection.
590	Conn net.Conn
591}
592
593func (e RecordHeaderError) Error() string { return "tls: " + e.Msg }
594
595func (c *Conn) newRecordHeaderError(conn net.Conn, msg string) (err RecordHeaderError) {
596	err.Msg = msg
597	err.Conn = conn
598	copy(err.RecordHeader[:], c.rawInput.Bytes())
599	return err
600}
601
602func (c *Conn) readRecord() error {
603	return c.readRecordOrCCS(false)
604}
605
606func (c *Conn) readChangeCipherSpec() error {
607	return c.readRecordOrCCS(true)
608}
609
610// readRecordOrCCS reads one or more TLS records from the connection and
611// updates the record layer state. Some invariants:
612//   * c.in must be locked
613//   * c.input must be empty
614// During the handshake one and only one of the following will happen:
615//   - c.hand grows
616//   - c.in.changeCipherSpec is called
617//   - an error is returned
618// After the handshake one and only one of the following will happen:
619//   - c.hand grows
620//   - c.input is set
621//   - an error is returned
622func (c *Conn) readRecordOrCCS(expectChangeCipherSpec bool) error {
623	if c.in.err != nil {
624		return c.in.err
625	}
626	handshakeComplete := c.handshakeComplete()
627
628	// This function modifies c.rawInput, which owns the c.input memory.
629	if c.input.Len() != 0 {
630		return c.in.setErrorLocked(errors.New("tls: internal error: attempted to read record with pending application data"))
631	}
632	c.input.Reset(nil)
633
634	// Read header, payload.
635	if err := c.readFromUntil(c.conn, recordHeaderLen); err != nil {
636		// RFC 8446, Section 6.1 suggests that EOF without an alertCloseNotify
637		// is an error, but popular web sites seem to do this, so we accept it
638		// if and only if at the record boundary.
639		if err == io.ErrUnexpectedEOF && c.rawInput.Len() == 0 {
640			err = io.EOF
641		}
642		if e, ok := err.(net.Error); !ok || !e.Temporary() {
643			c.in.setErrorLocked(err)
644		}
645		return err
646	}
647	hdr := c.rawInput.Bytes()[:recordHeaderLen]
648	typ := recordType(hdr[0])
649
650	// No valid TLS record has a type of 0x80, however SSLv2 handshakes
651	// start with a uint16 length where the MSB is set and the first record
652	// is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
653	// an SSLv2 client.
654	if !handshakeComplete && typ == 0x80 {
655		c.sendAlert(alertProtocolVersion)
656		return c.in.setErrorLocked(c.newRecordHeaderError(nil, "unsupported SSLv2 handshake received"))
657	}
658
659	vers := uint16(hdr[1])<<8 | uint16(hdr[2])
660	n := int(hdr[3])<<8 | int(hdr[4])
661	if c.haveVers && c.vers != VersionTLS13 && vers != c.vers {
662		c.sendAlert(alertProtocolVersion)
663		msg := fmt.Sprintf("received record with version %x when expecting version %x", vers, c.vers)
664		return c.in.setErrorLocked(c.newRecordHeaderError(nil, msg))
665	}
666	if !c.haveVers {
667		// First message, be extra suspicious: this might not be a TLS
668		// client. Bail out before reading a full 'body', if possible.
669		// The current max version is 3.3 so if the version is >= 16.0,
670		// it's probably not real.
671		if (typ != recordTypeAlert && typ != recordTypeHandshake) || vers >= 0x1000 {
672			return c.in.setErrorLocked(c.newRecordHeaderError(c.conn, "first record does not look like a TLS handshake"))
673		}
674	}
675	if c.vers == VersionTLS13 && n > maxCiphertextTLS13 || n > maxCiphertext {
676		c.sendAlert(alertRecordOverflow)
677		msg := fmt.Sprintf("oversized record received with length %d", n)
678		return c.in.setErrorLocked(c.newRecordHeaderError(nil, msg))
679	}
680	if err := c.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
681		if e, ok := err.(net.Error); !ok || !e.Temporary() {
682			c.in.setErrorLocked(err)
683		}
684		return err
685	}
686
687	// Process message.
688	record := c.rawInput.Next(recordHeaderLen + n)
689	data, typ, err := c.in.decrypt(record)
690	if err != nil {
691		return c.in.setErrorLocked(c.sendAlert(err.(alert)))
692	}
693	if len(data) > maxPlaintext {
694		return c.in.setErrorLocked(c.sendAlert(alertRecordOverflow))
695	}
696
697	// Application Data messages are always protected.
698	if c.in.cipher == nil && typ == recordTypeApplicationData {
699		return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
700	}
701
702	if typ != recordTypeAlert && typ != recordTypeChangeCipherSpec && len(data) > 0 {
703		// This is a state-advancing message: reset the retry count.
704		c.retryCount = 0
705	}
706
707	// Handshake messages MUST NOT be interleaved with other record types in TLS 1.3.
708	if c.vers == VersionTLS13 && typ != recordTypeHandshake && c.hand.Len() > 0 {
709		return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
710	}
711
712	switch typ {
713	default:
714		return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
715
716	case recordTypeAlert:
717		if len(data) != 2 {
718			return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
719		}
720		if alert(data[1]) == alertCloseNotify {
721			return c.in.setErrorLocked(io.EOF)
722		}
723		if c.vers == VersionTLS13 {
724			return c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
725		}
726		switch data[0] {
727		case alertLevelWarning:
728			// Drop the record on the floor and retry.
729			return c.retryReadRecord(expectChangeCipherSpec)
730		case alertLevelError:
731			return c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
732		default:
733			return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
734		}
735
736	case recordTypeChangeCipherSpec:
737		if len(data) != 1 || data[0] != 1 {
738			return c.in.setErrorLocked(c.sendAlert(alertDecodeError))
739		}
740		// Handshake messages are not allowed to fragment across the CCS.
741		if c.hand.Len() > 0 {
742			return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
743		}
744		// In TLS 1.3, change_cipher_spec records are ignored until the
745		// Finished. See RFC 8446, Appendix D.4. Note that according to Section
746		// 5, a server can send a ChangeCipherSpec before its ServerHello, when
747		// c.vers is still unset. That's not useful though and suspicious if the
748		// server then selects a lower protocol version, so don't allow that.
749		if c.vers == VersionTLS13 {
750			return c.retryReadRecord(expectChangeCipherSpec)
751		}
752		if !expectChangeCipherSpec {
753			return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
754		}
755		if err := c.in.changeCipherSpec(); err != nil {
756			return c.in.setErrorLocked(c.sendAlert(err.(alert)))
757		}
758
759	case recordTypeApplicationData:
760		if !handshakeComplete || expectChangeCipherSpec {
761			return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
762		}
763		// Some OpenSSL servers send empty records in order to randomize the
764		// CBC IV. Ignore a limited number of empty records.
765		if len(data) == 0 {
766			return c.retryReadRecord(expectChangeCipherSpec)
767		}
768		// Note that data is owned by c.rawInput, following the Next call above,
769		// to avoid copying the plaintext. This is safe because c.rawInput is
770		// not read from or written to until c.input is drained.
771		c.input.Reset(data)
772
773	case recordTypeHandshake:
774		if len(data) == 0 || expectChangeCipherSpec {
775			return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
776		}
777		c.hand.Write(data)
778	}
779
780	return nil
781}
782
783// retryReadRecord recurses into readRecordOrCCS to drop a non-advancing record, like
784// a warning alert, empty application_data, or a change_cipher_spec in TLS 1.3.
785func (c *Conn) retryReadRecord(expectChangeCipherSpec bool) error {
786	c.retryCount++
787	if c.retryCount > maxUselessRecords {
788		c.sendAlert(alertUnexpectedMessage)
789		return c.in.setErrorLocked(errors.New("tls: too many ignored records"))
790	}
791	return c.readRecordOrCCS(expectChangeCipherSpec)
792}
793
794// atLeastReader reads from R, stopping with EOF once at least N bytes have been
795// read. It is different from an io.LimitedReader in that it doesn't cut short
796// the last Read call, and in that it considers an early EOF an error.
797type atLeastReader struct {
798	R io.Reader
799	N int64
800}
801
802func (r *atLeastReader) Read(p []byte) (int, error) {
803	if r.N <= 0 {
804		return 0, io.EOF
805	}
806	n, err := r.R.Read(p)
807	r.N -= int64(n) // won't underflow unless len(p) >= n > 9223372036854775809
808	if r.N > 0 && err == io.EOF {
809		return n, io.ErrUnexpectedEOF
810	}
811	if r.N <= 0 && err == nil {
812		return n, io.EOF
813	}
814	return n, err
815}
816
817// readFromUntil reads from r into c.rawInput until c.rawInput contains
818// at least n bytes or else returns an error.
819func (c *Conn) readFromUntil(r io.Reader, n int) error {
820	if c.rawInput.Len() >= n {
821		return nil
822	}
823	needs := n - c.rawInput.Len()
824	// There might be extra input waiting on the wire. Make a best effort
825	// attempt to fetch it so that it can be used in (*Conn).Read to
826	// "predict" closeNotify alerts.
827	c.rawInput.Grow(needs + bytes.MinRead)
828	_, err := c.rawInput.ReadFrom(&atLeastReader{r, int64(needs)})
829	return err
830}
831
832// sendAlert sends a TLS alert message.
833func (c *Conn) sendAlertLocked(err alert) error {
834	switch err {
835	case alertNoRenegotiation, alertCloseNotify:
836		c.tmp[0] = alertLevelWarning
837	default:
838		c.tmp[0] = alertLevelError
839	}
840	c.tmp[1] = byte(err)
841
842	_, writeErr := c.writeRecordLocked(recordTypeAlert, c.tmp[0:2])
843	if err == alertCloseNotify {
844		// closeNotify is a special case in that it isn't an error.
845		return writeErr
846	}
847
848	return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
849}
850
851// sendAlert sends a TLS alert message.
852func (c *Conn) sendAlert(err alert) error {
853	if c.extraConfig != nil && c.extraConfig.AlternativeRecordLayer != nil {
854		c.extraConfig.AlternativeRecordLayer.SendAlert(uint8(err))
855		return &net.OpError{Op: "local error", Err: err}
856	}
857
858	c.out.Lock()
859	defer c.out.Unlock()
860	return c.sendAlertLocked(err)
861}
862
863const (
864	// tcpMSSEstimate is a conservative estimate of the TCP maximum segment
865	// size (MSS). A constant is used, rather than querying the kernel for
866	// the actual MSS, to avoid complexity. The value here is the IPv6
867	// minimum MTU (1280 bytes) minus the overhead of an IPv6 header (40
868	// bytes) and a TCP header with timestamps (32 bytes).
869	tcpMSSEstimate = 1208
870
871	// recordSizeBoostThreshold is the number of bytes of application data
872	// sent after which the TLS record size will be increased to the
873	// maximum.
874	recordSizeBoostThreshold = 128 * 1024
875)
876
877// maxPayloadSizeForWrite returns the maximum TLS payload size to use for the
878// next application data record. There is the following trade-off:
879//
880//   - For latency-sensitive applications, such as web browsing, each TLS
881//     record should fit in one TCP segment.
882//   - For throughput-sensitive applications, such as large file transfers,
883//     larger TLS records better amortize framing and encryption overheads.
884//
885// A simple heuristic that works well in practice is to use small records for
886// the first 1MB of data, then use larger records for subsequent data, and
887// reset back to smaller records after the connection becomes idle. See "High
888// Performance Web Networking", Chapter 4, or:
889// https://www.igvita.com/2013/10/24/optimizing-tls-record-size-and-buffering-latency/
890//
891// In the interests of simplicity and determinism, this code does not attempt
892// to reset the record size once the connection is idle, however.
893func (c *Conn) maxPayloadSizeForWrite(typ recordType) int {
894	if c.config.DynamicRecordSizingDisabled || typ != recordTypeApplicationData {
895		return maxPlaintext
896	}
897
898	if c.bytesSent >= recordSizeBoostThreshold {
899		return maxPlaintext
900	}
901
902	// Subtract TLS overheads to get the maximum payload size.
903	payloadBytes := tcpMSSEstimate - recordHeaderLen - c.out.explicitNonceLen()
904	if c.out.cipher != nil {
905		switch ciph := c.out.cipher.(type) {
906		case cipher.Stream:
907			payloadBytes -= c.out.mac.Size()
908		case cipher.AEAD:
909			payloadBytes -= ciph.Overhead()
910		case cbcMode:
911			blockSize := ciph.BlockSize()
912			// The payload must fit in a multiple of blockSize, with
913			// room for at least one padding byte.
914			payloadBytes = (payloadBytes & ^(blockSize - 1)) - 1
915			// The MAC is appended before padding so affects the
916			// payload size directly.
917			payloadBytes -= c.out.mac.Size()
918		default:
919			panic("unknown cipher type")
920		}
921	}
922	if c.vers == VersionTLS13 {
923		payloadBytes-- // encrypted ContentType
924	}
925
926	// Allow packet growth in arithmetic progression up to max.
927	pkt := c.packetsSent
928	c.packetsSent++
929	if pkt > 1000 {
930		return maxPlaintext // avoid overflow in multiply below
931	}
932
933	n := payloadBytes * int(pkt+1)
934	if n > maxPlaintext {
935		n = maxPlaintext
936	}
937	return n
938}
939
940func (c *Conn) write(data []byte) (int, error) {
941	if c.buffering {
942		c.sendBuf = append(c.sendBuf, data...)
943		return len(data), nil
944	}
945
946	n, err := c.conn.Write(data)
947	c.bytesSent += int64(n)
948	return n, err
949}
950
951func (c *Conn) flush() (int, error) {
952	if len(c.sendBuf) == 0 {
953		return 0, nil
954	}
955
956	n, err := c.conn.Write(c.sendBuf)
957	c.bytesSent += int64(n)
958	c.sendBuf = nil
959	c.buffering = false
960	return n, err
961}
962
963// outBufPool pools the record-sized scratch buffers used by writeRecordLocked.
964var outBufPool = sync.Pool{
965	New: func() interface{} {
966		return new([]byte)
967	},
968}
969
970// writeRecordLocked writes a TLS record with the given type and payload to the
971// connection and updates the record layer state.
972func (c *Conn) writeRecordLocked(typ recordType, data []byte) (int, error) {
973	outBufPtr := outBufPool.Get().(*[]byte)
974	outBuf := *outBufPtr
975	defer func() {
976		// You might be tempted to simplify this by just passing &outBuf to Put,
977		// but that would make the local copy of the outBuf slice header escape
978		// to the heap, causing an allocation. Instead, we keep around the
979		// pointer to the slice header returned by Get, which is already on the
980		// heap, and overwrite and return that.
981		*outBufPtr = outBuf
982		outBufPool.Put(outBufPtr)
983	}()
984
985	var n int
986	for len(data) > 0 {
987		m := len(data)
988		if maxPayload := c.maxPayloadSizeForWrite(typ); m > maxPayload {
989			m = maxPayload
990		}
991
992		_, outBuf = sliceForAppend(outBuf[:0], recordHeaderLen)
993		outBuf[0] = byte(typ)
994		vers := c.vers
995		if vers == 0 {
996			// Some TLS servers fail if the record version is
997			// greater than TLS 1.0 for the initial ClientHello.
998			vers = VersionTLS10
999		} else if vers == VersionTLS13 {
1000			// TLS 1.3 froze the record layer version to 1.2.
1001			// See RFC 8446, Section 5.1.
1002			vers = VersionTLS12
1003		}
1004		outBuf[1] = byte(vers >> 8)
1005		outBuf[2] = byte(vers)
1006		outBuf[3] = byte(m >> 8)
1007		outBuf[4] = byte(m)
1008
1009		var err error
1010		outBuf, err = c.out.encrypt(outBuf, data[:m], c.config.rand())
1011		if err != nil {
1012			return n, err
1013		}
1014		if _, err := c.write(outBuf); err != nil {
1015			return n, err
1016		}
1017		n += m
1018		data = data[m:]
1019	}
1020
1021	if typ == recordTypeChangeCipherSpec && c.vers != VersionTLS13 {
1022		if err := c.out.changeCipherSpec(); err != nil {
1023			return n, c.sendAlertLocked(err.(alert))
1024		}
1025	}
1026
1027	return n, nil
1028}
1029
1030// writeRecord writes a TLS record with the given type and payload to the
1031// connection and updates the record layer state.
1032func (c *Conn) writeRecord(typ recordType, data []byte) (int, error) {
1033	if c.extraConfig != nil && c.extraConfig.AlternativeRecordLayer != nil {
1034		if typ == recordTypeChangeCipherSpec {
1035			return len(data), nil
1036		}
1037		return c.extraConfig.AlternativeRecordLayer.WriteRecord(data)
1038	}
1039
1040	c.out.Lock()
1041	defer c.out.Unlock()
1042
1043	return c.writeRecordLocked(typ, data)
1044}
1045
1046// readHandshake reads the next handshake message from
1047// the record layer.
1048func (c *Conn) readHandshake() (interface{}, error) {
1049	var data []byte
1050	if c.extraConfig != nil && c.extraConfig.AlternativeRecordLayer != nil {
1051		var err error
1052		data, err = c.extraConfig.AlternativeRecordLayer.ReadHandshakeMessage()
1053		if err != nil {
1054			return nil, err
1055		}
1056	} else {
1057		for c.hand.Len() < 4 {
1058			if err := c.readRecord(); err != nil {
1059				return nil, err
1060			}
1061		}
1062
1063		data = c.hand.Bytes()
1064		n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1065		if n > maxHandshake {
1066			c.sendAlertLocked(alertInternalError)
1067			return nil, c.in.setErrorLocked(fmt.Errorf("tls: handshake message of length %d bytes exceeds maximum of %d bytes", n, maxHandshake))
1068		}
1069		for c.hand.Len() < 4+n {
1070			if err := c.readRecord(); err != nil {
1071				return nil, err
1072			}
1073		}
1074		data = c.hand.Next(4 + n)
1075	}
1076	var m handshakeMessage
1077	switch data[0] {
1078	case typeHelloRequest:
1079		m = new(helloRequestMsg)
1080	case typeClientHello:
1081		m = new(clientHelloMsg)
1082	case typeServerHello:
1083		m = new(serverHelloMsg)
1084	case typeNewSessionTicket:
1085		if c.vers == VersionTLS13 {
1086			m = new(newSessionTicketMsgTLS13)
1087		} else {
1088			m = new(newSessionTicketMsg)
1089		}
1090	case typeCertificate:
1091		if c.vers == VersionTLS13 {
1092			m = new(certificateMsgTLS13)
1093		} else {
1094			m = new(certificateMsg)
1095		}
1096	case typeCertificateRequest:
1097		if c.vers == VersionTLS13 {
1098			m = new(certificateRequestMsgTLS13)
1099		} else {
1100			m = &certificateRequestMsg{
1101				hasSignatureAlgorithm: c.vers >= VersionTLS12,
1102			}
1103		}
1104	case typeCertificateStatus:
1105		m = new(certificateStatusMsg)
1106	case typeServerKeyExchange:
1107		m = new(serverKeyExchangeMsg)
1108	case typeServerHelloDone:
1109		m = new(serverHelloDoneMsg)
1110	case typeClientKeyExchange:
1111		m = new(clientKeyExchangeMsg)
1112	case typeCertificateVerify:
1113		m = &certificateVerifyMsg{
1114			hasSignatureAlgorithm: c.vers >= VersionTLS12,
1115		}
1116	case typeFinished:
1117		m = new(finishedMsg)
1118	case typeEncryptedExtensions:
1119		m = new(encryptedExtensionsMsg)
1120	case typeEndOfEarlyData:
1121		m = new(endOfEarlyDataMsg)
1122	case typeKeyUpdate:
1123		m = new(keyUpdateMsg)
1124	default:
1125		return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1126	}
1127
1128	// The handshake message unmarshalers
1129	// expect to be able to keep references to data,
1130	// so pass in a fresh copy that won't be overwritten.
1131	data = append([]byte(nil), data...)
1132
1133	if !m.unmarshal(data) {
1134		return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1135	}
1136	return m, nil
1137}
1138
1139var (
1140	errShutdown = errors.New("tls: protocol is shutdown")
1141)
1142
1143// Write writes data to the connection.
1144//
1145// As Write calls Handshake, in order to prevent indefinite blocking a deadline
1146// must be set for both Read and Write before Write is called when the handshake
1147// has not yet completed. See SetDeadline, SetReadDeadline, and
1148// SetWriteDeadline.
1149func (c *Conn) Write(b []byte) (int, error) {
1150	// interlock with Close below
1151	for {
1152		x := atomic.LoadInt32(&c.activeCall)
1153		if x&1 != 0 {
1154			return 0, net.ErrClosed
1155		}
1156		if atomic.CompareAndSwapInt32(&c.activeCall, x, x+2) {
1157			break
1158		}
1159	}
1160	defer atomic.AddInt32(&c.activeCall, -2)
1161
1162	if err := c.Handshake(); err != nil {
1163		return 0, err
1164	}
1165
1166	c.out.Lock()
1167	defer c.out.Unlock()
1168
1169	if err := c.out.err; err != nil {
1170		return 0, err
1171	}
1172
1173	if !c.handshakeComplete() {
1174		return 0, alertInternalError
1175	}
1176
1177	if c.closeNotifySent {
1178		return 0, errShutdown
1179	}
1180
1181	// TLS 1.0 is susceptible to a chosen-plaintext
1182	// attack when using block mode ciphers due to predictable IVs.
1183	// This can be prevented by splitting each Application Data
1184	// record into two records, effectively randomizing the IV.
1185	//
1186	// https://www.openssl.org/~bodo/tls-cbc.txt
1187	// https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1188	// https://www.imperialviolet.org/2012/01/15/beastfollowup.html
1189
1190	var m int
1191	if len(b) > 1 && c.vers == VersionTLS10 {
1192		if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1193			n, err := c.writeRecordLocked(recordTypeApplicationData, b[:1])
1194			if err != nil {
1195				return n, c.out.setErrorLocked(err)
1196			}
1197			m, b = 1, b[1:]
1198		}
1199	}
1200
1201	n, err := c.writeRecordLocked(recordTypeApplicationData, b)
1202	return n + m, c.out.setErrorLocked(err)
1203}
1204
1205// handleRenegotiation processes a HelloRequest handshake message.
1206func (c *Conn) handleRenegotiation() error {
1207	if c.vers == VersionTLS13 {
1208		return errors.New("tls: internal error: unexpected renegotiation")
1209	}
1210
1211	msg, err := c.readHandshake()
1212	if err != nil {
1213		return err
1214	}
1215
1216	helloReq, ok := msg.(*helloRequestMsg)
1217	if !ok {
1218		c.sendAlert(alertUnexpectedMessage)
1219		return unexpectedMessageError(helloReq, msg)
1220	}
1221
1222	if !c.isClient {
1223		return c.sendAlert(alertNoRenegotiation)
1224	}
1225
1226	switch c.config.Renegotiation {
1227	case RenegotiateNever:
1228		return c.sendAlert(alertNoRenegotiation)
1229	case RenegotiateOnceAsClient:
1230		if c.handshakes > 1 {
1231			return c.sendAlert(alertNoRenegotiation)
1232		}
1233	case RenegotiateFreelyAsClient:
1234		// Ok.
1235	default:
1236		c.sendAlert(alertInternalError)
1237		return errors.New("tls: unknown Renegotiation value")
1238	}
1239
1240	c.handshakeMutex.Lock()
1241	defer c.handshakeMutex.Unlock()
1242
1243	atomic.StoreUint32(&c.handshakeStatus, 0)
1244	if c.handshakeErr = c.clientHandshake(); c.handshakeErr == nil {
1245		c.handshakes++
1246	}
1247	return c.handshakeErr
1248}
1249
1250func (c *Conn) HandlePostHandshakeMessage() error {
1251	return c.handlePostHandshakeMessage()
1252}
1253
1254// handlePostHandshakeMessage processes a handshake message arrived after the
1255// handshake is complete. Up to TLS 1.2, it indicates the start of a renegotiation.
1256func (c *Conn) handlePostHandshakeMessage() error {
1257	if c.vers != VersionTLS13 {
1258		return c.handleRenegotiation()
1259	}
1260
1261	msg, err := c.readHandshake()
1262	if err != nil {
1263		return err
1264	}
1265
1266	c.retryCount++
1267	if c.retryCount > maxUselessRecords {
1268		c.sendAlert(alertUnexpectedMessage)
1269		return c.in.setErrorLocked(errors.New("tls: too many non-advancing records"))
1270	}
1271
1272	switch msg := msg.(type) {
1273	case *newSessionTicketMsgTLS13:
1274		return c.handleNewSessionTicket(msg)
1275	case *keyUpdateMsg:
1276		return c.handleKeyUpdate(msg)
1277	default:
1278		c.sendAlert(alertUnexpectedMessage)
1279		return fmt.Errorf("tls: received unexpected handshake message of type %T", msg)
1280	}
1281}
1282
1283func (c *Conn) handleKeyUpdate(keyUpdate *keyUpdateMsg) error {
1284	cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite)
1285	if cipherSuite == nil {
1286		return c.in.setErrorLocked(c.sendAlert(alertInternalError))
1287	}
1288
1289	newSecret := cipherSuite.nextTrafficSecret(c.in.trafficSecret)
1290	c.in.setTrafficSecret(cipherSuite, newSecret)
1291
1292	if keyUpdate.updateRequested {
1293		c.out.Lock()
1294		defer c.out.Unlock()
1295
1296		msg := &keyUpdateMsg{}
1297		_, err := c.writeRecordLocked(recordTypeHandshake, msg.marshal())
1298		if err != nil {
1299			// Surface the error at the next write.
1300			c.out.setErrorLocked(err)
1301			return nil
1302		}
1303
1304		newSecret := cipherSuite.nextTrafficSecret(c.out.trafficSecret)
1305		c.out.setTrafficSecret(cipherSuite, newSecret)
1306	}
1307
1308	return nil
1309}
1310
1311// Read reads data from the connection.
1312//
1313// As Read calls Handshake, in order to prevent indefinite blocking a deadline
1314// must be set for both Read and Write before Read is called when the handshake
1315// has not yet completed. See SetDeadline, SetReadDeadline, and
1316// SetWriteDeadline.
1317func (c *Conn) Read(b []byte) (int, error) {
1318	if err := c.Handshake(); err != nil {
1319		return 0, err
1320	}
1321	if len(b) == 0 {
1322		// Put this after Handshake, in case people were calling
1323		// Read(nil) for the side effect of the Handshake.
1324		return 0, nil
1325	}
1326
1327	c.in.Lock()
1328	defer c.in.Unlock()
1329
1330	for c.input.Len() == 0 {
1331		if err := c.readRecord(); err != nil {
1332			return 0, err
1333		}
1334		for c.hand.Len() > 0 {
1335			if err := c.handlePostHandshakeMessage(); err != nil {
1336				return 0, err
1337			}
1338		}
1339	}
1340
1341	n, _ := c.input.Read(b)
1342
1343	// If a close-notify alert is waiting, read it so that we can return (n,
1344	// EOF) instead of (n, nil), to signal to the HTTP response reading
1345	// goroutine that the connection is now closed. This eliminates a race
1346	// where the HTTP response reading goroutine would otherwise not observe
1347	// the EOF until its next read, by which time a client goroutine might
1348	// have already tried to reuse the HTTP connection for a new request.
1349	// See https://golang.org/cl/76400046 and https://golang.org/issue/3514
1350	if n != 0 && c.input.Len() == 0 && c.rawInput.Len() > 0 &&
1351		recordType(c.rawInput.Bytes()[0]) == recordTypeAlert {
1352		if err := c.readRecord(); err != nil {
1353			return n, err // will be io.EOF on closeNotify
1354		}
1355	}
1356
1357	return n, nil
1358}
1359
1360// Close closes the connection.
1361func (c *Conn) Close() error {
1362	// Interlock with Conn.Write above.
1363	var x int32
1364	for {
1365		x = atomic.LoadInt32(&c.activeCall)
1366		if x&1 != 0 {
1367			return net.ErrClosed
1368		}
1369		if atomic.CompareAndSwapInt32(&c.activeCall, x, x|1) {
1370			break
1371		}
1372	}
1373	if x != 0 {
1374		// io.Writer and io.Closer should not be used concurrently.
1375		// If Close is called while a Write is currently in-flight,
1376		// interpret that as a sign that this Close is really just
1377		// being used to break the Write and/or clean up resources and
1378		// avoid sending the alertCloseNotify, which may block
1379		// waiting on handshakeMutex or the c.out mutex.
1380		return c.conn.Close()
1381	}
1382
1383	var alertErr error
1384	if c.handshakeComplete() {
1385		if err := c.closeNotify(); err != nil {
1386			alertErr = fmt.Errorf("tls: failed to send closeNotify alert (but connection was closed anyway): %w", err)
1387		}
1388	}
1389
1390	if err := c.conn.Close(); err != nil {
1391		return err
1392	}
1393	return alertErr
1394}
1395
1396var errEarlyCloseWrite = errors.New("tls: CloseWrite called before handshake complete")
1397
1398// CloseWrite shuts down the writing side of the connection. It should only be
1399// called once the handshake has completed and does not call CloseWrite on the
1400// underlying connection. Most callers should just use Close.
1401func (c *Conn) CloseWrite() error {
1402	if !c.handshakeComplete() {
1403		return errEarlyCloseWrite
1404	}
1405
1406	return c.closeNotify()
1407}
1408
1409func (c *Conn) closeNotify() error {
1410	c.out.Lock()
1411	defer c.out.Unlock()
1412
1413	if !c.closeNotifySent {
1414		// Set a Write Deadline to prevent possibly blocking forever.
1415		c.SetWriteDeadline(time.Now().Add(time.Second * 5))
1416		c.closeNotifyErr = c.sendAlertLocked(alertCloseNotify)
1417		c.closeNotifySent = true
1418		// Any subsequent writes will fail.
1419		c.SetWriteDeadline(time.Now())
1420	}
1421	return c.closeNotifyErr
1422}
1423
1424// Handshake runs the client or server handshake
1425// protocol if it has not yet been run.
1426//
1427// Most uses of this package need not call Handshake explicitly: the
1428// first Read or Write will call it automatically.
1429//
1430// For control over canceling or setting a timeout on a handshake, use
1431// the Dialer's DialContext method.
1432func (c *Conn) Handshake() error {
1433	c.handshakeMutex.Lock()
1434	defer c.handshakeMutex.Unlock()
1435
1436	if err := c.handshakeErr; err != nil {
1437		return err
1438	}
1439	if c.handshakeComplete() {
1440		return nil
1441	}
1442
1443	c.in.Lock()
1444	defer c.in.Unlock()
1445
1446	c.handshakeErr = c.handshakeFn()
1447	if c.handshakeErr == nil {
1448		c.handshakes++
1449	} else {
1450		// If an error occurred during the handshake try to flush the
1451		// alert that might be left in the buffer.
1452		c.flush()
1453	}
1454
1455	if c.handshakeErr == nil && !c.handshakeComplete() {
1456		c.handshakeErr = errors.New("tls: internal error: handshake should have had a result")
1457	}
1458
1459	return c.handshakeErr
1460}
1461
1462// ConnectionState returns basic TLS details about the connection.
1463func (c *Conn) ConnectionState() ConnectionState {
1464	c.handshakeMutex.Lock()
1465	defer c.handshakeMutex.Unlock()
1466	return c.connectionStateLocked()
1467}
1468
1469// ConnectionStateWith0RTT returns basic TLS details (incl. 0-RTT status) about the connection.
1470func (c *Conn) ConnectionStateWith0RTT() ConnectionStateWith0RTT {
1471	c.handshakeMutex.Lock()
1472	defer c.handshakeMutex.Unlock()
1473	return ConnectionStateWith0RTT{
1474		ConnectionState: c.connectionStateLocked(),
1475		Used0RTT:        c.used0RTT,
1476	}
1477}
1478
1479func (c *Conn) connectionStateLocked() ConnectionState {
1480	var state connectionState
1481	state.HandshakeComplete = c.handshakeComplete()
1482	state.Version = c.vers
1483	state.NegotiatedProtocol = c.clientProtocol
1484	state.DidResume = c.didResume
1485	state.NegotiatedProtocolIsMutual = true
1486	state.ServerName = c.serverName
1487	state.CipherSuite = c.cipherSuite
1488	state.PeerCertificates = c.peerCertificates
1489	state.VerifiedChains = c.verifiedChains
1490	state.SignedCertificateTimestamps = c.scts
1491	state.OCSPResponse = c.ocspResponse
1492	if !c.didResume && c.vers != VersionTLS13 {
1493		if c.clientFinishedIsFirst {
1494			state.TLSUnique = c.clientFinished[:]
1495		} else {
1496			state.TLSUnique = c.serverFinished[:]
1497		}
1498	}
1499	if c.config.Renegotiation != RenegotiateNever {
1500		state.ekm = noExportedKeyingMaterial
1501	} else {
1502		state.ekm = c.ekm
1503	}
1504	return toConnectionState(state)
1505}
1506
1507// OCSPResponse returns the stapled OCSP response from the TLS server, if
1508// any. (Only valid for client connections.)
1509func (c *Conn) OCSPResponse() []byte {
1510	c.handshakeMutex.Lock()
1511	defer c.handshakeMutex.Unlock()
1512
1513	return c.ocspResponse
1514}
1515
1516// VerifyHostname checks that the peer certificate chain is valid for
1517// connecting to host. If so, it returns nil; if not, it returns an error
1518// describing the problem.
1519func (c *Conn) VerifyHostname(host string) error {
1520	c.handshakeMutex.Lock()
1521	defer c.handshakeMutex.Unlock()
1522	if !c.isClient {
1523		return errors.New("tls: VerifyHostname called on TLS server connection")
1524	}
1525	if !c.handshakeComplete() {
1526		return errors.New("tls: handshake has not yet been performed")
1527	}
1528	if len(c.verifiedChains) == 0 {
1529		return errors.New("tls: handshake did not verify certificate chain")
1530	}
1531	return c.peerCertificates[0].VerifyHostname(host)
1532}
1533
1534func (c *Conn) handshakeComplete() bool {
1535	return atomic.LoadUint32(&c.handshakeStatus) == 1
1536}
1537