...

Source file src/crypto/tls/conn.go

Documentation: crypto/tls

     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  //
   594  // During the handshake one and only one of the following will happen:
   595  //   - c.hand grows
   596  //   - c.in.changeCipherSpec is called
   597  //   - an error is returned
   598  //
   599  // After the handshake one and only one of the following will happen:
   600  //   - c.hand grows
   601  //   - c.input is set
   602  //   - an error is returned
   603  func (c *Conn) readRecordOrCCS(expectChangeCipherSpec bool) error {
   604  	if c.in.err != nil {
   605  		return c.in.err
   606  	}
   607  	handshakeComplete := c.handshakeComplete()
   608  
   609  	// This function modifies c.rawInput, which owns the c.input memory.
   610  	if c.input.Len() != 0 {
   611  		return c.in.setErrorLocked(errors.New("tls: internal error: attempted to read record with pending application data"))
   612  	}
   613  	c.input.Reset(nil)
   614  
   615  	// Read header, payload.
   616  	if err := c.readFromUntil(c.conn, recordHeaderLen); err != nil {
   617  		// RFC 8446, Section 6.1 suggests that EOF without an alertCloseNotify
   618  		// is an error, but popular web sites seem to do this, so we accept it
   619  		// if and only if at the record boundary.
   620  		if err == io.ErrUnexpectedEOF && c.rawInput.Len() == 0 {
   621  			err = io.EOF
   622  		}
   623  		if e, ok := err.(net.Error); !ok || !e.Temporary() {
   624  			c.in.setErrorLocked(err)
   625  		}
   626  		return err
   627  	}
   628  	hdr := c.rawInput.Bytes()[:recordHeaderLen]
   629  	typ := recordType(hdr[0])
   630  
   631  	// No valid TLS record has a type of 0x80, however SSLv2 handshakes
   632  	// start with a uint16 length where the MSB is set and the first record
   633  	// is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
   634  	// an SSLv2 client.
   635  	if !handshakeComplete && typ == 0x80 {
   636  		c.sendAlert(alertProtocolVersion)
   637  		return c.in.setErrorLocked(c.newRecordHeaderError(nil, "unsupported SSLv2 handshake received"))
   638  	}
   639  
   640  	vers := uint16(hdr[1])<<8 | uint16(hdr[2])
   641  	n := int(hdr[3])<<8 | int(hdr[4])
   642  	if c.haveVers && c.vers != VersionTLS13 && vers != c.vers {
   643  		c.sendAlert(alertProtocolVersion)
   644  		msg := fmt.Sprintf("received record with version %x when expecting version %x", vers, c.vers)
   645  		return c.in.setErrorLocked(c.newRecordHeaderError(nil, msg))
   646  	}
   647  	if !c.haveVers {
   648  		// First message, be extra suspicious: this might not be a TLS
   649  		// client. Bail out before reading a full 'body', if possible.
   650  		// The current max version is 3.3 so if the version is >= 16.0,
   651  		// it's probably not real.
   652  		if (typ != recordTypeAlert && typ != recordTypeHandshake) || vers >= 0x1000 {
   653  			return c.in.setErrorLocked(c.newRecordHeaderError(c.conn, "first record does not look like a TLS handshake"))
   654  		}
   655  	}
   656  	if c.vers == VersionTLS13 && n > maxCiphertextTLS13 || n > maxCiphertext {
   657  		c.sendAlert(alertRecordOverflow)
   658  		msg := fmt.Sprintf("oversized record received with length %d", n)
   659  		return c.in.setErrorLocked(c.newRecordHeaderError(nil, msg))
   660  	}
   661  	if err := c.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
   662  		if e, ok := err.(net.Error); !ok || !e.Temporary() {
   663  			c.in.setErrorLocked(err)
   664  		}
   665  		return err
   666  	}
   667  
   668  	// Process message.
   669  	record := c.rawInput.Next(recordHeaderLen + n)
   670  	data, typ, err := c.in.decrypt(record)
   671  	if err != nil {
   672  		return c.in.setErrorLocked(c.sendAlert(err.(alert)))
   673  	}
   674  	if len(data) > maxPlaintext {
   675  		return c.in.setErrorLocked(c.sendAlert(alertRecordOverflow))
   676  	}
   677  
   678  	// Application Data messages are always protected.
   679  	if c.in.cipher == nil && typ == recordTypeApplicationData {
   680  		return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   681  	}
   682  
   683  	if typ != recordTypeAlert && typ != recordTypeChangeCipherSpec && len(data) > 0 {
   684  		// This is a state-advancing message: reset the retry count.
   685  		c.retryCount = 0
   686  	}
   687  
   688  	// Handshake messages MUST NOT be interleaved with other record types in TLS 1.3.
   689  	if c.vers == VersionTLS13 && typ != recordTypeHandshake && c.hand.Len() > 0 {
   690  		return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   691  	}
   692  
   693  	switch typ {
   694  	default:
   695  		return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   696  
   697  	case recordTypeAlert:
   698  		if len(data) != 2 {
   699  			return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   700  		}
   701  		if alert(data[1]) == alertCloseNotify {
   702  			return c.in.setErrorLocked(io.EOF)
   703  		}
   704  		if c.vers == VersionTLS13 {
   705  			return c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
   706  		}
   707  		switch data[0] {
   708  		case alertLevelWarning:
   709  			// Drop the record on the floor and retry.
   710  			return c.retryReadRecord(expectChangeCipherSpec)
   711  		case alertLevelError:
   712  			return c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
   713  		default:
   714  			return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   715  		}
   716  
   717  	case recordTypeChangeCipherSpec:
   718  		if len(data) != 1 || data[0] != 1 {
   719  			return c.in.setErrorLocked(c.sendAlert(alertDecodeError))
   720  		}
   721  		// Handshake messages are not allowed to fragment across the CCS.
   722  		if c.hand.Len() > 0 {
   723  			return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   724  		}
   725  		// In TLS 1.3, change_cipher_spec records are ignored until the
   726  		// Finished. See RFC 8446, Appendix D.4. Note that according to Section
   727  		// 5, a server can send a ChangeCipherSpec before its ServerHello, when
   728  		// c.vers is still unset. That's not useful though and suspicious if the
   729  		// server then selects a lower protocol version, so don't allow that.
   730  		if c.vers == VersionTLS13 {
   731  			return c.retryReadRecord(expectChangeCipherSpec)
   732  		}
   733  		if !expectChangeCipherSpec {
   734  			return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   735  		}
   736  		if err := c.in.changeCipherSpec(); err != nil {
   737  			return c.in.setErrorLocked(c.sendAlert(err.(alert)))
   738  		}
   739  
   740  	case recordTypeApplicationData:
   741  		if !handshakeComplete || expectChangeCipherSpec {
   742  			return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   743  		}
   744  		// Some OpenSSL servers send empty records in order to randomize the
   745  		// CBC IV. Ignore a limited number of empty records.
   746  		if len(data) == 0 {
   747  			return c.retryReadRecord(expectChangeCipherSpec)
   748  		}
   749  		// Note that data is owned by c.rawInput, following the Next call above,
   750  		// to avoid copying the plaintext. This is safe because c.rawInput is
   751  		// not read from or written to until c.input is drained.
   752  		c.input.Reset(data)
   753  
   754  	case recordTypeHandshake:
   755  		if len(data) == 0 || expectChangeCipherSpec {
   756  			return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   757  		}
   758  		c.hand.Write(data)
   759  	}
   760  
   761  	return nil
   762  }
   763  
   764  // retryReadRecord recurs into readRecordOrCCS to drop a non-advancing record, like
   765  // a warning alert, empty application_data, or a change_cipher_spec in TLS 1.3.
   766  func (c *Conn) retryReadRecord(expectChangeCipherSpec bool) error {
   767  	c.retryCount++
   768  	if c.retryCount > maxUselessRecords {
   769  		c.sendAlert(alertUnexpectedMessage)
   770  		return c.in.setErrorLocked(errors.New("tls: too many ignored records"))
   771  	}
   772  	return c.readRecordOrCCS(expectChangeCipherSpec)
   773  }
   774  
   775  // atLeastReader reads from R, stopping with EOF once at least N bytes have been
   776  // read. It is different from an io.LimitedReader in that it doesn't cut short
   777  // the last Read call, and in that it considers an early EOF an error.
   778  type atLeastReader struct {
   779  	R io.Reader
   780  	N int64
   781  }
   782  
   783  func (r *atLeastReader) Read(p []byte) (int, error) {
   784  	if r.N <= 0 {
   785  		return 0, io.EOF
   786  	}
   787  	n, err := r.R.Read(p)
   788  	r.N -= int64(n) // won't underflow unless len(p) >= n > 9223372036854775809
   789  	if r.N > 0 && err == io.EOF {
   790  		return n, io.ErrUnexpectedEOF
   791  	}
   792  	if r.N <= 0 && err == nil {
   793  		return n, io.EOF
   794  	}
   795  	return n, err
   796  }
   797  
   798  // readFromUntil reads from r into c.rawInput until c.rawInput contains
   799  // at least n bytes or else returns an error.
   800  func (c *Conn) readFromUntil(r io.Reader, n int) error {
   801  	if c.rawInput.Len() >= n {
   802  		return nil
   803  	}
   804  	needs := n - c.rawInput.Len()
   805  	// There might be extra input waiting on the wire. Make a best effort
   806  	// attempt to fetch it so that it can be used in (*Conn).Read to
   807  	// "predict" closeNotify alerts.
   808  	c.rawInput.Grow(needs + bytes.MinRead)
   809  	_, err := c.rawInput.ReadFrom(&atLeastReader{r, int64(needs)})
   810  	return err
   811  }
   812  
   813  // sendAlert sends a TLS alert message.
   814  func (c *Conn) sendAlertLocked(err alert) error {
   815  	switch err {
   816  	case alertNoRenegotiation, alertCloseNotify:
   817  		c.tmp[0] = alertLevelWarning
   818  	default:
   819  		c.tmp[0] = alertLevelError
   820  	}
   821  	c.tmp[1] = byte(err)
   822  
   823  	_, writeErr := c.writeRecordLocked(recordTypeAlert, c.tmp[0:2])
   824  	if err == alertCloseNotify {
   825  		// closeNotify is a special case in that it isn't an error.
   826  		return writeErr
   827  	}
   828  
   829  	return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
   830  }
   831  
   832  // sendAlert sends a TLS alert message.
   833  func (c *Conn) sendAlert(err alert) error {
   834  	c.out.Lock()
   835  	defer c.out.Unlock()
   836  	return c.sendAlertLocked(err)
   837  }
   838  
   839  const (
   840  	// tcpMSSEstimate is a conservative estimate of the TCP maximum segment
   841  	// size (MSS). A constant is used, rather than querying the kernel for
   842  	// the actual MSS, to avoid complexity. The value here is the IPv6
   843  	// minimum MTU (1280 bytes) minus the overhead of an IPv6 header (40
   844  	// bytes) and a TCP header with timestamps (32 bytes).
   845  	tcpMSSEstimate = 1208
   846  
   847  	// recordSizeBoostThreshold is the number of bytes of application data
   848  	// sent after which the TLS record size will be increased to the
   849  	// maximum.
   850  	recordSizeBoostThreshold = 128 * 1024
   851  )
   852  
   853  // maxPayloadSizeForWrite returns the maximum TLS payload size to use for the
   854  // next application data record. There is the following trade-off:
   855  //
   856  //   - For latency-sensitive applications, such as web browsing, each TLS
   857  //     record should fit in one TCP segment.
   858  //   - For throughput-sensitive applications, such as large file transfers,
   859  //     larger TLS records better amortize framing and encryption overheads.
   860  //
   861  // A simple heuristic that works well in practice is to use small records for
   862  // the first 1MB of data, then use larger records for subsequent data, and
   863  // reset back to smaller records after the connection becomes idle. See "High
   864  // Performance Web Networking", Chapter 4, or:
   865  // https://www.igvita.com/2013/10/24/optimizing-tls-record-size-and-buffering-latency/
   866  //
   867  // In the interests of simplicity and determinism, this code does not attempt
   868  // to reset the record size once the connection is idle, however.
   869  func (c *Conn) maxPayloadSizeForWrite(typ recordType) int {
   870  	if c.config.DynamicRecordSizingDisabled || typ != recordTypeApplicationData {
   871  		return maxPlaintext
   872  	}
   873  
   874  	if c.bytesSent >= recordSizeBoostThreshold {
   875  		return maxPlaintext
   876  	}
   877  
   878  	// Subtract TLS overheads to get the maximum payload size.
   879  	payloadBytes := tcpMSSEstimate - recordHeaderLen - c.out.explicitNonceLen()
   880  	if c.out.cipher != nil {
   881  		switch ciph := c.out.cipher.(type) {
   882  		case cipher.Stream:
   883  			payloadBytes -= c.out.mac.Size()
   884  		case cipher.AEAD:
   885  			payloadBytes -= ciph.Overhead()
   886  		case cbcMode:
   887  			blockSize := ciph.BlockSize()
   888  			// The payload must fit in a multiple of blockSize, with
   889  			// room for at least one padding byte.
   890  			payloadBytes = (payloadBytes & ^(blockSize - 1)) - 1
   891  			// The MAC is appended before padding so affects the
   892  			// payload size directly.
   893  			payloadBytes -= c.out.mac.Size()
   894  		default:
   895  			panic("unknown cipher type")
   896  		}
   897  	}
   898  	if c.vers == VersionTLS13 {
   899  		payloadBytes-- // encrypted ContentType
   900  	}
   901  
   902  	// Allow packet growth in arithmetic progression up to max.
   903  	pkt := c.packetsSent
   904  	c.packetsSent++
   905  	if pkt > 1000 {
   906  		return maxPlaintext // avoid overflow in multiply below
   907  	}
   908  
   909  	n := payloadBytes * int(pkt+1)
   910  	if n > maxPlaintext {
   911  		n = maxPlaintext
   912  	}
   913  	return n
   914  }
   915  
   916  func (c *Conn) write(data []byte) (int, error) {
   917  	if c.buffering {
   918  		c.sendBuf = append(c.sendBuf, data...)
   919  		return len(data), nil
   920  	}
   921  
   922  	n, err := c.conn.Write(data)
   923  	c.bytesSent += int64(n)
   924  	return n, err
   925  }
   926  
   927  func (c *Conn) flush() (int, error) {
   928  	if len(c.sendBuf) == 0 {
   929  		return 0, nil
   930  	}
   931  
   932  	n, err := c.conn.Write(c.sendBuf)
   933  	c.bytesSent += int64(n)
   934  	c.sendBuf = nil
   935  	c.buffering = false
   936  	return n, err
   937  }
   938  
   939  // outBufPool pools the record-sized scratch buffers used by writeRecordLocked.
   940  var outBufPool = sync.Pool{
   941  	New: func() any {
   942  		return new([]byte)
   943  	},
   944  }
   945  
   946  // writeRecordLocked writes a TLS record with the given type and payload to the
   947  // connection and updates the record layer state.
   948  func (c *Conn) writeRecordLocked(typ recordType, data []byte) (int, error) {
   949  	outBufPtr := outBufPool.Get().(*[]byte)
   950  	outBuf := *outBufPtr
   951  	defer func() {
   952  		// You might be tempted to simplify this by just passing &outBuf to Put,
   953  		// but that would make the local copy of the outBuf slice header escape
   954  		// to the heap, causing an allocation. Instead, we keep around the
   955  		// pointer to the slice header returned by Get, which is already on the
   956  		// heap, and overwrite and return that.
   957  		*outBufPtr = outBuf
   958  		outBufPool.Put(outBufPtr)
   959  	}()
   960  
   961  	var n int
   962  	for len(data) > 0 {
   963  		m := len(data)
   964  		if maxPayload := c.maxPayloadSizeForWrite(typ); m > maxPayload {
   965  			m = maxPayload
   966  		}
   967  
   968  		_, outBuf = sliceForAppend(outBuf[:0], recordHeaderLen)
   969  		outBuf[0] = byte(typ)
   970  		vers := c.vers
   971  		if vers == 0 {
   972  			// Some TLS servers fail if the record version is
   973  			// greater than TLS 1.0 for the initial ClientHello.
   974  			vers = VersionTLS10
   975  		} else if vers == VersionTLS13 {
   976  			// TLS 1.3 froze the record layer version to 1.2.
   977  			// See RFC 8446, Section 5.1.
   978  			vers = VersionTLS12
   979  		}
   980  		outBuf[1] = byte(vers >> 8)
   981  		outBuf[2] = byte(vers)
   982  		outBuf[3] = byte(m >> 8)
   983  		outBuf[4] = byte(m)
   984  
   985  		var err error
   986  		outBuf, err = c.out.encrypt(outBuf, data[:m], c.config.rand())
   987  		if err != nil {
   988  			return n, err
   989  		}
   990  		if _, err := c.write(outBuf); err != nil {
   991  			return n, err
   992  		}
   993  		n += m
   994  		data = data[m:]
   995  	}
   996  
   997  	if typ == recordTypeChangeCipherSpec && c.vers != VersionTLS13 {
   998  		if err := c.out.changeCipherSpec(); err != nil {
   999  			return n, c.sendAlertLocked(err.(alert))
  1000  		}
  1001  	}
  1002  
  1003  	return n, nil
  1004  }
  1005  
  1006  // writeRecord writes a TLS record with the given type and payload to the
  1007  // connection and updates the record layer state.
  1008  func (c *Conn) writeRecord(typ recordType, data []byte) (int, error) {
  1009  	c.out.Lock()
  1010  	defer c.out.Unlock()
  1011  
  1012  	return c.writeRecordLocked(typ, data)
  1013  }
  1014  
  1015  // readHandshake reads the next handshake message from
  1016  // the record layer.
  1017  func (c *Conn) readHandshake() (any, error) {
  1018  	for c.hand.Len() < 4 {
  1019  		if err := c.readRecord(); err != nil {
  1020  			return nil, err
  1021  		}
  1022  	}
  1023  
  1024  	data := c.hand.Bytes()
  1025  	n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
  1026  	if n > maxHandshake {
  1027  		c.sendAlertLocked(alertInternalError)
  1028  		return nil, c.in.setErrorLocked(fmt.Errorf("tls: handshake message of length %d bytes exceeds maximum of %d bytes", n, maxHandshake))
  1029  	}
  1030  	for c.hand.Len() < 4+n {
  1031  		if err := c.readRecord(); err != nil {
  1032  			return nil, err
  1033  		}
  1034  	}
  1035  	data = c.hand.Next(4 + n)
  1036  	var m handshakeMessage
  1037  	switch data[0] {
  1038  	case typeHelloRequest:
  1039  		m = new(helloRequestMsg)
  1040  	case typeClientHello:
  1041  		m = new(clientHelloMsg)
  1042  	case typeServerHello:
  1043  		m = new(serverHelloMsg)
  1044  	case typeNewSessionTicket:
  1045  		if c.vers == VersionTLS13 {
  1046  			m = new(newSessionTicketMsgTLS13)
  1047  		} else {
  1048  			m = new(newSessionTicketMsg)
  1049  		}
  1050  	case typeCertificate:
  1051  		if c.vers == VersionTLS13 {
  1052  			m = new(certificateMsgTLS13)
  1053  		} else {
  1054  			m = new(certificateMsg)
  1055  		}
  1056  	case typeCertificateRequest:
  1057  		if c.vers == VersionTLS13 {
  1058  			m = new(certificateRequestMsgTLS13)
  1059  		} else {
  1060  			m = &certificateRequestMsg{
  1061  				hasSignatureAlgorithm: c.vers >= VersionTLS12,
  1062  			}
  1063  		}
  1064  	case typeCertificateStatus:
  1065  		m = new(certificateStatusMsg)
  1066  	case typeServerKeyExchange:
  1067  		m = new(serverKeyExchangeMsg)
  1068  	case typeServerHelloDone:
  1069  		m = new(serverHelloDoneMsg)
  1070  	case typeClientKeyExchange:
  1071  		m = new(clientKeyExchangeMsg)
  1072  	case typeCertificateVerify:
  1073  		m = &certificateVerifyMsg{
  1074  			hasSignatureAlgorithm: c.vers >= VersionTLS12,
  1075  		}
  1076  	case typeFinished:
  1077  		m = new(finishedMsg)
  1078  	case typeEncryptedExtensions:
  1079  		m = new(encryptedExtensionsMsg)
  1080  	case typeEndOfEarlyData:
  1081  		m = new(endOfEarlyDataMsg)
  1082  	case typeKeyUpdate:
  1083  		m = new(keyUpdateMsg)
  1084  	default:
  1085  		return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  1086  	}
  1087  
  1088  	// The handshake message unmarshalers
  1089  	// expect to be able to keep references to data,
  1090  	// so pass in a fresh copy that won't be overwritten.
  1091  	data = append([]byte(nil), data...)
  1092  
  1093  	if !m.unmarshal(data) {
  1094  		return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  1095  	}
  1096  	return m, nil
  1097  }
  1098  
  1099  var (
  1100  	errShutdown = errors.New("tls: protocol is shutdown")
  1101  )
  1102  
  1103  // Write writes data to the connection.
  1104  //
  1105  // As Write calls Handshake, in order to prevent indefinite blocking a deadline
  1106  // must be set for both Read and Write before Write is called when the handshake
  1107  // has not yet completed. See SetDeadline, SetReadDeadline, and
  1108  // SetWriteDeadline.
  1109  func (c *Conn) Write(b []byte) (int, error) {
  1110  	// interlock with Close below
  1111  	for {
  1112  		x := atomic.LoadInt32(&c.activeCall)
  1113  		if x&1 != 0 {
  1114  			return 0, net.ErrClosed
  1115  		}
  1116  		if atomic.CompareAndSwapInt32(&c.activeCall, x, x+2) {
  1117  			break
  1118  		}
  1119  	}
  1120  	defer atomic.AddInt32(&c.activeCall, -2)
  1121  
  1122  	if err := c.Handshake(); err != nil {
  1123  		return 0, err
  1124  	}
  1125  
  1126  	c.out.Lock()
  1127  	defer c.out.Unlock()
  1128  
  1129  	if err := c.out.err; err != nil {
  1130  		return 0, err
  1131  	}
  1132  
  1133  	if !c.handshakeComplete() {
  1134  		return 0, alertInternalError
  1135  	}
  1136  
  1137  	if c.closeNotifySent {
  1138  		return 0, errShutdown
  1139  	}
  1140  
  1141  	// TLS 1.0 is susceptible to a chosen-plaintext
  1142  	// attack when using block mode ciphers due to predictable IVs.
  1143  	// This can be prevented by splitting each Application Data
  1144  	// record into two records, effectively randomizing the IV.
  1145  	//
  1146  	// https://www.openssl.org/~bodo/tls-cbc.txt
  1147  	// https://bugzilla.mozilla.org/show_bug.cgi?id=665814
  1148  	// https://www.imperialviolet.org/2012/01/15/beastfollowup.html
  1149  
  1150  	var m int
  1151  	if len(b) > 1 && c.vers == VersionTLS10 {
  1152  		if _, ok := c.out.cipher.(cipher.BlockMode); ok {
  1153  			n, err := c.writeRecordLocked(recordTypeApplicationData, b[:1])
  1154  			if err != nil {
  1155  				return n, c.out.setErrorLocked(err)
  1156  			}
  1157  			m, b = 1, b[1:]
  1158  		}
  1159  	}
  1160  
  1161  	n, err := c.writeRecordLocked(recordTypeApplicationData, b)
  1162  	return n + m, c.out.setErrorLocked(err)
  1163  }
  1164  
  1165  // handleRenegotiation processes a HelloRequest handshake message.
  1166  func (c *Conn) handleRenegotiation() error {
  1167  	if c.vers == VersionTLS13 {
  1168  		return errors.New("tls: internal error: unexpected renegotiation")
  1169  	}
  1170  
  1171  	msg, err := c.readHandshake()
  1172  	if err != nil {
  1173  		return err
  1174  	}
  1175  
  1176  	helloReq, ok := msg.(*helloRequestMsg)
  1177  	if !ok {
  1178  		c.sendAlert(alertUnexpectedMessage)
  1179  		return unexpectedMessageError(helloReq, msg)
  1180  	}
  1181  
  1182  	if !c.isClient {
  1183  		return c.sendAlert(alertNoRenegotiation)
  1184  	}
  1185  
  1186  	switch c.config.Renegotiation {
  1187  	case RenegotiateNever:
  1188  		return c.sendAlert(alertNoRenegotiation)
  1189  	case RenegotiateOnceAsClient:
  1190  		if c.handshakes > 1 {
  1191  			return c.sendAlert(alertNoRenegotiation)
  1192  		}
  1193  	case RenegotiateFreelyAsClient:
  1194  		// Ok.
  1195  	default:
  1196  		c.sendAlert(alertInternalError)
  1197  		return errors.New("tls: unknown Renegotiation value")
  1198  	}
  1199  
  1200  	c.handshakeMutex.Lock()
  1201  	defer c.handshakeMutex.Unlock()
  1202  
  1203  	atomic.StoreUint32(&c.handshakeStatus, 0)
  1204  	if c.handshakeErr = c.clientHandshake(context.Background()); c.handshakeErr == nil {
  1205  		c.handshakes++
  1206  	}
  1207  	return c.handshakeErr
  1208  }
  1209  
  1210  // handlePostHandshakeMessage processes a handshake message arrived after the
  1211  // handshake is complete. Up to TLS 1.2, it indicates the start of a renegotiation.
  1212  func (c *Conn) handlePostHandshakeMessage() error {
  1213  	if c.vers != VersionTLS13 {
  1214  		return c.handleRenegotiation()
  1215  	}
  1216  
  1217  	msg, err := c.readHandshake()
  1218  	if err != nil {
  1219  		return err
  1220  	}
  1221  
  1222  	c.retryCount++
  1223  	if c.retryCount > maxUselessRecords {
  1224  		c.sendAlert(alertUnexpectedMessage)
  1225  		return c.in.setErrorLocked(errors.New("tls: too many non-advancing records"))
  1226  	}
  1227  
  1228  	switch msg := msg.(type) {
  1229  	case *newSessionTicketMsgTLS13:
  1230  		return c.handleNewSessionTicket(msg)
  1231  	case *keyUpdateMsg:
  1232  		return c.handleKeyUpdate(msg)
  1233  	default:
  1234  		c.sendAlert(alertUnexpectedMessage)
  1235  		return fmt.Errorf("tls: received unexpected handshake message of type %T", msg)
  1236  	}
  1237  }
  1238  
  1239  func (c *Conn) handleKeyUpdate(keyUpdate *keyUpdateMsg) error {
  1240  	cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite)
  1241  	if cipherSuite == nil {
  1242  		return c.in.setErrorLocked(c.sendAlert(alertInternalError))
  1243  	}
  1244  
  1245  	newSecret := cipherSuite.nextTrafficSecret(c.in.trafficSecret)
  1246  	c.in.setTrafficSecret(cipherSuite, newSecret)
  1247  
  1248  	if keyUpdate.updateRequested {
  1249  		c.out.Lock()
  1250  		defer c.out.Unlock()
  1251  
  1252  		msg := &keyUpdateMsg{}
  1253  		_, err := c.writeRecordLocked(recordTypeHandshake, msg.marshal())
  1254  		if err != nil {
  1255  			// Surface the error at the next write.
  1256  			c.out.setErrorLocked(err)
  1257  			return nil
  1258  		}
  1259  
  1260  		newSecret := cipherSuite.nextTrafficSecret(c.out.trafficSecret)
  1261  		c.out.setTrafficSecret(cipherSuite, newSecret)
  1262  	}
  1263  
  1264  	return nil
  1265  }
  1266  
  1267  // Read reads data from the connection.
  1268  //
  1269  // As Read calls Handshake, in order to prevent indefinite blocking a deadline
  1270  // must be set for both Read and Write before Read is called when the handshake
  1271  // has not yet completed. See SetDeadline, SetReadDeadline, and
  1272  // SetWriteDeadline.
  1273  func (c *Conn) Read(b []byte) (int, error) {
  1274  	if err := c.Handshake(); err != nil {
  1275  		return 0, err
  1276  	}
  1277  	if len(b) == 0 {
  1278  		// Put this after Handshake, in case people were calling
  1279  		// Read(nil) for the side effect of the Handshake.
  1280  		return 0, nil
  1281  	}
  1282  
  1283  	c.in.Lock()
  1284  	defer c.in.Unlock()
  1285  
  1286  	for c.input.Len() == 0 {
  1287  		if err := c.readRecord(); err != nil {
  1288  			return 0, err
  1289  		}
  1290  		for c.hand.Len() > 0 {
  1291  			if err := c.handlePostHandshakeMessage(); err != nil {
  1292  				return 0, err
  1293  			}
  1294  		}
  1295  	}
  1296  
  1297  	n, _ := c.input.Read(b)
  1298  
  1299  	// If a close-notify alert is waiting, read it so that we can return (n,
  1300  	// EOF) instead of (n, nil), to signal to the HTTP response reading
  1301  	// goroutine that the connection is now closed. This eliminates a race
  1302  	// where the HTTP response reading goroutine would otherwise not observe
  1303  	// the EOF until its next read, by which time a client goroutine might
  1304  	// have already tried to reuse the HTTP connection for a new request.
  1305  	// See https://golang.org/cl/76400046 and https://golang.org/issue/3514
  1306  	if n != 0 && c.input.Len() == 0 && c.rawInput.Len() > 0 &&
  1307  		recordType(c.rawInput.Bytes()[0]) == recordTypeAlert {
  1308  		if err := c.readRecord(); err != nil {
  1309  			return n, err // will be io.EOF on closeNotify
  1310  		}
  1311  	}
  1312  
  1313  	return n, nil
  1314  }
  1315  
  1316  // Close closes the connection.
  1317  func (c *Conn) Close() error {
  1318  	// Interlock with Conn.Write above.
  1319  	var x int32
  1320  	for {
  1321  		x = atomic.LoadInt32(&c.activeCall)
  1322  		if x&1 != 0 {
  1323  			return net.ErrClosed
  1324  		}
  1325  		if atomic.CompareAndSwapInt32(&c.activeCall, x, x|1) {
  1326  			break
  1327  		}
  1328  	}
  1329  	if x != 0 {
  1330  		// io.Writer and io.Closer should not be used concurrently.
  1331  		// If Close is called while a Write is currently in-flight,
  1332  		// interpret that as a sign that this Close is really just
  1333  		// being used to break the Write and/or clean up resources and
  1334  		// avoid sending the alertCloseNotify, which may block
  1335  		// waiting on handshakeMutex or the c.out mutex.
  1336  		return c.conn.Close()
  1337  	}
  1338  
  1339  	var alertErr error
  1340  	if c.handshakeComplete() {
  1341  		if err := c.closeNotify(); err != nil {
  1342  			alertErr = fmt.Errorf("tls: failed to send closeNotify alert (but connection was closed anyway): %w", err)
  1343  		}
  1344  	}
  1345  
  1346  	if err := c.conn.Close(); err != nil {
  1347  		return err
  1348  	}
  1349  	return alertErr
  1350  }
  1351  
  1352  var errEarlyCloseWrite = errors.New("tls: CloseWrite called before handshake complete")
  1353  
  1354  // CloseWrite shuts down the writing side of the connection. It should only be
  1355  // called once the handshake has completed and does not call CloseWrite on the
  1356  // underlying connection. Most callers should just use Close.
  1357  func (c *Conn) CloseWrite() error {
  1358  	if !c.handshakeComplete() {
  1359  		return errEarlyCloseWrite
  1360  	}
  1361  
  1362  	return c.closeNotify()
  1363  }
  1364  
  1365  func (c *Conn) closeNotify() error {
  1366  	c.out.Lock()
  1367  	defer c.out.Unlock()
  1368  
  1369  	if !c.closeNotifySent {
  1370  		// Set a Write Deadline to prevent possibly blocking forever.
  1371  		c.SetWriteDeadline(time.Now().Add(time.Second * 5))
  1372  		c.closeNotifyErr = c.sendAlertLocked(alertCloseNotify)
  1373  		c.closeNotifySent = true
  1374  		// Any subsequent writes will fail.
  1375  		c.SetWriteDeadline(time.Now())
  1376  	}
  1377  	return c.closeNotifyErr
  1378  }
  1379  
  1380  // Handshake runs the client or server handshake
  1381  // protocol if it has not yet been run.
  1382  //
  1383  // Most uses of this package need not call Handshake explicitly: the
  1384  // first Read or Write will call it automatically.
  1385  //
  1386  // For control over canceling or setting a timeout on a handshake, use
  1387  // HandshakeContext or the Dialer's DialContext method instead.
  1388  func (c *Conn) Handshake() error {
  1389  	return c.HandshakeContext(context.Background())
  1390  }
  1391  
  1392  // HandshakeContext runs the client or server handshake
  1393  // protocol if it has not yet been run.
  1394  //
  1395  // The provided Context must be non-nil. If the context is canceled before
  1396  // the handshake is complete, the handshake is interrupted and an error is returned.
  1397  // Once the handshake has completed, cancellation of the context will not affect the
  1398  // connection.
  1399  //
  1400  // Most uses of this package need not call HandshakeContext explicitly: the
  1401  // first Read or Write will call it automatically.
  1402  func (c *Conn) HandshakeContext(ctx context.Context) error {
  1403  	// Delegate to unexported method for named return
  1404  	// without confusing documented signature.
  1405  	return c.handshakeContext(ctx)
  1406  }
  1407  
  1408  func (c *Conn) handshakeContext(ctx context.Context) (ret error) {
  1409  	// Fast sync/atomic-based exit if there is no handshake in flight and the
  1410  	// last one succeeded without an error. Avoids the expensive context setup
  1411  	// and mutex for most Read and Write calls.
  1412  	if c.handshakeComplete() {
  1413  		return nil
  1414  	}
  1415  
  1416  	handshakeCtx, cancel := context.WithCancel(ctx)
  1417  	// Note: defer this before starting the "interrupter" goroutine
  1418  	// so that we can tell the difference between the input being canceled and
  1419  	// this cancellation. In the former case, we need to close the connection.
  1420  	defer cancel()
  1421  
  1422  	// Start the "interrupter" goroutine, if this context might be canceled.
  1423  	// (The background context cannot).
  1424  	//
  1425  	// The interrupter goroutine waits for the input context to be done and
  1426  	// closes the connection if this happens before the function returns.
  1427  	if ctx.Done() != nil {
  1428  		done := make(chan struct{})
  1429  		interruptRes := make(chan error, 1)
  1430  		defer func() {
  1431  			close(done)
  1432  			if ctxErr := <-interruptRes; ctxErr != nil {
  1433  				// Return context error to user.
  1434  				ret = ctxErr
  1435  			}
  1436  		}()
  1437  		go func() {
  1438  			select {
  1439  			case <-handshakeCtx.Done():
  1440  				// Close the connection, discarding the error
  1441  				_ = c.conn.Close()
  1442  				interruptRes <- handshakeCtx.Err()
  1443  			case <-done:
  1444  				interruptRes <- nil
  1445  			}
  1446  		}()
  1447  	}
  1448  
  1449  	c.handshakeMutex.Lock()
  1450  	defer c.handshakeMutex.Unlock()
  1451  
  1452  	if err := c.handshakeErr; err != nil {
  1453  		return err
  1454  	}
  1455  	if c.handshakeComplete() {
  1456  		return nil
  1457  	}
  1458  
  1459  	c.in.Lock()
  1460  	defer c.in.Unlock()
  1461  
  1462  	c.handshakeErr = c.handshakeFn(handshakeCtx)
  1463  	if c.handshakeErr == nil {
  1464  		c.handshakes++
  1465  	} else {
  1466  		// If an error occurred during the handshake try to flush the
  1467  		// alert that might be left in the buffer.
  1468  		c.flush()
  1469  	}
  1470  
  1471  	if c.handshakeErr == nil && !c.handshakeComplete() {
  1472  		c.handshakeErr = errors.New("tls: internal error: handshake should have had a result")
  1473  	}
  1474  	if c.handshakeErr != nil && c.handshakeComplete() {
  1475  		panic("tls: internal error: handshake returned an error but is marked successful")
  1476  	}
  1477  
  1478  	return c.handshakeErr
  1479  }
  1480  
  1481  // ConnectionState returns basic TLS details about the connection.
  1482  func (c *Conn) ConnectionState() ConnectionState {
  1483  	c.handshakeMutex.Lock()
  1484  	defer c.handshakeMutex.Unlock()
  1485  	return c.connectionStateLocked()
  1486  }
  1487  
  1488  func (c *Conn) connectionStateLocked() ConnectionState {
  1489  	var state ConnectionState
  1490  	state.HandshakeComplete = c.handshakeComplete()
  1491  	state.Version = c.vers
  1492  	state.NegotiatedProtocol = c.clientProtocol
  1493  	state.DidResume = c.didResume
  1494  	state.NegotiatedProtocolIsMutual = true
  1495  	state.ServerName = c.serverName
  1496  	state.CipherSuite = c.cipherSuite
  1497  	state.PeerCertificates = c.peerCertificates
  1498  	state.VerifiedChains = c.verifiedChains
  1499  	state.SignedCertificateTimestamps = c.scts
  1500  	state.OCSPResponse = c.ocspResponse
  1501  	if !c.didResume && c.vers != VersionTLS13 {
  1502  		if c.clientFinishedIsFirst {
  1503  			state.TLSUnique = c.clientFinished[:]
  1504  		} else {
  1505  			state.TLSUnique = c.serverFinished[:]
  1506  		}
  1507  	}
  1508  	if c.config.Renegotiation != RenegotiateNever {
  1509  		state.ekm = noExportedKeyingMaterial
  1510  	} else {
  1511  		state.ekm = c.ekm
  1512  	}
  1513  	return state
  1514  }
  1515  
  1516  // OCSPResponse returns the stapled OCSP response from the TLS server, if
  1517  // any. (Only valid for client connections.)
  1518  func (c *Conn) OCSPResponse() []byte {
  1519  	c.handshakeMutex.Lock()
  1520  	defer c.handshakeMutex.Unlock()
  1521  
  1522  	return c.ocspResponse
  1523  }
  1524  
  1525  // VerifyHostname checks that the peer certificate chain is valid for
  1526  // connecting to host. If so, it returns nil; if not, it returns an error
  1527  // describing the problem.
  1528  func (c *Conn) VerifyHostname(host string) error {
  1529  	c.handshakeMutex.Lock()
  1530  	defer c.handshakeMutex.Unlock()
  1531  	if !c.isClient {
  1532  		return errors.New("tls: VerifyHostname called on TLS server connection")
  1533  	}
  1534  	if !c.handshakeComplete() {
  1535  		return errors.New("tls: handshake has not yet been performed")
  1536  	}
  1537  	if len(c.verifiedChains) == 0 {
  1538  		return errors.New("tls: handshake did not verify certificate chain")
  1539  	}
  1540  	return c.peerCertificates[0].VerifyHostname(host)
  1541  }
  1542  
  1543  func (c *Conn) handshakeComplete() bool {
  1544  	return atomic.LoadUint32(&c.handshakeStatus) == 1
  1545  }
  1546  

View as plain text