github.com/goproxy0/go@v0.0.0-20171111080102-49cc0c489d2c/src/crypto/tls/conn.go (about)

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