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

View as plain text