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

View as plain text