Black Lives Matter. Support the Equal Justice Initiative.

Source file src/crypto/tls/conn.go

Documentation: crypto/tls

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

View as plain text