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