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