...

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

View as plain text