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

View as plain text