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