blob: 0eb64e71e6962bd427da9d65da57774db324d236 [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 }
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 Benjaminbbba9392017-04-06 12:54:12 -0400865 case recordTypeAlert, recordTypeHandshake:
866 // Looking for a close_notify or handshake message. Note: unlike
867 // a real implementation, this is not tolerant of additional
868 // records. See the documentation for ExpectCloseNotify.
869 // Post-handshake requests for handshake messages are allowed if
870 // the caller used ReadKeyUpdateACK.
Adam Langley95c29f32014-06-20 12:00:00 -0700871 }
872
873Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400874 typ, b, err := c.doReadRecord(want)
875 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700876 return err
877 }
Adam Langley95c29f32014-06-20 12:00:00 -0700878 data := b.data[b.off:]
David Benjamine3fbb362017-01-06 16:19:28 -0500879 max := maxPlaintext
880 if c.config.Bugs.MaxReceivePlaintext != 0 {
881 max = c.config.Bugs.MaxReceivePlaintext
882 }
883 if len(data) > max {
Adam Langley95c29f32014-06-20 12:00:00 -0700884 err := c.sendAlert(alertRecordOverflow)
885 c.in.freeBlock(b)
886 return c.in.setErrorLocked(err)
887 }
888
889 switch typ {
890 default:
891 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
892
893 case recordTypeAlert:
894 if len(data) != 2 {
895 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
896 break
897 }
898 if alert(data[1]) == alertCloseNotify {
899 c.in.setErrorLocked(io.EOF)
900 break
901 }
902 switch data[0] {
903 case alertLevelWarning:
David Benjamin053fee92017-01-02 08:30:36 -0500904 if alert(data[1]) == alertNoCertificate {
905 c.in.freeBlock(b)
906 return errNoCertificateAlert
907 }
Nick Harperab20cec2016-12-19 17:38:41 -0800908 if alert(data[1]) == alertEndOfEarlyData {
909 c.in.freeBlock(b)
910 return errEndOfEarlyDataAlert
911 }
David Benjamin053fee92017-01-02 08:30:36 -0500912
Adam Langley95c29f32014-06-20 12:00:00 -0700913 // drop on the floor
914 c.in.freeBlock(b)
915 goto Again
916 case alertLevelError:
917 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
918 default:
919 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
920 }
921
922 case recordTypeChangeCipherSpec:
923 if typ != want || len(data) != 1 || data[0] != 1 {
924 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
925 break
926 }
Adam Langley80842bd2014-06-20 12:00:00 -0700927 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700928 if err != nil {
929 c.in.setErrorLocked(c.sendAlert(err.(alert)))
930 }
931
932 case recordTypeApplicationData:
933 if typ != want {
934 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
935 break
936 }
937 c.input = b
938 b = nil
939
940 case recordTypeHandshake:
David Benjamind5a4ecb2016-07-18 01:17:13 +0200941 // Allow handshake data while reading application data to
942 // trigger post-handshake messages.
Adam Langley95c29f32014-06-20 12:00:00 -0700943 // TODO(rsc): Should at least pick off connection close.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200944 if typ != want && want != recordTypeApplicationData {
945 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
Adam Langley95c29f32014-06-20 12:00:00 -0700946 }
947 c.hand.Write(data)
948 }
949
950 if b != nil {
951 c.in.freeBlock(b)
952 }
953 return c.in.err
954}
955
956// sendAlert sends a TLS alert message.
957// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400958func (c *Conn) sendAlertLocked(level byte, err alert) error {
959 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700960 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400961 if c.config.Bugs.FragmentAlert {
962 c.writeRecord(recordTypeAlert, c.tmp[0:1])
963 c.writeRecord(recordTypeAlert, c.tmp[1:2])
David Benjamin0d3a8c62016-03-11 22:25:18 -0500964 } else if c.config.Bugs.DoubleAlert {
965 copy(c.tmp[2:4], c.tmp[0:2])
966 c.writeRecord(recordTypeAlert, c.tmp[0:4])
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400967 } else {
968 c.writeRecord(recordTypeAlert, c.tmp[0:2])
969 }
David Benjamin24f346d2015-06-06 03:28:08 -0400970 // Error alerts are fatal to the connection.
971 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700972 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
973 }
974 return nil
975}
976
977// sendAlert sends a TLS alert message.
978// L < c.out.Mutex.
979func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400980 level := byte(alertLevelError)
Nick Harperf2511f12016-12-06 16:02:31 -0800981 if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertificate || err == alertEndOfEarlyData {
David Benjamin24f346d2015-06-06 03:28:08 -0400982 level = alertLevelWarning
983 }
984 return c.SendAlert(level, err)
985}
986
987func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700988 c.out.Lock()
989 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -0400990 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -0700991}
992
David Benjamind86c7672014-08-02 04:07:12 -0400993// writeV2Record writes a record for a V2ClientHello.
994func (c *Conn) writeV2Record(data []byte) (n int, err error) {
995 record := make([]byte, 2+len(data))
996 record[0] = uint8(len(data)>>8) | 0x80
997 record[1] = uint8(len(data))
998 copy(record[2:], data)
999 return c.conn.Write(record)
1000}
1001
Adam Langley95c29f32014-06-20 12:00:00 -07001002// writeRecord writes a TLS record with the given type and payload
1003// to the connection and updates the record layer state.
1004// c.out.Mutex <= L.
1005func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjaminebacdee2017-04-08 11:00:45 -04001006 if typ == recordTypeHandshake {
1007 msgType := data[0]
1008 if c.config.Bugs.SendWrongMessageType != 0 && msgType == c.config.Bugs.SendWrongMessageType {
1009 msgType += 42
1010 } else if msgType == typeServerHello && c.config.Bugs.SendServerHelloAsHelloRetryRequest {
1011 msgType = typeHelloRetryRequest
1012 }
1013 if msgType != data[0] {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001014 newData := make([]byte, len(data))
1015 copy(newData, data)
David Benjaminebacdee2017-04-08 11:00:45 -04001016 newData[0] = msgType
David Benjamin0b8d5da2016-07-15 00:39:56 -04001017 data = newData
1018 }
1019 }
1020
David Benjamin639846e2016-09-09 11:41:18 -04001021 if msgType := c.config.Bugs.SendTrailingMessageData; msgType != 0 {
1022 if typ == recordTypeHandshake && data[0] == msgType {
1023 newData := make([]byte, len(data))
1024 copy(newData, data)
1025
1026 // Add a 0 to the body.
1027 newData = append(newData, 0)
1028 // Fix the header.
1029 newLen := len(newData) - 4
1030 newData[1] = byte(newLen >> 16)
1031 newData[2] = byte(newLen >> 8)
1032 newData[3] = byte(newLen)
1033
1034 data = newData
1035 }
1036 }
1037
David Benjamin83c0bc92014-08-04 01:23:53 -04001038 if c.isDTLS {
1039 return c.dtlsWriteRecord(typ, data)
1040 }
1041
David Benjamin71dd6662016-07-08 14:10:48 -07001042 if typ == recordTypeHandshake {
1043 if c.config.Bugs.SendHelloRequestBeforeEveryHandshakeMessage {
1044 newData := make([]byte, 0, 4+len(data))
1045 newData = append(newData, typeHelloRequest, 0, 0, 0)
1046 newData = append(newData, data...)
1047 data = newData
1048 }
1049
1050 if c.config.Bugs.PackHandshakeFlight {
1051 c.pendingFlight.Write(data)
1052 return len(data), nil
1053 }
David Benjamin582ba042016-07-07 12:33:25 -07001054 }
1055
1056 return c.doWriteRecord(typ, data)
1057}
1058
1059func (c *Conn) doWriteRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin6f600d62016-12-21 16:06:54 -05001060 recordHeaderLen := c.out.recordHeaderLen()
Adam Langley95c29f32014-06-20 12:00:00 -07001061 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -04001062 first := true
1063 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -04001064 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -07001065 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -04001066 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -07001067 m = maxPlaintext
1068 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001069 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
1070 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -04001071 // By default, do not fragment the client_version or
1072 // server_version, which are located in the first 6
1073 // bytes.
1074 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
1075 m = 6
1076 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001077 }
Adam Langley95c29f32014-06-20 12:00:00 -07001078 explicitIVLen := 0
1079 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -04001080 first = false
Adam Langley95c29f32014-06-20 12:00:00 -07001081
1082 var cbc cbcMode
1083 if c.out.version >= VersionTLS11 {
1084 var ok bool
1085 if cbc, ok = c.out.cipher.(cbcMode); ok {
1086 explicitIVLen = cbc.BlockSize()
1087 }
1088 }
1089 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -04001090 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -07001091 explicitIVLen = 8
1092 // The AES-GCM construction in TLS has an
1093 // explicit nonce so that the nonce can be
1094 // random. However, the nonce is only 8 bytes
1095 // which is too small for a secure, random
1096 // nonce. Therefore we use the sequence number
1097 // as the nonce.
1098 explicitIVIsSeq = true
1099 }
1100 }
1101 b.resize(recordHeaderLen + explicitIVLen + m)
Steven Valdez924a3522017-03-02 16:05:03 -05001102 b.data[0] = byte(typ)
1103 if c.vers >= VersionTLS13 && c.out.cipher != nil {
1104 b.data[0] = byte(recordTypeApplicationData)
1105 if outerType := c.config.Bugs.OuterRecordType; outerType != 0 {
1106 b.data[0] = byte(outerType)
David Benjaminc9ae27c2016-06-24 22:56:37 -04001107 }
Nick Harper1fd39d82016-06-14 18:14:35 -07001108 }
Steven Valdez924a3522017-03-02 16:05:03 -05001109 vers := c.vers
1110 if vers == 0 || vers >= VersionTLS13 {
1111 // Some TLS servers fail if the record version is
1112 // greater than TLS 1.0 for the initial ClientHello.
1113 //
1114 // TLS 1.3 fixes the version number in the record
1115 // layer to {3, 1}.
1116 vers = VersionTLS10
1117 }
1118 if c.config.Bugs.SendRecordVersion != 0 {
1119 vers = c.config.Bugs.SendRecordVersion
1120 }
1121 if c.vers == 0 && c.config.Bugs.SendInitialRecordVersion != 0 {
1122 vers = c.config.Bugs.SendInitialRecordVersion
1123 }
1124 b.data[1] = byte(vers >> 8)
1125 b.data[2] = byte(vers)
1126 b.data[3] = byte(m >> 8)
1127 b.data[4] = byte(m)
Adam Langley95c29f32014-06-20 12:00:00 -07001128 if explicitIVLen > 0 {
1129 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
1130 if explicitIVIsSeq {
1131 copy(explicitIV, c.out.seq[:])
1132 } else {
1133 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
1134 break
1135 }
1136 }
1137 }
1138 copy(b.data[recordHeaderLen+explicitIVLen:], data)
Nick Harper1fd39d82016-06-14 18:14:35 -07001139 c.out.encrypt(b, explicitIVLen, typ)
Adam Langley95c29f32014-06-20 12:00:00 -07001140 _, err = c.conn.Write(b.data)
1141 if err != nil {
1142 break
1143 }
1144 n += m
1145 data = data[m:]
1146 }
1147 c.out.freeBlock(b)
1148
1149 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -07001150 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -07001151 if err != nil {
1152 // Cannot call sendAlert directly,
1153 // because we already hold c.out.Mutex.
1154 c.tmp[0] = alertLevelError
1155 c.tmp[1] = byte(err.(alert))
1156 c.writeRecord(recordTypeAlert, c.tmp[0:2])
1157 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
1158 }
1159 }
1160 return
1161}
1162
David Benjamin582ba042016-07-07 12:33:25 -07001163func (c *Conn) flushHandshake() error {
1164 if c.isDTLS {
1165 return c.dtlsFlushHandshake()
1166 }
1167
1168 for c.pendingFlight.Len() > 0 {
1169 var buf [maxPlaintext]byte
1170 n, _ := c.pendingFlight.Read(buf[:])
1171 if _, err := c.doWriteRecord(recordTypeHandshake, buf[:n]); err != nil {
1172 return err
1173 }
1174 }
1175
1176 c.pendingFlight.Reset()
1177 return nil
1178}
1179
David Benjamin83c0bc92014-08-04 01:23:53 -04001180func (c *Conn) doReadHandshake() ([]byte, error) {
1181 if c.isDTLS {
1182 return c.dtlsDoReadHandshake()
1183 }
1184
Adam Langley95c29f32014-06-20 12:00:00 -07001185 for c.hand.Len() < 4 {
1186 if err := c.in.err; err != nil {
1187 return nil, err
1188 }
1189 if err := c.readRecord(recordTypeHandshake); err != nil {
1190 return nil, err
1191 }
1192 }
1193
1194 data := c.hand.Bytes()
1195 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1196 if n > maxHandshake {
1197 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
1198 }
1199 for c.hand.Len() < 4+n {
1200 if err := c.in.err; err != nil {
1201 return nil, err
1202 }
1203 if err := c.readRecord(recordTypeHandshake); err != nil {
1204 return nil, err
1205 }
1206 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001207 return c.hand.Next(4 + n), nil
1208}
1209
1210// readHandshake reads the next handshake message from
1211// the record layer.
1212// c.in.Mutex < L; c.out.Mutex < L.
1213func (c *Conn) readHandshake() (interface{}, error) {
1214 data, err := c.doReadHandshake()
David Benjamin053fee92017-01-02 08:30:36 -05001215 if err == errNoCertificateAlert {
1216 if c.hand.Len() != 0 {
1217 // The warning alert may not interleave with a handshake message.
1218 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1219 }
1220 return new(ssl3NoCertificateMsg), nil
1221 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001222 if err != nil {
1223 return nil, err
1224 }
1225
Adam Langley95c29f32014-06-20 12:00:00 -07001226 var m handshakeMessage
1227 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001228 case typeHelloRequest:
1229 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001230 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001231 m = &clientHelloMsg{
1232 isDTLS: c.isDTLS,
1233 }
Adam Langley95c29f32014-06-20 12:00:00 -07001234 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001235 m = &serverHelloMsg{
1236 isDTLS: c.isDTLS,
1237 }
Nick Harperdcfbc672016-07-16 17:47:31 +02001238 case typeHelloRetryRequest:
1239 m = new(helloRetryRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001240 case typeNewSessionTicket:
David Benjamin58104882016-07-18 01:25:41 +02001241 m = &newSessionTicketMsg{
1242 version: c.vers,
1243 }
Nick Harperb41d2e42016-07-01 17:50:32 -04001244 case typeEncryptedExtensions:
1245 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001246 case typeCertificate:
Nick Harperb41d2e42016-07-01 17:50:32 -04001247 m = &certificateMsg{
David Benjamin8d315d72016-07-18 01:03:18 +02001248 hasRequestContext: c.vers >= VersionTLS13,
Nick Harperb41d2e42016-07-01 17:50:32 -04001249 }
Adam Langley95c29f32014-06-20 12:00:00 -07001250 case typeCertificateRequest:
1251 m = &certificateRequestMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001252 hasSignatureAlgorithm: c.vers >= VersionTLS12,
David Benjamin8d315d72016-07-18 01:03:18 +02001253 hasRequestContext: c.vers >= VersionTLS13,
Adam Langley95c29f32014-06-20 12:00:00 -07001254 }
1255 case typeCertificateStatus:
1256 m = new(certificateStatusMsg)
1257 case typeServerKeyExchange:
1258 m = new(serverKeyExchangeMsg)
1259 case typeServerHelloDone:
1260 m = new(serverHelloDoneMsg)
1261 case typeClientKeyExchange:
1262 m = new(clientKeyExchangeMsg)
1263 case typeCertificateVerify:
1264 m = &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001265 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001266 }
1267 case typeNextProtocol:
1268 m = new(nextProtoMsg)
1269 case typeFinished:
1270 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001271 case typeHelloVerifyRequest:
1272 m = new(helloVerifyRequestMsg)
David Benjamin24599a82016-06-30 18:56:53 -04001273 case typeChannelID:
1274 m = new(channelIDMsg)
David Benjamin21c00282016-07-18 21:56:23 +02001275 case typeKeyUpdate:
1276 m = new(keyUpdateMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001277 default:
1278 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1279 }
1280
1281 // The handshake message unmarshallers
1282 // expect to be able to keep references to data,
1283 // so pass in a fresh copy that won't be overwritten.
1284 data = append([]byte(nil), data...)
1285
1286 if !m.unmarshal(data) {
1287 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1288 }
1289 return m, nil
1290}
1291
David Benjamin83f90402015-01-27 01:09:43 -05001292// skipPacket processes all the DTLS records in packet. It updates
1293// sequence number expectations but otherwise ignores them.
1294func (c *Conn) skipPacket(packet []byte) error {
1295 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001296 if len(packet) < 13 {
1297 return errors.New("tls: bad packet")
1298 }
David Benjamin83f90402015-01-27 01:09:43 -05001299 // Dropped packets are completely ignored save to update
1300 // expected sequence numbers for this and the next epoch. (We
1301 // don't assert on the contents of the packets both for
1302 // simplicity and because a previous test with one shorter
1303 // timeout schedule would have done so.)
1304 epoch := packet[3:5]
1305 seq := packet[5:11]
1306 length := uint16(packet[11])<<8 | uint16(packet[12])
1307 if bytes.Equal(c.in.seq[:2], epoch) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001308 if bytes.Compare(seq, c.in.seq[2:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001309 return errors.New("tls: sequence mismatch")
1310 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001311 copy(c.in.seq[2:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001312 c.in.incSeq(false)
1313 } else {
David Benjamin13e81fc2015-11-02 17:16:13 -05001314 if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001315 return errors.New("tls: sequence mismatch")
1316 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001317 copy(c.in.nextSeq[:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001318 c.in.incNextSeq()
1319 }
David Benjamin6ca93552015-08-28 16:16:25 -04001320 if len(packet) < 13+int(length) {
1321 return errors.New("tls: bad packet")
1322 }
David Benjamin83f90402015-01-27 01:09:43 -05001323 packet = packet[13+length:]
1324 }
1325 return nil
1326}
1327
1328// simulatePacketLoss simulates the loss of a handshake leg from the
1329// peer based on the schedule in c.config.Bugs. If resendFunc is
1330// non-nil, it is called after each simulated timeout to retransmit
1331// handshake messages from the local end. This is used in cases where
1332// the peer retransmits on a stale Finished rather than a timeout.
1333func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1334 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1335 return nil
1336 }
1337 if !c.isDTLS {
1338 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1339 }
1340 if c.config.Bugs.PacketAdaptor == nil {
1341 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1342 }
1343 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1344 // Simulate a timeout.
1345 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1346 if err != nil {
1347 return err
1348 }
1349 for _, packet := range packets {
1350 if err := c.skipPacket(packet); err != nil {
1351 return err
1352 }
1353 }
1354 if resendFunc != nil {
1355 resendFunc()
1356 }
1357 }
1358 return nil
1359}
1360
David Benjamin47921102016-07-28 11:29:18 -04001361func (c *Conn) SendHalfHelloRequest() error {
1362 if err := c.Handshake(); err != nil {
1363 return err
1364 }
1365
1366 c.out.Lock()
1367 defer c.out.Unlock()
1368
1369 if _, err := c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0}); err != nil {
1370 return err
1371 }
1372 return c.flushHandshake()
1373}
1374
Adam Langley95c29f32014-06-20 12:00:00 -07001375// Write writes data to the connection.
1376func (c *Conn) Write(b []byte) (int, error) {
1377 if err := c.Handshake(); err != nil {
1378 return 0, err
1379 }
1380
1381 c.out.Lock()
1382 defer c.out.Unlock()
1383
David Benjamin12d2c482016-07-24 10:56:51 -04001384 // Flush any pending handshake data. PackHelloRequestWithFinished may
1385 // have been set and the handshake not followed by Renegotiate.
1386 c.flushHandshake()
1387
Adam Langley95c29f32014-06-20 12:00:00 -07001388 if err := c.out.err; err != nil {
1389 return 0, err
1390 }
1391
1392 if !c.handshakeComplete {
1393 return 0, alertInternalError
1394 }
1395
Steven Valdezc4aa7272016-10-03 12:25:56 -04001396 if c.keyUpdateRequested {
1397 if err := c.sendKeyUpdateLocked(keyUpdateNotRequested); err != nil {
David Benjamin21c00282016-07-18 21:56:23 +02001398 return 0, err
1399 }
Steven Valdezc4aa7272016-10-03 12:25:56 -04001400 c.keyUpdateRequested = false
David Benjamin21c00282016-07-18 21:56:23 +02001401 }
1402
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001403 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001404 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001405 }
1406
Adam Langley27a0d082015-11-03 13:34:10 -08001407 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1408 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
David Benjamin582ba042016-07-07 12:33:25 -07001409 c.flushHandshake()
Adam Langley27a0d082015-11-03 13:34:10 -08001410 }
1411
Adam Langley95c29f32014-06-20 12:00:00 -07001412 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1413 // attack when using block mode ciphers due to predictable IVs.
1414 // This can be prevented by splitting each Application Data
1415 // record into two records, effectively randomizing the IV.
1416 //
1417 // http://www.openssl.org/~bodo/tls-cbc.txt
1418 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1419 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1420
1421 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001422 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001423 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1424 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1425 if err != nil {
1426 return n, c.out.setErrorLocked(err)
1427 }
1428 m, b = 1, b[1:]
1429 }
1430 }
1431
1432 n, err := c.writeRecord(recordTypeApplicationData, b)
1433 return n + m, c.out.setErrorLocked(err)
1434}
1435
David Benjamin794cc592017-03-25 22:24:23 -05001436func (c *Conn) processTLS13NewSessionTicket(newSessionTicket *newSessionTicketMsg, cipherSuite *cipherSuite) error {
1437 if c.config.Bugs.ExpectGREASE && !newSessionTicket.hasGREASEExtension {
1438 return errors.New("tls: no GREASE ticket extension found")
1439 }
1440
1441 if c.config.Bugs.ExpectTicketEarlyDataInfo && newSessionTicket.maxEarlyDataSize == 0 {
1442 return errors.New("tls: no ticket_early_data_info extension found")
1443 }
1444
1445 if c.config.Bugs.ExpectNoNewSessionTicket {
1446 return errors.New("tls: received unexpected NewSessionTicket")
1447 }
1448
1449 if c.config.ClientSessionCache == nil || newSessionTicket.ticketLifetime == 0 {
1450 return nil
1451 }
1452
1453 session := &ClientSessionState{
1454 sessionTicket: newSessionTicket.ticket,
1455 vers: c.vers,
1456 cipherSuite: cipherSuite.id,
1457 masterSecret: c.resumptionSecret,
1458 serverCertificates: c.peerCertificates,
1459 sctList: c.sctList,
1460 ocspResponse: c.ocspResponse,
1461 ticketCreationTime: c.config.time(),
1462 ticketExpiration: c.config.time().Add(time.Duration(newSessionTicket.ticketLifetime) * time.Second),
1463 ticketAgeAdd: newSessionTicket.ticketAgeAdd,
1464 maxEarlyDataSize: newSessionTicket.maxEarlyDataSize,
1465 earlyALPN: c.clientProtocol,
1466 }
1467
1468 cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
1469 c.config.ClientSessionCache.Put(cacheKey, session)
1470 return nil
1471}
1472
David Benjamind5a4ecb2016-07-18 01:17:13 +02001473func (c *Conn) handlePostHandshakeMessage() error {
Adam Langley2ae77d22014-10-28 17:29:33 -07001474 msg, err := c.readHandshake()
1475 if err != nil {
1476 return err
1477 }
David Benjamind5a4ecb2016-07-18 01:17:13 +02001478
1479 if c.vers < VersionTLS13 {
1480 if !c.isClient {
1481 c.sendAlert(alertUnexpectedMessage)
1482 return errors.New("tls: unexpected post-handshake message")
1483 }
1484
1485 _, ok := msg.(*helloRequestMsg)
1486 if !ok {
1487 c.sendAlert(alertUnexpectedMessage)
1488 return alertUnexpectedMessage
1489 }
1490
1491 c.handshakeComplete = false
1492 return c.Handshake()
Adam Langley2ae77d22014-10-28 17:29:33 -07001493 }
1494
David Benjamind5a4ecb2016-07-18 01:17:13 +02001495 if c.isClient {
1496 if newSessionTicket, ok := msg.(*newSessionTicketMsg); ok {
David Benjamin794cc592017-03-25 22:24:23 -05001497 return c.processTLS13NewSessionTicket(newSessionTicket, c.cipherSuite)
David Benjamind5a4ecb2016-07-18 01:17:13 +02001498 }
1499 }
1500
Steven Valdezc4aa7272016-10-03 12:25:56 -04001501 if keyUpdate, ok := msg.(*keyUpdateMsg); ok {
David Benjaminbbba9392017-04-06 12:54:12 -04001502 if c.config.Bugs.RejectUnsolicitedKeyUpdate {
1503 return errors.New("tls: unexpected KeyUpdate message")
1504 }
Steven Valdez1dc53d22016-07-26 12:27:38 -04001505 c.in.doKeyUpdate(c, false)
Steven Valdezc4aa7272016-10-03 12:25:56 -04001506 if keyUpdate.keyUpdateRequest == keyUpdateRequested {
1507 c.keyUpdateRequested = true
1508 }
David Benjamin21c00282016-07-18 21:56:23 +02001509 return nil
1510 }
1511
David Benjamind5a4ecb2016-07-18 01:17:13 +02001512 c.sendAlert(alertUnexpectedMessage)
David Benjaminbbba9392017-04-06 12:54:12 -04001513 return errors.New("tls: unexpected post-handshake message")
1514}
1515
1516// Reads a KeyUpdate acknowledgment from the peer. There may not be any
1517// application data records before the message.
1518func (c *Conn) ReadKeyUpdateACK() error {
1519 c.in.Lock()
1520 defer c.in.Unlock()
1521
1522 msg, err := c.readHandshake()
1523 if err != nil {
1524 return err
1525 }
1526
1527 keyUpdate, ok := msg.(*keyUpdateMsg)
1528 if !ok {
1529 c.sendAlert(alertUnexpectedMessage)
1530 return errors.New("tls: unexpected message when reading KeyUpdate")
1531 }
1532
1533 if keyUpdate.keyUpdateRequest != keyUpdateNotRequested {
1534 return errors.New("tls: received invalid KeyUpdate message")
1535 }
1536
1537 c.in.doKeyUpdate(c, false)
1538 return nil
Adam Langley2ae77d22014-10-28 17:29:33 -07001539}
1540
Adam Langleycf2d4f42014-10-28 19:06:14 -07001541func (c *Conn) Renegotiate() error {
1542 if !c.isClient {
David Benjaminef5dfd22015-12-06 13:17:07 -05001543 helloReq := new(helloRequestMsg).marshal()
1544 if c.config.Bugs.BadHelloRequest != nil {
1545 helloReq = c.config.Bugs.BadHelloRequest
1546 }
1547 c.writeRecord(recordTypeHandshake, helloReq)
David Benjamin582ba042016-07-07 12:33:25 -07001548 c.flushHandshake()
Adam Langleycf2d4f42014-10-28 19:06:14 -07001549 }
1550
1551 c.handshakeComplete = false
1552 return c.Handshake()
1553}
1554
Adam Langley95c29f32014-06-20 12:00:00 -07001555// Read can be made to time out and return a net.Error with Timeout() == true
1556// after a fixed time limit; see SetDeadline and SetReadDeadline.
1557func (c *Conn) Read(b []byte) (n int, err error) {
1558 if err = c.Handshake(); err != nil {
1559 return
1560 }
1561
1562 c.in.Lock()
1563 defer c.in.Unlock()
1564
1565 // Some OpenSSL servers send empty records in order to randomize the
1566 // CBC IV. So this loop ignores a limited number of empty records.
1567 const maxConsecutiveEmptyRecords = 100
1568 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1569 for c.input == nil && c.in.err == nil {
1570 if err := c.readRecord(recordTypeApplicationData); err != nil {
1571 // Soft error, like EAGAIN
1572 return 0, err
1573 }
David Benjamind9b091b2015-01-27 01:10:54 -05001574 if c.hand.Len() > 0 {
David Benjamind5a4ecb2016-07-18 01:17:13 +02001575 // We received handshake bytes, indicating a
1576 // post-handshake message.
1577 if err := c.handlePostHandshakeMessage(); err != nil {
Adam Langley2ae77d22014-10-28 17:29:33 -07001578 return 0, err
1579 }
1580 continue
1581 }
Adam Langley95c29f32014-06-20 12:00:00 -07001582 }
1583 if err := c.in.err; err != nil {
1584 return 0, err
1585 }
1586
1587 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001588 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001589 c.in.freeBlock(c.input)
1590 c.input = nil
1591 }
1592
1593 // If a close-notify alert is waiting, read it so that
1594 // we can return (n, EOF) instead of (n, nil), to signal
1595 // to the HTTP response reading goroutine that the
1596 // connection is now closed. This eliminates a race
1597 // where the HTTP response reading goroutine would
1598 // otherwise not observe the EOF until its next read,
1599 // by which time a client goroutine might have already
1600 // tried to reuse the HTTP connection for a new
1601 // request.
1602 // See https://codereview.appspot.com/76400046
1603 // and http://golang.org/issue/3514
1604 if ri := c.rawInput; ri != nil &&
1605 n != 0 && err == nil &&
1606 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1607 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1608 err = recErr // will be io.EOF on closeNotify
1609 }
1610 }
1611
1612 if n != 0 || err != nil {
1613 return n, err
1614 }
1615 }
1616
1617 return 0, io.ErrNoProgress
1618}
1619
1620// Close closes the connection.
1621func (c *Conn) Close() error {
1622 var alertErr error
1623
1624 c.handshakeMutex.Lock()
1625 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001626 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
David Benjaminfa214e42016-05-10 17:03:10 -04001627 alert := alertCloseNotify
1628 if c.config.Bugs.SendAlertOnShutdown != 0 {
1629 alert = c.config.Bugs.SendAlertOnShutdown
1630 }
1631 alertErr = c.sendAlert(alert)
David Benjamin4d559612016-05-18 14:31:51 -04001632 // Clear local alerts when sending alerts so we continue to wait
1633 // for the peer rather than closing the socket early.
1634 if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1635 alertErr = nil
1636 }
Adam Langley95c29f32014-06-20 12:00:00 -07001637 }
1638
David Benjamin30789da2015-08-29 22:56:45 -04001639 // Consume a close_notify from the peer if one hasn't been received
1640 // already. This avoids the peer from failing |SSL_shutdown| due to a
1641 // write failing.
1642 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1643 for c.in.error() == nil {
1644 c.readRecord(recordTypeAlert)
1645 }
1646 if c.in.error() != io.EOF {
1647 alertErr = c.in.error()
1648 }
1649 }
1650
Adam Langley95c29f32014-06-20 12:00:00 -07001651 if err := c.conn.Close(); err != nil {
1652 return err
1653 }
1654 return alertErr
1655}
1656
1657// Handshake runs the client or server handshake
1658// protocol if it has not yet been run.
1659// Most uses of this package need not call Handshake
1660// explicitly: the first Read or Write will call it automatically.
1661func (c *Conn) Handshake() error {
1662 c.handshakeMutex.Lock()
1663 defer c.handshakeMutex.Unlock()
1664 if err := c.handshakeErr; err != nil {
1665 return err
1666 }
1667 if c.handshakeComplete {
1668 return nil
1669 }
1670
David Benjamin9a41d1b2015-05-16 01:30:09 -04001671 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1672 c.conn.Write([]byte{
1673 byte(recordTypeAlert), // type
1674 0xfe, 0xff, // version
1675 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1676 0x0, 0x2, // length
1677 })
1678 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1679 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001680 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1681 c.writeRecord(recordTypeApplicationData, data)
1682 }
Adam Langley95c29f32014-06-20 12:00:00 -07001683 if c.isClient {
1684 c.handshakeErr = c.clientHandshake()
1685 } else {
1686 c.handshakeErr = c.serverHandshake()
1687 }
David Benjaminddb9f152015-02-03 15:44:39 -05001688 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1689 c.writeRecord(recordType(42), []byte("invalid record"))
1690 }
Adam Langley95c29f32014-06-20 12:00:00 -07001691 return c.handshakeErr
1692}
1693
1694// ConnectionState returns basic TLS details about the connection.
1695func (c *Conn) ConnectionState() ConnectionState {
1696 c.handshakeMutex.Lock()
1697 defer c.handshakeMutex.Unlock()
1698
1699 var state ConnectionState
1700 state.HandshakeComplete = c.handshakeComplete
1701 if c.handshakeComplete {
1702 state.Version = c.vers
1703 state.NegotiatedProtocol = c.clientProtocol
1704 state.DidResume = c.didResume
1705 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001706 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001707 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001708 state.PeerCertificates = c.peerCertificates
1709 state.VerifiedChains = c.verifiedChains
1710 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001711 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001712 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001713 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001714 state.SCTList = c.sctList
Nick Harper60edffd2016-06-21 15:19:24 -07001715 state.PeerSignatureAlgorithm = c.peerSignatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -04001716 state.CurveID = c.curveID
Adam Langley95c29f32014-06-20 12:00:00 -07001717 }
1718
1719 return state
1720}
1721
1722// OCSPResponse returns the stapled OCSP response from the TLS server, if
1723// any. (Only valid for client connections.)
1724func (c *Conn) OCSPResponse() []byte {
1725 c.handshakeMutex.Lock()
1726 defer c.handshakeMutex.Unlock()
1727
1728 return c.ocspResponse
1729}
1730
1731// VerifyHostname checks that the peer certificate chain is valid for
1732// connecting to host. If so, it returns nil; if not, it returns an error
1733// describing the problem.
1734func (c *Conn) VerifyHostname(host string) error {
1735 c.handshakeMutex.Lock()
1736 defer c.handshakeMutex.Unlock()
1737 if !c.isClient {
1738 return errors.New("tls: VerifyHostname called on TLS server connection")
1739 }
1740 if !c.handshakeComplete {
1741 return errors.New("tls: handshake has not yet been performed")
1742 }
1743 return c.peerCertificates[0].VerifyHostname(host)
1744}
David Benjaminc565ebb2015-04-03 04:06:36 -04001745
1746// ExportKeyingMaterial exports keying material from the current connection
1747// state, as per RFC 5705.
1748func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1749 c.handshakeMutex.Lock()
1750 defer c.handshakeMutex.Unlock()
1751 if !c.handshakeComplete {
1752 return nil, errors.New("tls: handshake has not yet been performed")
1753 }
1754
David Benjamin8d315d72016-07-18 01:03:18 +02001755 if c.vers >= VersionTLS13 {
David Benjamin97a0a082016-07-13 17:57:35 -04001756 // TODO(davidben): What should we do with useContext? See
1757 // https://github.com/tlswg/tls13-spec/issues/546
1758 return hkdfExpandLabel(c.cipherSuite.hash(), c.exporterSecret, label, context, length), nil
1759 }
1760
David Benjaminc565ebb2015-04-03 04:06:36 -04001761 seedLen := len(c.clientRandom) + len(c.serverRandom)
1762 if useContext {
1763 seedLen += 2 + len(context)
1764 }
1765 seed := make([]byte, 0, seedLen)
1766 seed = append(seed, c.clientRandom[:]...)
1767 seed = append(seed, c.serverRandom[:]...)
1768 if useContext {
1769 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1770 seed = append(seed, context...)
1771 }
1772 result := make([]byte, length)
David Benjamin97a0a082016-07-13 17:57:35 -04001773 prfForVersion(c.vers, c.cipherSuite)(result, c.exporterSecret, label, seed)
David Benjaminc565ebb2015-04-03 04:06:36 -04001774 return result, nil
1775}
David Benjamin3e052de2015-11-25 20:10:31 -05001776
1777// noRenegotiationInfo returns true if the renegotiation info extension
1778// should be supported in the current handshake.
1779func (c *Conn) noRenegotiationInfo() bool {
1780 if c.config.Bugs.NoRenegotiationInfo {
1781 return true
1782 }
1783 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1784 return true
1785 }
1786 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1787 return true
1788 }
1789 return false
1790}
David Benjamin58104882016-07-18 01:25:41 +02001791
1792func (c *Conn) SendNewSessionTicket() error {
1793 if c.isClient || c.vers < VersionTLS13 {
1794 return errors.New("tls: cannot send post-handshake NewSessionTicket")
1795 }
1796
1797 var peerCertificatesRaw [][]byte
1798 for _, cert := range c.peerCertificates {
1799 peerCertificatesRaw = append(peerCertificatesRaw, cert.Raw)
1800 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001801
Steven Valdeza833c352016-11-01 13:39:36 -04001802 addBuffer := make([]byte, 4)
1803 _, err := io.ReadFull(c.config.rand(), addBuffer)
1804 if err != nil {
1805 c.sendAlert(alertInternalError)
1806 return errors.New("tls: short read from Rand: " + err.Error())
1807 }
1808 ticketAgeAdd := uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0])
1809
David Benjamin58104882016-07-18 01:25:41 +02001810 // TODO(davidben): Allow configuring these values.
1811 m := &newSessionTicketMsg{
David Benjamin9c33ae82017-01-08 06:04:43 -05001812 version: c.vers,
1813 ticketLifetime: uint32(24 * time.Hour / time.Second),
David Benjamin9c33ae82017-01-08 06:04:43 -05001814 duplicateEarlyDataInfo: c.config.Bugs.DuplicateTicketEarlyDataInfo,
1815 customExtension: c.config.Bugs.CustomTicketExtension,
1816 ticketAgeAdd: ticketAgeAdd,
Nick Harperab20cec2016-12-19 17:38:41 -08001817 maxEarlyDataSize: c.config.MaxEarlyDataSize,
David Benjamin58104882016-07-18 01:25:41 +02001818 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001819
David Benjamin17b30832017-01-28 14:00:32 -05001820 if c.config.Bugs.SendTicketLifetime != 0 {
1821 m.ticketLifetime = uint32(c.config.Bugs.SendTicketLifetime / time.Second)
1822 }
1823
Nick Harper0b3625b2016-07-25 16:16:28 -07001824 state := sessionState{
1825 vers: c.vers,
1826 cipherSuite: c.cipherSuite.id,
1827 masterSecret: c.resumptionSecret,
1828 certificates: peerCertificatesRaw,
1829 ticketCreationTime: c.config.time(),
1830 ticketExpiration: c.config.time().Add(time.Duration(m.ticketLifetime) * time.Second),
Steven Valdeza833c352016-11-01 13:39:36 -04001831 ticketAgeAdd: uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0]),
Steven Valdez2d850622017-01-11 11:34:52 -05001832 earlyALPN: []byte(c.clientProtocol),
Nick Harper0b3625b2016-07-25 16:16:28 -07001833 }
1834
David Benjamin58104882016-07-18 01:25:41 +02001835 if !c.config.Bugs.SendEmptySessionTicket {
1836 var err error
1837 m.ticket, err = c.encryptTicket(&state)
1838 if err != nil {
1839 return err
1840 }
1841 }
David Benjamin58104882016-07-18 01:25:41 +02001842 c.out.Lock()
1843 defer c.out.Unlock()
Steven Valdeza833c352016-11-01 13:39:36 -04001844 _, err = c.writeRecord(recordTypeHandshake, m.marshal())
David Benjamin58104882016-07-18 01:25:41 +02001845 return err
1846}
David Benjamin21c00282016-07-18 21:56:23 +02001847
Steven Valdezc4aa7272016-10-03 12:25:56 -04001848func (c *Conn) SendKeyUpdate(keyUpdateRequest byte) error {
David Benjamin21c00282016-07-18 21:56:23 +02001849 c.out.Lock()
1850 defer c.out.Unlock()
Steven Valdezc4aa7272016-10-03 12:25:56 -04001851 return c.sendKeyUpdateLocked(keyUpdateRequest)
David Benjamin21c00282016-07-18 21:56:23 +02001852}
1853
Steven Valdezc4aa7272016-10-03 12:25:56 -04001854func (c *Conn) sendKeyUpdateLocked(keyUpdateRequest byte) error {
David Benjamin7f0965a2016-09-30 15:14:01 -04001855 if c.vers < VersionTLS13 {
1856 return errors.New("tls: attempted to send KeyUpdate before TLS 1.3")
1857 }
1858
Steven Valdezc4aa7272016-10-03 12:25:56 -04001859 m := keyUpdateMsg{
1860 keyUpdateRequest: keyUpdateRequest,
1861 }
David Benjamin21c00282016-07-18 21:56:23 +02001862 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
1863 return err
1864 }
1865 if err := c.flushHandshake(); err != nil {
1866 return err
1867 }
Steven Valdez1dc53d22016-07-26 12:27:38 -04001868 c.out.doKeyUpdate(c, true)
David Benjamin21c00282016-07-18 21:56:23 +02001869 return nil
1870}
Steven Valdeza4ee74d2016-11-29 13:36:45 -05001871
1872func (c *Conn) sendFakeEarlyData(len int) error {
1873 // Assemble a fake early data record. This does not use writeRecord
1874 // because the record layer may be using different keys at this point.
1875 payload := make([]byte, 5+len)
1876 payload[0] = byte(recordTypeApplicationData)
1877 payload[1] = 3
1878 payload[2] = 1
1879 payload[3] = byte(len >> 8)
1880 payload[4] = byte(len)
1881 _, err := c.conn.Write(payload)
1882 return err
1883}