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