blob: ffe4f3473a2df021fc8b8c462a34dff8f31bd365 [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"))
855 case recordTypeHandshake, recordTypeChangeCipherSpec:
856 if c.handshakeComplete {
857 c.sendAlert(alertInternalError)
858 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
859 }
860 case recordTypeApplicationData:
Nick Harperab20cec2016-12-19 17:38:41 -0800861 if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart && len(c.config.Bugs.ExpectHalfRTTData) == 0 && len(c.config.Bugs.ExpectEarlyData) == 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700862 c.sendAlert(alertInternalError)
863 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
864 }
David Benjamin30789da2015-08-29 22:56:45 -0400865 case recordTypeAlert:
866 // Looking for a close_notify. Note: unlike a real
867 // implementation, this is not tolerant of additional records.
868 // See the documentation for ExpectCloseNotify.
Adam Langley95c29f32014-06-20 12:00:00 -0700869 }
870
871Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400872 typ, b, err := c.doReadRecord(want)
873 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700874 return err
875 }
Adam Langley95c29f32014-06-20 12:00:00 -0700876 data := b.data[b.off:]
David Benjamine3fbb362017-01-06 16:19:28 -0500877 max := maxPlaintext
878 if c.config.Bugs.MaxReceivePlaintext != 0 {
879 max = c.config.Bugs.MaxReceivePlaintext
880 }
881 if len(data) > max {
Adam Langley95c29f32014-06-20 12:00:00 -0700882 err := c.sendAlert(alertRecordOverflow)
883 c.in.freeBlock(b)
884 return c.in.setErrorLocked(err)
885 }
886
887 switch typ {
888 default:
889 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
890
891 case recordTypeAlert:
892 if len(data) != 2 {
893 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
894 break
895 }
896 if alert(data[1]) == alertCloseNotify {
897 c.in.setErrorLocked(io.EOF)
898 break
899 }
900 switch data[0] {
901 case alertLevelWarning:
David Benjamin053fee92017-01-02 08:30:36 -0500902 if alert(data[1]) == alertNoCertificate {
903 c.in.freeBlock(b)
904 return errNoCertificateAlert
905 }
Nick Harperab20cec2016-12-19 17:38:41 -0800906 if alert(data[1]) == alertEndOfEarlyData {
907 c.in.freeBlock(b)
908 return errEndOfEarlyDataAlert
909 }
David Benjamin053fee92017-01-02 08:30:36 -0500910
Adam Langley95c29f32014-06-20 12:00:00 -0700911 // drop on the floor
912 c.in.freeBlock(b)
913 goto Again
914 case alertLevelError:
915 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
916 default:
917 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
918 }
919
920 case recordTypeChangeCipherSpec:
921 if typ != want || len(data) != 1 || data[0] != 1 {
922 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
923 break
924 }
Adam Langley80842bd2014-06-20 12:00:00 -0700925 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700926 if err != nil {
927 c.in.setErrorLocked(c.sendAlert(err.(alert)))
928 }
929
930 case recordTypeApplicationData:
931 if typ != want {
932 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
933 break
934 }
935 c.input = b
936 b = nil
937
938 case recordTypeHandshake:
David Benjamind5a4ecb2016-07-18 01:17:13 +0200939 // Allow handshake data while reading application data to
940 // trigger post-handshake messages.
Adam Langley95c29f32014-06-20 12:00:00 -0700941 // TODO(rsc): Should at least pick off connection close.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200942 if typ != want && want != recordTypeApplicationData {
943 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
Adam Langley95c29f32014-06-20 12:00:00 -0700944 }
945 c.hand.Write(data)
946 }
947
948 if b != nil {
949 c.in.freeBlock(b)
950 }
951 return c.in.err
952}
953
954// sendAlert sends a TLS alert message.
955// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400956func (c *Conn) sendAlertLocked(level byte, err alert) error {
957 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700958 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400959 if c.config.Bugs.FragmentAlert {
960 c.writeRecord(recordTypeAlert, c.tmp[0:1])
961 c.writeRecord(recordTypeAlert, c.tmp[1:2])
David Benjamin0d3a8c62016-03-11 22:25:18 -0500962 } else if c.config.Bugs.DoubleAlert {
963 copy(c.tmp[2:4], c.tmp[0:2])
964 c.writeRecord(recordTypeAlert, c.tmp[0:4])
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400965 } else {
966 c.writeRecord(recordTypeAlert, c.tmp[0:2])
967 }
David Benjamin24f346d2015-06-06 03:28:08 -0400968 // Error alerts are fatal to the connection.
969 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700970 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
971 }
972 return nil
973}
974
975// sendAlert sends a TLS alert message.
976// L < c.out.Mutex.
977func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400978 level := byte(alertLevelError)
Nick Harperf2511f12016-12-06 16:02:31 -0800979 if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertificate || err == alertEndOfEarlyData {
David Benjamin24f346d2015-06-06 03:28:08 -0400980 level = alertLevelWarning
981 }
982 return c.SendAlert(level, err)
983}
984
985func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700986 c.out.Lock()
987 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -0400988 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -0700989}
990
David Benjamind86c7672014-08-02 04:07:12 -0400991// writeV2Record writes a record for a V2ClientHello.
992func (c *Conn) writeV2Record(data []byte) (n int, err error) {
993 record := make([]byte, 2+len(data))
994 record[0] = uint8(len(data)>>8) | 0x80
995 record[1] = uint8(len(data))
996 copy(record[2:], data)
997 return c.conn.Write(record)
998}
999
Adam Langley95c29f32014-06-20 12:00:00 -07001000// writeRecord writes a TLS record with the given type and payload
1001// to the connection and updates the record layer state.
1002// c.out.Mutex <= L.
1003func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin639846e2016-09-09 11:41:18 -04001004 if msgType := c.config.Bugs.SendWrongMessageType; msgType != 0 {
1005 if typ == recordTypeHandshake && data[0] == msgType {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001006 newData := make([]byte, len(data))
1007 copy(newData, data)
1008 newData[0] += 42
1009 data = newData
1010 }
1011 }
1012
David Benjamin639846e2016-09-09 11:41:18 -04001013 if msgType := c.config.Bugs.SendTrailingMessageData; msgType != 0 {
1014 if typ == recordTypeHandshake && data[0] == msgType {
1015 newData := make([]byte, len(data))
1016 copy(newData, data)
1017
1018 // Add a 0 to the body.
1019 newData = append(newData, 0)
1020 // Fix the header.
1021 newLen := len(newData) - 4
1022 newData[1] = byte(newLen >> 16)
1023 newData[2] = byte(newLen >> 8)
1024 newData[3] = byte(newLen)
1025
1026 data = newData
1027 }
1028 }
1029
David Benjamin83c0bc92014-08-04 01:23:53 -04001030 if c.isDTLS {
1031 return c.dtlsWriteRecord(typ, data)
1032 }
1033
David Benjamin71dd6662016-07-08 14:10:48 -07001034 if typ == recordTypeHandshake {
1035 if c.config.Bugs.SendHelloRequestBeforeEveryHandshakeMessage {
1036 newData := make([]byte, 0, 4+len(data))
1037 newData = append(newData, typeHelloRequest, 0, 0, 0)
1038 newData = append(newData, data...)
1039 data = newData
1040 }
1041
1042 if c.config.Bugs.PackHandshakeFlight {
1043 c.pendingFlight.Write(data)
1044 return len(data), nil
1045 }
David Benjamin582ba042016-07-07 12:33:25 -07001046 }
1047
1048 return c.doWriteRecord(typ, data)
1049}
1050
1051func (c *Conn) doWriteRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin6f600d62016-12-21 16:06:54 -05001052 recordHeaderLen := c.out.recordHeaderLen()
Adam Langley95c29f32014-06-20 12:00:00 -07001053 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -04001054 first := true
1055 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -04001056 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -07001057 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -04001058 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -07001059 m = maxPlaintext
1060 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001061 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
1062 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -04001063 // By default, do not fragment the client_version or
1064 // server_version, which are located in the first 6
1065 // bytes.
1066 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
1067 m = 6
1068 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001069 }
Adam Langley95c29f32014-06-20 12:00:00 -07001070 explicitIVLen := 0
1071 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -04001072 first = false
Adam Langley95c29f32014-06-20 12:00:00 -07001073
1074 var cbc cbcMode
1075 if c.out.version >= VersionTLS11 {
1076 var ok bool
1077 if cbc, ok = c.out.cipher.(cbcMode); ok {
1078 explicitIVLen = cbc.BlockSize()
1079 }
1080 }
1081 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -04001082 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -07001083 explicitIVLen = 8
1084 // The AES-GCM construction in TLS has an
1085 // explicit nonce so that the nonce can be
1086 // random. However, the nonce is only 8 bytes
1087 // which is too small for a secure, random
1088 // nonce. Therefore we use the sequence number
1089 // as the nonce.
1090 explicitIVIsSeq = true
1091 }
1092 }
1093 b.resize(recordHeaderLen + explicitIVLen + m)
Steven Valdez924a3522017-03-02 16:05:03 -05001094 b.data[0] = byte(typ)
1095 if c.vers >= VersionTLS13 && c.out.cipher != nil {
1096 b.data[0] = byte(recordTypeApplicationData)
1097 if outerType := c.config.Bugs.OuterRecordType; outerType != 0 {
1098 b.data[0] = byte(outerType)
David Benjaminc9ae27c2016-06-24 22:56:37 -04001099 }
Nick Harper1fd39d82016-06-14 18:14:35 -07001100 }
Steven Valdez924a3522017-03-02 16:05:03 -05001101 vers := c.vers
1102 if vers == 0 || vers >= VersionTLS13 {
1103 // Some TLS servers fail if the record version is
1104 // greater than TLS 1.0 for the initial ClientHello.
1105 //
1106 // TLS 1.3 fixes the version number in the record
1107 // layer to {3, 1}.
1108 vers = VersionTLS10
1109 }
1110 if c.config.Bugs.SendRecordVersion != 0 {
1111 vers = c.config.Bugs.SendRecordVersion
1112 }
1113 if c.vers == 0 && c.config.Bugs.SendInitialRecordVersion != 0 {
1114 vers = c.config.Bugs.SendInitialRecordVersion
1115 }
1116 b.data[1] = byte(vers >> 8)
1117 b.data[2] = byte(vers)
1118 b.data[3] = byte(m >> 8)
1119 b.data[4] = byte(m)
Adam Langley95c29f32014-06-20 12:00:00 -07001120 if explicitIVLen > 0 {
1121 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
1122 if explicitIVIsSeq {
1123 copy(explicitIV, c.out.seq[:])
1124 } else {
1125 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
1126 break
1127 }
1128 }
1129 }
1130 copy(b.data[recordHeaderLen+explicitIVLen:], data)
Nick Harper1fd39d82016-06-14 18:14:35 -07001131 c.out.encrypt(b, explicitIVLen, typ)
Adam Langley95c29f32014-06-20 12:00:00 -07001132 _, err = c.conn.Write(b.data)
1133 if err != nil {
1134 break
1135 }
1136 n += m
1137 data = data[m:]
1138 }
1139 c.out.freeBlock(b)
1140
1141 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -07001142 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -07001143 if err != nil {
1144 // Cannot call sendAlert directly,
1145 // because we already hold c.out.Mutex.
1146 c.tmp[0] = alertLevelError
1147 c.tmp[1] = byte(err.(alert))
1148 c.writeRecord(recordTypeAlert, c.tmp[0:2])
1149 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
1150 }
1151 }
1152 return
1153}
1154
David Benjamin582ba042016-07-07 12:33:25 -07001155func (c *Conn) flushHandshake() error {
1156 if c.isDTLS {
1157 return c.dtlsFlushHandshake()
1158 }
1159
1160 for c.pendingFlight.Len() > 0 {
1161 var buf [maxPlaintext]byte
1162 n, _ := c.pendingFlight.Read(buf[:])
1163 if _, err := c.doWriteRecord(recordTypeHandshake, buf[:n]); err != nil {
1164 return err
1165 }
1166 }
1167
1168 c.pendingFlight.Reset()
1169 return nil
1170}
1171
David Benjamin83c0bc92014-08-04 01:23:53 -04001172func (c *Conn) doReadHandshake() ([]byte, error) {
1173 if c.isDTLS {
1174 return c.dtlsDoReadHandshake()
1175 }
1176
Adam Langley95c29f32014-06-20 12:00:00 -07001177 for c.hand.Len() < 4 {
1178 if err := c.in.err; err != nil {
1179 return nil, err
1180 }
1181 if err := c.readRecord(recordTypeHandshake); err != nil {
1182 return nil, err
1183 }
1184 }
1185
1186 data := c.hand.Bytes()
1187 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1188 if n > maxHandshake {
1189 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
1190 }
1191 for c.hand.Len() < 4+n {
1192 if err := c.in.err; err != nil {
1193 return nil, err
1194 }
1195 if err := c.readRecord(recordTypeHandshake); err != nil {
1196 return nil, err
1197 }
1198 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001199 return c.hand.Next(4 + n), nil
1200}
1201
1202// readHandshake reads the next handshake message from
1203// the record layer.
1204// c.in.Mutex < L; c.out.Mutex < L.
1205func (c *Conn) readHandshake() (interface{}, error) {
1206 data, err := c.doReadHandshake()
David Benjamin053fee92017-01-02 08:30:36 -05001207 if err == errNoCertificateAlert {
1208 if c.hand.Len() != 0 {
1209 // The warning alert may not interleave with a handshake message.
1210 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1211 }
1212 return new(ssl3NoCertificateMsg), nil
1213 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001214 if err != nil {
1215 return nil, err
1216 }
1217
Adam Langley95c29f32014-06-20 12:00:00 -07001218 var m handshakeMessage
1219 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001220 case typeHelloRequest:
1221 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001222 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001223 m = &clientHelloMsg{
1224 isDTLS: c.isDTLS,
1225 }
Adam Langley95c29f32014-06-20 12:00:00 -07001226 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001227 m = &serverHelloMsg{
1228 isDTLS: c.isDTLS,
1229 }
Nick Harperdcfbc672016-07-16 17:47:31 +02001230 case typeHelloRetryRequest:
1231 m = new(helloRetryRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001232 case typeNewSessionTicket:
David Benjamin58104882016-07-18 01:25:41 +02001233 m = &newSessionTicketMsg{
1234 version: c.vers,
1235 }
Nick Harperb41d2e42016-07-01 17:50:32 -04001236 case typeEncryptedExtensions:
1237 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001238 case typeCertificate:
Nick Harperb41d2e42016-07-01 17:50:32 -04001239 m = &certificateMsg{
David Benjamin8d315d72016-07-18 01:03:18 +02001240 hasRequestContext: c.vers >= VersionTLS13,
Nick Harperb41d2e42016-07-01 17:50:32 -04001241 }
Adam Langley95c29f32014-06-20 12:00:00 -07001242 case typeCertificateRequest:
1243 m = &certificateRequestMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001244 hasSignatureAlgorithm: c.vers >= VersionTLS12,
David Benjamin8d315d72016-07-18 01:03:18 +02001245 hasRequestContext: c.vers >= VersionTLS13,
Adam Langley95c29f32014-06-20 12:00:00 -07001246 }
1247 case typeCertificateStatus:
1248 m = new(certificateStatusMsg)
1249 case typeServerKeyExchange:
1250 m = new(serverKeyExchangeMsg)
1251 case typeServerHelloDone:
1252 m = new(serverHelloDoneMsg)
1253 case typeClientKeyExchange:
1254 m = new(clientKeyExchangeMsg)
1255 case typeCertificateVerify:
1256 m = &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001257 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001258 }
1259 case typeNextProtocol:
1260 m = new(nextProtoMsg)
1261 case typeFinished:
1262 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001263 case typeHelloVerifyRequest:
1264 m = new(helloVerifyRequestMsg)
David Benjamin24599a82016-06-30 18:56:53 -04001265 case typeChannelID:
1266 m = new(channelIDMsg)
David Benjamin21c00282016-07-18 21:56:23 +02001267 case typeKeyUpdate:
1268 m = new(keyUpdateMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001269 default:
1270 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1271 }
1272
1273 // The handshake message unmarshallers
1274 // expect to be able to keep references to data,
1275 // so pass in a fresh copy that won't be overwritten.
1276 data = append([]byte(nil), data...)
1277
1278 if !m.unmarshal(data) {
1279 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1280 }
1281 return m, nil
1282}
1283
David Benjamin83f90402015-01-27 01:09:43 -05001284// skipPacket processes all the DTLS records in packet. It updates
1285// sequence number expectations but otherwise ignores them.
1286func (c *Conn) skipPacket(packet []byte) error {
1287 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001288 if len(packet) < 13 {
1289 return errors.New("tls: bad packet")
1290 }
David Benjamin83f90402015-01-27 01:09:43 -05001291 // Dropped packets are completely ignored save to update
1292 // expected sequence numbers for this and the next epoch. (We
1293 // don't assert on the contents of the packets both for
1294 // simplicity and because a previous test with one shorter
1295 // timeout schedule would have done so.)
1296 epoch := packet[3:5]
1297 seq := packet[5:11]
1298 length := uint16(packet[11])<<8 | uint16(packet[12])
1299 if bytes.Equal(c.in.seq[:2], epoch) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001300 if bytes.Compare(seq, c.in.seq[2:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001301 return errors.New("tls: sequence mismatch")
1302 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001303 copy(c.in.seq[2:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001304 c.in.incSeq(false)
1305 } else {
David Benjamin13e81fc2015-11-02 17:16:13 -05001306 if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001307 return errors.New("tls: sequence mismatch")
1308 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001309 copy(c.in.nextSeq[:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001310 c.in.incNextSeq()
1311 }
David Benjamin6ca93552015-08-28 16:16:25 -04001312 if len(packet) < 13+int(length) {
1313 return errors.New("tls: bad packet")
1314 }
David Benjamin83f90402015-01-27 01:09:43 -05001315 packet = packet[13+length:]
1316 }
1317 return nil
1318}
1319
1320// simulatePacketLoss simulates the loss of a handshake leg from the
1321// peer based on the schedule in c.config.Bugs. If resendFunc is
1322// non-nil, it is called after each simulated timeout to retransmit
1323// handshake messages from the local end. This is used in cases where
1324// the peer retransmits on a stale Finished rather than a timeout.
1325func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1326 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1327 return nil
1328 }
1329 if !c.isDTLS {
1330 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1331 }
1332 if c.config.Bugs.PacketAdaptor == nil {
1333 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1334 }
1335 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1336 // Simulate a timeout.
1337 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1338 if err != nil {
1339 return err
1340 }
1341 for _, packet := range packets {
1342 if err := c.skipPacket(packet); err != nil {
1343 return err
1344 }
1345 }
1346 if resendFunc != nil {
1347 resendFunc()
1348 }
1349 }
1350 return nil
1351}
1352
David Benjamin47921102016-07-28 11:29:18 -04001353func (c *Conn) SendHalfHelloRequest() error {
1354 if err := c.Handshake(); err != nil {
1355 return err
1356 }
1357
1358 c.out.Lock()
1359 defer c.out.Unlock()
1360
1361 if _, err := c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0}); err != nil {
1362 return err
1363 }
1364 return c.flushHandshake()
1365}
1366
Adam Langley95c29f32014-06-20 12:00:00 -07001367// Write writes data to the connection.
1368func (c *Conn) Write(b []byte) (int, error) {
1369 if err := c.Handshake(); err != nil {
1370 return 0, err
1371 }
1372
1373 c.out.Lock()
1374 defer c.out.Unlock()
1375
David Benjamin12d2c482016-07-24 10:56:51 -04001376 // Flush any pending handshake data. PackHelloRequestWithFinished may
1377 // have been set and the handshake not followed by Renegotiate.
1378 c.flushHandshake()
1379
Adam Langley95c29f32014-06-20 12:00:00 -07001380 if err := c.out.err; err != nil {
1381 return 0, err
1382 }
1383
1384 if !c.handshakeComplete {
1385 return 0, alertInternalError
1386 }
1387
Steven Valdezc4aa7272016-10-03 12:25:56 -04001388 if c.keyUpdateRequested {
1389 if err := c.sendKeyUpdateLocked(keyUpdateNotRequested); err != nil {
David Benjamin21c00282016-07-18 21:56:23 +02001390 return 0, err
1391 }
Steven Valdezc4aa7272016-10-03 12:25:56 -04001392 c.keyUpdateRequested = false
David Benjamin21c00282016-07-18 21:56:23 +02001393 }
1394
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001395 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001396 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001397 }
1398
Adam Langley27a0d082015-11-03 13:34:10 -08001399 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1400 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
David Benjamin582ba042016-07-07 12:33:25 -07001401 c.flushHandshake()
Adam Langley27a0d082015-11-03 13:34:10 -08001402 }
1403
Adam Langley95c29f32014-06-20 12:00:00 -07001404 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1405 // attack when using block mode ciphers due to predictable IVs.
1406 // This can be prevented by splitting each Application Data
1407 // record into two records, effectively randomizing the IV.
1408 //
1409 // http://www.openssl.org/~bodo/tls-cbc.txt
1410 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1411 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1412
1413 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001414 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001415 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1416 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1417 if err != nil {
1418 return n, c.out.setErrorLocked(err)
1419 }
1420 m, b = 1, b[1:]
1421 }
1422 }
1423
1424 n, err := c.writeRecord(recordTypeApplicationData, b)
1425 return n + m, c.out.setErrorLocked(err)
1426}
1427
David Benjamind5a4ecb2016-07-18 01:17:13 +02001428func (c *Conn) handlePostHandshakeMessage() error {
Adam Langley2ae77d22014-10-28 17:29:33 -07001429 msg, err := c.readHandshake()
1430 if err != nil {
1431 return err
1432 }
David Benjamind5a4ecb2016-07-18 01:17:13 +02001433
1434 if c.vers < VersionTLS13 {
1435 if !c.isClient {
1436 c.sendAlert(alertUnexpectedMessage)
1437 return errors.New("tls: unexpected post-handshake message")
1438 }
1439
1440 _, ok := msg.(*helloRequestMsg)
1441 if !ok {
1442 c.sendAlert(alertUnexpectedMessage)
1443 return alertUnexpectedMessage
1444 }
1445
1446 c.handshakeComplete = false
1447 return c.Handshake()
Adam Langley2ae77d22014-10-28 17:29:33 -07001448 }
1449
David Benjamind5a4ecb2016-07-18 01:17:13 +02001450 if c.isClient {
1451 if newSessionTicket, ok := msg.(*newSessionTicketMsg); ok {
David Benjamin1a5e8ec2016-10-07 15:19:18 -04001452 if c.config.Bugs.ExpectGREASE && !newSessionTicket.hasGREASEExtension {
1453 return errors.New("tls: no GREASE ticket extension found")
1454 }
1455
Nick Harperf2511f12016-12-06 16:02:31 -08001456 if c.config.Bugs.ExpectTicketEarlyDataInfo && newSessionTicket.maxEarlyDataSize == 0 {
Steven Valdez08b65f42016-12-07 15:29:45 -05001457 return errors.New("tls: no ticket_early_data_info extension found")
1458 }
1459
Steven Valdeza833c352016-11-01 13:39:36 -04001460 if c.config.Bugs.ExpectNoNewSessionTicket {
1461 return errors.New("tls: received unexpected NewSessionTicket")
1462 }
1463
David Benjamind5a4ecb2016-07-18 01:17:13 +02001464 if c.config.ClientSessionCache == nil || newSessionTicket.ticketLifetime == 0 {
1465 return nil
1466 }
1467
1468 session := &ClientSessionState{
1469 sessionTicket: newSessionTicket.ticket,
1470 vers: c.vers,
1471 cipherSuite: c.cipherSuite.id,
1472 masterSecret: c.resumptionSecret,
1473 serverCertificates: c.peerCertificates,
1474 sctList: c.sctList,
1475 ocspResponse: c.ocspResponse,
Nick Harper0b3625b2016-07-25 16:16:28 -07001476 ticketCreationTime: c.config.time(),
1477 ticketExpiration: c.config.time().Add(time.Duration(newSessionTicket.ticketLifetime) * time.Second),
Steven Valdeza833c352016-11-01 13:39:36 -04001478 ticketAgeAdd: newSessionTicket.ticketAgeAdd,
Nick Harperf2511f12016-12-06 16:02:31 -08001479 maxEarlyDataSize: newSessionTicket.maxEarlyDataSize,
Steven Valdez2d850622017-01-11 11:34:52 -05001480 earlyALPN: c.clientProtocol,
David Benjamind5a4ecb2016-07-18 01:17:13 +02001481 }
1482
1483 cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
1484 c.config.ClientSessionCache.Put(cacheKey, session)
1485 return nil
1486 }
1487 }
1488
Steven Valdezc4aa7272016-10-03 12:25:56 -04001489 if keyUpdate, ok := msg.(*keyUpdateMsg); ok {
Steven Valdez1dc53d22016-07-26 12:27:38 -04001490 c.in.doKeyUpdate(c, false)
Steven Valdezc4aa7272016-10-03 12:25:56 -04001491 if keyUpdate.keyUpdateRequest == keyUpdateRequested {
1492 c.keyUpdateRequested = true
1493 }
David Benjamin21c00282016-07-18 21:56:23 +02001494 return nil
1495 }
1496
David Benjamind5a4ecb2016-07-18 01:17:13 +02001497 // TODO(davidben): Add support for KeyUpdate.
1498 c.sendAlert(alertUnexpectedMessage)
1499 return alertUnexpectedMessage
Adam Langley2ae77d22014-10-28 17:29:33 -07001500}
1501
Adam Langleycf2d4f42014-10-28 19:06:14 -07001502func (c *Conn) Renegotiate() error {
1503 if !c.isClient {
David Benjaminef5dfd22015-12-06 13:17:07 -05001504 helloReq := new(helloRequestMsg).marshal()
1505 if c.config.Bugs.BadHelloRequest != nil {
1506 helloReq = c.config.Bugs.BadHelloRequest
1507 }
1508 c.writeRecord(recordTypeHandshake, helloReq)
David Benjamin582ba042016-07-07 12:33:25 -07001509 c.flushHandshake()
Adam Langleycf2d4f42014-10-28 19:06:14 -07001510 }
1511
1512 c.handshakeComplete = false
1513 return c.Handshake()
1514}
1515
Adam Langley95c29f32014-06-20 12:00:00 -07001516// Read can be made to time out and return a net.Error with Timeout() == true
1517// after a fixed time limit; see SetDeadline and SetReadDeadline.
1518func (c *Conn) Read(b []byte) (n int, err error) {
1519 if err = c.Handshake(); err != nil {
1520 return
1521 }
1522
1523 c.in.Lock()
1524 defer c.in.Unlock()
1525
1526 // Some OpenSSL servers send empty records in order to randomize the
1527 // CBC IV. So this loop ignores a limited number of empty records.
1528 const maxConsecutiveEmptyRecords = 100
1529 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1530 for c.input == nil && c.in.err == nil {
1531 if err := c.readRecord(recordTypeApplicationData); err != nil {
1532 // Soft error, like EAGAIN
1533 return 0, err
1534 }
David Benjamind9b091b2015-01-27 01:10:54 -05001535 if c.hand.Len() > 0 {
David Benjamind5a4ecb2016-07-18 01:17:13 +02001536 // We received handshake bytes, indicating a
1537 // post-handshake message.
1538 if err := c.handlePostHandshakeMessage(); err != nil {
Adam Langley2ae77d22014-10-28 17:29:33 -07001539 return 0, err
1540 }
1541 continue
1542 }
Adam Langley95c29f32014-06-20 12:00:00 -07001543 }
1544 if err := c.in.err; err != nil {
1545 return 0, err
1546 }
1547
1548 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001549 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001550 c.in.freeBlock(c.input)
1551 c.input = nil
1552 }
1553
1554 // If a close-notify alert is waiting, read it so that
1555 // we can return (n, EOF) instead of (n, nil), to signal
1556 // to the HTTP response reading goroutine that the
1557 // connection is now closed. This eliminates a race
1558 // where the HTTP response reading goroutine would
1559 // otherwise not observe the EOF until its next read,
1560 // by which time a client goroutine might have already
1561 // tried to reuse the HTTP connection for a new
1562 // request.
1563 // See https://codereview.appspot.com/76400046
1564 // and http://golang.org/issue/3514
1565 if ri := c.rawInput; ri != nil &&
1566 n != 0 && err == nil &&
1567 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1568 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1569 err = recErr // will be io.EOF on closeNotify
1570 }
1571 }
1572
1573 if n != 0 || err != nil {
1574 return n, err
1575 }
1576 }
1577
1578 return 0, io.ErrNoProgress
1579}
1580
1581// Close closes the connection.
1582func (c *Conn) Close() error {
1583 var alertErr error
1584
1585 c.handshakeMutex.Lock()
1586 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001587 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
David Benjaminfa214e42016-05-10 17:03:10 -04001588 alert := alertCloseNotify
1589 if c.config.Bugs.SendAlertOnShutdown != 0 {
1590 alert = c.config.Bugs.SendAlertOnShutdown
1591 }
1592 alertErr = c.sendAlert(alert)
David Benjamin4d559612016-05-18 14:31:51 -04001593 // Clear local alerts when sending alerts so we continue to wait
1594 // for the peer rather than closing the socket early.
1595 if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1596 alertErr = nil
1597 }
Adam Langley95c29f32014-06-20 12:00:00 -07001598 }
1599
David Benjamin30789da2015-08-29 22:56:45 -04001600 // Consume a close_notify from the peer if one hasn't been received
1601 // already. This avoids the peer from failing |SSL_shutdown| due to a
1602 // write failing.
1603 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1604 for c.in.error() == nil {
1605 c.readRecord(recordTypeAlert)
1606 }
1607 if c.in.error() != io.EOF {
1608 alertErr = c.in.error()
1609 }
1610 }
1611
Adam Langley95c29f32014-06-20 12:00:00 -07001612 if err := c.conn.Close(); err != nil {
1613 return err
1614 }
1615 return alertErr
1616}
1617
1618// Handshake runs the client or server handshake
1619// protocol if it has not yet been run.
1620// Most uses of this package need not call Handshake
1621// explicitly: the first Read or Write will call it automatically.
1622func (c *Conn) Handshake() error {
1623 c.handshakeMutex.Lock()
1624 defer c.handshakeMutex.Unlock()
1625 if err := c.handshakeErr; err != nil {
1626 return err
1627 }
1628 if c.handshakeComplete {
1629 return nil
1630 }
1631
David Benjamin9a41d1b2015-05-16 01:30:09 -04001632 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1633 c.conn.Write([]byte{
1634 byte(recordTypeAlert), // type
1635 0xfe, 0xff, // version
1636 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1637 0x0, 0x2, // length
1638 })
1639 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1640 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001641 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1642 c.writeRecord(recordTypeApplicationData, data)
1643 }
Adam Langley95c29f32014-06-20 12:00:00 -07001644 if c.isClient {
1645 c.handshakeErr = c.clientHandshake()
1646 } else {
1647 c.handshakeErr = c.serverHandshake()
1648 }
David Benjaminddb9f152015-02-03 15:44:39 -05001649 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1650 c.writeRecord(recordType(42), []byte("invalid record"))
1651 }
Adam Langley95c29f32014-06-20 12:00:00 -07001652 return c.handshakeErr
1653}
1654
1655// ConnectionState returns basic TLS details about the connection.
1656func (c *Conn) ConnectionState() ConnectionState {
1657 c.handshakeMutex.Lock()
1658 defer c.handshakeMutex.Unlock()
1659
1660 var state ConnectionState
1661 state.HandshakeComplete = c.handshakeComplete
1662 if c.handshakeComplete {
1663 state.Version = c.vers
1664 state.NegotiatedProtocol = c.clientProtocol
1665 state.DidResume = c.didResume
1666 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001667 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001668 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001669 state.PeerCertificates = c.peerCertificates
1670 state.VerifiedChains = c.verifiedChains
1671 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001672 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001673 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001674 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001675 state.SCTList = c.sctList
Nick Harper60edffd2016-06-21 15:19:24 -07001676 state.PeerSignatureAlgorithm = c.peerSignatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -04001677 state.CurveID = c.curveID
Adam Langley95c29f32014-06-20 12:00:00 -07001678 }
1679
1680 return state
1681}
1682
1683// OCSPResponse returns the stapled OCSP response from the TLS server, if
1684// any. (Only valid for client connections.)
1685func (c *Conn) OCSPResponse() []byte {
1686 c.handshakeMutex.Lock()
1687 defer c.handshakeMutex.Unlock()
1688
1689 return c.ocspResponse
1690}
1691
1692// VerifyHostname checks that the peer certificate chain is valid for
1693// connecting to host. If so, it returns nil; if not, it returns an error
1694// describing the problem.
1695func (c *Conn) VerifyHostname(host string) error {
1696 c.handshakeMutex.Lock()
1697 defer c.handshakeMutex.Unlock()
1698 if !c.isClient {
1699 return errors.New("tls: VerifyHostname called on TLS server connection")
1700 }
1701 if !c.handshakeComplete {
1702 return errors.New("tls: handshake has not yet been performed")
1703 }
1704 return c.peerCertificates[0].VerifyHostname(host)
1705}
David Benjaminc565ebb2015-04-03 04:06:36 -04001706
1707// ExportKeyingMaterial exports keying material from the current connection
1708// state, as per RFC 5705.
1709func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1710 c.handshakeMutex.Lock()
1711 defer c.handshakeMutex.Unlock()
1712 if !c.handshakeComplete {
1713 return nil, errors.New("tls: handshake has not yet been performed")
1714 }
1715
David Benjamin8d315d72016-07-18 01:03:18 +02001716 if c.vers >= VersionTLS13 {
David Benjamin97a0a082016-07-13 17:57:35 -04001717 // TODO(davidben): What should we do with useContext? See
1718 // https://github.com/tlswg/tls13-spec/issues/546
1719 return hkdfExpandLabel(c.cipherSuite.hash(), c.exporterSecret, label, context, length), nil
1720 }
1721
David Benjaminc565ebb2015-04-03 04:06:36 -04001722 seedLen := len(c.clientRandom) + len(c.serverRandom)
1723 if useContext {
1724 seedLen += 2 + len(context)
1725 }
1726 seed := make([]byte, 0, seedLen)
1727 seed = append(seed, c.clientRandom[:]...)
1728 seed = append(seed, c.serverRandom[:]...)
1729 if useContext {
1730 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1731 seed = append(seed, context...)
1732 }
1733 result := make([]byte, length)
David Benjamin97a0a082016-07-13 17:57:35 -04001734 prfForVersion(c.vers, c.cipherSuite)(result, c.exporterSecret, label, seed)
David Benjaminc565ebb2015-04-03 04:06:36 -04001735 return result, nil
1736}
David Benjamin3e052de2015-11-25 20:10:31 -05001737
1738// noRenegotiationInfo returns true if the renegotiation info extension
1739// should be supported in the current handshake.
1740func (c *Conn) noRenegotiationInfo() bool {
1741 if c.config.Bugs.NoRenegotiationInfo {
1742 return true
1743 }
1744 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1745 return true
1746 }
1747 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1748 return true
1749 }
1750 return false
1751}
David Benjamin58104882016-07-18 01:25:41 +02001752
1753func (c *Conn) SendNewSessionTicket() error {
1754 if c.isClient || c.vers < VersionTLS13 {
1755 return errors.New("tls: cannot send post-handshake NewSessionTicket")
1756 }
1757
1758 var peerCertificatesRaw [][]byte
1759 for _, cert := range c.peerCertificates {
1760 peerCertificatesRaw = append(peerCertificatesRaw, cert.Raw)
1761 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001762
Steven Valdeza833c352016-11-01 13:39:36 -04001763 addBuffer := make([]byte, 4)
1764 _, err := io.ReadFull(c.config.rand(), addBuffer)
1765 if err != nil {
1766 c.sendAlert(alertInternalError)
1767 return errors.New("tls: short read from Rand: " + err.Error())
1768 }
1769 ticketAgeAdd := uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0])
1770
David Benjamin58104882016-07-18 01:25:41 +02001771 // TODO(davidben): Allow configuring these values.
1772 m := &newSessionTicketMsg{
David Benjamin9c33ae82017-01-08 06:04:43 -05001773 version: c.vers,
1774 ticketLifetime: uint32(24 * time.Hour / time.Second),
David Benjamin9c33ae82017-01-08 06:04:43 -05001775 duplicateEarlyDataInfo: c.config.Bugs.DuplicateTicketEarlyDataInfo,
1776 customExtension: c.config.Bugs.CustomTicketExtension,
1777 ticketAgeAdd: ticketAgeAdd,
Nick Harperab20cec2016-12-19 17:38:41 -08001778 maxEarlyDataSize: c.config.MaxEarlyDataSize,
David Benjamin58104882016-07-18 01:25:41 +02001779 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001780
David Benjamin17b30832017-01-28 14:00:32 -05001781 if c.config.Bugs.SendTicketLifetime != 0 {
1782 m.ticketLifetime = uint32(c.config.Bugs.SendTicketLifetime / time.Second)
1783 }
1784
Nick Harper0b3625b2016-07-25 16:16:28 -07001785 state := sessionState{
1786 vers: c.vers,
1787 cipherSuite: c.cipherSuite.id,
1788 masterSecret: c.resumptionSecret,
1789 certificates: peerCertificatesRaw,
1790 ticketCreationTime: c.config.time(),
1791 ticketExpiration: c.config.time().Add(time.Duration(m.ticketLifetime) * time.Second),
Steven Valdeza833c352016-11-01 13:39:36 -04001792 ticketAgeAdd: uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0]),
Steven Valdez2d850622017-01-11 11:34:52 -05001793 earlyALPN: []byte(c.clientProtocol),
Nick Harper0b3625b2016-07-25 16:16:28 -07001794 }
1795
David Benjamin58104882016-07-18 01:25:41 +02001796 if !c.config.Bugs.SendEmptySessionTicket {
1797 var err error
1798 m.ticket, err = c.encryptTicket(&state)
1799 if err != nil {
1800 return err
1801 }
1802 }
David Benjamin58104882016-07-18 01:25:41 +02001803 c.out.Lock()
1804 defer c.out.Unlock()
Steven Valdeza833c352016-11-01 13:39:36 -04001805 _, err = c.writeRecord(recordTypeHandshake, m.marshal())
David Benjamin58104882016-07-18 01:25:41 +02001806 return err
1807}
David Benjamin21c00282016-07-18 21:56:23 +02001808
Steven Valdezc4aa7272016-10-03 12:25:56 -04001809func (c *Conn) SendKeyUpdate(keyUpdateRequest byte) error {
David Benjamin21c00282016-07-18 21:56:23 +02001810 c.out.Lock()
1811 defer c.out.Unlock()
Steven Valdezc4aa7272016-10-03 12:25:56 -04001812 return c.sendKeyUpdateLocked(keyUpdateRequest)
David Benjamin21c00282016-07-18 21:56:23 +02001813}
1814
Steven Valdezc4aa7272016-10-03 12:25:56 -04001815func (c *Conn) sendKeyUpdateLocked(keyUpdateRequest byte) error {
David Benjamin7f0965a2016-09-30 15:14:01 -04001816 if c.vers < VersionTLS13 {
1817 return errors.New("tls: attempted to send KeyUpdate before TLS 1.3")
1818 }
1819
Steven Valdezc4aa7272016-10-03 12:25:56 -04001820 m := keyUpdateMsg{
1821 keyUpdateRequest: keyUpdateRequest,
1822 }
David Benjamin21c00282016-07-18 21:56:23 +02001823 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
1824 return err
1825 }
1826 if err := c.flushHandshake(); err != nil {
1827 return err
1828 }
Steven Valdez1dc53d22016-07-26 12:27:38 -04001829 c.out.doKeyUpdate(c, true)
David Benjamin21c00282016-07-18 21:56:23 +02001830 return nil
1831}
Steven Valdeza4ee74d2016-11-29 13:36:45 -05001832
1833func (c *Conn) sendFakeEarlyData(len int) error {
1834 // Assemble a fake early data record. This does not use writeRecord
1835 // because the record layer may be using different keys at this point.
1836 payload := make([]byte, 5+len)
1837 payload[0] = byte(recordTypeApplicationData)
1838 payload[1] = 3
1839 payload[2] = 1
1840 payload[3] = byte(len >> 8)
1841 payload[4] = byte(len)
1842 _, err := c.conn.Write(payload)
1843 return err
1844}