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

View as plain text