Source file src/crypto/tls/conn.go

     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  	"internal/godebug"
    19  	"io"
    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  	didHRR           bool // whether a HelloRetryRequest was sent/received
    52  	cipherSuite      uint16
    53  	curveID          CurveID
    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  	echAccepted      bool
    75  
    76  	// ticketKeys is the set of active session ticket keys for this
    77  	// connection. The first one is used to encrypt new tickets and
    78  	// all are tried to decrypt tickets.
    79  	ticketKeys []ticketKey
    80  
    81  	// clientFinishedIsFirst is true if the client sent the first Finished
    82  	// message during the most recent handshake. This is recorded because
    83  	// the first transmitted Finished message is the tls-unique
    84  	// channel-binding value.
    85  	clientFinishedIsFirst bool
    86  
    87  	// closeNotifyErr is any error from sending the alertCloseNotify record.
    88  	closeNotifyErr error
    89  	// closeNotifySent is true if the Conn attempted to send an
    90  	// alertCloseNotify record.
    91  	closeNotifySent bool
    92  
    93  	// clientFinished and serverFinished contain the Finished message sent
    94  	// by the client or server in the most recent handshake. This is
    95  	// retained to support the renegotiation extension and tls-unique
    96  	// channel-binding.
    97  	clientFinished [12]byte
    98  	serverFinished [12]byte
    99  
   100  	// clientProtocol is the negotiated ALPN protocol.
   101  	clientProtocol string
   102  
   103  	// input/output
   104  	in, out   halfConn
   105  	rawInput  bytes.Buffer // raw input, starting with a record header
   106  	input     bytes.Reader // application data waiting to be read, from rawInput.Next
   107  	hand      bytes.Buffer // handshake data waiting to be read
   108  	buffering bool         // whether records are buffered in sendBuf
   109  	sendBuf   []byte       // a buffer of records waiting to be sent
   110  
   111  	// bytesSent counts the bytes of application data sent.
   112  	// packetsSent counts packets.
   113  	bytesSent   int64
   114  	packetsSent int64
   115  
   116  	// retryCount counts the number of consecutive non-advancing records
   117  	// received by Conn.readRecord. That is, records that neither advance the
   118  	// handshake, nor deliver application data. Protected by in.Mutex.
   119  	retryCount int
   120  
   121  	// activeCall indicates whether Close has been call in the low bit.
   122  	// the rest of the bits are the number of goroutines in Conn.Write.
   123  	activeCall atomic.Int32
   124  
   125  	tmp [16]byte
   126  }
   127  
   128  // Access to net.Conn methods.
   129  // Cannot just embed net.Conn because that would
   130  // export the struct field too.
   131  
   132  // LocalAddr returns the local network address.
   133  func (c *Conn) LocalAddr() net.Addr {
   134  	return c.conn.LocalAddr()
   135  }
   136  
   137  // RemoteAddr returns the remote network address.
   138  func (c *Conn) RemoteAddr() net.Addr {
   139  	return c.conn.RemoteAddr()
   140  }
   141  
   142  // SetDeadline sets the read and write deadlines associated with the connection.
   143  // A zero value for t means [Conn.Read] and [Conn.Write] will not time out.
   144  // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
   145  func (c *Conn) SetDeadline(t time.Time) error {
   146  	return c.conn.SetDeadline(t)
   147  }
   148  
   149  // SetReadDeadline sets the read deadline on the underlying connection.
   150  // A zero value for t means [Conn.Read] will not time out.
   151  func (c *Conn) SetReadDeadline(t time.Time) error {
   152  	return c.conn.SetReadDeadline(t)
   153  }
   154  
   155  // SetWriteDeadline sets the write deadline on the underlying connection.
   156  // A zero value for t means [Conn.Write] will not time out.
   157  // After a [Conn.Write] has timed out, the TLS state is corrupt and all future writes will return the same error.
   158  func (c *Conn) SetWriteDeadline(t time.Time) error {
   159  	return c.conn.SetWriteDeadline(t)
   160  }
   161  
   162  // NetConn returns the underlying connection that is wrapped by c.
   163  // Note that writing to or reading from this connection directly will corrupt the
   164  // TLS session.
   165  func (c *Conn) NetConn() net.Conn {
   166  	return c.conn
   167  }
   168  
   169  // A halfConn represents one direction of the record layer
   170  // connection, either sending or receiving.
   171  type halfConn struct {
   172  	sync.Mutex
   173  
   174  	err     error  // first permanent error
   175  	version uint16 // protocol version
   176  	cipher  any    // cipher algorithm
   177  	mac     hash.Hash
   178  	seq     [8]byte // 64-bit sequence number
   179  
   180  	scratchBuf [13]byte // to avoid allocs; interface method args escape
   181  
   182  	nextCipher any       // next encryption state
   183  	nextMac    hash.Hash // next MAC algorithm
   184  
   185  	level         QUICEncryptionLevel // current QUIC encryption level
   186  	trafficSecret []byte              // current TLS 1.3 traffic secret
   187  }
   188  
   189  type permanentError struct {
   190  	err net.Error
   191  }
   192  
   193  func (e *permanentError) Error() string   { return e.err.Error() }
   194  func (e *permanentError) Unwrap() error   { return e.err }
   195  func (e *permanentError) Timeout() bool   { return e.err.Timeout() }
   196  func (e *permanentError) Temporary() bool { return false }
   197  
   198  func (hc *halfConn) setErrorLocked(err error) error {
   199  	if e, ok := err.(net.Error); ok {
   200  		hc.err = &permanentError{err: e}
   201  	} else {
   202  		hc.err = err
   203  	}
   204  	return hc.err
   205  }
   206  
   207  // prepareCipherSpec sets the encryption and MAC states
   208  // that a subsequent changeCipherSpec will use.
   209  func (hc *halfConn) prepareCipherSpec(version uint16, cipher any, mac hash.Hash) {
   210  	hc.version = version
   211  	hc.nextCipher = cipher
   212  	hc.nextMac = mac
   213  }
   214  
   215  // changeCipherSpec changes the encryption and MAC states
   216  // to the ones previously passed to prepareCipherSpec.
   217  func (hc *halfConn) changeCipherSpec() error {
   218  	if hc.nextCipher == nil || hc.version == VersionTLS13 {
   219  		return alertInternalError
   220  	}
   221  	hc.cipher = hc.nextCipher
   222  	hc.mac = hc.nextMac
   223  	hc.nextCipher = nil
   224  	hc.nextMac = nil
   225  	for i := range hc.seq {
   226  		hc.seq[i] = 0
   227  	}
   228  	return nil
   229  }
   230  
   231  func (hc *halfConn) setTrafficSecret(suite *cipherSuiteTLS13, level QUICEncryptionLevel, secret []byte) {
   232  	hc.trafficSecret = secret
   233  	hc.level = level
   234  	key, iv := suite.trafficKey(secret)
   235  	hc.cipher = suite.aead(key, iv)
   236  	for i := range hc.seq {
   237  		hc.seq[i] = 0
   238  	}
   239  }
   240  
   241  // incSeq increments the sequence number.
   242  func (hc *halfConn) incSeq() {
   243  	for i := 7; i >= 0; i-- {
   244  		hc.seq[i]++
   245  		if hc.seq[i] != 0 {
   246  			return
   247  		}
   248  	}
   249  
   250  	// Not allowed to let sequence number wrap.
   251  	// Instead, must renegotiate before it does.
   252  	// Not likely enough to bother.
   253  	panic("TLS: sequence number wraparound")
   254  }
   255  
   256  // explicitNonceLen returns the number of bytes of explicit nonce or IV included
   257  // in each record. Explicit nonces are present only in CBC modes after TLS 1.0
   258  // and in certain AEAD modes in TLS 1.2.
   259  func (hc *halfConn) explicitNonceLen() int {
   260  	if hc.cipher == nil {
   261  		return 0
   262  	}
   263  
   264  	switch c := hc.cipher.(type) {
   265  	case cipher.Stream:
   266  		return 0
   267  	case aead:
   268  		return c.explicitNonceLen()
   269  	case cbcMode:
   270  		// TLS 1.1 introduced a per-record explicit IV to fix the BEAST attack.
   271  		if hc.version >= VersionTLS11 {
   272  			return c.BlockSize()
   273  		}
   274  		return 0
   275  	default:
   276  		panic("unknown cipher type")
   277  	}
   278  }
   279  
   280  // extractPadding returns, in constant time, the length of the padding to remove
   281  // from the end of payload. It also returns a byte which is equal to 255 if the
   282  // padding was valid and 0 otherwise. See RFC 2246, Section 6.2.3.2.
   283  func extractPadding(payload []byte) (toRemove int, good byte) {
   284  	if len(payload) < 1 {
   285  		return 0, 0
   286  	}
   287  
   288  	paddingLen := payload[len(payload)-1]
   289  	t := uint(len(payload)-1) - uint(paddingLen)
   290  	// if len(payload) >= (paddingLen - 1) then the MSB of t is zero
   291  	good = byte(int32(^t) >> 31)
   292  
   293  	// The maximum possible padding length plus the actual length field
   294  	toCheck := 256
   295  	// The length of the padded data is public, so we can use an if here
   296  	if toCheck > len(payload) {
   297  		toCheck = len(payload)
   298  	}
   299  
   300  	for i := 0; i < toCheck; i++ {
   301  		t := uint(paddingLen) - uint(i)
   302  		// if i <= paddingLen then the MSB of t is zero
   303  		mask := byte(int32(^t) >> 31)
   304  		b := payload[len(payload)-1-i]
   305  		good &^= mask&paddingLen ^ mask&b
   306  	}
   307  
   308  	// We AND together the bits of good and replicate the result across
   309  	// all the bits.
   310  	good &= good << 4
   311  	good &= good << 2
   312  	good &= good << 1
   313  	good = uint8(int8(good) >> 7)
   314  
   315  	// Zero the padding length on error. This ensures any unchecked bytes
   316  	// are included in the MAC. Otherwise, an attacker that could
   317  	// distinguish MAC failures from padding failures could mount an attack
   318  	// similar to POODLE in SSL 3.0: given a good ciphertext that uses a
   319  	// full block's worth of padding, replace the final block with another
   320  	// block. If the MAC check passed but the padding check failed, the
   321  	// last byte of that block decrypted to the block size.
   322  	//
   323  	// See also macAndPaddingGood logic below.
   324  	paddingLen &= good
   325  
   326  	toRemove = int(paddingLen) + 1
   327  	return
   328  }
   329  
   330  func roundUp(a, b int) int {
   331  	return a + (b-a%b)%b
   332  }
   333  
   334  // cbcMode is an interface for block ciphers using cipher block chaining.
   335  type cbcMode interface {
   336  	cipher.BlockMode
   337  	SetIV([]byte)
   338  }
   339  
   340  // decrypt authenticates and decrypts the record if protection is active at
   341  // this stage. The returned plaintext might overlap with the input.
   342  func (hc *halfConn) decrypt(record []byte) ([]byte, recordType, error) {
   343  	var plaintext []byte
   344  	typ := recordType(record[0])
   345  	payload := record[recordHeaderLen:]
   346  
   347  	// In TLS 1.3, change_cipher_spec messages are to be ignored without being
   348  	// decrypted. See RFC 8446, Appendix D.4.
   349  	if hc.version == VersionTLS13 && typ == recordTypeChangeCipherSpec {
   350  		return payload, typ, nil
   351  	}
   352  
   353  	paddingGood := byte(255)
   354  	paddingLen := 0
   355  
   356  	explicitNonceLen := hc.explicitNonceLen()
   357  
   358  	if hc.cipher != nil {
   359  		switch c := hc.cipher.(type) {
   360  		case cipher.Stream:
   361  			c.XORKeyStream(payload, payload)
   362  		case aead:
   363  			if len(payload) < explicitNonceLen {
   364  				return nil, 0, alertBadRecordMAC
   365  			}
   366  			nonce := payload[:explicitNonceLen]
   367  			if len(nonce) == 0 {
   368  				nonce = hc.seq[:]
   369  			}
   370  			payload = payload[explicitNonceLen:]
   371  
   372  			var additionalData []byte
   373  			if hc.version == VersionTLS13 {
   374  				additionalData = record[:recordHeaderLen]
   375  			} else {
   376  				additionalData = append(hc.scratchBuf[:0], hc.seq[:]...)
   377  				additionalData = append(additionalData, record[:3]...)
   378  				n := len(payload) - c.Overhead()
   379  				additionalData = append(additionalData, byte(n>>8), byte(n))
   380  			}
   381  
   382  			var err error
   383  			plaintext, err = c.Open(payload[:0], nonce, payload, additionalData)
   384  			if err != nil {
   385  				return nil, 0, alertBadRecordMAC
   386  			}
   387  		case cbcMode:
   388  			blockSize := c.BlockSize()
   389  			minPayload := explicitNonceLen + roundUp(hc.mac.Size()+1, blockSize)
   390  			if len(payload)%blockSize != 0 || len(payload) < minPayload {
   391  				return nil, 0, alertBadRecordMAC
   392  			}
   393  
   394  			if explicitNonceLen > 0 {
   395  				c.SetIV(payload[:explicitNonceLen])
   396  				payload = payload[explicitNonceLen:]
   397  			}
   398  			c.CryptBlocks(payload, payload)
   399  
   400  			// In a limited attempt to protect against CBC padding oracles like
   401  			// Lucky13, the data past paddingLen (which is secret) is passed to
   402  			// the MAC function as extra data, to be fed into the HMAC after
   403  			// computing the digest. This makes the MAC roughly constant time as
   404  			// long as the digest computation is constant time and does not
   405  			// affect the subsequent write, modulo cache effects.
   406  			paddingLen, paddingGood = extractPadding(payload)
   407  		default:
   408  			panic("unknown cipher type")
   409  		}
   410  
   411  		if hc.version == VersionTLS13 {
   412  			if typ != recordTypeApplicationData {
   413  				return nil, 0, alertUnexpectedMessage
   414  			}
   415  			if len(plaintext) > maxPlaintext+1 {
   416  				return nil, 0, alertRecordOverflow
   417  			}
   418  			// Remove padding and find the ContentType scanning from the end.
   419  			for i := len(plaintext) - 1; i >= 0; i-- {
   420  				if plaintext[i] != 0 {
   421  					typ = recordType(plaintext[i])
   422  					plaintext = plaintext[:i]
   423  					break
   424  				}
   425  				if i == 0 {
   426  					return nil, 0, alertUnexpectedMessage
   427  				}
   428  			}
   429  		}
   430  	} else {
   431  		plaintext = payload
   432  	}
   433  
   434  	if hc.mac != nil {
   435  		macSize := hc.mac.Size()
   436  		if len(payload) < macSize {
   437  			return nil, 0, alertBadRecordMAC
   438  		}
   439  
   440  		n := len(payload) - macSize - paddingLen
   441  		n = subtle.ConstantTimeSelect(int(uint32(n)>>31), 0, n) // if n < 0 { n = 0 }
   442  		record[3] = byte(n >> 8)
   443  		record[4] = byte(n)
   444  		remoteMAC := payload[n : n+macSize]
   445  		localMAC := tls10MAC(hc.mac, hc.scratchBuf[:0], hc.seq[:], record[:recordHeaderLen], payload[:n], payload[n+macSize:])
   446  
   447  		// This is equivalent to checking the MACs and paddingGood
   448  		// separately, but in constant-time to prevent distinguishing
   449  		// padding failures from MAC failures. Depending on what value
   450  		// of paddingLen was returned on bad padding, distinguishing
   451  		// bad MAC from bad padding can lead to an attack.
   452  		//
   453  		// See also the logic at the end of extractPadding.
   454  		macAndPaddingGood := subtle.ConstantTimeCompare(localMAC, remoteMAC) & int(paddingGood)
   455  		if macAndPaddingGood != 1 {
   456  			return nil, 0, alertBadRecordMAC
   457  		}
   458  
   459  		plaintext = payload[:n]
   460  	}
   461  
   462  	hc.incSeq()
   463  	return plaintext, typ, nil
   464  }
   465  
   466  // sliceForAppend extends the input slice by n bytes. head is the full extended
   467  // slice, while tail is the appended part. If the original slice has sufficient
   468  // capacity no allocation is performed.
   469  func sliceForAppend(in []byte, n int) (head, tail []byte) {
   470  	if total := len(in) + n; cap(in) >= total {
   471  		head = in[:total]
   472  	} else {
   473  		head = make([]byte, total)
   474  		copy(head, in)
   475  	}
   476  	tail = head[len(in):]
   477  	return
   478  }
   479  
   480  // encrypt encrypts payload, adding the appropriate nonce and/or MAC, and
   481  // appends it to record, which must already contain the record header.
   482  func (hc *halfConn) encrypt(record, payload []byte, rand io.Reader) ([]byte, error) {
   483  	if hc.cipher == nil {
   484  		return append(record, payload...), nil
   485  	}
   486  
   487  	var explicitNonce []byte
   488  	if explicitNonceLen := hc.explicitNonceLen(); explicitNonceLen > 0 {
   489  		record, explicitNonce = sliceForAppend(record, explicitNonceLen)
   490  		if _, isCBC := hc.cipher.(cbcMode); !isCBC && explicitNonceLen < 16 {
   491  			// The AES-GCM construction in TLS has an explicit nonce so that the
   492  			// nonce can be random. However, the nonce is only 8 bytes which is
   493  			// too small for a secure, random nonce. Therefore we use the
   494  			// sequence number as the nonce. The 3DES-CBC construction also has
   495  			// an 8 bytes nonce but its nonces must be unpredictable (see RFC
   496  			// 5246, Appendix F.3), forcing us to use randomness. That's not
   497  			// 3DES' biggest problem anyway because the birthday bound on block
   498  			// collision is reached first due to its similarly small block size
   499  			// (see the Sweet32 attack).
   500  			copy(explicitNonce, hc.seq[:])
   501  		} else {
   502  			if _, err := io.ReadFull(rand, explicitNonce); err != nil {
   503  				return nil, err
   504  			}
   505  		}
   506  	}
   507  
   508  	var dst []byte
   509  	switch c := hc.cipher.(type) {
   510  	case cipher.Stream:
   511  		mac := tls10MAC(hc.mac, hc.scratchBuf[:0], hc.seq[:], record[:recordHeaderLen], payload, nil)
   512  		record, dst = sliceForAppend(record, len(payload)+len(mac))
   513  		c.XORKeyStream(dst[:len(payload)], payload)
   514  		c.XORKeyStream(dst[len(payload):], mac)
   515  	case aead:
   516  		nonce := explicitNonce
   517  		if len(nonce) == 0 {
   518  			nonce = hc.seq[:]
   519  		}
   520  
   521  		if hc.version == VersionTLS13 {
   522  			record = append(record, payload...)
   523  
   524  			// Encrypt the actual ContentType and replace the plaintext one.
   525  			record = append(record, record[0])
   526  			record[0] = byte(recordTypeApplicationData)
   527  
   528  			n := len(payload) + 1 + c.Overhead()
   529  			record[3] = byte(n >> 8)
   530  			record[4] = byte(n)
   531  
   532  			record = c.Seal(record[:recordHeaderLen],
   533  				nonce, record[recordHeaderLen:], record[:recordHeaderLen])
   534  		} else {
   535  			additionalData := append(hc.scratchBuf[:0], hc.seq[:]...)
   536  			additionalData = append(additionalData, record[:recordHeaderLen]...)
   537  			record = c.Seal(record, nonce, payload, additionalData)
   538  		}
   539  	case cbcMode:
   540  		mac := tls10MAC(hc.mac, hc.scratchBuf[:0], hc.seq[:], record[:recordHeaderLen], payload, nil)
   541  		blockSize := c.BlockSize()
   542  		plaintextLen := len(payload) + len(mac)
   543  		paddingLen := blockSize - plaintextLen%blockSize
   544  		record, dst = sliceForAppend(record, plaintextLen+paddingLen)
   545  		copy(dst, payload)
   546  		copy(dst[len(payload):], mac)
   547  		for i := plaintextLen; i < len(dst); i++ {
   548  			dst[i] = byte(paddingLen - 1)
   549  		}
   550  		if len(explicitNonce) > 0 {
   551  			c.SetIV(explicitNonce)
   552  		}
   553  		c.CryptBlocks(dst, dst)
   554  	default:
   555  		panic("unknown cipher type")
   556  	}
   557  
   558  	// Update length to include nonce, MAC and any block padding needed.
   559  	n := len(record) - recordHeaderLen
   560  	record[3] = byte(n >> 8)
   561  	record[4] = byte(n)
   562  	hc.incSeq()
   563  
   564  	return record, nil
   565  }
   566  
   567  // RecordHeaderError is returned when a TLS record header is invalid.
   568  type RecordHeaderError struct {
   569  	// Msg contains a human readable string that describes the error.
   570  	Msg string
   571  	// RecordHeader contains the five bytes of TLS record header that
   572  	// triggered the error.
   573  	RecordHeader [5]byte
   574  	// Conn provides the underlying net.Conn in the case that a client
   575  	// sent an initial handshake that didn't look like TLS.
   576  	// It is nil if there's already been a handshake or a TLS alert has
   577  	// been written to the connection.
   578  	Conn net.Conn
   579  }
   580  
   581  func (e RecordHeaderError) Error() string { return "tls: " + e.Msg }
   582  
   583  func (c *Conn) newRecordHeaderError(conn net.Conn, msg string) (err RecordHeaderError) {
   584  	err.Msg = msg
   585  	err.Conn = conn
   586  	copy(err.RecordHeader[:], c.rawInput.Bytes())
   587  	return err
   588  }
   589  
   590  func (c *Conn) readRecord() error {
   591  	return c.readRecordOrCCS(false)
   592  }
   593  
   594  func (c *Conn) readChangeCipherSpec() error {
   595  	return c.readRecordOrCCS(true)
   596  }
   597  
   598  // readRecordOrCCS reads one or more TLS records from the connection and
   599  // updates the record layer state. Some invariants:
   600  //   - c.in must be locked
   601  //   - c.input must be empty
   602  //
   603  // During the handshake one and only one of the following will happen:
   604  //   - c.hand grows
   605  //   - c.in.changeCipherSpec is called
   606  //   - an error is returned
   607  //
   608  // After the handshake one and only one of the following will happen:
   609  //   - c.hand grows
   610  //   - c.input is set
   611  //   - an error is returned
   612  func (c *Conn) readRecordOrCCS(expectChangeCipherSpec bool) error {
   613  	if c.in.err != nil {
   614  		return c.in.err
   615  	}
   616  	handshakeComplete := c.isHandshakeComplete.Load()
   617  
   618  	// This function modifies c.rawInput, which owns the c.input memory.
   619  	if c.input.Len() != 0 {
   620  		return c.in.setErrorLocked(errors.New("tls: internal error: attempted to read record with pending application data"))
   621  	}
   622  	c.input.Reset(nil)
   623  
   624  	if c.quic != nil {
   625  		return c.in.setErrorLocked(errors.New("tls: internal error: attempted to read record with QUIC transport"))
   626  	}
   627  
   628  	// Read header, payload.
   629  	if err := c.readFromUntil(c.conn, recordHeaderLen); err != nil {
   630  		// RFC 8446, Section 6.1 suggests that EOF without an alertCloseNotify
   631  		// is an error, but popular web sites seem to do this, so we accept it
   632  		// if and only if at the record boundary.
   633  		if err == io.ErrUnexpectedEOF && c.rawInput.Len() == 0 {
   634  			err = io.EOF
   635  		}
   636  		if e, ok := err.(net.Error); !ok || !e.Temporary() {
   637  			c.in.setErrorLocked(err)
   638  		}
   639  		return err
   640  	}
   641  	hdr := c.rawInput.Bytes()[:recordHeaderLen]
   642  	typ := recordType(hdr[0])
   643  
   644  	// No valid TLS record has a type of 0x80, however SSLv2 handshakes
   645  	// start with a uint16 length where the MSB is set and the first record
   646  	// is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
   647  	// an SSLv2 client.
   648  	if !handshakeComplete && typ == 0x80 {
   649  		c.sendAlert(alertProtocolVersion)
   650  		return c.in.setErrorLocked(c.newRecordHeaderError(nil, "unsupported SSLv2 handshake received"))
   651  	}
   652  
   653  	vers := uint16(hdr[1])<<8 | uint16(hdr[2])
   654  	expectedVers := c.vers
   655  	if expectedVers == VersionTLS13 {
   656  		// All TLS 1.3 records are expected to have 0x0303 (1.2) after
   657  		// the initial hello (RFC 8446 Section 5.1).
   658  		expectedVers = VersionTLS12
   659  	}
   660  	n := int(hdr[3])<<8 | int(hdr[4])
   661  	if c.haveVers && vers != expectedVers {
   662  		c.sendAlert(alertProtocolVersion)
   663  		msg := fmt.Sprintf("received record with version %x when expecting version %x", vers, expectedVers)
   664  		return c.in.setErrorLocked(c.newRecordHeaderError(nil, msg))
   665  	}
   666  	if !c.haveVers {
   667  		// First message, be extra suspicious: this might not be a TLS
   668  		// client. Bail out before reading a full 'body', if possible.
   669  		// The current max version is 3.3 so if the version is >= 16.0,
   670  		// it's probably not real.
   671  		if (typ != recordTypeAlert && typ != recordTypeHandshake) || vers >= 0x1000 {
   672  			return c.in.setErrorLocked(c.newRecordHeaderError(c.conn, "first record does not look like a TLS handshake"))
   673  		}
   674  	}
   675  	if c.vers == VersionTLS13 && n > maxCiphertextTLS13 || n > maxCiphertext {
   676  		c.sendAlert(alertRecordOverflow)
   677  		msg := fmt.Sprintf("oversized record received with length %d", n)
   678  		return c.in.setErrorLocked(c.newRecordHeaderError(nil, msg))
   679  	}
   680  	if err := c.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
   681  		if e, ok := err.(net.Error); !ok || !e.Temporary() {
   682  			c.in.setErrorLocked(err)
   683  		}
   684  		return err
   685  	}
   686  
   687  	// Process message.
   688  	record := c.rawInput.Next(recordHeaderLen + n)
   689  	data, typ, err := c.in.decrypt(record)
   690  	if err != nil {
   691  		return c.in.setErrorLocked(c.sendAlert(err.(alert)))
   692  	}
   693  	if len(data) > maxPlaintext {
   694  		return c.in.setErrorLocked(c.sendAlert(alertRecordOverflow))
   695  	}
   696  
   697  	// Application Data messages are always protected.
   698  	if c.in.cipher == nil && typ == recordTypeApplicationData {
   699  		return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   700  	}
   701  
   702  	if typ != recordTypeAlert && typ != recordTypeChangeCipherSpec && len(data) > 0 {
   703  		// This is a state-advancing message: reset the retry count.
   704  		c.retryCount = 0
   705  	}
   706  
   707  	// Handshake messages MUST NOT be interleaved with other record types in TLS 1.3.
   708  	if c.vers == VersionTLS13 && typ != recordTypeHandshake && c.hand.Len() > 0 {
   709  		return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   710  	}
   711  
   712  	switch typ {
   713  	default:
   714  		return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   715  
   716  	case recordTypeAlert:
   717  		if c.quic != nil {
   718  			return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   719  		}
   720  		if len(data) != 2 {
   721  			return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   722  		}
   723  		if alert(data[1]) == alertCloseNotify {
   724  			return c.in.setErrorLocked(io.EOF)
   725  		}
   726  		if c.vers == VersionTLS13 {
   727  			return c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
   728  		}
   729  		switch data[0] {
   730  		case alertLevelWarning:
   731  			// Drop the record on the floor and retry.
   732  			return c.retryReadRecord(expectChangeCipherSpec)
   733  		case alertLevelError:
   734  			return c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
   735  		default:
   736  			return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   737  		}
   738  
   739  	case recordTypeChangeCipherSpec:
   740  		if len(data) != 1 || data[0] != 1 {
   741  			return c.in.setErrorLocked(c.sendAlert(alertDecodeError))
   742  		}
   743  		// Handshake messages are not allowed to fragment across the CCS.
   744  		if c.hand.Len() > 0 {
   745  			return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   746  		}
   747  		// In TLS 1.3, change_cipher_spec records are ignored until the
   748  		// Finished. See RFC 8446, Appendix D.4. Note that according to Section
   749  		// 5, a server can send a ChangeCipherSpec before its ServerHello, when
   750  		// c.vers is still unset. That's not useful though and suspicious if the
   751  		// server then selects a lower protocol version, so don't allow that.
   752  		if c.vers == VersionTLS13 {
   753  			return c.retryReadRecord(expectChangeCipherSpec)
   754  		}
   755  		if !expectChangeCipherSpec {
   756  			return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   757  		}
   758  		if err := c.in.changeCipherSpec(); err != nil {
   759  			return c.in.setErrorLocked(c.sendAlert(err.(alert)))
   760  		}
   761  
   762  	case recordTypeApplicationData:
   763  		if !handshakeComplete || expectChangeCipherSpec {
   764  			return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   765  		}
   766  		// Some OpenSSL servers send empty records in order to randomize the
   767  		// CBC IV. Ignore a limited number of empty records.
   768  		if len(data) == 0 {
   769  			return c.retryReadRecord(expectChangeCipherSpec)
   770  		}
   771  		// Note that data is owned by c.rawInput, following the Next call above,
   772  		// to avoid copying the plaintext. This is safe because c.rawInput is
   773  		// not read from or written to until c.input is drained.
   774  		c.input.Reset(data)
   775  
   776  	case recordTypeHandshake:
   777  		if len(data) == 0 || expectChangeCipherSpec {
   778  			return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   779  		}
   780  		c.hand.Write(data)
   781  	}
   782  
   783  	return nil
   784  }
   785  
   786  // retryReadRecord recurs into readRecordOrCCS to drop a non-advancing record, like
   787  // a warning alert, empty application_data, or a change_cipher_spec in TLS 1.3.
   788  func (c *Conn) retryReadRecord(expectChangeCipherSpec bool) error {
   789  	c.retryCount++
   790  	if c.retryCount > maxUselessRecords {
   791  		c.sendAlert(alertUnexpectedMessage)
   792  		return c.in.setErrorLocked(errors.New("tls: too many ignored records"))
   793  	}
   794  	return c.readRecordOrCCS(expectChangeCipherSpec)
   795  }
   796  
   797  // atLeastReader reads from R, stopping with EOF once at least N bytes have been
   798  // read. It is different from an io.LimitedReader in that it doesn't cut short
   799  // the last Read call, and in that it considers an early EOF an error.
   800  type atLeastReader struct {
   801  	R io.Reader
   802  	N int64
   803  }
   804  
   805  func (r *atLeastReader) Read(p []byte) (int, error) {
   806  	if r.N <= 0 {
   807  		return 0, io.EOF
   808  	}
   809  	n, err := r.R.Read(p)
   810  	r.N -= int64(n) // won't underflow unless len(p) >= n > 9223372036854775809
   811  	if r.N > 0 && err == io.EOF {
   812  		return n, io.ErrUnexpectedEOF
   813  	}
   814  	if r.N <= 0 && err == nil {
   815  		return n, io.EOF
   816  	}
   817  	return n, err
   818  }
   819  
   820  // readFromUntil reads from r into c.rawInput until c.rawInput contains
   821  // at least n bytes or else returns an error.
   822  func (c *Conn) readFromUntil(r io.Reader, n int) error {
   823  	if c.rawInput.Len() >= n {
   824  		return nil
   825  	}
   826  	needs := n - c.rawInput.Len()
   827  	// There might be extra input waiting on the wire. Make a best effort
   828  	// attempt to fetch it so that it can be used in (*Conn).Read to
   829  	// "predict" closeNotify alerts.
   830  	c.rawInput.Grow(needs + bytes.MinRead)
   831  	_, err := c.rawInput.ReadFrom(&atLeastReader{r, int64(needs)})
   832  	return err
   833  }
   834  
   835  // sendAlertLocked sends a TLS alert message.
   836  func (c *Conn) sendAlertLocked(err alert) error {
   837  	if c.quic != nil {
   838  		return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
   839  	}
   840  
   841  	switch err {
   842  	case alertNoRenegotiation, alertCloseNotify:
   843  		c.tmp[0] = alertLevelWarning
   844  	default:
   845  		c.tmp[0] = alertLevelError
   846  	}
   847  	c.tmp[1] = byte(err)
   848  
   849  	_, writeErr := c.writeRecordLocked(recordTypeAlert, c.tmp[0:2])
   850  	if err == alertCloseNotify {
   851  		// closeNotify is a special case in that it isn't an error.
   852  		return writeErr
   853  	}
   854  
   855  	return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
   856  }
   857  
   858  // sendAlert sends a TLS alert message.
   859  func (c *Conn) sendAlert(err alert) error {
   860  	c.out.Lock()
   861  	defer c.out.Unlock()
   862  	return c.sendAlertLocked(err)
   863  }
   864  
   865  const (
   866  	// tcpMSSEstimate is a conservative estimate of the TCP maximum segment
   867  	// size (MSS). A constant is used, rather than querying the kernel for
   868  	// the actual MSS, to avoid complexity. The value here is the IPv6
   869  	// minimum MTU (1280 bytes) minus the overhead of an IPv6 header (40
   870  	// bytes) and a TCP header with timestamps (32 bytes).
   871  	tcpMSSEstimate = 1208
   872  
   873  	// recordSizeBoostThreshold is the number of bytes of application data
   874  	// sent after which the TLS record size will be increased to the
   875  	// maximum.
   876  	recordSizeBoostThreshold = 128 * 1024
   877  )
   878  
   879  // maxPayloadSizeForWrite returns the maximum TLS payload size to use for the
   880  // next application data record. There is the following trade-off:
   881  //
   882  //   - For latency-sensitive applications, such as web browsing, each TLS
   883  //     record should fit in one TCP segment.
   884  //   - For throughput-sensitive applications, such as large file transfers,
   885  //     larger TLS records better amortize framing and encryption overheads.
   886  //
   887  // A simple heuristic that works well in practice is to use small records for
   888  // the first 1MB of data, then use larger records for subsequent data, and
   889  // reset back to smaller records after the connection becomes idle. See "High
   890  // Performance Web Networking", Chapter 4, or:
   891  // https://www.igvita.com/2013/10/24/optimizing-tls-record-size-and-buffering-latency/
   892  //
   893  // In the interests of simplicity and determinism, this code does not attempt
   894  // to reset the record size once the connection is idle, however.
   895  func (c *Conn) maxPayloadSizeForWrite(typ recordType) int {
   896  	if c.config.DynamicRecordSizingDisabled || typ != recordTypeApplicationData {
   897  		return maxPlaintext
   898  	}
   899  
   900  	if c.bytesSent >= recordSizeBoostThreshold {
   901  		return maxPlaintext
   902  	}
   903  
   904  	// Subtract TLS overheads to get the maximum payload size.
   905  	payloadBytes := tcpMSSEstimate - recordHeaderLen - c.out.explicitNonceLen()
   906  	if c.out.cipher != nil {
   907  		switch ciph := c.out.cipher.(type) {
   908  		case cipher.Stream:
   909  			payloadBytes -= c.out.mac.Size()
   910  		case cipher.AEAD:
   911  			payloadBytes -= ciph.Overhead()
   912  		case cbcMode:
   913  			blockSize := ciph.BlockSize()
   914  			// The payload must fit in a multiple of blockSize, with
   915  			// room for at least one padding byte.
   916  			payloadBytes = (payloadBytes & ^(blockSize - 1)) - 1
   917  			// The MAC is appended before padding so affects the
   918  			// payload size directly.
   919  			payloadBytes -= c.out.mac.Size()
   920  		default:
   921  			panic("unknown cipher type")
   922  		}
   923  	}
   924  	if c.vers == VersionTLS13 {
   925  		payloadBytes-- // encrypted ContentType
   926  	}
   927  
   928  	// Allow packet growth in arithmetic progression up to max.
   929  	pkt := c.packetsSent
   930  	c.packetsSent++
   931  	if pkt > 1000 {
   932  		return maxPlaintext // avoid overflow in multiply below
   933  	}
   934  
   935  	n := payloadBytes * int(pkt+1)
   936  	if n > maxPlaintext {
   937  		n = maxPlaintext
   938  	}
   939  	return n
   940  }
   941  
   942  func (c *Conn) write(data []byte) (int, error) {
   943  	if c.buffering {
   944  		c.sendBuf = append(c.sendBuf, data...)
   945  		return len(data), nil
   946  	}
   947  
   948  	n, err := c.conn.Write(data)
   949  	c.bytesSent += int64(n)
   950  	return n, err
   951  }
   952  
   953  func (c *Conn) flush() (int, error) {
   954  	if len(c.sendBuf) == 0 {
   955  		return 0, nil
   956  	}
   957  
   958  	n, err := c.conn.Write(c.sendBuf)
   959  	c.bytesSent += int64(n)
   960  	c.sendBuf = nil
   961  	c.buffering = false
   962  	return n, err
   963  }
   964  
   965  // outBufPool pools the record-sized scratch buffers used by writeRecordLocked.
   966  var outBufPool = sync.Pool{
   967  	New: func() any {
   968  		return new([]byte)
   969  	},
   970  }
   971  
   972  // writeRecordLocked writes a TLS record with the given type and payload to the
   973  // connection and updates the record layer state.
   974  func (c *Conn) writeRecordLocked(typ recordType, data []byte) (int, error) {
   975  	if c.quic != nil {
   976  		if typ != recordTypeHandshake {
   977  			return 0, errors.New("tls: internal error: sending non-handshake message to QUIC transport")
   978  		}
   979  		c.quicWriteCryptoData(c.out.level, data)
   980  		if !c.buffering {
   981  			if _, err := c.flush(); err != nil {
   982  				return 0, err
   983  			}
   984  		}
   985  		return len(data), nil
   986  	}
   987  
   988  	outBufPtr := outBufPool.Get().(*[]byte)
   989  	outBuf := *outBufPtr
   990  	defer func() {
   991  		// You might be tempted to simplify this by just passing &outBuf to Put,
   992  		// but that would make the local copy of the outBuf slice header escape
   993  		// to the heap, causing an allocation. Instead, we keep around the
   994  		// pointer to the slice header returned by Get, which is already on the
   995  		// heap, and overwrite and return that.
   996  		*outBufPtr = outBuf
   997  		outBufPool.Put(outBufPtr)
   998  	}()
   999  
  1000  	var n int
  1001  	for len(data) > 0 {
  1002  		m := len(data)
  1003  		if maxPayload := c.maxPayloadSizeForWrite(typ); m > maxPayload {
  1004  			m = maxPayload
  1005  		}
  1006  
  1007  		_, outBuf = sliceForAppend(outBuf[:0], recordHeaderLen)
  1008  		outBuf[0] = byte(typ)
  1009  		vers := c.vers
  1010  		if vers == 0 {
  1011  			// Some TLS servers fail if the record version is
  1012  			// greater than TLS 1.0 for the initial ClientHello.
  1013  			vers = VersionTLS10
  1014  		} else if vers == VersionTLS13 {
  1015  			// TLS 1.3 froze the record layer version to 1.2.
  1016  			// See RFC 8446, Section 5.1.
  1017  			vers = VersionTLS12
  1018  		}
  1019  		outBuf[1] = byte(vers >> 8)
  1020  		outBuf[2] = byte(vers)
  1021  		outBuf[3] = byte(m >> 8)
  1022  		outBuf[4] = byte(m)
  1023  
  1024  		var err error
  1025  		outBuf, err = c.out.encrypt(outBuf, data[:m], c.config.rand())
  1026  		if err != nil {
  1027  			return n, err
  1028  		}
  1029  		if _, err := c.write(outBuf); err != nil {
  1030  			return n, err
  1031  		}
  1032  		n += m
  1033  		data = data[m:]
  1034  	}
  1035  
  1036  	if typ == recordTypeChangeCipherSpec && c.vers != VersionTLS13 {
  1037  		if err := c.out.changeCipherSpec(); err != nil {
  1038  			return n, c.sendAlertLocked(err.(alert))
  1039  		}
  1040  	}
  1041  
  1042  	return n, nil
  1043  }
  1044  
  1045  // writeHandshakeRecord writes a handshake message to the connection and updates
  1046  // the record layer state. If transcript is non-nil the marshaled message is
  1047  // written to it.
  1048  func (c *Conn) writeHandshakeRecord(msg handshakeMessage, transcript transcriptHash) (int, error) {
  1049  	c.out.Lock()
  1050  	defer c.out.Unlock()
  1051  
  1052  	data, err := msg.marshal()
  1053  	if err != nil {
  1054  		return 0, err
  1055  	}
  1056  	if transcript != nil {
  1057  		transcript.Write(data)
  1058  	}
  1059  
  1060  	return c.writeRecordLocked(recordTypeHandshake, data)
  1061  }
  1062  
  1063  // writeChangeCipherRecord writes a ChangeCipherSpec message to the connection and
  1064  // updates the record layer state.
  1065  func (c *Conn) writeChangeCipherRecord() error {
  1066  	c.out.Lock()
  1067  	defer c.out.Unlock()
  1068  	_, err := c.writeRecordLocked(recordTypeChangeCipherSpec, []byte{1})
  1069  	return err
  1070  }
  1071  
  1072  // readHandshakeBytes reads handshake data until c.hand contains at least n bytes.
  1073  func (c *Conn) readHandshakeBytes(n int) error {
  1074  	if c.quic != nil {
  1075  		return c.quicReadHandshakeBytes(n)
  1076  	}
  1077  	for c.hand.Len() < n {
  1078  		if err := c.readRecord(); err != nil {
  1079  			return err
  1080  		}
  1081  	}
  1082  	return nil
  1083  }
  1084  
  1085  // readHandshake reads the next handshake message from
  1086  // the record layer. If transcript is non-nil, the message
  1087  // is written to the passed transcriptHash.
  1088  func (c *Conn) readHandshake(transcript transcriptHash) (any, error) {
  1089  	if err := c.readHandshakeBytes(4); err != nil {
  1090  		return nil, err
  1091  	}
  1092  	data := c.hand.Bytes()
  1093  
  1094  	maxHandshakeSize := maxHandshake
  1095  	// hasVers indicates we're past the first message, forcing someone trying to
  1096  	// make us just allocate a large buffer to at least do the initial part of
  1097  	// the handshake first.
  1098  	if c.haveVers && data[0] == typeCertificate {
  1099  		// Since certificate messages are likely to be the only messages that
  1100  		// can be larger than maxHandshake, we use a special limit for just
  1101  		// those messages.
  1102  		maxHandshakeSize = maxHandshakeCertificateMsg
  1103  	}
  1104  
  1105  	n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
  1106  	if n > maxHandshakeSize {
  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, maxHandshakeSize))
  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 [Conn.Handshake], in order to prevent indefinite blocking a deadline
  1193  // must be set for both [Conn.Read] and Write before Write is called when the handshake
  1194  // has not yet completed. See [Conn.SetDeadline], [Conn.SetReadDeadline], and
  1195  // [Conn.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 [Conn.Handshake], in order to prevent indefinite blocking a deadline
  1368  // must be set for both Read and [Conn.Write] before Read is called when the handshake
  1369  // has not yet completed. See [Conn.SetDeadline], [Conn.SetReadDeadline], and
  1370  // [Conn.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 [Conn.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 [Conn.Read] or [Conn.Write] will call it automatically.
  1483  //
  1484  // For control over canceling or setting a timeout on a handshake, use
  1485  // [Conn.HandshakeContext] or the [Dialer]'s DialContext method instead.
  1486  //
  1487  // In order to avoid denial of service attacks, the maximum RSA key size allowed
  1488  // in certificates sent by either the TLS server or client is limited to 8192
  1489  // bits. This limit can be overridden by setting tlsmaxrsasize in the GODEBUG
  1490  // environment variable (e.g. GODEBUG=tlsmaxrsasize=4096).
  1491  func (c *Conn) Handshake() error {
  1492  	return c.HandshakeContext(context.Background())
  1493  }
  1494  
  1495  // HandshakeContext runs the client or server handshake
  1496  // protocol if it has not yet been run.
  1497  //
  1498  // The provided Context must be non-nil. If the context is canceled before
  1499  // the handshake is complete, the handshake is interrupted and an error is returned.
  1500  // Once the handshake has completed, cancellation of the context will not affect the
  1501  // connection.
  1502  //
  1503  // Most uses of this package need not call HandshakeContext explicitly: the
  1504  // first [Conn.Read] or [Conn.Write] will call it automatically.
  1505  func (c *Conn) HandshakeContext(ctx context.Context) error {
  1506  	// Delegate to unexported method for named return
  1507  	// without confusing documented signature.
  1508  	return c.handshakeContext(ctx)
  1509  }
  1510  
  1511  func (c *Conn) handshakeContext(ctx context.Context) (ret error) {
  1512  	// Fast sync/atomic-based exit if there is no handshake in flight and the
  1513  	// last one succeeded without an error. Avoids the expensive context setup
  1514  	// and mutex for most Read and Write calls.
  1515  	if c.isHandshakeComplete.Load() {
  1516  		return nil
  1517  	}
  1518  
  1519  	handshakeCtx, cancel := context.WithCancel(ctx)
  1520  	// Note: defer this before starting the "interrupter" goroutine
  1521  	// so that we can tell the difference between the input being canceled and
  1522  	// this cancellation. In the former case, we need to close the connection.
  1523  	defer cancel()
  1524  
  1525  	if c.quic != nil {
  1526  		c.quic.cancelc = handshakeCtx.Done()
  1527  		c.quic.cancel = cancel
  1528  	} else if ctx.Done() != nil {
  1529  		// Start the "interrupter" goroutine, if this context might be canceled.
  1530  		// (The background context cannot).
  1531  		//
  1532  		// The interrupter goroutine waits for the input context to be done and
  1533  		// closes the connection if this happens before the function returns.
  1534  		done := make(chan struct{})
  1535  		interruptRes := make(chan error, 1)
  1536  		defer func() {
  1537  			close(done)
  1538  			if ctxErr := <-interruptRes; ctxErr != nil {
  1539  				// Return context error to user.
  1540  				ret = ctxErr
  1541  			}
  1542  		}()
  1543  		go func() {
  1544  			select {
  1545  			case <-handshakeCtx.Done():
  1546  				// Close the connection, discarding the error
  1547  				_ = c.conn.Close()
  1548  				interruptRes <- handshakeCtx.Err()
  1549  			case <-done:
  1550  				interruptRes <- nil
  1551  			}
  1552  		}()
  1553  	}
  1554  
  1555  	c.handshakeMutex.Lock()
  1556  	defer c.handshakeMutex.Unlock()
  1557  
  1558  	if err := c.handshakeErr; err != nil {
  1559  		return err
  1560  	}
  1561  	if c.isHandshakeComplete.Load() {
  1562  		return nil
  1563  	}
  1564  
  1565  	c.in.Lock()
  1566  	defer c.in.Unlock()
  1567  
  1568  	c.handshakeErr = c.handshakeFn(handshakeCtx)
  1569  	if c.handshakeErr == nil {
  1570  		c.handshakes++
  1571  	} else {
  1572  		// If an error occurred during the handshake try to flush the
  1573  		// alert that might be left in the buffer.
  1574  		c.flush()
  1575  	}
  1576  
  1577  	if c.handshakeErr == nil && !c.isHandshakeComplete.Load() {
  1578  		c.handshakeErr = errors.New("tls: internal error: handshake should have had a result")
  1579  	}
  1580  	if c.handshakeErr != nil && c.isHandshakeComplete.Load() {
  1581  		panic("tls: internal error: handshake returned an error but is marked successful")
  1582  	}
  1583  
  1584  	if c.quic != nil {
  1585  		if c.handshakeErr == nil {
  1586  			c.quicHandshakeComplete()
  1587  			// Provide the 1-RTT read secret now that the handshake is complete.
  1588  			// The QUIC layer MUST NOT decrypt 1-RTT packets prior to completing
  1589  			// the handshake (RFC 9001, Section 5.7).
  1590  			c.quicSetReadSecret(QUICEncryptionLevelApplication, c.cipherSuite, c.in.trafficSecret)
  1591  		} else {
  1592  			var a alert
  1593  			c.out.Lock()
  1594  			if !errors.As(c.out.err, &a) {
  1595  				a = alertInternalError
  1596  			}
  1597  			c.out.Unlock()
  1598  			// Return an error which wraps both the handshake error and
  1599  			// any alert error we may have sent, or alertInternalError
  1600  			// if we didn't send an alert.
  1601  			// Truncate the text of the alert to 0 characters.
  1602  			c.handshakeErr = fmt.Errorf("%w%.0w", c.handshakeErr, AlertError(a))
  1603  		}
  1604  		close(c.quic.blockedc)
  1605  		close(c.quic.signalc)
  1606  	}
  1607  
  1608  	return c.handshakeErr
  1609  }
  1610  
  1611  // ConnectionState returns basic TLS details about the connection.
  1612  func (c *Conn) ConnectionState() ConnectionState {
  1613  	c.handshakeMutex.Lock()
  1614  	defer c.handshakeMutex.Unlock()
  1615  	return c.connectionStateLocked()
  1616  }
  1617  
  1618  var tlsunsafeekm = godebug.New("tlsunsafeekm")
  1619  
  1620  func (c *Conn) connectionStateLocked() ConnectionState {
  1621  	var state ConnectionState
  1622  	state.HandshakeComplete = c.isHandshakeComplete.Load()
  1623  	state.Version = c.vers
  1624  	state.NegotiatedProtocol = c.clientProtocol
  1625  	state.DidResume = c.didResume
  1626  	state.testingOnlyDidHRR = c.didHRR
  1627  	// c.curveID is not set on TLS 1.0–1.2 resumptions. Fix that before exposing it.
  1628  	state.testingOnlyCurveID = c.curveID
  1629  	state.NegotiatedProtocolIsMutual = true
  1630  	state.ServerName = c.serverName
  1631  	state.CipherSuite = c.cipherSuite
  1632  	state.PeerCertificates = c.peerCertificates
  1633  	state.VerifiedChains = c.verifiedChains
  1634  	state.SignedCertificateTimestamps = c.scts
  1635  	state.OCSPResponse = c.ocspResponse
  1636  	if (!c.didResume || c.extMasterSecret) && c.vers != VersionTLS13 {
  1637  		if c.clientFinishedIsFirst {
  1638  			state.TLSUnique = c.clientFinished[:]
  1639  		} else {
  1640  			state.TLSUnique = c.serverFinished[:]
  1641  		}
  1642  	}
  1643  	if c.config.Renegotiation != RenegotiateNever {
  1644  		state.ekm = noEKMBecauseRenegotiation
  1645  	} else if c.vers != VersionTLS13 && !c.extMasterSecret {
  1646  		state.ekm = func(label string, context []byte, length int) ([]byte, error) {
  1647  			if tlsunsafeekm.Value() == "1" {
  1648  				tlsunsafeekm.IncNonDefault()
  1649  				return c.ekm(label, context, length)
  1650  			}
  1651  			return noEKMBecauseNoEMS(label, context, length)
  1652  		}
  1653  	} else {
  1654  		state.ekm = c.ekm
  1655  	}
  1656  	state.ECHAccepted = c.echAccepted
  1657  	return state
  1658  }
  1659  
  1660  // OCSPResponse returns the stapled OCSP response from the TLS server, if
  1661  // any. (Only valid for client connections.)
  1662  func (c *Conn) OCSPResponse() []byte {
  1663  	c.handshakeMutex.Lock()
  1664  	defer c.handshakeMutex.Unlock()
  1665  
  1666  	return c.ocspResponse
  1667  }
  1668  
  1669  // VerifyHostname checks that the peer certificate chain is valid for
  1670  // connecting to host. If so, it returns nil; if not, it returns an error
  1671  // describing the problem.
  1672  func (c *Conn) VerifyHostname(host string) error {
  1673  	c.handshakeMutex.Lock()
  1674  	defer c.handshakeMutex.Unlock()
  1675  	if !c.isClient {
  1676  		return errors.New("tls: VerifyHostname called on TLS server connection")
  1677  	}
  1678  	if !c.isHandshakeComplete.Load() {
  1679  		return errors.New("tls: handshake has not yet been performed")
  1680  	}
  1681  	if len(c.verifiedChains) == 0 {
  1682  		return errors.New("tls: handshake did not verify certificate chain")
  1683  	}
  1684  	return c.peerCertificates[0].VerifyHostname(host)
  1685  }
  1686  

View as plain text