gitlab.com/go-extension/tls@v0.0.0-20240304171319-e6745021905e/conn.go (about)

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