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