blob: fce00495af6e8eda271fb16ef6263d9e37801f85 [file] [log] [blame]
Adam Langley95c29f32014-06-20 12:00:00 -07001// 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
Adam Langleydc7e9c42015-09-29 15:21:04 -07007package runner
Adam Langley95c29f32014-06-20 12:00:00 -07008
9import (
10 "bytes"
11 "crypto/cipher"
David Benjamind30a9902014-08-24 01:44:23 -040012 "crypto/ecdsa"
Adam Langley95c29f32014-06-20 12:00:00 -070013 "crypto/subtle"
14 "crypto/x509"
David Benjamin8e6db492015-07-25 18:29:23 -040015 "encoding/binary"
Adam Langley95c29f32014-06-20 12:00:00 -070016 "errors"
17 "fmt"
18 "io"
19 "net"
20 "sync"
21 "time"
22)
23
David Benjamin053fee92017-01-02 08:30:36 -050024var errNoCertificateAlert = errors.New("tls: no certificate alert")
Nick Harperab20cec2016-12-19 17:38:41 -080025var errEndOfEarlyDataAlert = errors.New("tls: end of early data alert")
David Benjamin053fee92017-01-02 08:30:36 -050026
Adam Langley95c29f32014-06-20 12:00:00 -070027// A Conn represents a secured connection.
28// It implements the net.Conn interface.
29type Conn struct {
30 // constant
31 conn net.Conn
David Benjamin83c0bc92014-08-04 01:23:53 -040032 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -070033 isClient bool
34
35 // constant after handshake; protected by handshakeMutex
Adam Langley75712922014-10-10 16:23:43 -070036 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
Nick Harperab20cec2016-12-19 17:38:41 -080042 skipEarlyData bool // On a server, indicates that the client is sending early data that must be skipped over.
Adam Langley75712922014-10-10 16:23:43 -070043 didResume bool // whether this connection was a session resumption
44 extendedMasterSecret bool // whether this session used an extended master secret
David Benjaminc565ebb2015-04-03 04:06:36 -040045 cipherSuite *cipherSuite
Adam Langley75712922014-10-10 16:23:43 -070046 ocspResponse []byte // stapled OCSP response
Paul Lietar4fac72e2015-09-09 13:44:55 +010047 sctList []byte // signed certificate timestamp list
Adam Langley75712922014-10-10 16:23:43 -070048 peerCertificates []*x509.Certificate
Adam Langley95c29f32014-06-20 12:00:00 -070049 // 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.
Adam Langleyaf0e32c2015-06-03 09:57:23 -070053 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
Nick Harper60edffd2016-06-21 15:19:24 -070057 // peerSignatureAlgorithm contains the signature algorithm that was used
58 // by the peer in the handshake, or zero if not applicable.
59 peerSignatureAlgorithm signatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -040060 // curveID contains the curve that was used in the handshake, or zero if
61 // not applicable.
62 curveID CurveID
Adam Langleyaf0e32c2015-06-03 09:57:23 -070063
David Benjaminc565ebb2015-04-03 04:06:36 -040064 clientRandom, serverRandom [32]byte
David Benjamin97a0a082016-07-13 17:57:35 -040065 exporterSecret []byte
David Benjamin58104882016-07-18 01:25:41 +020066 resumptionSecret []byte
Adam Langley95c29f32014-06-20 12:00:00 -070067
68 clientProtocol string
69 clientProtocolFallback bool
David Benjaminfc7b0862014-09-06 13:21:53 -040070 usedALPN bool
Adam Langley95c29f32014-06-20 12:00:00 -070071
Adam Langley2ae77d22014-10-28 17:29:33 -070072 // verify_data values for the renegotiation extension.
73 clientVerify []byte
74 serverVerify []byte
75
David Benjamind30a9902014-08-24 01:44:23 -040076 channelID *ecdsa.PublicKey
77
David Benjaminca6c8262014-11-15 19:06:08 -050078 srtpProtectionProfile uint16
79
David Benjaminc44b1df2014-11-23 12:11:01 -050080 clientVersion uint16
81
Adam Langley95c29f32014-06-20 12:00:00 -070082 // input/output
83 in, out halfConn // in.Mutex < out.Mutex
84 rawInput *block // raw input, right off the wire
David Benjamin83c0bc92014-08-04 01:23:53 -040085 input *block // application record waiting to be read
86 hand bytes.Buffer // handshake record waiting to be read
87
David Benjamin582ba042016-07-07 12:33:25 -070088 // 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
David Benjamin83c0bc92014-08-04 01:23:53 -040092 // DTLS state
93 sendHandshakeSeq uint16
94 recvHandshakeSeq uint16
David Benjaminb3774b92015-01-31 17:16:01 -050095 handMsg []byte // pending assembled handshake message
96 handMsgLen int // handshake message length, not including the header
97 pendingFragments [][]byte // pending outgoing handshake fragments.
Adam Langley95c29f32014-06-20 12:00:00 -070098
Steven Valdezc4aa7272016-10-03 12:25:56 -040099 keyUpdateRequested bool
100
Adam Langley95c29f32014-06-20 12:00:00 -0700101 tmp [16]byte
102}
103
David Benjamin5e961c12014-11-07 01:48:35 -0500104func (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
David Benjamin8e6db492015-07-25 18:29:23 -0400109
110 c.out.updateOutSeq()
David Benjamin5e961c12014-11-07 01:48:35 -0500111}
112
Adam Langley95c29f32014-06-20 12:00:00 -0700113// 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
David Benjamin83c0bc92014-08-04 01:23:53 -0400152 err error // first permanent error
153 version uint16 // protocol version
154 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -0700155 cipher interface{} // cipher algorithm
156 mac macFunction
157 seq [8]byte // 64-bit sequence number
David Benjamin8e6db492015-07-25 18:29:23 -0400158 outSeq [8]byte // Mapped sequence number
Adam Langley95c29f32014-06-20 12:00:00 -0700159 bfree *block // list of free blocks
160
161 nextCipher interface{} // next encryption state
162 nextMac macFunction // next MAC algorithm
David Benjamin83f90402015-01-27 01:09:43 -0500163 nextSeq [6]byte // next epoch's starting sequence number in DTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700164
165 // used to save allocating a new buffer for each MAC.
166 inDigestBuf, outDigestBuf []byte
Adam Langley80842bd2014-06-20 12:00:00 -0700167
Steven Valdezc4aa7272016-10-03 12:25:56 -0400168 trafficSecret []byte
David Benjamin21c00282016-07-18 21:56:23 +0200169
Adam Langley80842bd2014-06-20 12:00:00 -0700170 config *Config
Adam Langley95c29f32014-06-20 12:00:00 -0700171}
172
173func (hc *halfConn) setErrorLocked(err error) error {
174 hc.err = err
175 return err
176}
177
178func (hc *halfConn) error() error {
Adam Langley2ae77d22014-10-28 17:29:33 -0700179 // 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.
Adam Langley95c29f32014-06-20 12:00:00 -0700182 err := hc.err
Adam Langley95c29f32014-06-20 12:00:00 -0700183 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.
Adam Langley80842bd2014-06-20 12:00:00 -0700196func (hc *halfConn) changeCipherSpec(config *Config) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700197 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
Adam Langley80842bd2014-06-20 12:00:00 -0700204 hc.config = config
David Benjamin83c0bc92014-08-04 01:23:53 -0400205 hc.incEpoch()
David Benjaminf2b83632016-03-01 22:57:46 -0500206
207 if config.Bugs.NullAllCiphers {
David Benjamin7a4aaa42016-09-20 17:58:14 -0400208 hc.cipher = nullCipher{}
David Benjaminf2b83632016-03-01 22:57:46 -0500209 hc.mac = nil
210 }
Adam Langley95c29f32014-06-20 12:00:00 -0700211 return nil
212}
213
David Benjamin21c00282016-07-18 21:56:23 +0200214// useTrafficSecret sets the current cipher state for TLS 1.3.
Steven Valdeza833c352016-11-01 13:39:36 -0400215func (hc *halfConn) useTrafficSecret(version uint16, suite *cipherSuite, secret []byte, side trafficDirection) {
Nick Harperb41d2e42016-07-01 17:50:32 -0400216 hc.version = version
Steven Valdeza833c352016-11-01 13:39:36 -0400217 hc.cipher = deriveTrafficAEAD(version, suite, secret, side)
David Benjamin7a4aaa42016-09-20 17:58:14 -0400218 if hc.config.Bugs.NullAllCiphers {
219 hc.cipher = nullCipher{}
220 }
David Benjamin21c00282016-07-18 21:56:23 +0200221 hc.trafficSecret = secret
Nick Harperb41d2e42016-07-01 17:50:32 -0400222 hc.incEpoch()
223}
224
Nick Harperf2511f12016-12-06 16:02:31 -0800225// 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
David Benjamin21c00282016-07-18 21:56:23 +0200233func (hc *halfConn) doKeyUpdate(c *Conn, isOutgoing bool) {
234 side := serverWrite
235 if c.isClient == isOutgoing {
236 side = clientWrite
237 }
Steven Valdeza833c352016-11-01 13:39:36 -0400238 hc.useTrafficSecret(hc.version, c.cipherSuite, updateTrafficSecret(c.cipherSuite.hash(), hc.trafficSecret), side)
David Benjamin21c00282016-07-18 21:56:23 +0200239}
240
Adam Langley95c29f32014-06-20 12:00:00 -0700241// incSeq increments the sequence number.
David Benjamin5e961c12014-11-07 01:48:35 -0500242func (hc *halfConn) incSeq(isOutgoing bool) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400243 limit := 0
David Benjamin5e961c12014-11-07 01:48:35 -0500244 increment := uint64(1)
David Benjamin83c0bc92014-08-04 01:23:53 -0400245 if hc.isDTLS {
246 // Increment up to the epoch in DTLS.
247 limit = 2
248 }
249 for i := 7; i >= limit; i-- {
David Benjamin5e961c12014-11-07 01:48:35 -0500250 increment += uint64(hc.seq[i])
251 hc.seq[i] = byte(increment)
252 increment >>= 8
Adam Langley95c29f32014-06-20 12:00:00 -0700253 }
254
255 // Not allowed to let sequence number wrap.
256 // Instead, must renegotiate before it does.
257 // Not likely enough to bother.
David Benjamin5e961c12014-11-07 01:48:35 -0500258 if increment != 0 {
259 panic("TLS: sequence number wraparound")
260 }
David Benjamin8e6db492015-07-25 18:29:23 -0400261
262 hc.updateOutSeq()
Adam Langley95c29f32014-06-20 12:00:00 -0700263}
264
David Benjamin83f90402015-01-27 01:09:43 -0500265// 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.
David Benjamin83c0bc92014-08-04 01:23:53 -0400278func (hc *halfConn) incEpoch() {
David Benjamin83c0bc92014-08-04 01:23:53 -0400279 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 }
David Benjamin83f90402015-01-27 01:09:43 -0500289 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 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400297 }
David Benjamin8e6db492015-07-25 18:29:23 -0400298
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[:])
David Benjamin83c0bc92014-08-04 01:23:53 -0400314}
315
316func (hc *halfConn) recordHeaderLen() int {
317 if hc.isDTLS {
318 return dtlsRecordHeaderLen
319 }
320 return tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700321}
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
Nick Harper1fd39d82016-06-14 18:14:35 -0700389// 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) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400392 recordHeaderLen := hc.recordHeaderLen()
393
Adam Langley95c29f32014-06-20 12:00:00 -0700394 // 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
David Benjamin83c0bc92014-08-04 01:23:53 -0400405 seq := hc.seq[:]
406 if hc.isDTLS {
407 // DTLS sequence numbers are explicit.
408 seq = b.data[3:11]
409 }
410
Adam Langley95c29f32014-06-20 12:00:00 -0700411 // decrypt
412 if hc.cipher != nil {
413 switch c := hc.cipher.(type) {
414 case cipher.Stream:
415 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400416 case *tlsAead:
417 nonce := seq
418 if c.explicitNonce {
419 explicitIVLen = 8
420 if len(payload) < explicitIVLen {
Nick Harper1fd39d82016-06-14 18:14:35 -0700421 return false, 0, 0, alertBadRecordMAC
David Benjamine9a80ff2015-04-07 00:46:46 -0400422 }
423 nonce = payload[:8]
424 payload = payload[8:]
Adam Langley95c29f32014-06-20 12:00:00 -0700425 }
Adam Langley95c29f32014-06-20 12:00:00 -0700426
Nick Harper1fd39d82016-06-14 18:14:35 -0700427 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 }
Adam Langley95c29f32014-06-20 12:00:00 -0700436 var err error
Nick Harper1fd39d82016-06-14 18:14:35 -0700437 payload, err = c.Open(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700438 if err != nil {
Nick Harper1fd39d82016-06-14 18:14:35 -0700439 return false, 0, 0, alertBadRecordMAC
440 }
Adam Langley95c29f32014-06-20 12:00:00 -0700441 b.resize(recordHeaderLen + explicitIVLen + len(payload))
442 case cbcMode:
443 blockSize := c.BlockSize()
David Benjamin83c0bc92014-08-04 01:23:53 -0400444 if hc.version >= VersionTLS11 || hc.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700445 explicitIVLen = blockSize
446 }
447
448 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
Nick Harper1fd39d82016-06-14 18:14:35 -0700449 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700450 }
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.
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700474 case nullCipher:
475 break
Adam Langley95c29f32014-06-20 12:00:00 -0700476 default:
477 panic("unknown cipher type")
478 }
David Benjamin7a4aaa42016-09-20 17:58:14 -0400479
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 }
Adam Langley95c29f32014-06-20 12:00:00 -0700493 }
494
495 // check, strip mac
496 if hc.mac != nil {
497 if len(payload) < macSize {
Nick Harper1fd39d82016-06-14 18:14:35 -0700498 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700499 }
500
501 // strip mac off payload, b.data
502 n := len(payload) - macSize
David Benjamin83c0bc92014-08-04 01:23:53 -0400503 b.data[recordHeaderLen-2] = byte(n >> 8)
504 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700505 b.resize(recordHeaderLen + explicitIVLen + n)
506 remoteMAC := payload[n:]
David Benjamin83c0bc92014-08-04 01:23:53 -0400507 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
Adam Langley95c29f32014-06-20 12:00:00 -0700508
509 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
Nick Harper1fd39d82016-06-14 18:14:35 -0700510 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700511 }
512 hc.inDigestBuf = localMAC
513 }
David Benjamin5e961c12014-11-07 01:48:35 -0500514 hc.incSeq(false)
Adam Langley95c29f32014-06-20 12:00:00 -0700515
Nick Harper1fd39d82016-06-14 18:14:35 -0700516 return true, recordHeaderLen + explicitIVLen, contentType, 0
Adam Langley95c29f32014-06-20 12:00:00 -0700517}
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.
Adam Langley80842bd2014-06-20 12:00:00 -0700524func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
Adam Langley95c29f32014-06-20 12:00:00 -0700525 overrun := len(payload) % blockSize
Adam Langley95c29f32014-06-20 12:00:00 -0700526 prefix = payload[:len(payload)-overrun]
Adam Langley80842bd2014-06-20 12:00:00 -0700527
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 {
Adam Langley95c29f32014-06-20 12:00:00 -0700538 finalBlock[i] = byte(paddingLen - 1)
539 }
Adam Langley80842bd2014-06-20 12:00:00 -0700540 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
541 finalBlock[overrun] ^= 0xff
542 }
543 copy(finalBlock, payload[len(payload)-overrun:])
Adam Langley95c29f32014-06-20 12:00:00 -0700544 return
545}
546
547// encrypt encrypts and macs the data in b.
Nick Harper1fd39d82016-06-14 18:14:35 -0700548func (hc *halfConn) encrypt(b *block, explicitIVLen int, typ recordType) (bool, alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400549 recordHeaderLen := hc.recordHeaderLen()
550
Adam Langley95c29f32014-06-20 12:00:00 -0700551 // mac
552 if hc.mac != nil {
David Benjamin8e6db492015-07-25 18:29:23 -0400553 mac := hc.mac.MAC(hc.outDigestBuf, hc.outSeq[0:], b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], b.data[recordHeaderLen+explicitIVLen:])
Adam Langley95c29f32014-06-20 12:00:00 -0700554
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 {
David Benjamin7a4aaa42016-09-20 17:58:14 -0400565 // 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
Adam Langley95c29f32014-06-20 12:00:00 -0700579 switch c := hc.cipher.(type) {
580 case cipher.Stream:
581 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400582 case *tlsAead:
Adam Langley95c29f32014-06-20 12:00:00 -0700583 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
David Benjamin7a4aaa42016-09-20 17:58:14 -0400584 b.resize(len(b.data) + c.Overhead())
David Benjamin8e6db492015-07-25 18:29:23 -0400585 nonce := hc.outSeq[:]
David Benjamine9a80ff2015-04-07 00:46:46 -0400586 if c.explicitNonce {
587 nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
588 }
Adam Langley95c29f32014-06-20 12:00:00 -0700589 payload := b.data[recordHeaderLen+explicitIVLen:]
590 payload = payload[:payloadLen]
591
Nick Harper1fd39d82016-06-14 18:14:35 -0700592 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 }
Adam Langley95c29f32014-06-20 12:00:00 -0700600
Nick Harper1fd39d82016-06-14 18:14:35 -0700601 c.Seal(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700602 case cbcMode:
603 blockSize := c.BlockSize()
604 if explicitIVLen > 0 {
605 c.SetIV(payload[:explicitIVLen])
606 payload = payload[explicitIVLen:]
607 }
Adam Langley80842bd2014-06-20 12:00:00 -0700608 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700609 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)
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700612 case nullCipher:
613 break
Adam Langley95c29f32014-06-20 12:00:00 -0700614 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
David Benjamin83c0bc92014-08-04 01:23:53 -0400621 b.data[recordHeaderLen-2] = byte(n >> 8)
622 b.data[recordHeaderLen-1] = byte(n)
David Benjamin5e961c12014-11-07 01:48:35 -0500623 hc.incSeq(true)
Adam Langley95c29f32014-06-20 12:00:00 -0700624
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
David Benjamin83c0bc92014-08-04 01:23:53 -0400726func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
Nick Harper47383aa2016-11-30 12:50:43 -0800727RestartReadRecord:
David Benjamin83c0bc92014-08-04 01:23:53 -0400728 if c.isDTLS {
729 return c.dtlsDoReadRecord(want)
730 }
731
David Benjamin6f600d62016-12-21 16:06:54 -0500732 recordHeaderLen := c.in.recordHeaderLen()
David Benjamin83c0bc92014-08-04 01:23:53 -0400733
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,
David Benjamin30789da2015-08-29 22:56:45 -0400743 // 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 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400747 if e, ok := err.(net.Error); !ok || !e.Temporary() {
748 c.in.setErrorLocked(err)
749 }
750 return 0, nil, err
751 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400752
Steven Valdez924a3522017-03-02 16:05:03 -0500753 typ := recordType(b.data[0])
David Benjamin6f600d62016-12-21 16:06:54 -0500754
Steven Valdez924a3522017-03-02 16:05:03 -0500755 // 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"))
David Benjamin83c0bc92014-08-04 01:23:53 -0400762 }
763
Steven Valdez924a3522017-03-02 16:05:03 -0500764 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
765 n := int(b.data[3])<<8 | int(b.data[4])
766
David Benjaminbde00392016-06-21 12:19:28 -0400767 // 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 {
David Benjamine6f22212016-11-08 14:28:24 -0500771 var expect uint16
David Benjaminbde00392016-06-21 12:19:28 -0400772 if c.haveVers {
David Benjamine6f22212016-11-08 14:28:24 -0500773 expect = c.vers
774 if c.vers >= VersionTLS13 {
775 expect = VersionTLS10
David Benjaminbde00392016-06-21 12:19:28 -0400776 }
777 } else {
David Benjamine6f22212016-11-08 14:28:24 -0500778 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))
David Benjamin1e29a6b2014-12-10 02:27:24 -0500783 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400784 }
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)
David Benjaminff26f092016-07-01 16:13:42 -0400815 ok, off, encTyp, alertValue := c.in.decrypt(b)
Nick Harper47383aa2016-11-30 12:50:43 -0800816
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
David Benjaminff26f092016-07-01 16:13:42 -0400829 if !ok {
830 return 0, nil, c.in.setErrorLocked(c.sendAlert(alertValue))
831 }
832 b.off = off
Nick Harper47383aa2016-11-30 12:50:43 -0800833 c.skipEarlyData = false
David Benjaminff26f092016-07-01 16:13:42 -0400834
Nick Harper1fd39d82016-06-14 18:14:35 -0700835 if c.vers >= VersionTLS13 && c.in.cipher != nil {
David Benjaminc9ae27c2016-06-24 22:56:37 -0400836 if typ != recordTypeApplicationData {
837 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: outer record type is not application data"))
838 }
Nick Harper1fd39d82016-06-14 18:14:35 -0700839 typ = encTyp
840 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400841 return typ, b, nil
842}
843
Adam Langley95c29f32014-06-20 12:00:00 -0700844// 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,
Adam Langley2ae77d22014-10-28 17:29:33 -0700850 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700851 switch want {
852 default:
853 c.sendAlert(alertInternalError)
854 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
David Benjaminbbba9392017-04-06 12:54:12 -0400855 case recordTypeChangeCipherSpec:
Adam Langley95c29f32014-06-20 12:00:00 -0700856 if c.handshakeComplete {
857 c.sendAlert(alertInternalError)
David Benjaminbbba9392017-04-06 12:54:12 -0400858 return c.in.setErrorLocked(errors.New("tls: ChangeCipherSpec requested after handshake complete"))
Adam Langley95c29f32014-06-20 12:00:00 -0700859 }
Steven Valdeze831a812017-03-09 14:56:07 -0500860 case recordTypeApplicationData, recordTypeAlert, recordTypeHandshake:
861 break
Adam Langley95c29f32014-06-20 12:00:00 -0700862 }
863
864Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400865 typ, b, err := c.doReadRecord(want)
866 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700867 return err
868 }
Adam Langley95c29f32014-06-20 12:00:00 -0700869 data := b.data[b.off:]
David Benjamine3fbb362017-01-06 16:19:28 -0500870 max := maxPlaintext
871 if c.config.Bugs.MaxReceivePlaintext != 0 {
872 max = c.config.Bugs.MaxReceivePlaintext
873 }
874 if len(data) > max {
Adam Langley95c29f32014-06-20 12:00:00 -0700875 err := c.sendAlert(alertRecordOverflow)
876 c.in.freeBlock(b)
877 return c.in.setErrorLocked(err)
878 }
879
880 switch typ {
881 default:
882 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
883
884 case recordTypeAlert:
885 if len(data) != 2 {
886 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
887 break
888 }
889 if alert(data[1]) == alertCloseNotify {
890 c.in.setErrorLocked(io.EOF)
891 break
892 }
893 switch data[0] {
894 case alertLevelWarning:
David Benjamin053fee92017-01-02 08:30:36 -0500895 if alert(data[1]) == alertNoCertificate {
896 c.in.freeBlock(b)
897 return errNoCertificateAlert
898 }
Nick Harperab20cec2016-12-19 17:38:41 -0800899 if alert(data[1]) == alertEndOfEarlyData {
900 c.in.freeBlock(b)
901 return errEndOfEarlyDataAlert
902 }
David Benjamin053fee92017-01-02 08:30:36 -0500903
Adam Langley95c29f32014-06-20 12:00:00 -0700904 // drop on the floor
905 c.in.freeBlock(b)
906 goto Again
907 case alertLevelError:
908 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
909 default:
910 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
911 }
912
913 case recordTypeChangeCipherSpec:
914 if typ != want || len(data) != 1 || data[0] != 1 {
915 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
916 break
917 }
Adam Langley80842bd2014-06-20 12:00:00 -0700918 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700919 if err != nil {
920 c.in.setErrorLocked(c.sendAlert(err.(alert)))
921 }
922
923 case recordTypeApplicationData:
924 if typ != want {
925 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
926 break
927 }
928 c.input = b
929 b = nil
930
931 case recordTypeHandshake:
David Benjamind5a4ecb2016-07-18 01:17:13 +0200932 // Allow handshake data while reading application data to
933 // trigger post-handshake messages.
Adam Langley95c29f32014-06-20 12:00:00 -0700934 // TODO(rsc): Should at least pick off connection close.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200935 if typ != want && want != recordTypeApplicationData {
936 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
Adam Langley95c29f32014-06-20 12:00:00 -0700937 }
938 c.hand.Write(data)
939 }
940
941 if b != nil {
942 c.in.freeBlock(b)
943 }
944 return c.in.err
945}
946
947// sendAlert sends a TLS alert message.
948// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400949func (c *Conn) sendAlertLocked(level byte, err alert) error {
950 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700951 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400952 if c.config.Bugs.FragmentAlert {
953 c.writeRecord(recordTypeAlert, c.tmp[0:1])
954 c.writeRecord(recordTypeAlert, c.tmp[1:2])
David Benjamin0d3a8c62016-03-11 22:25:18 -0500955 } else if c.config.Bugs.DoubleAlert {
956 copy(c.tmp[2:4], c.tmp[0:2])
957 c.writeRecord(recordTypeAlert, c.tmp[0:4])
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400958 } else {
959 c.writeRecord(recordTypeAlert, c.tmp[0:2])
960 }
David Benjamin24f346d2015-06-06 03:28:08 -0400961 // Error alerts are fatal to the connection.
962 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700963 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
964 }
965 return nil
966}
967
968// sendAlert sends a TLS alert message.
969// L < c.out.Mutex.
970func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400971 level := byte(alertLevelError)
Nick Harperf2511f12016-12-06 16:02:31 -0800972 if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertificate || err == alertEndOfEarlyData {
David Benjamin24f346d2015-06-06 03:28:08 -0400973 level = alertLevelWarning
974 }
975 return c.SendAlert(level, err)
976}
977
978func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700979 c.out.Lock()
980 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -0400981 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -0700982}
983
David Benjamind86c7672014-08-02 04:07:12 -0400984// writeV2Record writes a record for a V2ClientHello.
985func (c *Conn) writeV2Record(data []byte) (n int, err error) {
986 record := make([]byte, 2+len(data))
987 record[0] = uint8(len(data)>>8) | 0x80
988 record[1] = uint8(len(data))
989 copy(record[2:], data)
990 return c.conn.Write(record)
991}
992
Adam Langley95c29f32014-06-20 12:00:00 -0700993// writeRecord writes a TLS record with the given type and payload
994// to the connection and updates the record layer state.
995// c.out.Mutex <= L.
996func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjaminebacdee2017-04-08 11:00:45 -0400997 if typ == recordTypeHandshake {
998 msgType := data[0]
999 if c.config.Bugs.SendWrongMessageType != 0 && msgType == c.config.Bugs.SendWrongMessageType {
1000 msgType += 42
1001 } else if msgType == typeServerHello && c.config.Bugs.SendServerHelloAsHelloRetryRequest {
1002 msgType = typeHelloRetryRequest
1003 }
1004 if msgType != data[0] {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001005 newData := make([]byte, len(data))
1006 copy(newData, data)
David Benjaminebacdee2017-04-08 11:00:45 -04001007 newData[0] = msgType
David Benjamin0b8d5da2016-07-15 00:39:56 -04001008 data = newData
1009 }
1010 }
1011
David Benjamin639846e2016-09-09 11:41:18 -04001012 if msgType := c.config.Bugs.SendTrailingMessageData; msgType != 0 {
1013 if typ == recordTypeHandshake && data[0] == msgType {
1014 newData := make([]byte, len(data))
1015 copy(newData, data)
1016
1017 // Add a 0 to the body.
1018 newData = append(newData, 0)
1019 // Fix the header.
1020 newLen := len(newData) - 4
1021 newData[1] = byte(newLen >> 16)
1022 newData[2] = byte(newLen >> 8)
1023 newData[3] = byte(newLen)
1024
1025 data = newData
1026 }
1027 }
1028
David Benjamin83c0bc92014-08-04 01:23:53 -04001029 if c.isDTLS {
1030 return c.dtlsWriteRecord(typ, data)
1031 }
1032
David Benjamin71dd6662016-07-08 14:10:48 -07001033 if typ == recordTypeHandshake {
1034 if c.config.Bugs.SendHelloRequestBeforeEveryHandshakeMessage {
1035 newData := make([]byte, 0, 4+len(data))
1036 newData = append(newData, typeHelloRequest, 0, 0, 0)
1037 newData = append(newData, data...)
1038 data = newData
1039 }
1040
1041 if c.config.Bugs.PackHandshakeFlight {
1042 c.pendingFlight.Write(data)
1043 return len(data), nil
1044 }
David Benjamin582ba042016-07-07 12:33:25 -07001045 }
1046
1047 return c.doWriteRecord(typ, data)
1048}
1049
1050func (c *Conn) doWriteRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin6f600d62016-12-21 16:06:54 -05001051 recordHeaderLen := c.out.recordHeaderLen()
Adam Langley95c29f32014-06-20 12:00:00 -07001052 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -04001053 first := true
1054 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -04001055 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -07001056 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -04001057 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -07001058 m = maxPlaintext
1059 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001060 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
1061 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -04001062 // By default, do not fragment the client_version or
1063 // server_version, which are located in the first 6
1064 // bytes.
1065 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
1066 m = 6
1067 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001068 }
Adam Langley95c29f32014-06-20 12:00:00 -07001069 explicitIVLen := 0
1070 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -04001071 first = false
Adam Langley95c29f32014-06-20 12:00:00 -07001072
1073 var cbc cbcMode
1074 if c.out.version >= VersionTLS11 {
1075 var ok bool
1076 if cbc, ok = c.out.cipher.(cbcMode); ok {
1077 explicitIVLen = cbc.BlockSize()
1078 }
1079 }
1080 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -04001081 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -07001082 explicitIVLen = 8
1083 // The AES-GCM construction in TLS has an
1084 // explicit nonce so that the nonce can be
1085 // random. However, the nonce is only 8 bytes
1086 // which is too small for a secure, random
1087 // nonce. Therefore we use the sequence number
1088 // as the nonce.
1089 explicitIVIsSeq = true
1090 }
1091 }
1092 b.resize(recordHeaderLen + explicitIVLen + m)
Steven Valdez924a3522017-03-02 16:05:03 -05001093 b.data[0] = byte(typ)
1094 if c.vers >= VersionTLS13 && c.out.cipher != nil {
1095 b.data[0] = byte(recordTypeApplicationData)
1096 if outerType := c.config.Bugs.OuterRecordType; outerType != 0 {
1097 b.data[0] = byte(outerType)
David Benjaminc9ae27c2016-06-24 22:56:37 -04001098 }
Nick Harper1fd39d82016-06-14 18:14:35 -07001099 }
Steven Valdez924a3522017-03-02 16:05:03 -05001100 vers := c.vers
1101 if vers == 0 || vers >= VersionTLS13 {
1102 // Some TLS servers fail if the record version is
1103 // greater than TLS 1.0 for the initial ClientHello.
1104 //
1105 // TLS 1.3 fixes the version number in the record
1106 // layer to {3, 1}.
1107 vers = VersionTLS10
1108 }
1109 if c.config.Bugs.SendRecordVersion != 0 {
1110 vers = c.config.Bugs.SendRecordVersion
1111 }
1112 if c.vers == 0 && c.config.Bugs.SendInitialRecordVersion != 0 {
1113 vers = c.config.Bugs.SendInitialRecordVersion
1114 }
1115 b.data[1] = byte(vers >> 8)
1116 b.data[2] = byte(vers)
1117 b.data[3] = byte(m >> 8)
1118 b.data[4] = byte(m)
Adam Langley95c29f32014-06-20 12:00:00 -07001119 if explicitIVLen > 0 {
1120 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
1121 if explicitIVIsSeq {
1122 copy(explicitIV, c.out.seq[:])
1123 } else {
1124 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
1125 break
1126 }
1127 }
1128 }
1129 copy(b.data[recordHeaderLen+explicitIVLen:], data)
Nick Harper1fd39d82016-06-14 18:14:35 -07001130 c.out.encrypt(b, explicitIVLen, typ)
Adam Langley95c29f32014-06-20 12:00:00 -07001131 _, err = c.conn.Write(b.data)
1132 if err != nil {
1133 break
1134 }
1135 n += m
1136 data = data[m:]
1137 }
1138 c.out.freeBlock(b)
1139
1140 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -07001141 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -07001142 if err != nil {
1143 // Cannot call sendAlert directly,
1144 // because we already hold c.out.Mutex.
1145 c.tmp[0] = alertLevelError
1146 c.tmp[1] = byte(err.(alert))
1147 c.writeRecord(recordTypeAlert, c.tmp[0:2])
1148 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
1149 }
1150 }
1151 return
1152}
1153
David Benjamin582ba042016-07-07 12:33:25 -07001154func (c *Conn) flushHandshake() error {
1155 if c.isDTLS {
1156 return c.dtlsFlushHandshake()
1157 }
1158
1159 for c.pendingFlight.Len() > 0 {
1160 var buf [maxPlaintext]byte
1161 n, _ := c.pendingFlight.Read(buf[:])
1162 if _, err := c.doWriteRecord(recordTypeHandshake, buf[:n]); err != nil {
1163 return err
1164 }
1165 }
1166
1167 c.pendingFlight.Reset()
1168 return nil
1169}
1170
David Benjamin83c0bc92014-08-04 01:23:53 -04001171func (c *Conn) doReadHandshake() ([]byte, error) {
1172 if c.isDTLS {
1173 return c.dtlsDoReadHandshake()
1174 }
1175
Adam Langley95c29f32014-06-20 12:00:00 -07001176 for c.hand.Len() < 4 {
1177 if err := c.in.err; err != nil {
1178 return nil, err
1179 }
1180 if err := c.readRecord(recordTypeHandshake); err != nil {
1181 return nil, err
1182 }
1183 }
1184
1185 data := c.hand.Bytes()
1186 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1187 if n > maxHandshake {
1188 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
1189 }
1190 for c.hand.Len() < 4+n {
1191 if err := c.in.err; err != nil {
1192 return nil, err
1193 }
1194 if err := c.readRecord(recordTypeHandshake); err != nil {
1195 return nil, err
1196 }
1197 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001198 return c.hand.Next(4 + n), nil
1199}
1200
1201// readHandshake reads the next handshake message from
1202// the record layer.
1203// c.in.Mutex < L; c.out.Mutex < L.
1204func (c *Conn) readHandshake() (interface{}, error) {
1205 data, err := c.doReadHandshake()
David Benjamin053fee92017-01-02 08:30:36 -05001206 if err == errNoCertificateAlert {
1207 if c.hand.Len() != 0 {
1208 // The warning alert may not interleave with a handshake message.
1209 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1210 }
1211 return new(ssl3NoCertificateMsg), nil
1212 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001213 if err != nil {
1214 return nil, err
1215 }
1216
Adam Langley95c29f32014-06-20 12:00:00 -07001217 var m handshakeMessage
1218 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001219 case typeHelloRequest:
1220 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001221 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001222 m = &clientHelloMsg{
1223 isDTLS: c.isDTLS,
1224 }
Adam Langley95c29f32014-06-20 12:00:00 -07001225 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001226 m = &serverHelloMsg{
1227 isDTLS: c.isDTLS,
1228 }
Nick Harperdcfbc672016-07-16 17:47:31 +02001229 case typeHelloRetryRequest:
1230 m = new(helloRetryRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001231 case typeNewSessionTicket:
David Benjamin58104882016-07-18 01:25:41 +02001232 m = &newSessionTicketMsg{
1233 version: c.vers,
1234 }
Nick Harperb41d2e42016-07-01 17:50:32 -04001235 case typeEncryptedExtensions:
1236 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001237 case typeCertificate:
Nick Harperb41d2e42016-07-01 17:50:32 -04001238 m = &certificateMsg{
David Benjamin8d315d72016-07-18 01:03:18 +02001239 hasRequestContext: c.vers >= VersionTLS13,
Nick Harperb41d2e42016-07-01 17:50:32 -04001240 }
Adam Langley95c29f32014-06-20 12:00:00 -07001241 case typeCertificateRequest:
1242 m = &certificateRequestMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001243 hasSignatureAlgorithm: c.vers >= VersionTLS12,
David Benjamin8d315d72016-07-18 01:03:18 +02001244 hasRequestContext: c.vers >= VersionTLS13,
Adam Langley95c29f32014-06-20 12:00:00 -07001245 }
1246 case typeCertificateStatus:
1247 m = new(certificateStatusMsg)
1248 case typeServerKeyExchange:
1249 m = new(serverKeyExchangeMsg)
1250 case typeServerHelloDone:
1251 m = new(serverHelloDoneMsg)
1252 case typeClientKeyExchange:
1253 m = new(clientKeyExchangeMsg)
1254 case typeCertificateVerify:
1255 m = &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001256 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001257 }
1258 case typeNextProtocol:
1259 m = new(nextProtoMsg)
1260 case typeFinished:
1261 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001262 case typeHelloVerifyRequest:
1263 m = new(helloVerifyRequestMsg)
David Benjamin24599a82016-06-30 18:56:53 -04001264 case typeChannelID:
1265 m = new(channelIDMsg)
David Benjamin21c00282016-07-18 21:56:23 +02001266 case typeKeyUpdate:
1267 m = new(keyUpdateMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001268 default:
1269 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1270 }
1271
1272 // The handshake message unmarshallers
1273 // expect to be able to keep references to data,
1274 // so pass in a fresh copy that won't be overwritten.
1275 data = append([]byte(nil), data...)
1276
1277 if !m.unmarshal(data) {
1278 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1279 }
1280 return m, nil
1281}
1282
David Benjamin83f90402015-01-27 01:09:43 -05001283// skipPacket processes all the DTLS records in packet. It updates
1284// sequence number expectations but otherwise ignores them.
1285func (c *Conn) skipPacket(packet []byte) error {
1286 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001287 if len(packet) < 13 {
1288 return errors.New("tls: bad packet")
1289 }
David Benjamin83f90402015-01-27 01:09:43 -05001290 // Dropped packets are completely ignored save to update
1291 // expected sequence numbers for this and the next epoch. (We
1292 // don't assert on the contents of the packets both for
1293 // simplicity and because a previous test with one shorter
1294 // timeout schedule would have done so.)
1295 epoch := packet[3:5]
1296 seq := packet[5:11]
1297 length := uint16(packet[11])<<8 | uint16(packet[12])
1298 if bytes.Equal(c.in.seq[:2], epoch) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001299 if bytes.Compare(seq, c.in.seq[2:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001300 return errors.New("tls: sequence mismatch")
1301 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001302 copy(c.in.seq[2:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001303 c.in.incSeq(false)
1304 } else {
David Benjamin13e81fc2015-11-02 17:16:13 -05001305 if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001306 return errors.New("tls: sequence mismatch")
1307 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001308 copy(c.in.nextSeq[:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001309 c.in.incNextSeq()
1310 }
David Benjamin6ca93552015-08-28 16:16:25 -04001311 if len(packet) < 13+int(length) {
1312 return errors.New("tls: bad packet")
1313 }
David Benjamin83f90402015-01-27 01:09:43 -05001314 packet = packet[13+length:]
1315 }
1316 return nil
1317}
1318
1319// simulatePacketLoss simulates the loss of a handshake leg from the
1320// peer based on the schedule in c.config.Bugs. If resendFunc is
1321// non-nil, it is called after each simulated timeout to retransmit
1322// handshake messages from the local end. This is used in cases where
1323// the peer retransmits on a stale Finished rather than a timeout.
1324func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1325 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1326 return nil
1327 }
1328 if !c.isDTLS {
1329 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1330 }
1331 if c.config.Bugs.PacketAdaptor == nil {
1332 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1333 }
1334 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1335 // Simulate a timeout.
1336 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1337 if err != nil {
1338 return err
1339 }
1340 for _, packet := range packets {
1341 if err := c.skipPacket(packet); err != nil {
1342 return err
1343 }
1344 }
1345 if resendFunc != nil {
1346 resendFunc()
1347 }
1348 }
1349 return nil
1350}
1351
David Benjamin47921102016-07-28 11:29:18 -04001352func (c *Conn) SendHalfHelloRequest() error {
1353 if err := c.Handshake(); err != nil {
1354 return err
1355 }
1356
1357 c.out.Lock()
1358 defer c.out.Unlock()
1359
1360 if _, err := c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0}); err != nil {
1361 return err
1362 }
1363 return c.flushHandshake()
1364}
1365
Adam Langley95c29f32014-06-20 12:00:00 -07001366// Write writes data to the connection.
1367func (c *Conn) Write(b []byte) (int, error) {
1368 if err := c.Handshake(); err != nil {
1369 return 0, err
1370 }
1371
1372 c.out.Lock()
1373 defer c.out.Unlock()
1374
David Benjamin12d2c482016-07-24 10:56:51 -04001375 // Flush any pending handshake data. PackHelloRequestWithFinished may
1376 // have been set and the handshake not followed by Renegotiate.
1377 c.flushHandshake()
1378
Adam Langley95c29f32014-06-20 12:00:00 -07001379 if err := c.out.err; err != nil {
1380 return 0, err
1381 }
1382
1383 if !c.handshakeComplete {
1384 return 0, alertInternalError
1385 }
1386
Steven Valdezc4aa7272016-10-03 12:25:56 -04001387 if c.keyUpdateRequested {
1388 if err := c.sendKeyUpdateLocked(keyUpdateNotRequested); err != nil {
David Benjamin21c00282016-07-18 21:56:23 +02001389 return 0, err
1390 }
Steven Valdezc4aa7272016-10-03 12:25:56 -04001391 c.keyUpdateRequested = false
David Benjamin21c00282016-07-18 21:56:23 +02001392 }
1393
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001394 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001395 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001396 }
1397
Adam Langley27a0d082015-11-03 13:34:10 -08001398 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1399 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
David Benjamin582ba042016-07-07 12:33:25 -07001400 c.flushHandshake()
Adam Langley27a0d082015-11-03 13:34:10 -08001401 }
1402
Adam Langley95c29f32014-06-20 12:00:00 -07001403 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1404 // attack when using block mode ciphers due to predictable IVs.
1405 // This can be prevented by splitting each Application Data
1406 // record into two records, effectively randomizing the IV.
1407 //
1408 // http://www.openssl.org/~bodo/tls-cbc.txt
1409 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1410 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1411
1412 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001413 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001414 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1415 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1416 if err != nil {
1417 return n, c.out.setErrorLocked(err)
1418 }
1419 m, b = 1, b[1:]
1420 }
1421 }
1422
1423 n, err := c.writeRecord(recordTypeApplicationData, b)
1424 return n + m, c.out.setErrorLocked(err)
1425}
1426
David Benjamin794cc592017-03-25 22:24:23 -05001427func (c *Conn) processTLS13NewSessionTicket(newSessionTicket *newSessionTicketMsg, cipherSuite *cipherSuite) error {
1428 if c.config.Bugs.ExpectGREASE && !newSessionTicket.hasGREASEExtension {
1429 return errors.New("tls: no GREASE ticket extension found")
1430 }
1431
1432 if c.config.Bugs.ExpectTicketEarlyDataInfo && newSessionTicket.maxEarlyDataSize == 0 {
1433 return errors.New("tls: no ticket_early_data_info extension found")
1434 }
1435
1436 if c.config.Bugs.ExpectNoNewSessionTicket {
1437 return errors.New("tls: received unexpected NewSessionTicket")
1438 }
1439
1440 if c.config.ClientSessionCache == nil || newSessionTicket.ticketLifetime == 0 {
1441 return nil
1442 }
1443
1444 session := &ClientSessionState{
1445 sessionTicket: newSessionTicket.ticket,
1446 vers: c.vers,
1447 cipherSuite: cipherSuite.id,
1448 masterSecret: c.resumptionSecret,
1449 serverCertificates: c.peerCertificates,
1450 sctList: c.sctList,
1451 ocspResponse: c.ocspResponse,
1452 ticketCreationTime: c.config.time(),
1453 ticketExpiration: c.config.time().Add(time.Duration(newSessionTicket.ticketLifetime) * time.Second),
1454 ticketAgeAdd: newSessionTicket.ticketAgeAdd,
1455 maxEarlyDataSize: newSessionTicket.maxEarlyDataSize,
1456 earlyALPN: c.clientProtocol,
1457 }
1458
1459 cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
1460 c.config.ClientSessionCache.Put(cacheKey, session)
1461 return nil
1462}
1463
David Benjamind5a4ecb2016-07-18 01:17:13 +02001464func (c *Conn) handlePostHandshakeMessage() error {
Adam Langley2ae77d22014-10-28 17:29:33 -07001465 msg, err := c.readHandshake()
1466 if err != nil {
1467 return err
1468 }
David Benjamind5a4ecb2016-07-18 01:17:13 +02001469
1470 if c.vers < VersionTLS13 {
1471 if !c.isClient {
1472 c.sendAlert(alertUnexpectedMessage)
1473 return errors.New("tls: unexpected post-handshake message")
1474 }
1475
1476 _, ok := msg.(*helloRequestMsg)
1477 if !ok {
1478 c.sendAlert(alertUnexpectedMessage)
1479 return alertUnexpectedMessage
1480 }
1481
1482 c.handshakeComplete = false
1483 return c.Handshake()
Adam Langley2ae77d22014-10-28 17:29:33 -07001484 }
1485
David Benjamind5a4ecb2016-07-18 01:17:13 +02001486 if c.isClient {
1487 if newSessionTicket, ok := msg.(*newSessionTicketMsg); ok {
David Benjamin794cc592017-03-25 22:24:23 -05001488 return c.processTLS13NewSessionTicket(newSessionTicket, c.cipherSuite)
David Benjamind5a4ecb2016-07-18 01:17:13 +02001489 }
1490 }
1491
Steven Valdezc4aa7272016-10-03 12:25:56 -04001492 if keyUpdate, ok := msg.(*keyUpdateMsg); ok {
David Benjaminbbba9392017-04-06 12:54:12 -04001493 if c.config.Bugs.RejectUnsolicitedKeyUpdate {
1494 return errors.New("tls: unexpected KeyUpdate message")
1495 }
Steven Valdez1dc53d22016-07-26 12:27:38 -04001496 c.in.doKeyUpdate(c, false)
Steven Valdezc4aa7272016-10-03 12:25:56 -04001497 if keyUpdate.keyUpdateRequest == keyUpdateRequested {
1498 c.keyUpdateRequested = true
1499 }
David Benjamin21c00282016-07-18 21:56:23 +02001500 return nil
1501 }
1502
David Benjamind5a4ecb2016-07-18 01:17:13 +02001503 c.sendAlert(alertUnexpectedMessage)
David Benjaminbbba9392017-04-06 12:54:12 -04001504 return errors.New("tls: unexpected post-handshake message")
1505}
1506
1507// Reads a KeyUpdate acknowledgment from the peer. There may not be any
1508// application data records before the message.
1509func (c *Conn) ReadKeyUpdateACK() error {
1510 c.in.Lock()
1511 defer c.in.Unlock()
1512
1513 msg, err := c.readHandshake()
1514 if err != nil {
1515 return err
1516 }
1517
1518 keyUpdate, ok := msg.(*keyUpdateMsg)
1519 if !ok {
1520 c.sendAlert(alertUnexpectedMessage)
1521 return errors.New("tls: unexpected message when reading KeyUpdate")
1522 }
1523
1524 if keyUpdate.keyUpdateRequest != keyUpdateNotRequested {
1525 return errors.New("tls: received invalid KeyUpdate message")
1526 }
1527
1528 c.in.doKeyUpdate(c, false)
1529 return nil
Adam Langley2ae77d22014-10-28 17:29:33 -07001530}
1531
Adam Langleycf2d4f42014-10-28 19:06:14 -07001532func (c *Conn) Renegotiate() error {
1533 if !c.isClient {
David Benjaminef5dfd22015-12-06 13:17:07 -05001534 helloReq := new(helloRequestMsg).marshal()
1535 if c.config.Bugs.BadHelloRequest != nil {
1536 helloReq = c.config.Bugs.BadHelloRequest
1537 }
1538 c.writeRecord(recordTypeHandshake, helloReq)
David Benjamin582ba042016-07-07 12:33:25 -07001539 c.flushHandshake()
Adam Langleycf2d4f42014-10-28 19:06:14 -07001540 }
1541
1542 c.handshakeComplete = false
1543 return c.Handshake()
1544}
1545
Adam Langley95c29f32014-06-20 12:00:00 -07001546// Read can be made to time out and return a net.Error with Timeout() == true
1547// after a fixed time limit; see SetDeadline and SetReadDeadline.
1548func (c *Conn) Read(b []byte) (n int, err error) {
1549 if err = c.Handshake(); err != nil {
1550 return
1551 }
1552
1553 c.in.Lock()
1554 defer c.in.Unlock()
1555
1556 // Some OpenSSL servers send empty records in order to randomize the
1557 // CBC IV. So this loop ignores a limited number of empty records.
1558 const maxConsecutiveEmptyRecords = 100
1559 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1560 for c.input == nil && c.in.err == nil {
1561 if err := c.readRecord(recordTypeApplicationData); err != nil {
1562 // Soft error, like EAGAIN
1563 return 0, err
1564 }
David Benjamind9b091b2015-01-27 01:10:54 -05001565 if c.hand.Len() > 0 {
David Benjamind5a4ecb2016-07-18 01:17:13 +02001566 // We received handshake bytes, indicating a
1567 // post-handshake message.
1568 if err := c.handlePostHandshakeMessage(); err != nil {
Adam Langley2ae77d22014-10-28 17:29:33 -07001569 return 0, err
1570 }
1571 continue
1572 }
Adam Langley95c29f32014-06-20 12:00:00 -07001573 }
1574 if err := c.in.err; err != nil {
1575 return 0, err
1576 }
1577
1578 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001579 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001580 c.in.freeBlock(c.input)
1581 c.input = nil
1582 }
1583
1584 // If a close-notify alert is waiting, read it so that
1585 // we can return (n, EOF) instead of (n, nil), to signal
1586 // to the HTTP response reading goroutine that the
1587 // connection is now closed. This eliminates a race
1588 // where the HTTP response reading goroutine would
1589 // otherwise not observe the EOF until its next read,
1590 // by which time a client goroutine might have already
1591 // tried to reuse the HTTP connection for a new
1592 // request.
1593 // See https://codereview.appspot.com/76400046
1594 // and http://golang.org/issue/3514
1595 if ri := c.rawInput; ri != nil &&
1596 n != 0 && err == nil &&
1597 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1598 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1599 err = recErr // will be io.EOF on closeNotify
1600 }
1601 }
1602
1603 if n != 0 || err != nil {
1604 return n, err
1605 }
1606 }
1607
1608 return 0, io.ErrNoProgress
1609}
1610
1611// Close closes the connection.
1612func (c *Conn) Close() error {
1613 var alertErr error
1614
1615 c.handshakeMutex.Lock()
1616 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001617 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
David Benjaminfa214e42016-05-10 17:03:10 -04001618 alert := alertCloseNotify
1619 if c.config.Bugs.SendAlertOnShutdown != 0 {
1620 alert = c.config.Bugs.SendAlertOnShutdown
1621 }
1622 alertErr = c.sendAlert(alert)
David Benjamin4d559612016-05-18 14:31:51 -04001623 // Clear local alerts when sending alerts so we continue to wait
1624 // for the peer rather than closing the socket early.
1625 if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1626 alertErr = nil
1627 }
Adam Langley95c29f32014-06-20 12:00:00 -07001628 }
1629
David Benjamin30789da2015-08-29 22:56:45 -04001630 // Consume a close_notify from the peer if one hasn't been received
1631 // already. This avoids the peer from failing |SSL_shutdown| due to a
1632 // write failing.
1633 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1634 for c.in.error() == nil {
1635 c.readRecord(recordTypeAlert)
1636 }
1637 if c.in.error() != io.EOF {
1638 alertErr = c.in.error()
1639 }
1640 }
1641
Adam Langley95c29f32014-06-20 12:00:00 -07001642 if err := c.conn.Close(); err != nil {
1643 return err
1644 }
1645 return alertErr
1646}
1647
1648// Handshake runs the client or server handshake
1649// protocol if it has not yet been run.
1650// Most uses of this package need not call Handshake
1651// explicitly: the first Read or Write will call it automatically.
1652func (c *Conn) Handshake() error {
1653 c.handshakeMutex.Lock()
1654 defer c.handshakeMutex.Unlock()
1655 if err := c.handshakeErr; err != nil {
1656 return err
1657 }
1658 if c.handshakeComplete {
1659 return nil
1660 }
1661
David Benjamin9a41d1b2015-05-16 01:30:09 -04001662 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1663 c.conn.Write([]byte{
1664 byte(recordTypeAlert), // type
1665 0xfe, 0xff, // version
1666 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1667 0x0, 0x2, // length
1668 })
1669 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1670 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001671 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1672 c.writeRecord(recordTypeApplicationData, data)
1673 }
Adam Langley95c29f32014-06-20 12:00:00 -07001674 if c.isClient {
1675 c.handshakeErr = c.clientHandshake()
1676 } else {
1677 c.handshakeErr = c.serverHandshake()
1678 }
David Benjaminddb9f152015-02-03 15:44:39 -05001679 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1680 c.writeRecord(recordType(42), []byte("invalid record"))
1681 }
Adam Langley95c29f32014-06-20 12:00:00 -07001682 return c.handshakeErr
1683}
1684
1685// ConnectionState returns basic TLS details about the connection.
1686func (c *Conn) ConnectionState() ConnectionState {
1687 c.handshakeMutex.Lock()
1688 defer c.handshakeMutex.Unlock()
1689
1690 var state ConnectionState
1691 state.HandshakeComplete = c.handshakeComplete
1692 if c.handshakeComplete {
1693 state.Version = c.vers
1694 state.NegotiatedProtocol = c.clientProtocol
1695 state.DidResume = c.didResume
1696 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001697 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001698 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001699 state.PeerCertificates = c.peerCertificates
1700 state.VerifiedChains = c.verifiedChains
1701 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001702 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001703 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001704 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001705 state.SCTList = c.sctList
Nick Harper60edffd2016-06-21 15:19:24 -07001706 state.PeerSignatureAlgorithm = c.peerSignatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -04001707 state.CurveID = c.curveID
Adam Langley95c29f32014-06-20 12:00:00 -07001708 }
1709
1710 return state
1711}
1712
1713// OCSPResponse returns the stapled OCSP response from the TLS server, if
1714// any. (Only valid for client connections.)
1715func (c *Conn) OCSPResponse() []byte {
1716 c.handshakeMutex.Lock()
1717 defer c.handshakeMutex.Unlock()
1718
1719 return c.ocspResponse
1720}
1721
1722// VerifyHostname checks that the peer certificate chain is valid for
1723// connecting to host. If so, it returns nil; if not, it returns an error
1724// describing the problem.
1725func (c *Conn) VerifyHostname(host string) error {
1726 c.handshakeMutex.Lock()
1727 defer c.handshakeMutex.Unlock()
1728 if !c.isClient {
1729 return errors.New("tls: VerifyHostname called on TLS server connection")
1730 }
1731 if !c.handshakeComplete {
1732 return errors.New("tls: handshake has not yet been performed")
1733 }
1734 return c.peerCertificates[0].VerifyHostname(host)
1735}
David Benjaminc565ebb2015-04-03 04:06:36 -04001736
1737// ExportKeyingMaterial exports keying material from the current connection
1738// state, as per RFC 5705.
1739func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1740 c.handshakeMutex.Lock()
1741 defer c.handshakeMutex.Unlock()
1742 if !c.handshakeComplete {
1743 return nil, errors.New("tls: handshake has not yet been performed")
1744 }
1745
David Benjamin8d315d72016-07-18 01:03:18 +02001746 if c.vers >= VersionTLS13 {
David Benjamin97a0a082016-07-13 17:57:35 -04001747 // TODO(davidben): What should we do with useContext? See
1748 // https://github.com/tlswg/tls13-spec/issues/546
1749 return hkdfExpandLabel(c.cipherSuite.hash(), c.exporterSecret, label, context, length), nil
1750 }
1751
David Benjaminc565ebb2015-04-03 04:06:36 -04001752 seedLen := len(c.clientRandom) + len(c.serverRandom)
1753 if useContext {
1754 seedLen += 2 + len(context)
1755 }
1756 seed := make([]byte, 0, seedLen)
1757 seed = append(seed, c.clientRandom[:]...)
1758 seed = append(seed, c.serverRandom[:]...)
1759 if useContext {
1760 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1761 seed = append(seed, context...)
1762 }
1763 result := make([]byte, length)
David Benjamin97a0a082016-07-13 17:57:35 -04001764 prfForVersion(c.vers, c.cipherSuite)(result, c.exporterSecret, label, seed)
David Benjaminc565ebb2015-04-03 04:06:36 -04001765 return result, nil
1766}
David Benjamin3e052de2015-11-25 20:10:31 -05001767
1768// noRenegotiationInfo returns true if the renegotiation info extension
1769// should be supported in the current handshake.
1770func (c *Conn) noRenegotiationInfo() bool {
1771 if c.config.Bugs.NoRenegotiationInfo {
1772 return true
1773 }
1774 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1775 return true
1776 }
1777 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1778 return true
1779 }
1780 return false
1781}
David Benjamin58104882016-07-18 01:25:41 +02001782
1783func (c *Conn) SendNewSessionTicket() error {
1784 if c.isClient || c.vers < VersionTLS13 {
1785 return errors.New("tls: cannot send post-handshake NewSessionTicket")
1786 }
1787
1788 var peerCertificatesRaw [][]byte
1789 for _, cert := range c.peerCertificates {
1790 peerCertificatesRaw = append(peerCertificatesRaw, cert.Raw)
1791 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001792
Steven Valdeza833c352016-11-01 13:39:36 -04001793 addBuffer := make([]byte, 4)
1794 _, err := io.ReadFull(c.config.rand(), addBuffer)
1795 if err != nil {
1796 c.sendAlert(alertInternalError)
1797 return errors.New("tls: short read from Rand: " + err.Error())
1798 }
1799 ticketAgeAdd := uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0])
1800
David Benjamin58104882016-07-18 01:25:41 +02001801 // TODO(davidben): Allow configuring these values.
1802 m := &newSessionTicketMsg{
David Benjamin9c33ae82017-01-08 06:04:43 -05001803 version: c.vers,
1804 ticketLifetime: uint32(24 * time.Hour / time.Second),
David Benjamin9c33ae82017-01-08 06:04:43 -05001805 duplicateEarlyDataInfo: c.config.Bugs.DuplicateTicketEarlyDataInfo,
1806 customExtension: c.config.Bugs.CustomTicketExtension,
1807 ticketAgeAdd: ticketAgeAdd,
Nick Harperab20cec2016-12-19 17:38:41 -08001808 maxEarlyDataSize: c.config.MaxEarlyDataSize,
David Benjamin58104882016-07-18 01:25:41 +02001809 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001810
David Benjamin17b30832017-01-28 14:00:32 -05001811 if c.config.Bugs.SendTicketLifetime != 0 {
1812 m.ticketLifetime = uint32(c.config.Bugs.SendTicketLifetime / time.Second)
1813 }
1814
Nick Harper0b3625b2016-07-25 16:16:28 -07001815 state := sessionState{
1816 vers: c.vers,
1817 cipherSuite: c.cipherSuite.id,
1818 masterSecret: c.resumptionSecret,
1819 certificates: peerCertificatesRaw,
1820 ticketCreationTime: c.config.time(),
1821 ticketExpiration: c.config.time().Add(time.Duration(m.ticketLifetime) * time.Second),
Steven Valdeza833c352016-11-01 13:39:36 -04001822 ticketAgeAdd: uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0]),
Steven Valdez2d850622017-01-11 11:34:52 -05001823 earlyALPN: []byte(c.clientProtocol),
Nick Harper0b3625b2016-07-25 16:16:28 -07001824 }
1825
David Benjamin58104882016-07-18 01:25:41 +02001826 if !c.config.Bugs.SendEmptySessionTicket {
1827 var err error
1828 m.ticket, err = c.encryptTicket(&state)
1829 if err != nil {
1830 return err
1831 }
1832 }
David Benjamin58104882016-07-18 01:25:41 +02001833 c.out.Lock()
1834 defer c.out.Unlock()
Steven Valdeza833c352016-11-01 13:39:36 -04001835 _, err = c.writeRecord(recordTypeHandshake, m.marshal())
David Benjamin58104882016-07-18 01:25:41 +02001836 return err
1837}
David Benjamin21c00282016-07-18 21:56:23 +02001838
Steven Valdezc4aa7272016-10-03 12:25:56 -04001839func (c *Conn) SendKeyUpdate(keyUpdateRequest byte) error {
David Benjamin21c00282016-07-18 21:56:23 +02001840 c.out.Lock()
1841 defer c.out.Unlock()
Steven Valdezc4aa7272016-10-03 12:25:56 -04001842 return c.sendKeyUpdateLocked(keyUpdateRequest)
David Benjamin21c00282016-07-18 21:56:23 +02001843}
1844
Steven Valdezc4aa7272016-10-03 12:25:56 -04001845func (c *Conn) sendKeyUpdateLocked(keyUpdateRequest byte) error {
David Benjamin7f0965a2016-09-30 15:14:01 -04001846 if c.vers < VersionTLS13 {
1847 return errors.New("tls: attempted to send KeyUpdate before TLS 1.3")
1848 }
1849
Steven Valdezc4aa7272016-10-03 12:25:56 -04001850 m := keyUpdateMsg{
1851 keyUpdateRequest: keyUpdateRequest,
1852 }
David Benjamin21c00282016-07-18 21:56:23 +02001853 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
1854 return err
1855 }
1856 if err := c.flushHandshake(); err != nil {
1857 return err
1858 }
Steven Valdez1dc53d22016-07-26 12:27:38 -04001859 c.out.doKeyUpdate(c, true)
David Benjamin21c00282016-07-18 21:56:23 +02001860 return nil
1861}
Steven Valdeza4ee74d2016-11-29 13:36:45 -05001862
1863func (c *Conn) sendFakeEarlyData(len int) error {
1864 // Assemble a fake early data record. This does not use writeRecord
1865 // because the record layer may be using different keys at this point.
1866 payload := make([]byte, 5+len)
1867 payload[0] = byte(recordTypeApplicationData)
1868 payload[1] = 3
1869 payload[2] = 1
1870 payload[3] = byte(len >> 8)
1871 payload[4] = byte(len)
1872 _, err := c.conn.Write(payload)
1873 return err
1874}