github.com/ooni/psiphon/tunnel-core@v0.0.0-20230105123940-fe12a24c96ee/oovendor/qtls-go1-18/conn.go (about)

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