Home | History | Annotate | Download | only in runner
      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 runner
      8 
      9 import (
     10 	"bytes"
     11 	"crypto/cipher"
     12 	"crypto/ecdsa"
     13 	"crypto/subtle"
     14 	"crypto/x509"
     15 	"encoding/binary"
     16 	"errors"
     17 	"fmt"
     18 	"io"
     19 	"net"
     20 	"sync"
     21 	"time"
     22 )
     23 
     24 var errNoCertificateAlert = errors.New("tls: no certificate alert")
     25 var errEndOfEarlyDataAlert = errors.New("tls: end of early data alert")
     26 
     27 // A Conn represents a secured connection.
     28 // It implements the net.Conn interface.
     29 type Conn struct {
     30 	// constant
     31 	conn     net.Conn
     32 	isDTLS   bool
     33 	isClient bool
     34 
     35 	// constant after handshake; protected by handshakeMutex
     36 	handshakeMutex       sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
     37 	handshakeErr         error      // error resulting from handshake
     38 	wireVersion          uint16     // TLS wire version
     39 	vers                 uint16     // TLS version
     40 	haveVers             bool       // version has been negotiated
     41 	config               *Config    // configuration passed to constructor
     42 	handshakeComplete    bool
     43 	skipEarlyData        bool // On a server, indicates that the client is sending early data that must be skipped over.
     44 	didResume            bool // whether this connection was a session resumption
     45 	extendedMasterSecret bool // whether this session used an extended master secret
     46 	cipherSuite          *cipherSuite
     47 	earlyCipherSuite     *cipherSuite
     48 	ocspResponse         []byte // stapled OCSP response
     49 	sctList              []byte // signed certificate timestamp list
     50 	peerCertificates     []*x509.Certificate
     51 	// verifiedChains contains the certificate chains that we built, as
     52 	// opposed to the ones presented by the server.
     53 	verifiedChains [][]*x509.Certificate
     54 	// serverName contains the server name indicated by the client, if any.
     55 	serverName string
     56 	// firstFinished contains the first Finished hash sent during the
     57 	// handshake. This is the "tls-unique" channel binding value.
     58 	firstFinished [12]byte
     59 	// peerSignatureAlgorithm contains the signature algorithm that was used
     60 	// by the peer in the handshake, or zero if not applicable.
     61 	peerSignatureAlgorithm signatureAlgorithm
     62 	// curveID contains the curve that was used in the handshake, or zero if
     63 	// not applicable.
     64 	curveID CurveID
     65 	// quicTransportParams contains the QUIC transport params received
     66 	// by the peer.
     67 	quicTransportParams []byte
     68 
     69 	clientRandom, serverRandom [32]byte
     70 	earlyExporterSecret        []byte
     71 	exporterSecret             []byte
     72 	resumptionSecret           []byte
     73 
     74 	clientProtocol         string
     75 	clientProtocolFallback bool
     76 	usedALPN               bool
     77 
     78 	// verify_data values for the renegotiation extension.
     79 	clientVerify []byte
     80 	serverVerify []byte
     81 
     82 	channelID *ecdsa.PublicKey
     83 
     84 	tokenBindingNegotiated bool
     85 	tokenBindingParam      uint8
     86 
     87 	srtpProtectionProfile uint16
     88 
     89 	clientVersion uint16
     90 
     91 	// input/output
     92 	in, out  halfConn     // in.Mutex < out.Mutex
     93 	rawInput *block       // raw input, right off the wire
     94 	input    *block       // application record waiting to be read
     95 	hand     bytes.Buffer // handshake record waiting to be read
     96 
     97 	// pendingFlight, if PackHandshakeFlight is enabled, is the buffer of
     98 	// handshake data to be split into records at the end of the flight.
     99 	pendingFlight bytes.Buffer
    100 
    101 	// DTLS state
    102 	sendHandshakeSeq uint16
    103 	recvHandshakeSeq uint16
    104 	handMsg          []byte   // pending assembled handshake message
    105 	handMsgLen       int      // handshake message length, not including the header
    106 	pendingFragments [][]byte // pending outgoing handshake fragments.
    107 	pendingPacket    []byte   // pending outgoing packet.
    108 
    109 	keyUpdateSeen      bool
    110 	keyUpdateRequested bool
    111 	seenOneByteRecord  bool
    112 
    113 	expectTLS13ChangeCipherSpec bool
    114 
    115 	// seenHandshakePackEnd is whether the most recent handshake record was
    116 	// not full for ExpectPackedEncryptedHandshake. If true, no more
    117 	// handshake data may be received until the next flight or epoch change.
    118 	seenHandshakePackEnd bool
    119 
    120 	tmp [16]byte
    121 }
    122 
    123 func (c *Conn) init() {
    124 	c.in.isDTLS = c.isDTLS
    125 	c.out.isDTLS = c.isDTLS
    126 	c.in.config = c.config
    127 	c.out.config = c.config
    128 
    129 	c.out.updateOutSeq()
    130 }
    131 
    132 // Access to net.Conn methods.
    133 // Cannot just embed net.Conn because that would
    134 // export the struct field too.
    135 
    136 // LocalAddr returns the local network address.
    137 func (c *Conn) LocalAddr() net.Addr {
    138 	return c.conn.LocalAddr()
    139 }
    140 
    141 // RemoteAddr returns the remote network address.
    142 func (c *Conn) RemoteAddr() net.Addr {
    143 	return c.conn.RemoteAddr()
    144 }
    145 
    146 // SetDeadline sets the read and write deadlines associated with the connection.
    147 // A zero value for t means Read and Write will not time out.
    148 // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
    149 func (c *Conn) SetDeadline(t time.Time) error {
    150 	return c.conn.SetDeadline(t)
    151 }
    152 
    153 // SetReadDeadline sets the read deadline on the underlying connection.
    154 // A zero value for t means Read will not time out.
    155 func (c *Conn) SetReadDeadline(t time.Time) error {
    156 	return c.conn.SetReadDeadline(t)
    157 }
    158 
    159 // SetWriteDeadline sets the write deadline on the underlying conneciton.
    160 // A zero value for t means Write will not time out.
    161 // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
    162 func (c *Conn) SetWriteDeadline(t time.Time) error {
    163 	return c.conn.SetWriteDeadline(t)
    164 }
    165 
    166 // A halfConn represents one direction of the record layer
    167 // connection, either sending or receiving.
    168 type halfConn struct {
    169 	sync.Mutex
    170 
    171 	err         error  // first permanent error
    172 	version     uint16 // protocol version
    173 	wireVersion uint16 // wire version
    174 	isDTLS      bool
    175 	cipher      interface{} // cipher algorithm
    176 	mac         macFunction
    177 	seq         [8]byte // 64-bit sequence number
    178 	outSeq      [8]byte // Mapped sequence number
    179 	bfree       *block  // list of free blocks
    180 
    181 	nextCipher interface{} // next encryption state
    182 	nextMac    macFunction // next MAC algorithm
    183 	nextSeq    [6]byte     // next epoch's starting sequence number in DTLS
    184 
    185 	// used to save allocating a new buffer for each MAC.
    186 	inDigestBuf, outDigestBuf []byte
    187 
    188 	trafficSecret []byte
    189 
    190 	config *Config
    191 }
    192 
    193 func (hc *halfConn) setErrorLocked(err error) error {
    194 	hc.err = err
    195 	return err
    196 }
    197 
    198 func (hc *halfConn) error() error {
    199 	// This should be locked, but I've removed it for the renegotiation
    200 	// tests since we don't concurrently read and write the same tls.Conn
    201 	// in any case during testing.
    202 	err := hc.err
    203 	return err
    204 }
    205 
    206 // prepareCipherSpec sets the encryption and MAC states
    207 // that a subsequent changeCipherSpec will use.
    208 func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
    209 	hc.wireVersion = version
    210 	protocolVersion, ok := wireToVersion(version, hc.isDTLS)
    211 	if !ok {
    212 		panic("TLS: unknown version")
    213 	}
    214 	hc.version = protocolVersion
    215 	hc.nextCipher = cipher
    216 	hc.nextMac = mac
    217 }
    218 
    219 // changeCipherSpec changes the encryption and MAC states
    220 // to the ones previously passed to prepareCipherSpec.
    221 func (hc *halfConn) changeCipherSpec(config *Config) error {
    222 	if hc.nextCipher == nil {
    223 		return alertInternalError
    224 	}
    225 	hc.cipher = hc.nextCipher
    226 	hc.mac = hc.nextMac
    227 	hc.nextCipher = nil
    228 	hc.nextMac = nil
    229 	hc.config = config
    230 	hc.incEpoch()
    231 
    232 	if config.Bugs.NullAllCiphers {
    233 		hc.cipher = nullCipher{}
    234 		hc.mac = nil
    235 	}
    236 	return nil
    237 }
    238 
    239 // useTrafficSecret sets the current cipher state for TLS 1.3.
    240 func (hc *halfConn) useTrafficSecret(version uint16, suite *cipherSuite, secret []byte, side trafficDirection) {
    241 	hc.wireVersion = version
    242 	protocolVersion, ok := wireToVersion(version, hc.isDTLS)
    243 	if !ok {
    244 		panic("TLS: unknown version")
    245 	}
    246 	hc.version = protocolVersion
    247 	hc.cipher = deriveTrafficAEAD(version, suite, secret, side)
    248 	if hc.config.Bugs.NullAllCiphers {
    249 		hc.cipher = nullCipher{}
    250 	}
    251 	hc.trafficSecret = secret
    252 	hc.incEpoch()
    253 }
    254 
    255 // resetCipher changes the cipher state back to no encryption to be able
    256 // to send an unencrypted ClientHello in response to HelloRetryRequest
    257 // after 0-RTT data was rejected.
    258 func (hc *halfConn) resetCipher() {
    259 	hc.cipher = nil
    260 	hc.incEpoch()
    261 }
    262 
    263 // incSeq increments the sequence number.
    264 func (hc *halfConn) incSeq(isOutgoing bool) {
    265 	limit := 0
    266 	increment := uint64(1)
    267 	if hc.isDTLS {
    268 		// Increment up to the epoch in DTLS.
    269 		limit = 2
    270 	}
    271 	for i := 7; i >= limit; i-- {
    272 		increment += uint64(hc.seq[i])
    273 		hc.seq[i] = byte(increment)
    274 		increment >>= 8
    275 	}
    276 
    277 	// Not allowed to let sequence number wrap.
    278 	// Instead, must renegotiate before it does.
    279 	// Not likely enough to bother.
    280 	if increment != 0 {
    281 		panic("TLS: sequence number wraparound")
    282 	}
    283 
    284 	hc.updateOutSeq()
    285 }
    286 
    287 // incNextSeq increments the starting sequence number for the next epoch.
    288 func (hc *halfConn) incNextSeq() {
    289 	for i := len(hc.nextSeq) - 1; i >= 0; i-- {
    290 		hc.nextSeq[i]++
    291 		if hc.nextSeq[i] != 0 {
    292 			return
    293 		}
    294 	}
    295 	panic("TLS: sequence number wraparound")
    296 }
    297 
    298 // incEpoch resets the sequence number. In DTLS, it also increments the epoch
    299 // half of the sequence number.
    300 func (hc *halfConn) incEpoch() {
    301 	if hc.isDTLS {
    302 		for i := 1; i >= 0; i-- {
    303 			hc.seq[i]++
    304 			if hc.seq[i] != 0 {
    305 				break
    306 			}
    307 			if i == 0 {
    308 				panic("TLS: epoch number wraparound")
    309 			}
    310 		}
    311 		copy(hc.seq[2:], hc.nextSeq[:])
    312 		for i := range hc.nextSeq {
    313 			hc.nextSeq[i] = 0
    314 		}
    315 	} else {
    316 		for i := range hc.seq {
    317 			hc.seq[i] = 0
    318 		}
    319 	}
    320 
    321 	hc.updateOutSeq()
    322 }
    323 
    324 func (hc *halfConn) updateOutSeq() {
    325 	if hc.config.Bugs.SequenceNumberMapping != nil {
    326 		seqU64 := binary.BigEndian.Uint64(hc.seq[:])
    327 		seqU64 = hc.config.Bugs.SequenceNumberMapping(seqU64)
    328 		binary.BigEndian.PutUint64(hc.outSeq[:], seqU64)
    329 
    330 		// The DTLS epoch cannot be changed.
    331 		copy(hc.outSeq[:2], hc.seq[:2])
    332 		return
    333 	}
    334 
    335 	copy(hc.outSeq[:], hc.seq[:])
    336 }
    337 
    338 func (hc *halfConn) recordHeaderLen() int {
    339 	if hc.isDTLS {
    340 		return dtlsRecordHeaderLen
    341 	}
    342 	return tlsRecordHeaderLen
    343 }
    344 
    345 // removePadding returns an unpadded slice, in constant time, which is a prefix
    346 // of the input. It also returns a byte which is equal to 255 if the padding
    347 // was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
    348 func removePadding(payload []byte) ([]byte, byte) {
    349 	if len(payload) < 1 {
    350 		return payload, 0
    351 	}
    352 
    353 	paddingLen := payload[len(payload)-1]
    354 	t := uint(len(payload)-1) - uint(paddingLen)
    355 	// if len(payload) >= (paddingLen - 1) then the MSB of t is zero
    356 	good := byte(int32(^t) >> 31)
    357 
    358 	toCheck := 255 // the maximum possible padding length
    359 	// The length of the padded data is public, so we can use an if here
    360 	if toCheck+1 > len(payload) {
    361 		toCheck = len(payload) - 1
    362 	}
    363 
    364 	for i := 0; i < toCheck; i++ {
    365 		t := uint(paddingLen) - uint(i)
    366 		// if i <= paddingLen then the MSB of t is zero
    367 		mask := byte(int32(^t) >> 31)
    368 		b := payload[len(payload)-1-i]
    369 		good &^= mask&paddingLen ^ mask&b
    370 	}
    371 
    372 	// We AND together the bits of good and replicate the result across
    373 	// all the bits.
    374 	good &= good << 4
    375 	good &= good << 2
    376 	good &= good << 1
    377 	good = uint8(int8(good) >> 7)
    378 
    379 	toRemove := good&paddingLen + 1
    380 	return payload[:len(payload)-int(toRemove)], good
    381 }
    382 
    383 // removePaddingSSL30 is a replacement for removePadding in the case that the
    384 // protocol version is SSLv3. In this version, the contents of the padding
    385 // are random and cannot be checked.
    386 func removePaddingSSL30(payload []byte) ([]byte, byte) {
    387 	if len(payload) < 1 {
    388 		return payload, 0
    389 	}
    390 
    391 	paddingLen := int(payload[len(payload)-1]) + 1
    392 	if paddingLen > len(payload) {
    393 		return payload, 0
    394 	}
    395 
    396 	return payload[:len(payload)-paddingLen], 255
    397 }
    398 
    399 func roundUp(a, b int) int {
    400 	return a + (b-a%b)%b
    401 }
    402 
    403 // cbcMode is an interface for block ciphers using cipher block chaining.
    404 type cbcMode interface {
    405 	cipher.BlockMode
    406 	SetIV([]byte)
    407 }
    408 
    409 // decrypt checks and strips the mac and decrypts the data in b. Returns a
    410 // success boolean, the number of bytes to skip from the start of the record in
    411 // order to get the application payload, the encrypted record type (or 0
    412 // if there is none), and an optional alert value.
    413 func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, contentType recordType, alertValue alert) {
    414 	recordHeaderLen := hc.recordHeaderLen()
    415 
    416 	// pull out payload
    417 	payload := b.data[recordHeaderLen:]
    418 
    419 	macSize := 0
    420 	if hc.mac != nil {
    421 		macSize = hc.mac.Size()
    422 	}
    423 
    424 	paddingGood := byte(255)
    425 	explicitIVLen := 0
    426 
    427 	seq := hc.seq[:]
    428 	if hc.isDTLS {
    429 		// DTLS sequence numbers are explicit.
    430 		seq = b.data[3:11]
    431 	}
    432 
    433 	// decrypt
    434 	if hc.cipher != nil {
    435 		switch c := hc.cipher.(type) {
    436 		case cipher.Stream:
    437 			c.XORKeyStream(payload, payload)
    438 		case *tlsAead:
    439 			nonce := seq
    440 			if c.explicitNonce {
    441 				explicitIVLen = 8
    442 				if len(payload) < explicitIVLen {
    443 					return false, 0, 0, alertBadRecordMAC
    444 				}
    445 				nonce = payload[:8]
    446 				payload = payload[8:]
    447 			}
    448 
    449 			var additionalData []byte
    450 			if hc.version < VersionTLS13 {
    451 				additionalData = make([]byte, 13)
    452 				copy(additionalData, seq)
    453 				copy(additionalData[8:], b.data[:3])
    454 				n := len(payload) - c.Overhead()
    455 				additionalData[11] = byte(n >> 8)
    456 				additionalData[12] = byte(n)
    457 			} else {
    458 				additionalData = b.data[:recordHeaderLen]
    459 			}
    460 			var err error
    461 			payload, err = c.Open(payload[:0], nonce, payload, additionalData)
    462 			if err != nil {
    463 				return false, 0, 0, alertBadRecordMAC
    464 			}
    465 			b.resize(recordHeaderLen + explicitIVLen + len(payload))
    466 		case cbcMode:
    467 			blockSize := c.BlockSize()
    468 			if hc.version >= VersionTLS11 || hc.isDTLS {
    469 				explicitIVLen = blockSize
    470 			}
    471 
    472 			if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
    473 				return false, 0, 0, alertBadRecordMAC
    474 			}
    475 
    476 			if explicitIVLen > 0 {
    477 				c.SetIV(payload[:explicitIVLen])
    478 				payload = payload[explicitIVLen:]
    479 			}
    480 			c.CryptBlocks(payload, payload)
    481 			if hc.version == VersionSSL30 {
    482 				payload, paddingGood = removePaddingSSL30(payload)
    483 			} else {
    484 				payload, paddingGood = removePadding(payload)
    485 			}
    486 			b.resize(recordHeaderLen + explicitIVLen + len(payload))
    487 
    488 			// note that we still have a timing side-channel in the
    489 			// MAC check, below. An attacker can align the record
    490 			// so that a correct padding will cause one less hash
    491 			// block to be calculated. Then they can iteratively
    492 			// decrypt a record by breaking each byte. See
    493 			// "Password Interception in a SSL/TLS Channel", Brice
    494 			// Canvel et al.
    495 			//
    496 			// However, our behavior matches OpenSSL, so we leak
    497 			// only as much as they do.
    498 		case nullCipher:
    499 			break
    500 		default:
    501 			panic("unknown cipher type")
    502 		}
    503 
    504 		if hc.version >= VersionTLS13 {
    505 			i := len(payload)
    506 			for i > 0 && payload[i-1] == 0 {
    507 				i--
    508 			}
    509 			payload = payload[:i]
    510 			if len(payload) == 0 {
    511 				return false, 0, 0, alertUnexpectedMessage
    512 			}
    513 			contentType = recordType(payload[len(payload)-1])
    514 			payload = payload[:len(payload)-1]
    515 			b.resize(recordHeaderLen + len(payload))
    516 		}
    517 	}
    518 
    519 	// check, strip mac
    520 	if hc.mac != nil {
    521 		if len(payload) < macSize {
    522 			return false, 0, 0, alertBadRecordMAC
    523 		}
    524 
    525 		// strip mac off payload, b.data
    526 		n := len(payload) - macSize
    527 		b.data[recordHeaderLen-2] = byte(n >> 8)
    528 		b.data[recordHeaderLen-1] = byte(n)
    529 		b.resize(recordHeaderLen + explicitIVLen + n)
    530 		remoteMAC := payload[n:]
    531 		localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
    532 
    533 		if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
    534 			return false, 0, 0, alertBadRecordMAC
    535 		}
    536 		hc.inDigestBuf = localMAC
    537 	}
    538 	hc.incSeq(false)
    539 
    540 	return true, recordHeaderLen + explicitIVLen, contentType, 0
    541 }
    542 
    543 // padToBlockSize calculates the needed padding block, if any, for a payload.
    544 // On exit, prefix aliases payload and extends to the end of the last full
    545 // block of payload. finalBlock is a fresh slice which contains the contents of
    546 // any suffix of payload as well as the needed padding to make finalBlock a
    547 // full block.
    548 func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
    549 	overrun := len(payload) % blockSize
    550 	prefix = payload[:len(payload)-overrun]
    551 
    552 	paddingLen := blockSize - overrun
    553 	finalSize := blockSize
    554 	if config.Bugs.MaxPadding {
    555 		for paddingLen+blockSize <= 256 {
    556 			paddingLen += blockSize
    557 		}
    558 		finalSize = 256
    559 	}
    560 	finalBlock = make([]byte, finalSize)
    561 	for i := range finalBlock {
    562 		finalBlock[i] = byte(paddingLen - 1)
    563 	}
    564 	if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
    565 		finalBlock[overrun] ^= 0xff
    566 	}
    567 	copy(finalBlock, payload[len(payload)-overrun:])
    568 	return
    569 }
    570 
    571 // encrypt encrypts and macs the data in b.
    572 func (hc *halfConn) encrypt(b *block, explicitIVLen int, typ recordType) (bool, alert) {
    573 	recordHeaderLen := hc.recordHeaderLen()
    574 
    575 	// mac
    576 	if hc.mac != nil {
    577 		mac := hc.mac.MAC(hc.outDigestBuf, hc.outSeq[0:], b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], b.data[recordHeaderLen+explicitIVLen:])
    578 
    579 		n := len(b.data)
    580 		b.resize(n + len(mac))
    581 		copy(b.data[n:], mac)
    582 		hc.outDigestBuf = mac
    583 	}
    584 
    585 	payload := b.data[recordHeaderLen:]
    586 
    587 	// encrypt
    588 	if hc.cipher != nil {
    589 		// Add TLS 1.3 padding.
    590 		if hc.version >= VersionTLS13 {
    591 			paddingLen := hc.config.Bugs.RecordPadding
    592 			if hc.config.Bugs.OmitRecordContents {
    593 				b.resize(recordHeaderLen + paddingLen)
    594 			} else {
    595 				b.resize(len(b.data) + 1 + paddingLen)
    596 				b.data[len(b.data)-paddingLen-1] = byte(typ)
    597 			}
    598 			for i := 0; i < paddingLen; i++ {
    599 				b.data[len(b.data)-paddingLen+i] = 0
    600 			}
    601 		}
    602 
    603 		switch c := hc.cipher.(type) {
    604 		case cipher.Stream:
    605 			c.XORKeyStream(payload, payload)
    606 		case *tlsAead:
    607 			payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
    608 			b.resize(len(b.data) + c.Overhead())
    609 			nonce := hc.outSeq[:]
    610 			if c.explicitNonce {
    611 				nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
    612 			}
    613 			payload := b.data[recordHeaderLen+explicitIVLen:]
    614 			payload = payload[:payloadLen]
    615 
    616 			var additionalData []byte
    617 			if hc.version < VersionTLS13 {
    618 				additionalData = make([]byte, 13)
    619 				copy(additionalData, hc.outSeq[:])
    620 				copy(additionalData[8:], b.data[:3])
    621 				additionalData[11] = byte(payloadLen >> 8)
    622 				additionalData[12] = byte(payloadLen)
    623 			} else {
    624 				additionalData = make([]byte, 5)
    625 				copy(additionalData, b.data[:3])
    626 				n := len(b.data) - recordHeaderLen
    627 				additionalData[3] = byte(n >> 8)
    628 				additionalData[4] = byte(n)
    629 			}
    630 
    631 			c.Seal(payload[:0], nonce, payload, additionalData)
    632 		case cbcMode:
    633 			blockSize := c.BlockSize()
    634 			if explicitIVLen > 0 {
    635 				c.SetIV(payload[:explicitIVLen])
    636 				payload = payload[explicitIVLen:]
    637 			}
    638 			prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
    639 			b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
    640 			c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
    641 			c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
    642 		case nullCipher:
    643 			break
    644 		default:
    645 			panic("unknown cipher type")
    646 		}
    647 	}
    648 
    649 	// update length to include MAC and any block padding needed.
    650 	n := len(b.data) - recordHeaderLen
    651 	b.data[recordHeaderLen-2] = byte(n >> 8)
    652 	b.data[recordHeaderLen-1] = byte(n)
    653 	hc.incSeq(true)
    654 
    655 	return true, 0
    656 }
    657 
    658 // A block is a simple data buffer.
    659 type block struct {
    660 	data []byte
    661 	off  int // index for Read
    662 	link *block
    663 }
    664 
    665 // resize resizes block to be n bytes, growing if necessary.
    666 func (b *block) resize(n int) {
    667 	if n > cap(b.data) {
    668 		b.reserve(n)
    669 	}
    670 	b.data = b.data[0:n]
    671 }
    672 
    673 // reserve makes sure that block contains a capacity of at least n bytes.
    674 func (b *block) reserve(n int) {
    675 	if cap(b.data) >= n {
    676 		return
    677 	}
    678 	m := cap(b.data)
    679 	if m == 0 {
    680 		m = 1024
    681 	}
    682 	for m < n {
    683 		m *= 2
    684 	}
    685 	data := make([]byte, len(b.data), m)
    686 	copy(data, b.data)
    687 	b.data = data
    688 }
    689 
    690 // readFromUntil reads from r into b until b contains at least n bytes
    691 // or else returns an error.
    692 func (b *block) readFromUntil(r io.Reader, n int) error {
    693 	// quick case
    694 	if len(b.data) >= n {
    695 		return nil
    696 	}
    697 
    698 	// read until have enough.
    699 	b.reserve(n)
    700 	for {
    701 		m, err := r.Read(b.data[len(b.data):cap(b.data)])
    702 		b.data = b.data[0 : len(b.data)+m]
    703 		if len(b.data) >= n {
    704 			// TODO(bradfitz,agl): slightly suspicious
    705 			// that we're throwing away r.Read's err here.
    706 			break
    707 		}
    708 		if err != nil {
    709 			return err
    710 		}
    711 	}
    712 	return nil
    713 }
    714 
    715 func (b *block) Read(p []byte) (n int, err error) {
    716 	n = copy(p, b.data[b.off:])
    717 	b.off += n
    718 	return
    719 }
    720 
    721 // newBlock allocates a new block, from hc's free list if possible.
    722 func (hc *halfConn) newBlock() *block {
    723 	b := hc.bfree
    724 	if b == nil {
    725 		return new(block)
    726 	}
    727 	hc.bfree = b.link
    728 	b.link = nil
    729 	b.resize(0)
    730 	return b
    731 }
    732 
    733 // freeBlock returns a block to hc's free list.
    734 // The protocol is such that each side only has a block or two on
    735 // its free list at a time, so there's no need to worry about
    736 // trimming the list, etc.
    737 func (hc *halfConn) freeBlock(b *block) {
    738 	b.link = hc.bfree
    739 	hc.bfree = b
    740 }
    741 
    742 // splitBlock splits a block after the first n bytes,
    743 // returning a block with those n bytes and a
    744 // block with the remainder.  the latter may be nil.
    745 func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
    746 	if len(b.data) <= n {
    747 		return b, nil
    748 	}
    749 	bb := hc.newBlock()
    750 	bb.resize(len(b.data) - n)
    751 	copy(bb.data, b.data[n:])
    752 	b.data = b.data[0:n]
    753 	return b, bb
    754 }
    755 
    756 func (c *Conn) useInTrafficSecret(version uint16, suite *cipherSuite, secret []byte) error {
    757 	if c.hand.Len() != 0 {
    758 		return c.in.setErrorLocked(errors.New("tls: buffered handshake messages on cipher change"))
    759 	}
    760 	side := serverWrite
    761 	if !c.isClient {
    762 		side = clientWrite
    763 	}
    764 	c.in.useTrafficSecret(version, suite, secret, side)
    765 	c.seenHandshakePackEnd = false
    766 	return nil
    767 }
    768 
    769 func (c *Conn) useOutTrafficSecret(version uint16, suite *cipherSuite, secret []byte) {
    770 	side := serverWrite
    771 	if c.isClient {
    772 		side = clientWrite
    773 	}
    774 	c.out.useTrafficSecret(version, suite, secret, side)
    775 }
    776 
    777 func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
    778 RestartReadRecord:
    779 	if c.isDTLS {
    780 		return c.dtlsDoReadRecord(want)
    781 	}
    782 
    783 	recordHeaderLen := c.in.recordHeaderLen()
    784 
    785 	if c.rawInput == nil {
    786 		c.rawInput = c.in.newBlock()
    787 	}
    788 	b := c.rawInput
    789 
    790 	// Read header, payload.
    791 	if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
    792 		// RFC suggests that EOF without an alertCloseNotify is
    793 		// an error, but popular web sites seem to do this,
    794 		// so we can't make it an error, outside of tests.
    795 		if err == io.EOF && c.config.Bugs.ExpectCloseNotify {
    796 			err = io.ErrUnexpectedEOF
    797 		}
    798 		if e, ok := err.(net.Error); !ok || !e.Temporary() {
    799 			c.in.setErrorLocked(err)
    800 		}
    801 		return 0, nil, err
    802 	}
    803 
    804 	typ := recordType(b.data[0])
    805 
    806 	// No valid TLS record has a type of 0x80, however SSLv2 handshakes
    807 	// start with a uint16 length where the MSB is set and the first record
    808 	// is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
    809 	// an SSLv2 client.
    810 	if want == recordTypeHandshake && typ == 0x80 {
    811 		c.sendAlert(alertProtocolVersion)
    812 		return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
    813 	}
    814 
    815 	vers := uint16(b.data[1])<<8 | uint16(b.data[2])
    816 	n := int(b.data[3])<<8 | int(b.data[4])
    817 
    818 	// Alerts sent near version negotiation do not have a well-defined
    819 	// record-layer version prior to TLS 1.3. (In TLS 1.3, the record-layer
    820 	// version is irrelevant.)
    821 	if typ != recordTypeAlert {
    822 		var expect uint16
    823 		if c.haveVers {
    824 			expect = c.vers
    825 			if c.vers >= VersionTLS13 {
    826 				expect = VersionTLS12
    827 			}
    828 		} else {
    829 			expect = c.config.Bugs.ExpectInitialRecordVersion
    830 		}
    831 		if expect != 0 && vers != expect {
    832 			c.sendAlert(alertProtocolVersion)
    833 			return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
    834 		}
    835 	}
    836 	if n > maxCiphertext {
    837 		c.sendAlert(alertRecordOverflow)
    838 		return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
    839 	}
    840 	if !c.haveVers {
    841 		// First message, be extra suspicious:
    842 		// this might not be a TLS client.
    843 		// Bail out before reading a full 'body', if possible.
    844 		// The current max version is 3.1.
    845 		// If the version is >= 16.0, it's probably not real.
    846 		// Similarly, a clientHello message encodes in
    847 		// well under a kilobyte.  If the length is >= 12 kB,
    848 		// it's probably not real.
    849 		if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
    850 			c.sendAlert(alertUnexpectedMessage)
    851 			return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
    852 		}
    853 	}
    854 	if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
    855 		if err == io.EOF {
    856 			err = io.ErrUnexpectedEOF
    857 		}
    858 		if e, ok := err.(net.Error); !ok || !e.Temporary() {
    859 			c.in.setErrorLocked(err)
    860 		}
    861 		return 0, nil, err
    862 	}
    863 
    864 	// Process message.
    865 	b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
    866 	ok, off, encTyp, alertValue := c.in.decrypt(b)
    867 
    868 	// Handle skipping over early data.
    869 	if !ok && c.skipEarlyData {
    870 		goto RestartReadRecord
    871 	}
    872 
    873 	// If the server is expecting a second ClientHello (in response to
    874 	// a HelloRetryRequest) and the client sends early data, there
    875 	// won't be a decryption failure but it still needs to be skipped.
    876 	if c.in.cipher == nil && typ == recordTypeApplicationData && c.skipEarlyData {
    877 		goto RestartReadRecord
    878 	}
    879 
    880 	if !ok {
    881 		return 0, nil, c.in.setErrorLocked(c.sendAlert(alertValue))
    882 	}
    883 	b.off = off
    884 	c.skipEarlyData = false
    885 
    886 	if c.vers >= VersionTLS13 && c.in.cipher != nil {
    887 		if typ != recordTypeApplicationData {
    888 			return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: outer record type is not application data"))
    889 		}
    890 		typ = encTyp
    891 	}
    892 
    893 	length := len(b.data[b.off:])
    894 	if c.config.Bugs.ExpectRecordSplitting && typ == recordTypeApplicationData && length != 1 && !c.seenOneByteRecord {
    895 		return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: application data records were not split"))
    896 	}
    897 
    898 	c.seenOneByteRecord = typ == recordTypeApplicationData && length == 1
    899 	return typ, b, nil
    900 }
    901 
    902 func (c *Conn) readTLS13ChangeCipherSpec() error {
    903 	if !c.expectTLS13ChangeCipherSpec {
    904 		panic("c.expectTLS13ChangeCipherSpec not set")
    905 	}
    906 
    907 	// Read the ChangeCipherSpec.
    908 	if c.rawInput == nil {
    909 		c.rawInput = c.in.newBlock()
    910 	}
    911 	b := c.rawInput
    912 	if err := b.readFromUntil(c.conn, 1); err != nil {
    913 		return c.in.setErrorLocked(fmt.Errorf("tls: error reading TLS 1.3 ChangeCipherSpec: %s", err))
    914 	}
    915 	if recordType(b.data[0]) == recordTypeAlert {
    916 		// If the client is sending an alert, allow the ChangeCipherSpec
    917 		// to be skipped. It may be rejecting a sufficiently malformed
    918 		// ServerHello that it can't parse out the version.
    919 		c.expectTLS13ChangeCipherSpec = false
    920 		return nil
    921 	}
    922 	if err := b.readFromUntil(c.conn, 6); err != nil {
    923 		return c.in.setErrorLocked(fmt.Errorf("tls: error reading TLS 1.3 ChangeCipherSpec: %s", err))
    924 	}
    925 
    926 	// Check they match that we expect.
    927 	expected := [6]byte{byte(recordTypeChangeCipherSpec), 3, 1, 0, 1, 1}
    928 	if c.vers >= VersionTLS13 {
    929 		expected[2] = 3
    930 	}
    931 	if !bytes.Equal(b.data[:6], expected[:]) {
    932 		return c.in.setErrorLocked(fmt.Errorf("tls: error invalid TLS 1.3 ChangeCipherSpec: %x", b.data[:6]))
    933 	}
    934 
    935 	// Discard the data.
    936 	b, c.rawInput = c.in.splitBlock(b, 6)
    937 	c.in.freeBlock(b)
    938 
    939 	c.expectTLS13ChangeCipherSpec = false
    940 	return nil
    941 }
    942 
    943 // readRecord reads the next TLS record from the connection
    944 // and updates the record layer state.
    945 // c.in.Mutex <= L; c.input == nil.
    946 func (c *Conn) readRecord(want recordType) error {
    947 	// Caller must be in sync with connection:
    948 	// handshake data if handshake not yet completed,
    949 	// else application data.
    950 	switch want {
    951 	default:
    952 		c.sendAlert(alertInternalError)
    953 		return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
    954 	case recordTypeChangeCipherSpec:
    955 		if c.handshakeComplete {
    956 			c.sendAlert(alertInternalError)
    957 			return c.in.setErrorLocked(errors.New("tls: ChangeCipherSpec requested after handshake complete"))
    958 		}
    959 	case recordTypeApplicationData, recordTypeAlert, recordTypeHandshake:
    960 		break
    961 	}
    962 
    963 	if c.expectTLS13ChangeCipherSpec {
    964 		if err := c.readTLS13ChangeCipherSpec(); err != nil {
    965 			return err
    966 		}
    967 	}
    968 
    969 Again:
    970 	typ, b, err := c.doReadRecord(want)
    971 	if err != nil {
    972 		return err
    973 	}
    974 	data := b.data[b.off:]
    975 	max := maxPlaintext
    976 	if c.config.Bugs.MaxReceivePlaintext != 0 {
    977 		max = c.config.Bugs.MaxReceivePlaintext
    978 	}
    979 	if len(data) > max {
    980 		err := c.sendAlert(alertRecordOverflow)
    981 		c.in.freeBlock(b)
    982 		return c.in.setErrorLocked(err)
    983 	}
    984 
    985 	if typ != recordTypeHandshake {
    986 		c.seenHandshakePackEnd = false
    987 	} else if c.seenHandshakePackEnd {
    988 		c.in.freeBlock(b)
    989 		return c.in.setErrorLocked(errors.New("tls: peer violated ExpectPackedEncryptedHandshake"))
    990 	}
    991 
    992 	switch typ {
    993 	default:
    994 		c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
    995 
    996 	case recordTypeAlert:
    997 		if len(data) != 2 {
    998 			c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
    999 			break
   1000 		}
   1001 		if alert(data[1]) == alertCloseNotify {
   1002 			c.in.setErrorLocked(io.EOF)
   1003 			break
   1004 		}
   1005 		switch data[0] {
   1006 		case alertLevelWarning:
   1007 			if alert(data[1]) == alertNoCertificate {
   1008 				c.in.freeBlock(b)
   1009 				return errNoCertificateAlert
   1010 			}
   1011 			if alert(data[1]) == alertEndOfEarlyData {
   1012 				c.in.freeBlock(b)
   1013 				return errEndOfEarlyDataAlert
   1014 			}
   1015 
   1016 			// drop on the floor
   1017 			c.in.freeBlock(b)
   1018 			goto Again
   1019 		case alertLevelError:
   1020 			c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
   1021 		default:
   1022 			c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   1023 		}
   1024 
   1025 	case recordTypeChangeCipherSpec:
   1026 		if typ != want || len(data) != 1 || data[0] != 1 {
   1027 			c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   1028 			break
   1029 		}
   1030 		if c.hand.Len() != 0 {
   1031 			c.in.setErrorLocked(errors.New("tls: buffered handshake messages on cipher change"))
   1032 			break
   1033 		}
   1034 		if err := c.in.changeCipherSpec(c.config); err != nil {
   1035 			c.in.setErrorLocked(c.sendAlert(err.(alert)))
   1036 		}
   1037 
   1038 	case recordTypeApplicationData:
   1039 		if typ != want {
   1040 			c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   1041 			break
   1042 		}
   1043 		c.input = b
   1044 		b = nil
   1045 
   1046 	case recordTypeHandshake:
   1047 		// Allow handshake data while reading application data to
   1048 		// trigger post-handshake messages.
   1049 		// TODO(rsc): Should at least pick off connection close.
   1050 		if typ != want && want != recordTypeApplicationData {
   1051 			return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
   1052 		}
   1053 		c.hand.Write(data)
   1054 		if pack := c.config.Bugs.ExpectPackedEncryptedHandshake; pack > 0 && len(data) < pack && c.out.cipher != nil {
   1055 			c.seenHandshakePackEnd = true
   1056 		}
   1057 	}
   1058 
   1059 	if b != nil {
   1060 		c.in.freeBlock(b)
   1061 	}
   1062 	return c.in.err
   1063 }
   1064 
   1065 // sendAlert sends a TLS alert message.
   1066 // c.out.Mutex <= L.
   1067 func (c *Conn) sendAlertLocked(level byte, err alert) error {
   1068 	c.tmp[0] = level
   1069 	c.tmp[1] = byte(err)
   1070 	if c.config.Bugs.FragmentAlert {
   1071 		c.writeRecord(recordTypeAlert, c.tmp[0:1])
   1072 		c.writeRecord(recordTypeAlert, c.tmp[1:2])
   1073 	} else if c.config.Bugs.DoubleAlert {
   1074 		copy(c.tmp[2:4], c.tmp[0:2])
   1075 		c.writeRecord(recordTypeAlert, c.tmp[0:4])
   1076 	} else {
   1077 		c.writeRecord(recordTypeAlert, c.tmp[0:2])
   1078 	}
   1079 	// Error alerts are fatal to the connection.
   1080 	if level == alertLevelError {
   1081 		return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
   1082 	}
   1083 	return nil
   1084 }
   1085 
   1086 // sendAlert sends a TLS alert message.
   1087 // L < c.out.Mutex.
   1088 func (c *Conn) sendAlert(err alert) error {
   1089 	level := byte(alertLevelError)
   1090 	if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertificate || err == alertEndOfEarlyData {
   1091 		level = alertLevelWarning
   1092 	}
   1093 	return c.SendAlert(level, err)
   1094 }
   1095 
   1096 func (c *Conn) SendAlert(level byte, err alert) error {
   1097 	c.out.Lock()
   1098 	defer c.out.Unlock()
   1099 	return c.sendAlertLocked(level, err)
   1100 }
   1101 
   1102 // writeV2Record writes a record for a V2ClientHello.
   1103 func (c *Conn) writeV2Record(data []byte) (n int, err error) {
   1104 	record := make([]byte, 2+len(data))
   1105 	record[0] = uint8(len(data)>>8) | 0x80
   1106 	record[1] = uint8(len(data))
   1107 	copy(record[2:], data)
   1108 	return c.conn.Write(record)
   1109 }
   1110 
   1111 // writeRecord writes a TLS record with the given type and payload
   1112 // to the connection and updates the record layer state.
   1113 // c.out.Mutex <= L.
   1114 func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
   1115 	c.seenHandshakePackEnd = false
   1116 	if typ == recordTypeHandshake {
   1117 		msgType := data[0]
   1118 		if c.config.Bugs.SendWrongMessageType != 0 && msgType == c.config.Bugs.SendWrongMessageType {
   1119 			msgType += 42
   1120 		} else if msgType == typeServerHello && c.config.Bugs.SendServerHelloAsHelloRetryRequest {
   1121 			msgType = typeHelloRetryRequest
   1122 		}
   1123 		if msgType != data[0] {
   1124 			newData := make([]byte, len(data))
   1125 			copy(newData, data)
   1126 			newData[0] = msgType
   1127 			data = newData
   1128 		}
   1129 
   1130 		if c.config.Bugs.SendTrailingMessageData != 0 && msgType == c.config.Bugs.SendTrailingMessageData {
   1131 			newData := make([]byte, len(data))
   1132 			copy(newData, data)
   1133 
   1134 			// Add a 0 to the body.
   1135 			newData = append(newData, 0)
   1136 			// Fix the header.
   1137 			newLen := len(newData) - 4
   1138 			newData[1] = byte(newLen >> 16)
   1139 			newData[2] = byte(newLen >> 8)
   1140 			newData[3] = byte(newLen)
   1141 
   1142 			data = newData
   1143 		}
   1144 	}
   1145 
   1146 	if c.isDTLS {
   1147 		return c.dtlsWriteRecord(typ, data)
   1148 	}
   1149 
   1150 	if typ == recordTypeHandshake {
   1151 		if c.config.Bugs.SendHelloRequestBeforeEveryHandshakeMessage {
   1152 			newData := make([]byte, 0, 4+len(data))
   1153 			newData = append(newData, typeHelloRequest, 0, 0, 0)
   1154 			newData = append(newData, data...)
   1155 			data = newData
   1156 		}
   1157 
   1158 		if c.config.Bugs.PackHandshakeFlight {
   1159 			c.pendingFlight.Write(data)
   1160 			return len(data), nil
   1161 		}
   1162 	}
   1163 
   1164 	// Flush buffered data before writing anything.
   1165 	if err := c.flushHandshake(); err != nil {
   1166 		return 0, err
   1167 	}
   1168 
   1169 	if typ == recordTypeApplicationData && c.config.Bugs.SendPostHandshakeChangeCipherSpec {
   1170 		if _, err := c.doWriteRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
   1171 			return 0, err
   1172 		}
   1173 	}
   1174 
   1175 	return c.doWriteRecord(typ, data)
   1176 }
   1177 
   1178 func (c *Conn) doWriteRecord(typ recordType, data []byte) (n int, err error) {
   1179 	recordHeaderLen := c.out.recordHeaderLen()
   1180 	b := c.out.newBlock()
   1181 	first := true
   1182 	isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
   1183 	for len(data) > 0 || first {
   1184 		m := len(data)
   1185 		if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
   1186 			m = maxPlaintext
   1187 		}
   1188 		if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
   1189 			m = c.config.Bugs.MaxHandshakeRecordLength
   1190 			// By default, do not fragment the client_version or
   1191 			// server_version, which are located in the first 6
   1192 			// bytes.
   1193 			if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
   1194 				m = 6
   1195 			}
   1196 		}
   1197 		explicitIVLen := 0
   1198 		explicitIVIsSeq := false
   1199 		first = false
   1200 
   1201 		var cbc cbcMode
   1202 		if c.out.version >= VersionTLS11 {
   1203 			var ok bool
   1204 			if cbc, ok = c.out.cipher.(cbcMode); ok {
   1205 				explicitIVLen = cbc.BlockSize()
   1206 			}
   1207 		}
   1208 		if explicitIVLen == 0 {
   1209 			if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
   1210 				explicitIVLen = 8
   1211 				// The AES-GCM construction in TLS has an
   1212 				// explicit nonce so that the nonce can be
   1213 				// random. However, the nonce is only 8 bytes
   1214 				// which is too small for a secure, random
   1215 				// nonce. Therefore we use the sequence number
   1216 				// as the nonce.
   1217 				explicitIVIsSeq = true
   1218 			}
   1219 		}
   1220 		b.resize(recordHeaderLen + explicitIVLen + m)
   1221 		b.data[0] = byte(typ)
   1222 		if c.vers >= VersionTLS13 && c.out.cipher != nil {
   1223 			b.data[0] = byte(recordTypeApplicationData)
   1224 			if outerType := c.config.Bugs.OuterRecordType; outerType != 0 {
   1225 				b.data[0] = byte(outerType)
   1226 			}
   1227 		}
   1228 		vers := c.vers
   1229 		if vers == 0 {
   1230 			// Some TLS servers fail if the record version is
   1231 			// greater than TLS 1.0 for the initial ClientHello.
   1232 			//
   1233 			// TLS 1.3 fixes the version number in the record
   1234 			// layer to {3, 1}.
   1235 			vers = VersionTLS10
   1236 		}
   1237 		if c.vers >= VersionTLS13 || c.out.version >= VersionTLS13 {
   1238 			vers = VersionTLS12
   1239 		}
   1240 
   1241 		if c.config.Bugs.SendRecordVersion != 0 {
   1242 			vers = c.config.Bugs.SendRecordVersion
   1243 		}
   1244 		if c.vers == 0 && c.config.Bugs.SendInitialRecordVersion != 0 {
   1245 			vers = c.config.Bugs.SendInitialRecordVersion
   1246 		}
   1247 		b.data[1] = byte(vers >> 8)
   1248 		b.data[2] = byte(vers)
   1249 		b.data[3] = byte(m >> 8)
   1250 		b.data[4] = byte(m)
   1251 		if explicitIVLen > 0 {
   1252 			explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
   1253 			if explicitIVIsSeq {
   1254 				copy(explicitIV, c.out.seq[:])
   1255 			} else {
   1256 				if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
   1257 					break
   1258 				}
   1259 			}
   1260 		}
   1261 		copy(b.data[recordHeaderLen+explicitIVLen:], data)
   1262 		c.out.encrypt(b, explicitIVLen, typ)
   1263 		_, err = c.conn.Write(b.data)
   1264 		if err != nil {
   1265 			break
   1266 		}
   1267 		n += m
   1268 		data = data[m:]
   1269 	}
   1270 	c.out.freeBlock(b)
   1271 
   1272 	if typ == recordTypeChangeCipherSpec && c.vers < VersionTLS13 {
   1273 		err = c.out.changeCipherSpec(c.config)
   1274 		if err != nil {
   1275 			return n, c.sendAlertLocked(alertLevelError, err.(alert))
   1276 		}
   1277 	}
   1278 	return
   1279 }
   1280 
   1281 func (c *Conn) flushHandshake() error {
   1282 	if c.isDTLS {
   1283 		return c.dtlsFlushHandshake()
   1284 	}
   1285 
   1286 	for c.pendingFlight.Len() > 0 {
   1287 		var buf [maxPlaintext]byte
   1288 		n, _ := c.pendingFlight.Read(buf[:])
   1289 		if _, err := c.doWriteRecord(recordTypeHandshake, buf[:n]); err != nil {
   1290 			return err
   1291 		}
   1292 	}
   1293 
   1294 	c.pendingFlight.Reset()
   1295 	return nil
   1296 }
   1297 
   1298 func (c *Conn) doReadHandshake() ([]byte, error) {
   1299 	if c.isDTLS {
   1300 		return c.dtlsDoReadHandshake()
   1301 	}
   1302 
   1303 	for c.hand.Len() < 4 {
   1304 		if err := c.in.err; err != nil {
   1305 			return nil, err
   1306 		}
   1307 		if err := c.readRecord(recordTypeHandshake); err != nil {
   1308 			return nil, err
   1309 		}
   1310 	}
   1311 
   1312 	data := c.hand.Bytes()
   1313 	n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
   1314 	if n > maxHandshake {
   1315 		return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
   1316 	}
   1317 	for c.hand.Len() < 4+n {
   1318 		if err := c.in.err; err != nil {
   1319 			return nil, err
   1320 		}
   1321 		if err := c.readRecord(recordTypeHandshake); err != nil {
   1322 			return nil, err
   1323 		}
   1324 	}
   1325 	return c.hand.Next(4 + n), nil
   1326 }
   1327 
   1328 // readHandshake reads the next handshake message from
   1329 // the record layer.
   1330 // c.in.Mutex < L; c.out.Mutex < L.
   1331 func (c *Conn) readHandshake() (interface{}, error) {
   1332 	data, err := c.doReadHandshake()
   1333 	if err == errNoCertificateAlert {
   1334 		if c.hand.Len() != 0 {
   1335 			// The warning alert may not interleave with a handshake message.
   1336 			return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   1337 		}
   1338 		return new(ssl3NoCertificateMsg), nil
   1339 	}
   1340 	if err != nil {
   1341 		return nil, err
   1342 	}
   1343 
   1344 	var m handshakeMessage
   1345 	switch data[0] {
   1346 	case typeHelloRequest:
   1347 		m = new(helloRequestMsg)
   1348 	case typeClientHello:
   1349 		m = &clientHelloMsg{
   1350 			isDTLS: c.isDTLS,
   1351 		}
   1352 	case typeServerHello:
   1353 		m = &serverHelloMsg{
   1354 			isDTLS: c.isDTLS,
   1355 		}
   1356 	case typeHelloRetryRequest:
   1357 		m = new(helloRetryRequestMsg)
   1358 	case typeNewSessionTicket:
   1359 		m = &newSessionTicketMsg{
   1360 			vers:   c.wireVersion,
   1361 			isDTLS: c.isDTLS,
   1362 		}
   1363 	case typeEncryptedExtensions:
   1364 		m = new(encryptedExtensionsMsg)
   1365 	case typeCertificate:
   1366 		m = &certificateMsg{
   1367 			hasRequestContext: c.vers >= VersionTLS13,
   1368 		}
   1369 	case typeCompressedCertificate:
   1370 		m = new(compressedCertificateMsg)
   1371 	case typeCertificateRequest:
   1372 		m = &certificateRequestMsg{
   1373 			vers:                  c.wireVersion,
   1374 			hasSignatureAlgorithm: c.vers >= VersionTLS12,
   1375 			hasRequestContext:     c.vers >= VersionTLS13,
   1376 		}
   1377 	case typeCertificateStatus:
   1378 		m = new(certificateStatusMsg)
   1379 	case typeServerKeyExchange:
   1380 		m = new(serverKeyExchangeMsg)
   1381 	case typeServerHelloDone:
   1382 		m = new(serverHelloDoneMsg)
   1383 	case typeClientKeyExchange:
   1384 		m = new(clientKeyExchangeMsg)
   1385 	case typeCertificateVerify:
   1386 		m = &certificateVerifyMsg{
   1387 			hasSignatureAlgorithm: c.vers >= VersionTLS12,
   1388 		}
   1389 	case typeNextProtocol:
   1390 		m = new(nextProtoMsg)
   1391 	case typeFinished:
   1392 		m = new(finishedMsg)
   1393 	case typeHelloVerifyRequest:
   1394 		m = new(helloVerifyRequestMsg)
   1395 	case typeChannelID:
   1396 		m = new(channelIDMsg)
   1397 	case typeKeyUpdate:
   1398 		m = new(keyUpdateMsg)
   1399 	case typeEndOfEarlyData:
   1400 		m = new(endOfEarlyDataMsg)
   1401 	default:
   1402 		return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   1403 	}
   1404 
   1405 	// The handshake message unmarshallers
   1406 	// expect to be able to keep references to data,
   1407 	// so pass in a fresh copy that won't be overwritten.
   1408 	data = append([]byte(nil), data...)
   1409 
   1410 	if data[0] == typeServerHello && len(data) >= 38 {
   1411 		vers := uint16(data[4])<<8 | uint16(data[5])
   1412 		if vers == VersionTLS12 && bytes.Equal(data[6:38], tls13HelloRetryRequest) {
   1413 			m = new(helloRetryRequestMsg)
   1414 			m.(*helloRetryRequestMsg).isServerHello = true
   1415 		}
   1416 	}
   1417 
   1418 	if !m.unmarshal(data) {
   1419 		return nil, c.in.setErrorLocked(c.sendAlert(alertDecodeError))
   1420 	}
   1421 	return m, nil
   1422 }
   1423 
   1424 // skipPacket processes all the DTLS records in packet. It updates
   1425 // sequence number expectations but otherwise ignores them.
   1426 func (c *Conn) skipPacket(packet []byte) error {
   1427 	for len(packet) > 0 {
   1428 		if len(packet) < 13 {
   1429 			return errors.New("tls: bad packet")
   1430 		}
   1431 		// Dropped packets are completely ignored save to update
   1432 		// expected sequence numbers for this and the next epoch. (We
   1433 		// don't assert on the contents of the packets both for
   1434 		// simplicity and because a previous test with one shorter
   1435 		// timeout schedule would have done so.)
   1436 		epoch := packet[3:5]
   1437 		seq := packet[5:11]
   1438 		length := uint16(packet[11])<<8 | uint16(packet[12])
   1439 		if bytes.Equal(c.in.seq[:2], epoch) {
   1440 			if bytes.Compare(seq, c.in.seq[2:]) < 0 {
   1441 				return errors.New("tls: sequence mismatch")
   1442 			}
   1443 			copy(c.in.seq[2:], seq)
   1444 			c.in.incSeq(false)
   1445 		} else {
   1446 			if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
   1447 				return errors.New("tls: sequence mismatch")
   1448 			}
   1449 			copy(c.in.nextSeq[:], seq)
   1450 			c.in.incNextSeq()
   1451 		}
   1452 		if len(packet) < 13+int(length) {
   1453 			return errors.New("tls: bad packet")
   1454 		}
   1455 		packet = packet[13+length:]
   1456 	}
   1457 	return nil
   1458 }
   1459 
   1460 // simulatePacketLoss simulates the loss of a handshake leg from the
   1461 // peer based on the schedule in c.config.Bugs. If resendFunc is
   1462 // non-nil, it is called after each simulated timeout to retransmit
   1463 // handshake messages from the local end. This is used in cases where
   1464 // the peer retransmits on a stale Finished rather than a timeout.
   1465 func (c *Conn) simulatePacketLoss(resendFunc func()) error {
   1466 	if len(c.config.Bugs.TimeoutSchedule) == 0 {
   1467 		return nil
   1468 	}
   1469 	if !c.isDTLS {
   1470 		return errors.New("tls: TimeoutSchedule may only be set in DTLS")
   1471 	}
   1472 	if c.config.Bugs.PacketAdaptor == nil {
   1473 		return errors.New("tls: TimeoutSchedule set without PacketAdapter")
   1474 	}
   1475 	for _, timeout := range c.config.Bugs.TimeoutSchedule {
   1476 		// Simulate a timeout.
   1477 		packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
   1478 		if err != nil {
   1479 			return err
   1480 		}
   1481 		for _, packet := range packets {
   1482 			if err := c.skipPacket(packet); err != nil {
   1483 				return err
   1484 			}
   1485 		}
   1486 		if resendFunc != nil {
   1487 			resendFunc()
   1488 		}
   1489 	}
   1490 	return nil
   1491 }
   1492 
   1493 func (c *Conn) SendHalfHelloRequest() error {
   1494 	if err := c.Handshake(); err != nil {
   1495 		return err
   1496 	}
   1497 
   1498 	c.out.Lock()
   1499 	defer c.out.Unlock()
   1500 
   1501 	if _, err := c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0}); err != nil {
   1502 		return err
   1503 	}
   1504 	return c.flushHandshake()
   1505 }
   1506 
   1507 // Write writes data to the connection.
   1508 func (c *Conn) Write(b []byte) (int, error) {
   1509 	if err := c.Handshake(); err != nil {
   1510 		return 0, err
   1511 	}
   1512 
   1513 	c.out.Lock()
   1514 	defer c.out.Unlock()
   1515 
   1516 	if err := c.out.err; err != nil {
   1517 		return 0, err
   1518 	}
   1519 
   1520 	if !c.handshakeComplete {
   1521 		return 0, alertInternalError
   1522 	}
   1523 
   1524 	if c.keyUpdateRequested {
   1525 		if err := c.sendKeyUpdateLocked(keyUpdateNotRequested); err != nil {
   1526 			return 0, err
   1527 		}
   1528 		c.keyUpdateRequested = false
   1529 	}
   1530 
   1531 	if c.config.Bugs.SendSpuriousAlert != 0 {
   1532 		c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
   1533 	}
   1534 
   1535 	if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
   1536 		c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
   1537 		c.flushHandshake()
   1538 	}
   1539 
   1540 	// SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
   1541 	// attack when using block mode ciphers due to predictable IVs.
   1542 	// This can be prevented by splitting each Application Data
   1543 	// record into two records, effectively randomizing the IV.
   1544 	//
   1545 	// http://www.openssl.org/~bodo/tls-cbc.txt
   1546 	// https://bugzilla.mozilla.org/show_bug.cgi?id=665814
   1547 	// http://www.imperialviolet.org/2012/01/15/beastfollowup.html
   1548 
   1549 	var m int
   1550 	if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
   1551 		if _, ok := c.out.cipher.(cipher.BlockMode); ok {
   1552 			n, err := c.writeRecord(recordTypeApplicationData, b[:1])
   1553 			if err != nil {
   1554 				return n, c.out.setErrorLocked(err)
   1555 			}
   1556 			m, b = 1, b[1:]
   1557 		}
   1558 	}
   1559 
   1560 	n, err := c.writeRecord(recordTypeApplicationData, b)
   1561 	return n + m, c.out.setErrorLocked(err)
   1562 }
   1563 
   1564 func (c *Conn) processTLS13NewSessionTicket(newSessionTicket *newSessionTicketMsg, cipherSuite *cipherSuite) error {
   1565 	if c.config.Bugs.ExpectGREASE && !newSessionTicket.hasGREASEExtension {
   1566 		return errors.New("tls: no GREASE ticket extension found")
   1567 	}
   1568 
   1569 	if c.config.Bugs.ExpectTicketEarlyData && newSessionTicket.maxEarlyDataSize == 0 {
   1570 		return errors.New("tls: no early_data ticket extension found")
   1571 	}
   1572 
   1573 	if c.config.Bugs.ExpectNoNewSessionTicket {
   1574 		return errors.New("tls: received unexpected NewSessionTicket")
   1575 	}
   1576 
   1577 	if c.config.ClientSessionCache == nil || newSessionTicket.ticketLifetime == 0 {
   1578 		return nil
   1579 	}
   1580 
   1581 	session := &ClientSessionState{
   1582 		sessionTicket:      newSessionTicket.ticket,
   1583 		vers:               c.vers,
   1584 		wireVersion:        c.wireVersion,
   1585 		cipherSuite:        cipherSuite.id,
   1586 		masterSecret:       c.resumptionSecret,
   1587 		serverCertificates: c.peerCertificates,
   1588 		sctList:            c.sctList,
   1589 		ocspResponse:       c.ocspResponse,
   1590 		ticketCreationTime: c.config.time(),
   1591 		ticketExpiration:   c.config.time().Add(time.Duration(newSessionTicket.ticketLifetime) * time.Second),
   1592 		ticketAgeAdd:       newSessionTicket.ticketAgeAdd,
   1593 		maxEarlyDataSize:   newSessionTicket.maxEarlyDataSize,
   1594 		earlyALPN:          c.clientProtocol,
   1595 	}
   1596 
   1597 	session.masterSecret = deriveSessionPSK(cipherSuite, c.wireVersion, c.resumptionSecret, newSessionTicket.ticketNonce)
   1598 
   1599 	cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
   1600 	_, ok := c.config.ClientSessionCache.Get(cacheKey)
   1601 	if !ok || !c.config.Bugs.UseFirstSessionTicket {
   1602 		c.config.ClientSessionCache.Put(cacheKey, session)
   1603 	}
   1604 	return nil
   1605 }
   1606 
   1607 func (c *Conn) handlePostHandshakeMessage() error {
   1608 	msg, err := c.readHandshake()
   1609 	if err != nil {
   1610 		return err
   1611 	}
   1612 
   1613 	if c.vers < VersionTLS13 {
   1614 		if !c.isClient {
   1615 			c.sendAlert(alertUnexpectedMessage)
   1616 			return errors.New("tls: unexpected post-handshake message")
   1617 		}
   1618 
   1619 		_, ok := msg.(*helloRequestMsg)
   1620 		if !ok {
   1621 			c.sendAlert(alertUnexpectedMessage)
   1622 			return alertUnexpectedMessage
   1623 		}
   1624 
   1625 		c.handshakeComplete = false
   1626 		return c.Handshake()
   1627 	}
   1628 
   1629 	if c.isClient {
   1630 		if newSessionTicket, ok := msg.(*newSessionTicketMsg); ok {
   1631 			return c.processTLS13NewSessionTicket(newSessionTicket, c.cipherSuite)
   1632 		}
   1633 	}
   1634 
   1635 	if keyUpdate, ok := msg.(*keyUpdateMsg); ok {
   1636 		c.keyUpdateSeen = true
   1637 
   1638 		if c.config.Bugs.RejectUnsolicitedKeyUpdate {
   1639 			return errors.New("tls: unexpected KeyUpdate message")
   1640 		}
   1641 		if err := c.useInTrafficSecret(c.in.wireVersion, c.cipherSuite, updateTrafficSecret(c.cipherSuite.hash(), c.wireVersion, c.in.trafficSecret)); err != nil {
   1642 			return err
   1643 		}
   1644 		if keyUpdate.keyUpdateRequest == keyUpdateRequested {
   1645 			c.keyUpdateRequested = true
   1646 		}
   1647 		return nil
   1648 	}
   1649 
   1650 	c.sendAlert(alertUnexpectedMessage)
   1651 	return errors.New("tls: unexpected post-handshake message")
   1652 }
   1653 
   1654 // Reads a KeyUpdate acknowledgment from the peer. There may not be any
   1655 // application data records before the message.
   1656 func (c *Conn) ReadKeyUpdateACK() error {
   1657 	c.in.Lock()
   1658 	defer c.in.Unlock()
   1659 
   1660 	msg, err := c.readHandshake()
   1661 	if err != nil {
   1662 		return err
   1663 	}
   1664 
   1665 	keyUpdate, ok := msg.(*keyUpdateMsg)
   1666 	if !ok {
   1667 		c.sendAlert(alertUnexpectedMessage)
   1668 		return fmt.Errorf("tls: unexpected message (%T) when reading KeyUpdate", msg)
   1669 	}
   1670 
   1671 	if keyUpdate.keyUpdateRequest != keyUpdateNotRequested {
   1672 		return errors.New("tls: received invalid KeyUpdate message")
   1673 	}
   1674 
   1675 	return c.useInTrafficSecret(c.in.wireVersion, c.cipherSuite, updateTrafficSecret(c.cipherSuite.hash(), c.wireVersion, c.in.trafficSecret))
   1676 }
   1677 
   1678 func (c *Conn) Renegotiate() error {
   1679 	if !c.isClient {
   1680 		helloReq := new(helloRequestMsg).marshal()
   1681 		if c.config.Bugs.BadHelloRequest != nil {
   1682 			helloReq = c.config.Bugs.BadHelloRequest
   1683 		}
   1684 		c.writeRecord(recordTypeHandshake, helloReq)
   1685 		c.flushHandshake()
   1686 	}
   1687 
   1688 	c.handshakeComplete = false
   1689 	return c.Handshake()
   1690 }
   1691 
   1692 // Read can be made to time out and return a net.Error with Timeout() == true
   1693 // after a fixed time limit; see SetDeadline and SetReadDeadline.
   1694 func (c *Conn) Read(b []byte) (n int, err error) {
   1695 	if err = c.Handshake(); err != nil {
   1696 		return
   1697 	}
   1698 
   1699 	c.in.Lock()
   1700 	defer c.in.Unlock()
   1701 
   1702 	// Some OpenSSL servers send empty records in order to randomize the
   1703 	// CBC IV. So this loop ignores a limited number of empty records.
   1704 	const maxConsecutiveEmptyRecords = 100
   1705 	for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
   1706 		for c.input == nil && c.in.err == nil {
   1707 			if err := c.readRecord(recordTypeApplicationData); err != nil {
   1708 				// Soft error, like EAGAIN
   1709 				return 0, err
   1710 			}
   1711 			for c.hand.Len() > 0 {
   1712 				// We received handshake bytes, indicating a
   1713 				// post-handshake message.
   1714 				if err := c.handlePostHandshakeMessage(); err != nil {
   1715 					return 0, err
   1716 				}
   1717 			}
   1718 		}
   1719 		if err := c.in.err; err != nil {
   1720 			return 0, err
   1721 		}
   1722 
   1723 		n, err = c.input.Read(b)
   1724 		if c.input.off >= len(c.input.data) || c.isDTLS {
   1725 			c.in.freeBlock(c.input)
   1726 			c.input = nil
   1727 		}
   1728 
   1729 		// If a close-notify alert is waiting, read it so that
   1730 		// we can return (n, EOF) instead of (n, nil), to signal
   1731 		// to the HTTP response reading goroutine that the
   1732 		// connection is now closed. This eliminates a race
   1733 		// where the HTTP response reading goroutine would
   1734 		// otherwise not observe the EOF until its next read,
   1735 		// by which time a client goroutine might have already
   1736 		// tried to reuse the HTTP connection for a new
   1737 		// request.
   1738 		// See https://codereview.appspot.com/76400046
   1739 		// and http://golang.org/issue/3514
   1740 		if ri := c.rawInput; ri != nil &&
   1741 			n != 0 && err == nil &&
   1742 			c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
   1743 			if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
   1744 				err = recErr // will be io.EOF on closeNotify
   1745 			}
   1746 		}
   1747 
   1748 		if n != 0 || err != nil {
   1749 			return n, err
   1750 		}
   1751 	}
   1752 
   1753 	return 0, io.ErrNoProgress
   1754 }
   1755 
   1756 // Close closes the connection.
   1757 func (c *Conn) Close() error {
   1758 	var alertErr error
   1759 
   1760 	c.handshakeMutex.Lock()
   1761 	defer c.handshakeMutex.Unlock()
   1762 	if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
   1763 		alert := alertCloseNotify
   1764 		if c.config.Bugs.SendAlertOnShutdown != 0 {
   1765 			alert = c.config.Bugs.SendAlertOnShutdown
   1766 		}
   1767 		alertErr = c.sendAlert(alert)
   1768 		// Clear local alerts when sending alerts so we continue to wait
   1769 		// for the peer rather than closing the socket early.
   1770 		if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
   1771 			alertErr = nil
   1772 		}
   1773 	}
   1774 
   1775 	// Consume a close_notify from the peer if one hasn't been received
   1776 	// already. This avoids the peer from failing |SSL_shutdown| due to a
   1777 	// write failing.
   1778 	if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
   1779 		for c.in.error() == nil {
   1780 			c.readRecord(recordTypeAlert)
   1781 		}
   1782 		if c.in.error() != io.EOF {
   1783 			alertErr = c.in.error()
   1784 		}
   1785 	}
   1786 
   1787 	if err := c.conn.Close(); err != nil {
   1788 		return err
   1789 	}
   1790 	return alertErr
   1791 }
   1792 
   1793 // Handshake runs the client or server handshake
   1794 // protocol if it has not yet been run.
   1795 // Most uses of this package need not call Handshake
   1796 // explicitly: the first Read or Write will call it automatically.
   1797 func (c *Conn) Handshake() error {
   1798 	c.handshakeMutex.Lock()
   1799 	defer c.handshakeMutex.Unlock()
   1800 	if err := c.handshakeErr; err != nil {
   1801 		return err
   1802 	}
   1803 	if c.handshakeComplete {
   1804 		return nil
   1805 	}
   1806 
   1807 	if c.isDTLS && c.config.Bugs.SendSplitAlert {
   1808 		c.conn.Write([]byte{
   1809 			byte(recordTypeAlert), // type
   1810 			0xfe, 0xff,            // version
   1811 			0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
   1812 			0x0, 0x2, // length
   1813 		})
   1814 		c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
   1815 	}
   1816 	if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
   1817 		c.writeRecord(recordTypeApplicationData, data)
   1818 	}
   1819 	if c.isClient {
   1820 		c.handshakeErr = c.clientHandshake()
   1821 	} else {
   1822 		c.handshakeErr = c.serverHandshake()
   1823 	}
   1824 	if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
   1825 		c.writeRecord(recordType(42), []byte("invalid record"))
   1826 	}
   1827 	return c.handshakeErr
   1828 }
   1829 
   1830 // ConnectionState returns basic TLS details about the connection.
   1831 func (c *Conn) ConnectionState() ConnectionState {
   1832 	c.handshakeMutex.Lock()
   1833 	defer c.handshakeMutex.Unlock()
   1834 
   1835 	var state ConnectionState
   1836 	state.HandshakeComplete = c.handshakeComplete
   1837 	if c.handshakeComplete {
   1838 		state.Version = c.vers
   1839 		state.NegotiatedProtocol = c.clientProtocol
   1840 		state.DidResume = c.didResume
   1841 		state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
   1842 		state.NegotiatedProtocolFromALPN = c.usedALPN
   1843 		state.CipherSuite = c.cipherSuite.id
   1844 		state.PeerCertificates = c.peerCertificates
   1845 		state.VerifiedChains = c.verifiedChains
   1846 		state.ServerName = c.serverName
   1847 		state.ChannelID = c.channelID
   1848 		state.TokenBindingNegotiated = c.tokenBindingNegotiated
   1849 		state.TokenBindingParam = c.tokenBindingParam
   1850 		state.SRTPProtectionProfile = c.srtpProtectionProfile
   1851 		state.TLSUnique = c.firstFinished[:]
   1852 		state.SCTList = c.sctList
   1853 		state.PeerSignatureAlgorithm = c.peerSignatureAlgorithm
   1854 		state.CurveID = c.curveID
   1855 		state.QUICTransportParams = c.quicTransportParams
   1856 	}
   1857 
   1858 	return state
   1859 }
   1860 
   1861 // OCSPResponse returns the stapled OCSP response from the TLS server, if
   1862 // any. (Only valid for client connections.)
   1863 func (c *Conn) OCSPResponse() []byte {
   1864 	c.handshakeMutex.Lock()
   1865 	defer c.handshakeMutex.Unlock()
   1866 
   1867 	return c.ocspResponse
   1868 }
   1869 
   1870 // VerifyHostname checks that the peer certificate chain is valid for
   1871 // connecting to host.  If so, it returns nil; if not, it returns an error
   1872 // describing the problem.
   1873 func (c *Conn) VerifyHostname(host string) error {
   1874 	c.handshakeMutex.Lock()
   1875 	defer c.handshakeMutex.Unlock()
   1876 	if !c.isClient {
   1877 		return errors.New("tls: VerifyHostname called on TLS server connection")
   1878 	}
   1879 	if !c.handshakeComplete {
   1880 		return errors.New("tls: handshake has not yet been performed")
   1881 	}
   1882 	return c.peerCertificates[0].VerifyHostname(host)
   1883 }
   1884 
   1885 func (c *Conn) exportKeyingMaterialTLS13(length int, secret, label, context []byte) []byte {
   1886 	cipherSuite := c.cipherSuite
   1887 	if cipherSuite == nil {
   1888 		cipherSuite = c.earlyCipherSuite
   1889 	}
   1890 	hash := cipherSuite.hash()
   1891 	exporterKeyingLabel := []byte("exporter")
   1892 	contextHash := hash.New()
   1893 	contextHash.Write(context)
   1894 	exporterContext := hash.New().Sum(nil)
   1895 	derivedSecret := hkdfExpandLabel(cipherSuite.hash(), secret, label, exporterContext, hash.Size())
   1896 	return hkdfExpandLabel(cipherSuite.hash(), derivedSecret, exporterKeyingLabel, contextHash.Sum(nil), length)
   1897 }
   1898 
   1899 // ExportKeyingMaterial exports keying material from the current connection
   1900 // state, as per RFC 5705.
   1901 func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
   1902 	c.handshakeMutex.Lock()
   1903 	defer c.handshakeMutex.Unlock()
   1904 	if !c.handshakeComplete {
   1905 		return nil, errors.New("tls: handshake has not yet been performed")
   1906 	}
   1907 
   1908 	if c.vers >= VersionTLS13 {
   1909 		return c.exportKeyingMaterialTLS13(length, c.exporterSecret, label, context), nil
   1910 	}
   1911 
   1912 	seedLen := len(c.clientRandom) + len(c.serverRandom)
   1913 	if useContext {
   1914 		seedLen += 2 + len(context)
   1915 	}
   1916 	seed := make([]byte, 0, seedLen)
   1917 	seed = append(seed, c.clientRandom[:]...)
   1918 	seed = append(seed, c.serverRandom[:]...)
   1919 	if useContext {
   1920 		seed = append(seed, byte(len(context)>>8), byte(len(context)))
   1921 		seed = append(seed, context...)
   1922 	}
   1923 	result := make([]byte, length)
   1924 	prfForVersion(c.vers, c.cipherSuite)(result, c.exporterSecret, label, seed)
   1925 	return result, nil
   1926 }
   1927 
   1928 func (c *Conn) ExportEarlyKeyingMaterial(length int, label, context []byte) ([]byte, error) {
   1929 	if c.vers < VersionTLS13 {
   1930 		return nil, errors.New("tls: early exporters not defined before TLS 1.3")
   1931 	}
   1932 
   1933 	if c.earlyExporterSecret == nil {
   1934 		return nil, errors.New("tls: no early exporter secret")
   1935 	}
   1936 
   1937 	return c.exportKeyingMaterialTLS13(length, c.earlyExporterSecret, label, context), nil
   1938 }
   1939 
   1940 // noRenegotiationInfo returns true if the renegotiation info extension
   1941 // should be supported in the current handshake.
   1942 func (c *Conn) noRenegotiationInfo() bool {
   1943 	if c.config.Bugs.NoRenegotiationInfo {
   1944 		return true
   1945 	}
   1946 	if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
   1947 		return true
   1948 	}
   1949 	if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
   1950 		return true
   1951 	}
   1952 	return false
   1953 }
   1954 
   1955 func (c *Conn) SendNewSessionTicket(nonce []byte) error {
   1956 	if c.isClient || c.vers < VersionTLS13 {
   1957 		return errors.New("tls: cannot send post-handshake NewSessionTicket")
   1958 	}
   1959 
   1960 	var peerCertificatesRaw [][]byte
   1961 	for _, cert := range c.peerCertificates {
   1962 		peerCertificatesRaw = append(peerCertificatesRaw, cert.Raw)
   1963 	}
   1964 
   1965 	addBuffer := make([]byte, 4)
   1966 	_, err := io.ReadFull(c.config.rand(), addBuffer)
   1967 	if err != nil {
   1968 		c.sendAlert(alertInternalError)
   1969 		return errors.New("tls: short read from Rand: " + err.Error())
   1970 	}
   1971 	ticketAgeAdd := uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0])
   1972 
   1973 	// TODO(davidben): Allow configuring these values.
   1974 	m := &newSessionTicketMsg{
   1975 		vers:                        c.wireVersion,
   1976 		isDTLS:                      c.isDTLS,
   1977 		ticketLifetime:              uint32(24 * time.Hour / time.Second),
   1978 		duplicateEarlyDataExtension: c.config.Bugs.DuplicateTicketEarlyData,
   1979 		customExtension:             c.config.Bugs.CustomTicketExtension,
   1980 		ticketAgeAdd:                ticketAgeAdd,
   1981 		ticketNonce:                 nonce,
   1982 		maxEarlyDataSize:            c.config.MaxEarlyDataSize,
   1983 	}
   1984 
   1985 	if c.config.Bugs.SendTicketLifetime != 0 {
   1986 		m.ticketLifetime = uint32(c.config.Bugs.SendTicketLifetime / time.Second)
   1987 	}
   1988 
   1989 	state := sessionState{
   1990 		vers:               c.vers,
   1991 		cipherSuite:        c.cipherSuite.id,
   1992 		masterSecret:       deriveSessionPSK(c.cipherSuite, c.wireVersion, c.resumptionSecret, nonce),
   1993 		certificates:       peerCertificatesRaw,
   1994 		ticketCreationTime: c.config.time(),
   1995 		ticketExpiration:   c.config.time().Add(time.Duration(m.ticketLifetime) * time.Second),
   1996 		ticketAgeAdd:       uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0]),
   1997 		earlyALPN:          []byte(c.clientProtocol),
   1998 	}
   1999 
   2000 	if !c.config.Bugs.SendEmptySessionTicket {
   2001 		var err error
   2002 		m.ticket, err = c.encryptTicket(&state)
   2003 		if err != nil {
   2004 			return err
   2005 		}
   2006 	}
   2007 	c.out.Lock()
   2008 	defer c.out.Unlock()
   2009 	_, err = c.writeRecord(recordTypeHandshake, m.marshal())
   2010 	return err
   2011 }
   2012 
   2013 func (c *Conn) SendKeyUpdate(keyUpdateRequest byte) error {
   2014 	c.out.Lock()
   2015 	defer c.out.Unlock()
   2016 	return c.sendKeyUpdateLocked(keyUpdateRequest)
   2017 }
   2018 
   2019 func (c *Conn) sendKeyUpdateLocked(keyUpdateRequest byte) error {
   2020 	if c.vers < VersionTLS13 {
   2021 		return errors.New("tls: attempted to send KeyUpdate before TLS 1.3")
   2022 	}
   2023 
   2024 	m := keyUpdateMsg{
   2025 		keyUpdateRequest: keyUpdateRequest,
   2026 	}
   2027 	if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
   2028 		return err
   2029 	}
   2030 	if err := c.flushHandshake(); err != nil {
   2031 		return err
   2032 	}
   2033 	c.useOutTrafficSecret(c.out.wireVersion, c.cipherSuite, updateTrafficSecret(c.cipherSuite.hash(), c.wireVersion, c.out.trafficSecret))
   2034 	return nil
   2035 }
   2036 
   2037 func (c *Conn) sendFakeEarlyData(len int) error {
   2038 	// Assemble a fake early data record. This does not use writeRecord
   2039 	// because the record layer may be using different keys at this point.
   2040 	payload := make([]byte, 5+len)
   2041 	payload[0] = byte(recordTypeApplicationData)
   2042 	payload[1] = 3
   2043 	payload[2] = 3
   2044 	payload[3] = byte(len >> 8)
   2045 	payload[4] = byte(len)
   2046 	_, err := c.conn.Write(payload)
   2047 	return err
   2048 }
   2049