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 // A Conn represents a secured connection.
     25 // It implements the net.Conn interface.
     26 type Conn struct {
     27 	// constant
     28 	conn     net.Conn
     29 	isDTLS   bool
     30 	isClient bool
     31 
     32 	// constant after handshake; protected by handshakeMutex
     33 	handshakeMutex       sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
     34 	handshakeErr         error      // error resulting from handshake
     35 	vers                 uint16     // TLS version
     36 	haveVers             bool       // version has been negotiated
     37 	config               *Config    // configuration passed to constructor
     38 	handshakeComplete    bool
     39 	didResume            bool // whether this connection was a session resumption
     40 	extendedMasterSecret bool // whether this session used an extended master secret
     41 	cipherSuite          *cipherSuite
     42 	ocspResponse         []byte // stapled OCSP response
     43 	sctList              []byte // signed certificate timestamp list
     44 	peerCertificates     []*x509.Certificate
     45 	// verifiedChains contains the certificate chains that we built, as
     46 	// opposed to the ones presented by the server.
     47 	verifiedChains [][]*x509.Certificate
     48 	// serverName contains the server name indicated by the client, if any.
     49 	serverName string
     50 	// firstFinished contains the first Finished hash sent during the
     51 	// handshake. This is the "tls-unique" channel binding value.
     52 	firstFinished [12]byte
     53 	// clientCertSignatureHash contains the TLS hash id for the hash that
     54 	// was used by the client to sign the handshake with a client
     55 	// certificate. This is only set by a server and is zero if no client
     56 	// certificates were used.
     57 	clientCertSignatureHash uint8
     58 
     59 	clientRandom, serverRandom [32]byte
     60 	masterSecret               [48]byte
     61 
     62 	clientProtocol         string
     63 	clientProtocolFallback bool
     64 	usedALPN               bool
     65 
     66 	// verify_data values for the renegotiation extension.
     67 	clientVerify []byte
     68 	serverVerify []byte
     69 
     70 	channelID *ecdsa.PublicKey
     71 
     72 	srtpProtectionProfile uint16
     73 
     74 	clientVersion uint16
     75 
     76 	// input/output
     77 	in, out  halfConn     // in.Mutex < out.Mutex
     78 	rawInput *block       // raw input, right off the wire
     79 	input    *block       // application record waiting to be read
     80 	hand     bytes.Buffer // handshake record waiting to be read
     81 
     82 	// DTLS state
     83 	sendHandshakeSeq uint16
     84 	recvHandshakeSeq uint16
     85 	handMsg          []byte   // pending assembled handshake message
     86 	handMsgLen       int      // handshake message length, not including the header
     87 	pendingFragments [][]byte // pending outgoing handshake fragments.
     88 
     89 	tmp [16]byte
     90 }
     91 
     92 func (c *Conn) init() {
     93 	c.in.isDTLS = c.isDTLS
     94 	c.out.isDTLS = c.isDTLS
     95 	c.in.config = c.config
     96 	c.out.config = c.config
     97 
     98 	c.out.updateOutSeq()
     99 }
    100 
    101 // Access to net.Conn methods.
    102 // Cannot just embed net.Conn because that would
    103 // export the struct field too.
    104 
    105 // LocalAddr returns the local network address.
    106 func (c *Conn) LocalAddr() net.Addr {
    107 	return c.conn.LocalAddr()
    108 }
    109 
    110 // RemoteAddr returns the remote network address.
    111 func (c *Conn) RemoteAddr() net.Addr {
    112 	return c.conn.RemoteAddr()
    113 }
    114 
    115 // SetDeadline sets the read and write deadlines associated with the connection.
    116 // A zero value for t means Read and Write will not time out.
    117 // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
    118 func (c *Conn) SetDeadline(t time.Time) error {
    119 	return c.conn.SetDeadline(t)
    120 }
    121 
    122 // SetReadDeadline sets the read deadline on the underlying connection.
    123 // A zero value for t means Read will not time out.
    124 func (c *Conn) SetReadDeadline(t time.Time) error {
    125 	return c.conn.SetReadDeadline(t)
    126 }
    127 
    128 // SetWriteDeadline sets the write deadline on the underlying conneciton.
    129 // A zero value for t means Write will not time out.
    130 // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
    131 func (c *Conn) SetWriteDeadline(t time.Time) error {
    132 	return c.conn.SetWriteDeadline(t)
    133 }
    134 
    135 // A halfConn represents one direction of the record layer
    136 // connection, either sending or receiving.
    137 type halfConn struct {
    138 	sync.Mutex
    139 
    140 	err     error  // first permanent error
    141 	version uint16 // protocol version
    142 	isDTLS  bool
    143 	cipher  interface{} // cipher algorithm
    144 	mac     macFunction
    145 	seq     [8]byte // 64-bit sequence number
    146 	outSeq  [8]byte // Mapped sequence number
    147 	bfree   *block  // list of free blocks
    148 
    149 	nextCipher interface{} // next encryption state
    150 	nextMac    macFunction // next MAC algorithm
    151 	nextSeq    [6]byte     // next epoch's starting sequence number in DTLS
    152 
    153 	// used to save allocating a new buffer for each MAC.
    154 	inDigestBuf, outDigestBuf []byte
    155 
    156 	config *Config
    157 }
    158 
    159 func (hc *halfConn) setErrorLocked(err error) error {
    160 	hc.err = err
    161 	return err
    162 }
    163 
    164 func (hc *halfConn) error() error {
    165 	// This should be locked, but I've removed it for the renegotiation
    166 	// tests since we don't concurrently read and write the same tls.Conn
    167 	// in any case during testing.
    168 	err := hc.err
    169 	return err
    170 }
    171 
    172 // prepareCipherSpec sets the encryption and MAC states
    173 // that a subsequent changeCipherSpec will use.
    174 func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
    175 	hc.version = version
    176 	hc.nextCipher = cipher
    177 	hc.nextMac = mac
    178 }
    179 
    180 // changeCipherSpec changes the encryption and MAC states
    181 // to the ones previously passed to prepareCipherSpec.
    182 func (hc *halfConn) changeCipherSpec(config *Config) error {
    183 	if hc.nextCipher == nil {
    184 		return alertInternalError
    185 	}
    186 	hc.cipher = hc.nextCipher
    187 	hc.mac = hc.nextMac
    188 	hc.nextCipher = nil
    189 	hc.nextMac = nil
    190 	hc.config = config
    191 	hc.incEpoch()
    192 	return nil
    193 }
    194 
    195 // incSeq increments the sequence number.
    196 func (hc *halfConn) incSeq(isOutgoing bool) {
    197 	limit := 0
    198 	increment := uint64(1)
    199 	if hc.isDTLS {
    200 		// Increment up to the epoch in DTLS.
    201 		limit = 2
    202 	}
    203 	for i := 7; i >= limit; i-- {
    204 		increment += uint64(hc.seq[i])
    205 		hc.seq[i] = byte(increment)
    206 		increment >>= 8
    207 	}
    208 
    209 	// Not allowed to let sequence number wrap.
    210 	// Instead, must renegotiate before it does.
    211 	// Not likely enough to bother.
    212 	if increment != 0 {
    213 		panic("TLS: sequence number wraparound")
    214 	}
    215 
    216 	hc.updateOutSeq()
    217 }
    218 
    219 // incNextSeq increments the starting sequence number for the next epoch.
    220 func (hc *halfConn) incNextSeq() {
    221 	for i := len(hc.nextSeq) - 1; i >= 0; i-- {
    222 		hc.nextSeq[i]++
    223 		if hc.nextSeq[i] != 0 {
    224 			return
    225 		}
    226 	}
    227 	panic("TLS: sequence number wraparound")
    228 }
    229 
    230 // incEpoch resets the sequence number. In DTLS, it also increments the epoch
    231 // half of the sequence number.
    232 func (hc *halfConn) incEpoch() {
    233 	if hc.isDTLS {
    234 		for i := 1; i >= 0; i-- {
    235 			hc.seq[i]++
    236 			if hc.seq[i] != 0 {
    237 				break
    238 			}
    239 			if i == 0 {
    240 				panic("TLS: epoch number wraparound")
    241 			}
    242 		}
    243 		copy(hc.seq[2:], hc.nextSeq[:])
    244 		for i := range hc.nextSeq {
    245 			hc.nextSeq[i] = 0
    246 		}
    247 	} else {
    248 		for i := range hc.seq {
    249 			hc.seq[i] = 0
    250 		}
    251 	}
    252 
    253 	hc.updateOutSeq()
    254 }
    255 
    256 func (hc *halfConn) updateOutSeq() {
    257 	if hc.config.Bugs.SequenceNumberMapping != nil {
    258 		seqU64 := binary.BigEndian.Uint64(hc.seq[:])
    259 		seqU64 = hc.config.Bugs.SequenceNumberMapping(seqU64)
    260 		binary.BigEndian.PutUint64(hc.outSeq[:], seqU64)
    261 
    262 		// The DTLS epoch cannot be changed.
    263 		copy(hc.outSeq[:2], hc.seq[:2])
    264 		return
    265 	}
    266 
    267 	copy(hc.outSeq[:], hc.seq[:])
    268 }
    269 
    270 func (hc *halfConn) recordHeaderLen() int {
    271 	if hc.isDTLS {
    272 		return dtlsRecordHeaderLen
    273 	}
    274 	return tlsRecordHeaderLen
    275 }
    276 
    277 // removePadding returns an unpadded slice, in constant time, which is a prefix
    278 // of the input. It also returns a byte which is equal to 255 if the padding
    279 // was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
    280 func removePadding(payload []byte) ([]byte, byte) {
    281 	if len(payload) < 1 {
    282 		return payload, 0
    283 	}
    284 
    285 	paddingLen := payload[len(payload)-1]
    286 	t := uint(len(payload)-1) - uint(paddingLen)
    287 	// if len(payload) >= (paddingLen - 1) then the MSB of t is zero
    288 	good := byte(int32(^t) >> 31)
    289 
    290 	toCheck := 255 // the maximum possible padding length
    291 	// The length of the padded data is public, so we can use an if here
    292 	if toCheck+1 > len(payload) {
    293 		toCheck = len(payload) - 1
    294 	}
    295 
    296 	for i := 0; i < toCheck; i++ {
    297 		t := uint(paddingLen) - uint(i)
    298 		// if i <= paddingLen then the MSB of t is zero
    299 		mask := byte(int32(^t) >> 31)
    300 		b := payload[len(payload)-1-i]
    301 		good &^= mask&paddingLen ^ mask&b
    302 	}
    303 
    304 	// We AND together the bits of good and replicate the result across
    305 	// all the bits.
    306 	good &= good << 4
    307 	good &= good << 2
    308 	good &= good << 1
    309 	good = uint8(int8(good) >> 7)
    310 
    311 	toRemove := good&paddingLen + 1
    312 	return payload[:len(payload)-int(toRemove)], good
    313 }
    314 
    315 // removePaddingSSL30 is a replacement for removePadding in the case that the
    316 // protocol version is SSLv3. In this version, the contents of the padding
    317 // are random and cannot be checked.
    318 func removePaddingSSL30(payload []byte) ([]byte, byte) {
    319 	if len(payload) < 1 {
    320 		return payload, 0
    321 	}
    322 
    323 	paddingLen := int(payload[len(payload)-1]) + 1
    324 	if paddingLen > len(payload) {
    325 		return payload, 0
    326 	}
    327 
    328 	return payload[:len(payload)-paddingLen], 255
    329 }
    330 
    331 func roundUp(a, b int) int {
    332 	return a + (b-a%b)%b
    333 }
    334 
    335 // cbcMode is an interface for block ciphers using cipher block chaining.
    336 type cbcMode interface {
    337 	cipher.BlockMode
    338 	SetIV([]byte)
    339 }
    340 
    341 // decrypt checks and strips the mac and decrypts the data in b. Returns a
    342 // success boolean, the number of bytes to skip from the start of the record in
    343 // order to get the application payload, and an optional alert value.
    344 func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, alertValue alert) {
    345 	recordHeaderLen := hc.recordHeaderLen()
    346 
    347 	// pull out payload
    348 	payload := b.data[recordHeaderLen:]
    349 
    350 	macSize := 0
    351 	if hc.mac != nil {
    352 		macSize = hc.mac.Size()
    353 	}
    354 
    355 	paddingGood := byte(255)
    356 	explicitIVLen := 0
    357 
    358 	seq := hc.seq[:]
    359 	if hc.isDTLS {
    360 		// DTLS sequence numbers are explicit.
    361 		seq = b.data[3:11]
    362 	}
    363 
    364 	// decrypt
    365 	if hc.cipher != nil {
    366 		switch c := hc.cipher.(type) {
    367 		case cipher.Stream:
    368 			c.XORKeyStream(payload, payload)
    369 		case *tlsAead:
    370 			nonce := seq
    371 			if c.explicitNonce {
    372 				explicitIVLen = 8
    373 				if len(payload) < explicitIVLen {
    374 					return false, 0, alertBadRecordMAC
    375 				}
    376 				nonce = payload[:8]
    377 				payload = payload[8:]
    378 			}
    379 
    380 			var additionalData [13]byte
    381 			copy(additionalData[:], seq)
    382 			copy(additionalData[8:], b.data[:3])
    383 			n := len(payload) - c.Overhead()
    384 			additionalData[11] = byte(n >> 8)
    385 			additionalData[12] = byte(n)
    386 			var err error
    387 			payload, err = c.Open(payload[:0], nonce, payload, additionalData[:])
    388 			if err != nil {
    389 				return false, 0, alertBadRecordMAC
    390 			}
    391 			b.resize(recordHeaderLen + explicitIVLen + len(payload))
    392 		case cbcMode:
    393 			blockSize := c.BlockSize()
    394 			if hc.version >= VersionTLS11 || hc.isDTLS {
    395 				explicitIVLen = blockSize
    396 			}
    397 
    398 			if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
    399 				return false, 0, alertBadRecordMAC
    400 			}
    401 
    402 			if explicitIVLen > 0 {
    403 				c.SetIV(payload[:explicitIVLen])
    404 				payload = payload[explicitIVLen:]
    405 			}
    406 			c.CryptBlocks(payload, payload)
    407 			if hc.version == VersionSSL30 {
    408 				payload, paddingGood = removePaddingSSL30(payload)
    409 			} else {
    410 				payload, paddingGood = removePadding(payload)
    411 			}
    412 			b.resize(recordHeaderLen + explicitIVLen + len(payload))
    413 
    414 			// note that we still have a timing side-channel in the
    415 			// MAC check, below. An attacker can align the record
    416 			// so that a correct padding will cause one less hash
    417 			// block to be calculated. Then they can iteratively
    418 			// decrypt a record by breaking each byte. See
    419 			// "Password Interception in a SSL/TLS Channel", Brice
    420 			// Canvel et al.
    421 			//
    422 			// However, our behavior matches OpenSSL, so we leak
    423 			// only as much as they do.
    424 		case nullCipher:
    425 			break
    426 		default:
    427 			panic("unknown cipher type")
    428 		}
    429 	}
    430 
    431 	// check, strip mac
    432 	if hc.mac != nil {
    433 		if len(payload) < macSize {
    434 			return false, 0, alertBadRecordMAC
    435 		}
    436 
    437 		// strip mac off payload, b.data
    438 		n := len(payload) - macSize
    439 		b.data[recordHeaderLen-2] = byte(n >> 8)
    440 		b.data[recordHeaderLen-1] = byte(n)
    441 		b.resize(recordHeaderLen + explicitIVLen + n)
    442 		remoteMAC := payload[n:]
    443 		localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
    444 
    445 		if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
    446 			return false, 0, alertBadRecordMAC
    447 		}
    448 		hc.inDigestBuf = localMAC
    449 	}
    450 	hc.incSeq(false)
    451 
    452 	return true, recordHeaderLen + explicitIVLen, 0
    453 }
    454 
    455 // padToBlockSize calculates the needed padding block, if any, for a payload.
    456 // On exit, prefix aliases payload and extends to the end of the last full
    457 // block of payload. finalBlock is a fresh slice which contains the contents of
    458 // any suffix of payload as well as the needed padding to make finalBlock a
    459 // full block.
    460 func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
    461 	overrun := len(payload) % blockSize
    462 	prefix = payload[:len(payload)-overrun]
    463 
    464 	paddingLen := blockSize - overrun
    465 	finalSize := blockSize
    466 	if config.Bugs.MaxPadding {
    467 		for paddingLen+blockSize <= 256 {
    468 			paddingLen += blockSize
    469 		}
    470 		finalSize = 256
    471 	}
    472 	finalBlock = make([]byte, finalSize)
    473 	for i := range finalBlock {
    474 		finalBlock[i] = byte(paddingLen - 1)
    475 	}
    476 	if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
    477 		finalBlock[overrun] ^= 0xff
    478 	}
    479 	copy(finalBlock, payload[len(payload)-overrun:])
    480 	return
    481 }
    482 
    483 // encrypt encrypts and macs the data in b.
    484 func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) {
    485 	recordHeaderLen := hc.recordHeaderLen()
    486 
    487 	// mac
    488 	if hc.mac != nil {
    489 		mac := hc.mac.MAC(hc.outDigestBuf, hc.outSeq[0:], b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], b.data[recordHeaderLen+explicitIVLen:])
    490 
    491 		n := len(b.data)
    492 		b.resize(n + len(mac))
    493 		copy(b.data[n:], mac)
    494 		hc.outDigestBuf = mac
    495 	}
    496 
    497 	payload := b.data[recordHeaderLen:]
    498 
    499 	// encrypt
    500 	if hc.cipher != nil {
    501 		switch c := hc.cipher.(type) {
    502 		case cipher.Stream:
    503 			c.XORKeyStream(payload, payload)
    504 		case *tlsAead:
    505 			payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
    506 			b.resize(len(b.data) + c.Overhead())
    507 			nonce := hc.outSeq[:]
    508 			if c.explicitNonce {
    509 				nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
    510 			}
    511 			payload := b.data[recordHeaderLen+explicitIVLen:]
    512 			payload = payload[:payloadLen]
    513 
    514 			var additionalData [13]byte
    515 			copy(additionalData[:], hc.outSeq[:])
    516 			copy(additionalData[8:], b.data[:3])
    517 			additionalData[11] = byte(payloadLen >> 8)
    518 			additionalData[12] = byte(payloadLen)
    519 
    520 			c.Seal(payload[:0], nonce, payload, additionalData[:])
    521 		case cbcMode:
    522 			blockSize := c.BlockSize()
    523 			if explicitIVLen > 0 {
    524 				c.SetIV(payload[:explicitIVLen])
    525 				payload = payload[explicitIVLen:]
    526 			}
    527 			prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
    528 			b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
    529 			c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
    530 			c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
    531 		case nullCipher:
    532 			break
    533 		default:
    534 			panic("unknown cipher type")
    535 		}
    536 	}
    537 
    538 	// update length to include MAC and any block padding needed.
    539 	n := len(b.data) - recordHeaderLen
    540 	b.data[recordHeaderLen-2] = byte(n >> 8)
    541 	b.data[recordHeaderLen-1] = byte(n)
    542 	hc.incSeq(true)
    543 
    544 	return true, 0
    545 }
    546 
    547 // A block is a simple data buffer.
    548 type block struct {
    549 	data []byte
    550 	off  int // index for Read
    551 	link *block
    552 }
    553 
    554 // resize resizes block to be n bytes, growing if necessary.
    555 func (b *block) resize(n int) {
    556 	if n > cap(b.data) {
    557 		b.reserve(n)
    558 	}
    559 	b.data = b.data[0:n]
    560 }
    561 
    562 // reserve makes sure that block contains a capacity of at least n bytes.
    563 func (b *block) reserve(n int) {
    564 	if cap(b.data) >= n {
    565 		return
    566 	}
    567 	m := cap(b.data)
    568 	if m == 0 {
    569 		m = 1024
    570 	}
    571 	for m < n {
    572 		m *= 2
    573 	}
    574 	data := make([]byte, len(b.data), m)
    575 	copy(data, b.data)
    576 	b.data = data
    577 }
    578 
    579 // readFromUntil reads from r into b until b contains at least n bytes
    580 // or else returns an error.
    581 func (b *block) readFromUntil(r io.Reader, n int) error {
    582 	// quick case
    583 	if len(b.data) >= n {
    584 		return nil
    585 	}
    586 
    587 	// read until have enough.
    588 	b.reserve(n)
    589 	for {
    590 		m, err := r.Read(b.data[len(b.data):cap(b.data)])
    591 		b.data = b.data[0 : len(b.data)+m]
    592 		if len(b.data) >= n {
    593 			// TODO(bradfitz,agl): slightly suspicious
    594 			// that we're throwing away r.Read's err here.
    595 			break
    596 		}
    597 		if err != nil {
    598 			return err
    599 		}
    600 	}
    601 	return nil
    602 }
    603 
    604 func (b *block) Read(p []byte) (n int, err error) {
    605 	n = copy(p, b.data[b.off:])
    606 	b.off += n
    607 	return
    608 }
    609 
    610 // newBlock allocates a new block, from hc's free list if possible.
    611 func (hc *halfConn) newBlock() *block {
    612 	b := hc.bfree
    613 	if b == nil {
    614 		return new(block)
    615 	}
    616 	hc.bfree = b.link
    617 	b.link = nil
    618 	b.resize(0)
    619 	return b
    620 }
    621 
    622 // freeBlock returns a block to hc's free list.
    623 // The protocol is such that each side only has a block or two on
    624 // its free list at a time, so there's no need to worry about
    625 // trimming the list, etc.
    626 func (hc *halfConn) freeBlock(b *block) {
    627 	b.link = hc.bfree
    628 	hc.bfree = b
    629 }
    630 
    631 // splitBlock splits a block after the first n bytes,
    632 // returning a block with those n bytes and a
    633 // block with the remainder.  the latter may be nil.
    634 func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
    635 	if len(b.data) <= n {
    636 		return b, nil
    637 	}
    638 	bb := hc.newBlock()
    639 	bb.resize(len(b.data) - n)
    640 	copy(bb.data, b.data[n:])
    641 	b.data = b.data[0:n]
    642 	return b, bb
    643 }
    644 
    645 func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
    646 	if c.isDTLS {
    647 		return c.dtlsDoReadRecord(want)
    648 	}
    649 
    650 	recordHeaderLen := tlsRecordHeaderLen
    651 
    652 	if c.rawInput == nil {
    653 		c.rawInput = c.in.newBlock()
    654 	}
    655 	b := c.rawInput
    656 
    657 	// Read header, payload.
    658 	if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
    659 		// RFC suggests that EOF without an alertCloseNotify is
    660 		// an error, but popular web sites seem to do this,
    661 		// so we can't make it an error, outside of tests.
    662 		if err == io.EOF && c.config.Bugs.ExpectCloseNotify {
    663 			err = io.ErrUnexpectedEOF
    664 		}
    665 		if e, ok := err.(net.Error); !ok || !e.Temporary() {
    666 			c.in.setErrorLocked(err)
    667 		}
    668 		return 0, nil, err
    669 	}
    670 	typ := recordType(b.data[0])
    671 
    672 	// No valid TLS record has a type of 0x80, however SSLv2 handshakes
    673 	// start with a uint16 length where the MSB is set and the first record
    674 	// is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
    675 	// an SSLv2 client.
    676 	if want == recordTypeHandshake && typ == 0x80 {
    677 		c.sendAlert(alertProtocolVersion)
    678 		return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
    679 	}
    680 
    681 	vers := uint16(b.data[1])<<8 | uint16(b.data[2])
    682 	n := int(b.data[3])<<8 | int(b.data[4])
    683 	if c.haveVers {
    684 		if vers != c.vers {
    685 			c.sendAlert(alertProtocolVersion)
    686 			return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers))
    687 		}
    688 	} else {
    689 		if expect := c.config.Bugs.ExpectInitialRecordVersion; expect != 0 && vers != expect {
    690 			c.sendAlert(alertProtocolVersion)
    691 			return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
    692 		}
    693 	}
    694 	if n > maxCiphertext {
    695 		c.sendAlert(alertRecordOverflow)
    696 		return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
    697 	}
    698 	if !c.haveVers {
    699 		// First message, be extra suspicious:
    700 		// this might not be a TLS client.
    701 		// Bail out before reading a full 'body', if possible.
    702 		// The current max version is 3.1.
    703 		// If the version is >= 16.0, it's probably not real.
    704 		// Similarly, a clientHello message encodes in
    705 		// well under a kilobyte.  If the length is >= 12 kB,
    706 		// it's probably not real.
    707 		if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
    708 			c.sendAlert(alertUnexpectedMessage)
    709 			return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
    710 		}
    711 	}
    712 	if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
    713 		if err == io.EOF {
    714 			err = io.ErrUnexpectedEOF
    715 		}
    716 		if e, ok := err.(net.Error); !ok || !e.Temporary() {
    717 			c.in.setErrorLocked(err)
    718 		}
    719 		return 0, nil, err
    720 	}
    721 
    722 	// Process message.
    723 	b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
    724 	ok, off, err := c.in.decrypt(b)
    725 	if !ok {
    726 		c.in.setErrorLocked(c.sendAlert(err))
    727 	}
    728 	b.off = off
    729 	return typ, b, nil
    730 }
    731 
    732 // readRecord reads the next TLS record from the connection
    733 // and updates the record layer state.
    734 // c.in.Mutex <= L; c.input == nil.
    735 func (c *Conn) readRecord(want recordType) error {
    736 	// Caller must be in sync with connection:
    737 	// handshake data if handshake not yet completed,
    738 	// else application data.
    739 	switch want {
    740 	default:
    741 		c.sendAlert(alertInternalError)
    742 		return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
    743 	case recordTypeHandshake, recordTypeChangeCipherSpec:
    744 		if c.handshakeComplete {
    745 			c.sendAlert(alertInternalError)
    746 			return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
    747 		}
    748 	case recordTypeApplicationData:
    749 		if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart {
    750 			c.sendAlert(alertInternalError)
    751 			return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
    752 		}
    753 	case recordTypeAlert:
    754 		// Looking for a close_notify. Note: unlike a real
    755 		// implementation, this is not tolerant of additional records.
    756 		// See the documentation for ExpectCloseNotify.
    757 	}
    758 
    759 Again:
    760 	typ, b, err := c.doReadRecord(want)
    761 	if err != nil {
    762 		return err
    763 	}
    764 	data := b.data[b.off:]
    765 	if len(data) > maxPlaintext {
    766 		err := c.sendAlert(alertRecordOverflow)
    767 		c.in.freeBlock(b)
    768 		return c.in.setErrorLocked(err)
    769 	}
    770 
    771 	switch typ {
    772 	default:
    773 		c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
    774 
    775 	case recordTypeAlert:
    776 		if len(data) != 2 {
    777 			c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
    778 			break
    779 		}
    780 		if alert(data[1]) == alertCloseNotify {
    781 			c.in.setErrorLocked(io.EOF)
    782 			break
    783 		}
    784 		switch data[0] {
    785 		case alertLevelWarning:
    786 			// drop on the floor
    787 			c.in.freeBlock(b)
    788 			goto Again
    789 		case alertLevelError:
    790 			c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
    791 		default:
    792 			c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
    793 		}
    794 
    795 	case recordTypeChangeCipherSpec:
    796 		if typ != want || len(data) != 1 || data[0] != 1 {
    797 			c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
    798 			break
    799 		}
    800 		err := c.in.changeCipherSpec(c.config)
    801 		if err != nil {
    802 			c.in.setErrorLocked(c.sendAlert(err.(alert)))
    803 		}
    804 
    805 	case recordTypeApplicationData:
    806 		if typ != want {
    807 			c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
    808 			break
    809 		}
    810 		c.input = b
    811 		b = nil
    812 
    813 	case recordTypeHandshake:
    814 		// TODO(rsc): Should at least pick off connection close.
    815 		if typ != want {
    816 			// A client might need to process a HelloRequest from
    817 			// the server, thus receiving a handshake message when
    818 			// application data is expected is ok.
    819 			if !c.isClient || want != recordTypeApplicationData {
    820 				return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
    821 			}
    822 		}
    823 		c.hand.Write(data)
    824 	}
    825 
    826 	if b != nil {
    827 		c.in.freeBlock(b)
    828 	}
    829 	return c.in.err
    830 }
    831 
    832 // sendAlert sends a TLS alert message.
    833 // c.out.Mutex <= L.
    834 func (c *Conn) sendAlertLocked(level byte, err alert) error {
    835 	c.tmp[0] = level
    836 	c.tmp[1] = byte(err)
    837 	if c.config.Bugs.FragmentAlert {
    838 		c.writeRecord(recordTypeAlert, c.tmp[0:1])
    839 		c.writeRecord(recordTypeAlert, c.tmp[1:2])
    840 	} else {
    841 		c.writeRecord(recordTypeAlert, c.tmp[0:2])
    842 	}
    843 	// Error alerts are fatal to the connection.
    844 	if level == alertLevelError {
    845 		return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
    846 	}
    847 	return nil
    848 }
    849 
    850 // sendAlert sends a TLS alert message.
    851 // L < c.out.Mutex.
    852 func (c *Conn) sendAlert(err alert) error {
    853 	level := byte(alertLevelError)
    854 	if err == alertNoRenegotiation || err == alertCloseNotify {
    855 		level = alertLevelWarning
    856 	}
    857 	return c.SendAlert(level, err)
    858 }
    859 
    860 func (c *Conn) SendAlert(level byte, err alert) error {
    861 	c.out.Lock()
    862 	defer c.out.Unlock()
    863 	return c.sendAlertLocked(level, err)
    864 }
    865 
    866 // writeV2Record writes a record for a V2ClientHello.
    867 func (c *Conn) writeV2Record(data []byte) (n int, err error) {
    868 	record := make([]byte, 2+len(data))
    869 	record[0] = uint8(len(data)>>8) | 0x80
    870 	record[1] = uint8(len(data))
    871 	copy(record[2:], data)
    872 	return c.conn.Write(record)
    873 }
    874 
    875 // writeRecord writes a TLS record with the given type and payload
    876 // to the connection and updates the record layer state.
    877 // c.out.Mutex <= L.
    878 func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
    879 	if c.isDTLS {
    880 		return c.dtlsWriteRecord(typ, data)
    881 	}
    882 
    883 	recordHeaderLen := tlsRecordHeaderLen
    884 	b := c.out.newBlock()
    885 	first := true
    886 	isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
    887 	for len(data) > 0 || first {
    888 		m := len(data)
    889 		if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
    890 			m = maxPlaintext
    891 		}
    892 		if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
    893 			m = c.config.Bugs.MaxHandshakeRecordLength
    894 			// By default, do not fragment the client_version or
    895 			// server_version, which are located in the first 6
    896 			// bytes.
    897 			if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
    898 				m = 6
    899 			}
    900 		}
    901 		explicitIVLen := 0
    902 		explicitIVIsSeq := false
    903 		first = false
    904 
    905 		var cbc cbcMode
    906 		if c.out.version >= VersionTLS11 {
    907 			var ok bool
    908 			if cbc, ok = c.out.cipher.(cbcMode); ok {
    909 				explicitIVLen = cbc.BlockSize()
    910 			}
    911 		}
    912 		if explicitIVLen == 0 {
    913 			if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
    914 				explicitIVLen = 8
    915 				// The AES-GCM construction in TLS has an
    916 				// explicit nonce so that the nonce can be
    917 				// random. However, the nonce is only 8 bytes
    918 				// which is too small for a secure, random
    919 				// nonce. Therefore we use the sequence number
    920 				// as the nonce.
    921 				explicitIVIsSeq = true
    922 			}
    923 		}
    924 		b.resize(recordHeaderLen + explicitIVLen + m)
    925 		b.data[0] = byte(typ)
    926 		vers := c.vers
    927 		if vers == 0 {
    928 			// Some TLS servers fail if the record version is
    929 			// greater than TLS 1.0 for the initial ClientHello.
    930 			vers = VersionTLS10
    931 		}
    932 		b.data[1] = byte(vers >> 8)
    933 		b.data[2] = byte(vers)
    934 		b.data[3] = byte(m >> 8)
    935 		b.data[4] = byte(m)
    936 		if explicitIVLen > 0 {
    937 			explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
    938 			if explicitIVIsSeq {
    939 				copy(explicitIV, c.out.seq[:])
    940 			} else {
    941 				if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
    942 					break
    943 				}
    944 			}
    945 		}
    946 		copy(b.data[recordHeaderLen+explicitIVLen:], data)
    947 		c.out.encrypt(b, explicitIVLen)
    948 		_, err = c.conn.Write(b.data)
    949 		if err != nil {
    950 			break
    951 		}
    952 		n += m
    953 		data = data[m:]
    954 	}
    955 	c.out.freeBlock(b)
    956 
    957 	if typ == recordTypeChangeCipherSpec {
    958 		err = c.out.changeCipherSpec(c.config)
    959 		if err != nil {
    960 			// Cannot call sendAlert directly,
    961 			// because we already hold c.out.Mutex.
    962 			c.tmp[0] = alertLevelError
    963 			c.tmp[1] = byte(err.(alert))
    964 			c.writeRecord(recordTypeAlert, c.tmp[0:2])
    965 			return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
    966 		}
    967 	}
    968 	return
    969 }
    970 
    971 func (c *Conn) doReadHandshake() ([]byte, error) {
    972 	if c.isDTLS {
    973 		return c.dtlsDoReadHandshake()
    974 	}
    975 
    976 	for c.hand.Len() < 4 {
    977 		if err := c.in.err; err != nil {
    978 			return nil, err
    979 		}
    980 		if err := c.readRecord(recordTypeHandshake); err != nil {
    981 			return nil, err
    982 		}
    983 	}
    984 
    985 	data := c.hand.Bytes()
    986 	n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
    987 	if n > maxHandshake {
    988 		return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
    989 	}
    990 	for c.hand.Len() < 4+n {
    991 		if err := c.in.err; err != nil {
    992 			return nil, err
    993 		}
    994 		if err := c.readRecord(recordTypeHandshake); err != nil {
    995 			return nil, err
    996 		}
    997 	}
    998 	return c.hand.Next(4 + n), nil
    999 }
   1000 
   1001 // readHandshake reads the next handshake message from
   1002 // the record layer.
   1003 // c.in.Mutex < L; c.out.Mutex < L.
   1004 func (c *Conn) readHandshake() (interface{}, error) {
   1005 	data, err := c.doReadHandshake()
   1006 	if err != nil {
   1007 		return nil, err
   1008 	}
   1009 
   1010 	var m handshakeMessage
   1011 	switch data[0] {
   1012 	case typeHelloRequest:
   1013 		m = new(helloRequestMsg)
   1014 	case typeClientHello:
   1015 		m = &clientHelloMsg{
   1016 			isDTLS: c.isDTLS,
   1017 		}
   1018 	case typeServerHello:
   1019 		m = &serverHelloMsg{
   1020 			isDTLS: c.isDTLS,
   1021 		}
   1022 	case typeNewSessionTicket:
   1023 		m = new(newSessionTicketMsg)
   1024 	case typeCertificate:
   1025 		m = new(certificateMsg)
   1026 	case typeCertificateRequest:
   1027 		m = &certificateRequestMsg{
   1028 			hasSignatureAndHash: c.vers >= VersionTLS12,
   1029 		}
   1030 	case typeCertificateStatus:
   1031 		m = new(certificateStatusMsg)
   1032 	case typeServerKeyExchange:
   1033 		m = new(serverKeyExchangeMsg)
   1034 	case typeServerHelloDone:
   1035 		m = new(serverHelloDoneMsg)
   1036 	case typeClientKeyExchange:
   1037 		m = new(clientKeyExchangeMsg)
   1038 	case typeCertificateVerify:
   1039 		m = &certificateVerifyMsg{
   1040 			hasSignatureAndHash: c.vers >= VersionTLS12,
   1041 		}
   1042 	case typeNextProtocol:
   1043 		m = new(nextProtoMsg)
   1044 	case typeFinished:
   1045 		m = new(finishedMsg)
   1046 	case typeHelloVerifyRequest:
   1047 		m = new(helloVerifyRequestMsg)
   1048 	case typeEncryptedExtensions:
   1049 		m = new(encryptedExtensionsMsg)
   1050 	default:
   1051 		return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   1052 	}
   1053 
   1054 	// The handshake message unmarshallers
   1055 	// expect to be able to keep references to data,
   1056 	// so pass in a fresh copy that won't be overwritten.
   1057 	data = append([]byte(nil), data...)
   1058 
   1059 	if !m.unmarshal(data) {
   1060 		return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   1061 	}
   1062 	return m, nil
   1063 }
   1064 
   1065 // skipPacket processes all the DTLS records in packet. It updates
   1066 // sequence number expectations but otherwise ignores them.
   1067 func (c *Conn) skipPacket(packet []byte) error {
   1068 	for len(packet) > 0 {
   1069 		if len(packet) < 13 {
   1070 			return errors.New("tls: bad packet")
   1071 		}
   1072 		// Dropped packets are completely ignored save to update
   1073 		// expected sequence numbers for this and the next epoch. (We
   1074 		// don't assert on the contents of the packets both for
   1075 		// simplicity and because a previous test with one shorter
   1076 		// timeout schedule would have done so.)
   1077 		epoch := packet[3:5]
   1078 		seq := packet[5:11]
   1079 		length := uint16(packet[11])<<8 | uint16(packet[12])
   1080 		if bytes.Equal(c.in.seq[:2], epoch) {
   1081 			if bytes.Compare(seq, c.in.seq[2:]) < 0 {
   1082 				return errors.New("tls: sequence mismatch")
   1083 			}
   1084 			copy(c.in.seq[2:], seq)
   1085 			c.in.incSeq(false)
   1086 		} else {
   1087 			if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
   1088 				return errors.New("tls: sequence mismatch")
   1089 			}
   1090 			copy(c.in.nextSeq[:], seq)
   1091 			c.in.incNextSeq()
   1092 		}
   1093 		if len(packet) < 13+int(length) {
   1094 			return errors.New("tls: bad packet")
   1095 		}
   1096 		packet = packet[13+length:]
   1097 	}
   1098 	return nil
   1099 }
   1100 
   1101 // simulatePacketLoss simulates the loss of a handshake leg from the
   1102 // peer based on the schedule in c.config.Bugs. If resendFunc is
   1103 // non-nil, it is called after each simulated timeout to retransmit
   1104 // handshake messages from the local end. This is used in cases where
   1105 // the peer retransmits on a stale Finished rather than a timeout.
   1106 func (c *Conn) simulatePacketLoss(resendFunc func()) error {
   1107 	if len(c.config.Bugs.TimeoutSchedule) == 0 {
   1108 		return nil
   1109 	}
   1110 	if !c.isDTLS {
   1111 		return errors.New("tls: TimeoutSchedule may only be set in DTLS")
   1112 	}
   1113 	if c.config.Bugs.PacketAdaptor == nil {
   1114 		return errors.New("tls: TimeoutSchedule set without PacketAdapter")
   1115 	}
   1116 	for _, timeout := range c.config.Bugs.TimeoutSchedule {
   1117 		// Simulate a timeout.
   1118 		packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
   1119 		if err != nil {
   1120 			return err
   1121 		}
   1122 		for _, packet := range packets {
   1123 			if err := c.skipPacket(packet); err != nil {
   1124 				return err
   1125 			}
   1126 		}
   1127 		if resendFunc != nil {
   1128 			resendFunc()
   1129 		}
   1130 	}
   1131 	return nil
   1132 }
   1133 
   1134 // Write writes data to the connection.
   1135 func (c *Conn) Write(b []byte) (int, error) {
   1136 	if err := c.Handshake(); err != nil {
   1137 		return 0, err
   1138 	}
   1139 
   1140 	c.out.Lock()
   1141 	defer c.out.Unlock()
   1142 
   1143 	if err := c.out.err; err != nil {
   1144 		return 0, err
   1145 	}
   1146 
   1147 	if !c.handshakeComplete {
   1148 		return 0, alertInternalError
   1149 	}
   1150 
   1151 	if c.config.Bugs.SendSpuriousAlert != 0 {
   1152 		c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
   1153 	}
   1154 
   1155 	if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
   1156 		c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
   1157 	}
   1158 
   1159 	// SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
   1160 	// attack when using block mode ciphers due to predictable IVs.
   1161 	// This can be prevented by splitting each Application Data
   1162 	// record into two records, effectively randomizing the IV.
   1163 	//
   1164 	// http://www.openssl.org/~bodo/tls-cbc.txt
   1165 	// https://bugzilla.mozilla.org/show_bug.cgi?id=665814
   1166 	// http://www.imperialviolet.org/2012/01/15/beastfollowup.html
   1167 
   1168 	var m int
   1169 	if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
   1170 		if _, ok := c.out.cipher.(cipher.BlockMode); ok {
   1171 			n, err := c.writeRecord(recordTypeApplicationData, b[:1])
   1172 			if err != nil {
   1173 				return n, c.out.setErrorLocked(err)
   1174 			}
   1175 			m, b = 1, b[1:]
   1176 		}
   1177 	}
   1178 
   1179 	n, err := c.writeRecord(recordTypeApplicationData, b)
   1180 	return n + m, c.out.setErrorLocked(err)
   1181 }
   1182 
   1183 func (c *Conn) handleRenegotiation() error {
   1184 	c.handshakeComplete = false
   1185 	if !c.isClient {
   1186 		panic("renegotiation should only happen for a client")
   1187 	}
   1188 
   1189 	msg, err := c.readHandshake()
   1190 	if err != nil {
   1191 		return err
   1192 	}
   1193 	_, ok := msg.(*helloRequestMsg)
   1194 	if !ok {
   1195 		c.sendAlert(alertUnexpectedMessage)
   1196 		return alertUnexpectedMessage
   1197 	}
   1198 
   1199 	return c.Handshake()
   1200 }
   1201 
   1202 func (c *Conn) Renegotiate() error {
   1203 	if !c.isClient {
   1204 		helloReq := new(helloRequestMsg).marshal()
   1205 		if c.config.Bugs.BadHelloRequest != nil {
   1206 			helloReq = c.config.Bugs.BadHelloRequest
   1207 		}
   1208 		c.writeRecord(recordTypeHandshake, helloReq)
   1209 	}
   1210 
   1211 	c.handshakeComplete = false
   1212 	return c.Handshake()
   1213 }
   1214 
   1215 // Read can be made to time out and return a net.Error with Timeout() == true
   1216 // after a fixed time limit; see SetDeadline and SetReadDeadline.
   1217 func (c *Conn) Read(b []byte) (n int, err error) {
   1218 	if err = c.Handshake(); err != nil {
   1219 		return
   1220 	}
   1221 
   1222 	c.in.Lock()
   1223 	defer c.in.Unlock()
   1224 
   1225 	// Some OpenSSL servers send empty records in order to randomize the
   1226 	// CBC IV. So this loop ignores a limited number of empty records.
   1227 	const maxConsecutiveEmptyRecords = 100
   1228 	for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
   1229 		for c.input == nil && c.in.err == nil {
   1230 			if err := c.readRecord(recordTypeApplicationData); err != nil {
   1231 				// Soft error, like EAGAIN
   1232 				return 0, err
   1233 			}
   1234 			if c.hand.Len() > 0 {
   1235 				// We received handshake bytes, indicating the
   1236 				// start of a renegotiation.
   1237 				if err := c.handleRenegotiation(); err != nil {
   1238 					return 0, err
   1239 				}
   1240 				continue
   1241 			}
   1242 		}
   1243 		if err := c.in.err; err != nil {
   1244 			return 0, err
   1245 		}
   1246 
   1247 		n, err = c.input.Read(b)
   1248 		if c.input.off >= len(c.input.data) || c.isDTLS {
   1249 			c.in.freeBlock(c.input)
   1250 			c.input = nil
   1251 		}
   1252 
   1253 		// If a close-notify alert is waiting, read it so that
   1254 		// we can return (n, EOF) instead of (n, nil), to signal
   1255 		// to the HTTP response reading goroutine that the
   1256 		// connection is now closed. This eliminates a race
   1257 		// where the HTTP response reading goroutine would
   1258 		// otherwise not observe the EOF until its next read,
   1259 		// by which time a client goroutine might have already
   1260 		// tried to reuse the HTTP connection for a new
   1261 		// request.
   1262 		// See https://codereview.appspot.com/76400046
   1263 		// and http://golang.org/issue/3514
   1264 		if ri := c.rawInput; ri != nil &&
   1265 			n != 0 && err == nil &&
   1266 			c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
   1267 			if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
   1268 				err = recErr // will be io.EOF on closeNotify
   1269 			}
   1270 		}
   1271 
   1272 		if n != 0 || err != nil {
   1273 			return n, err
   1274 		}
   1275 	}
   1276 
   1277 	return 0, io.ErrNoProgress
   1278 }
   1279 
   1280 // Close closes the connection.
   1281 func (c *Conn) Close() error {
   1282 	var alertErr error
   1283 
   1284 	c.handshakeMutex.Lock()
   1285 	defer c.handshakeMutex.Unlock()
   1286 	if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
   1287 		alertErr = c.sendAlert(alertCloseNotify)
   1288 	}
   1289 
   1290 	// Consume a close_notify from the peer if one hasn't been received
   1291 	// already. This avoids the peer from failing |SSL_shutdown| due to a
   1292 	// write failing.
   1293 	if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
   1294 		for c.in.error() == nil {
   1295 			c.readRecord(recordTypeAlert)
   1296 		}
   1297 		if c.in.error() != io.EOF {
   1298 			alertErr = c.in.error()
   1299 		}
   1300 	}
   1301 
   1302 	if err := c.conn.Close(); err != nil {
   1303 		return err
   1304 	}
   1305 	return alertErr
   1306 }
   1307 
   1308 // Handshake runs the client or server handshake
   1309 // protocol if it has not yet been run.
   1310 // Most uses of this package need not call Handshake
   1311 // explicitly: the first Read or Write will call it automatically.
   1312 func (c *Conn) Handshake() error {
   1313 	c.handshakeMutex.Lock()
   1314 	defer c.handshakeMutex.Unlock()
   1315 	if err := c.handshakeErr; err != nil {
   1316 		return err
   1317 	}
   1318 	if c.handshakeComplete {
   1319 		return nil
   1320 	}
   1321 
   1322 	if c.isDTLS && c.config.Bugs.SendSplitAlert {
   1323 		c.conn.Write([]byte{
   1324 			byte(recordTypeAlert), // type
   1325 			0xfe, 0xff, // version
   1326 			0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
   1327 			0x0, 0x2, // length
   1328 		})
   1329 		c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
   1330 	}
   1331 	if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
   1332 		c.writeRecord(recordTypeApplicationData, data)
   1333 	}
   1334 	if c.isClient {
   1335 		c.handshakeErr = c.clientHandshake()
   1336 	} else {
   1337 		c.handshakeErr = c.serverHandshake()
   1338 	}
   1339 	if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
   1340 		c.writeRecord(recordType(42), []byte("invalid record"))
   1341 	}
   1342 	return c.handshakeErr
   1343 }
   1344 
   1345 // ConnectionState returns basic TLS details about the connection.
   1346 func (c *Conn) ConnectionState() ConnectionState {
   1347 	c.handshakeMutex.Lock()
   1348 	defer c.handshakeMutex.Unlock()
   1349 
   1350 	var state ConnectionState
   1351 	state.HandshakeComplete = c.handshakeComplete
   1352 	if c.handshakeComplete {
   1353 		state.Version = c.vers
   1354 		state.NegotiatedProtocol = c.clientProtocol
   1355 		state.DidResume = c.didResume
   1356 		state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
   1357 		state.NegotiatedProtocolFromALPN = c.usedALPN
   1358 		state.CipherSuite = c.cipherSuite.id
   1359 		state.PeerCertificates = c.peerCertificates
   1360 		state.VerifiedChains = c.verifiedChains
   1361 		state.ServerName = c.serverName
   1362 		state.ChannelID = c.channelID
   1363 		state.SRTPProtectionProfile = c.srtpProtectionProfile
   1364 		state.TLSUnique = c.firstFinished[:]
   1365 		state.SCTList = c.sctList
   1366 		state.ClientCertSignatureHash = c.clientCertSignatureHash
   1367 	}
   1368 
   1369 	return state
   1370 }
   1371 
   1372 // OCSPResponse returns the stapled OCSP response from the TLS server, if
   1373 // any. (Only valid for client connections.)
   1374 func (c *Conn) OCSPResponse() []byte {
   1375 	c.handshakeMutex.Lock()
   1376 	defer c.handshakeMutex.Unlock()
   1377 
   1378 	return c.ocspResponse
   1379 }
   1380 
   1381 // VerifyHostname checks that the peer certificate chain is valid for
   1382 // connecting to host.  If so, it returns nil; if not, it returns an error
   1383 // describing the problem.
   1384 func (c *Conn) VerifyHostname(host string) error {
   1385 	c.handshakeMutex.Lock()
   1386 	defer c.handshakeMutex.Unlock()
   1387 	if !c.isClient {
   1388 		return errors.New("tls: VerifyHostname called on TLS server connection")
   1389 	}
   1390 	if !c.handshakeComplete {
   1391 		return errors.New("tls: handshake has not yet been performed")
   1392 	}
   1393 	return c.peerCertificates[0].VerifyHostname(host)
   1394 }
   1395 
   1396 // ExportKeyingMaterial exports keying material from the current connection
   1397 // state, as per RFC 5705.
   1398 func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
   1399 	c.handshakeMutex.Lock()
   1400 	defer c.handshakeMutex.Unlock()
   1401 	if !c.handshakeComplete {
   1402 		return nil, errors.New("tls: handshake has not yet been performed")
   1403 	}
   1404 
   1405 	seedLen := len(c.clientRandom) + len(c.serverRandom)
   1406 	if useContext {
   1407 		seedLen += 2 + len(context)
   1408 	}
   1409 	seed := make([]byte, 0, seedLen)
   1410 	seed = append(seed, c.clientRandom[:]...)
   1411 	seed = append(seed, c.serverRandom[:]...)
   1412 	if useContext {
   1413 		seed = append(seed, byte(len(context)>>8), byte(len(context)))
   1414 		seed = append(seed, context...)
   1415 	}
   1416 	result := make([]byte, length)
   1417 	prfForVersion(c.vers, c.cipherSuite)(result, c.masterSecret[:], label, seed)
   1418 	return result, nil
   1419 }
   1420 
   1421 // noRenegotiationInfo returns true if the renegotiation info extension
   1422 // should be supported in the current handshake.
   1423 func (c *Conn) noRenegotiationInfo() bool {
   1424 	if c.config.Bugs.NoRenegotiationInfo {
   1425 		return true
   1426 	}
   1427 	if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
   1428 		return true
   1429 	}
   1430 	if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
   1431 		return true
   1432 	}
   1433 	return false
   1434 }
   1435