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