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