blob: c974bd4397d573e54a120fa56b9d430df06c1945 [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
Steven Valdezc94998a2017-06-20 10:55:02 -040038 wireVersion uint16 // TLS wire version
Adam Langley75712922014-10-10 16:23:43 -070039 vers uint16 // TLS version
40 haveVers bool // version has been negotiated
41 config *Config // configuration passed to constructor
42 handshakeComplete bool
Nick Harperab20cec2016-12-19 17:38:41 -080043 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 -070044 didResume bool // whether this connection was a session resumption
45 extendedMasterSecret bool // whether this session used an extended master secret
David Benjaminc565ebb2015-04-03 04:06:36 -040046 cipherSuite *cipherSuite
Adam Langley75712922014-10-10 16:23:43 -070047 ocspResponse []byte // stapled OCSP response
Paul Lietar4fac72e2015-09-09 13:44:55 +010048 sctList []byte // signed certificate timestamp list
Adam Langley75712922014-10-10 16:23:43 -070049 peerCertificates []*x509.Certificate
Adam Langley95c29f32014-06-20 12:00:00 -070050 // verifiedChains contains the certificate chains that we built, as
51 // opposed to the ones presented by the server.
52 verifiedChains [][]*x509.Certificate
53 // serverName contains the server name indicated by the client, if any.
Adam Langleyaf0e32c2015-06-03 09:57:23 -070054 serverName string
55 // firstFinished contains the first Finished hash sent during the
56 // handshake. This is the "tls-unique" channel binding value.
57 firstFinished [12]byte
Nick Harper60edffd2016-06-21 15:19:24 -070058 // peerSignatureAlgorithm contains the signature algorithm that was used
59 // by the peer in the handshake, or zero if not applicable.
60 peerSignatureAlgorithm signatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -040061 // curveID contains the curve that was used in the handshake, or zero if
62 // not applicable.
63 curveID CurveID
Adam Langleyaf0e32c2015-06-03 09:57:23 -070064
David Benjaminc565ebb2015-04-03 04:06:36 -040065 clientRandom, serverRandom [32]byte
David Benjamin97a0a082016-07-13 17:57:35 -040066 exporterSecret []byte
David Benjamin58104882016-07-18 01:25:41 +020067 resumptionSecret []byte
Adam Langley95c29f32014-06-20 12:00:00 -070068
69 clientProtocol string
70 clientProtocolFallback bool
David Benjaminfc7b0862014-09-06 13:21:53 -040071 usedALPN bool
Adam Langley95c29f32014-06-20 12:00:00 -070072
Adam Langley2ae77d22014-10-28 17:29:33 -070073 // verify_data values for the renegotiation extension.
74 clientVerify []byte
75 serverVerify []byte
76
David Benjamind30a9902014-08-24 01:44:23 -040077 channelID *ecdsa.PublicKey
78
David Benjaminca6c8262014-11-15 19:06:08 -050079 srtpProtectionProfile uint16
80
David Benjaminc44b1df2014-11-23 12:11:01 -050081 clientVersion uint16
82
Adam Langley95c29f32014-06-20 12:00:00 -070083 // input/output
84 in, out halfConn // in.Mutex < out.Mutex
85 rawInput *block // raw input, right off the wire
David Benjamin83c0bc92014-08-04 01:23:53 -040086 input *block // application record waiting to be read
87 hand bytes.Buffer // handshake record waiting to be read
88
David Benjamin582ba042016-07-07 12:33:25 -070089 // pendingFlight, if PackHandshakeFlight is enabled, is the buffer of
90 // handshake data to be split into records at the end of the flight.
91 pendingFlight bytes.Buffer
92
David Benjamin83c0bc92014-08-04 01:23:53 -040093 // DTLS state
94 sendHandshakeSeq uint16
95 recvHandshakeSeq uint16
David Benjaminb3774b92015-01-31 17:16:01 -050096 handMsg []byte // pending assembled handshake message
97 handMsgLen int // handshake message length, not including the header
98 pendingFragments [][]byte // pending outgoing handshake fragments.
Adam Langley95c29f32014-06-20 12:00:00 -070099
Steven Valdezc4aa7272016-10-03 12:25:56 -0400100 keyUpdateRequested bool
101
Adam Langley95c29f32014-06-20 12:00:00 -0700102 tmp [16]byte
103}
104
David Benjamin5e961c12014-11-07 01:48:35 -0500105func (c *Conn) init() {
106 c.in.isDTLS = c.isDTLS
107 c.out.isDTLS = c.isDTLS
108 c.in.config = c.config
109 c.out.config = c.config
David Benjamin8e6db492015-07-25 18:29:23 -0400110
111 c.out.updateOutSeq()
David Benjamin5e961c12014-11-07 01:48:35 -0500112}
113
Adam Langley95c29f32014-06-20 12:00:00 -0700114// Access to net.Conn methods.
115// Cannot just embed net.Conn because that would
116// export the struct field too.
117
118// LocalAddr returns the local network address.
119func (c *Conn) LocalAddr() net.Addr {
120 return c.conn.LocalAddr()
121}
122
123// RemoteAddr returns the remote network address.
124func (c *Conn) RemoteAddr() net.Addr {
125 return c.conn.RemoteAddr()
126}
127
128// SetDeadline sets the read and write deadlines associated with the connection.
129// A zero value for t means Read and Write will not time out.
130// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
131func (c *Conn) SetDeadline(t time.Time) error {
132 return c.conn.SetDeadline(t)
133}
134
135// SetReadDeadline sets the read deadline on the underlying connection.
136// A zero value for t means Read will not time out.
137func (c *Conn) SetReadDeadline(t time.Time) error {
138 return c.conn.SetReadDeadline(t)
139}
140
141// SetWriteDeadline sets the write deadline on the underlying conneciton.
142// A zero value for t means Write will not time out.
143// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
144func (c *Conn) SetWriteDeadline(t time.Time) error {
145 return c.conn.SetWriteDeadline(t)
146}
147
148// A halfConn represents one direction of the record layer
149// connection, either sending or receiving.
150type halfConn struct {
151 sync.Mutex
152
David Benjamin83c0bc92014-08-04 01:23:53 -0400153 err error // first permanent error
154 version uint16 // protocol version
155 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -0700156 cipher interface{} // cipher algorithm
157 mac macFunction
158 seq [8]byte // 64-bit sequence number
David Benjamin8e6db492015-07-25 18:29:23 -0400159 outSeq [8]byte // Mapped sequence number
Adam Langley95c29f32014-06-20 12:00:00 -0700160 bfree *block // list of free blocks
161
162 nextCipher interface{} // next encryption state
163 nextMac macFunction // next MAC algorithm
David Benjamin83f90402015-01-27 01:09:43 -0500164 nextSeq [6]byte // next epoch's starting sequence number in DTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700165
166 // used to save allocating a new buffer for each MAC.
167 inDigestBuf, outDigestBuf []byte
Adam Langley80842bd2014-06-20 12:00:00 -0700168
Steven Valdezc4aa7272016-10-03 12:25:56 -0400169 trafficSecret []byte
David Benjamin21c00282016-07-18 21:56:23 +0200170
Adam Langley80842bd2014-06-20 12:00:00 -0700171 config *Config
Adam Langley95c29f32014-06-20 12:00:00 -0700172}
173
174func (hc *halfConn) setErrorLocked(err error) error {
175 hc.err = err
176 return err
177}
178
179func (hc *halfConn) error() error {
Adam Langley2ae77d22014-10-28 17:29:33 -0700180 // This should be locked, but I've removed it for the renegotiation
181 // tests since we don't concurrently read and write the same tls.Conn
182 // in any case during testing.
Adam Langley95c29f32014-06-20 12:00:00 -0700183 err := hc.err
Adam Langley95c29f32014-06-20 12:00:00 -0700184 return err
185}
186
187// prepareCipherSpec sets the encryption and MAC states
188// that a subsequent changeCipherSpec will use.
189func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
190 hc.version = version
191 hc.nextCipher = cipher
192 hc.nextMac = mac
193}
194
195// changeCipherSpec changes the encryption and MAC states
196// to the ones previously passed to prepareCipherSpec.
Adam Langley80842bd2014-06-20 12:00:00 -0700197func (hc *halfConn) changeCipherSpec(config *Config) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700198 if hc.nextCipher == nil {
199 return alertInternalError
200 }
201 hc.cipher = hc.nextCipher
202 hc.mac = hc.nextMac
203 hc.nextCipher = nil
204 hc.nextMac = nil
Adam Langley80842bd2014-06-20 12:00:00 -0700205 hc.config = config
David Benjamin83c0bc92014-08-04 01:23:53 -0400206 hc.incEpoch()
David Benjaminf2b83632016-03-01 22:57:46 -0500207
208 if config.Bugs.NullAllCiphers {
David Benjamin7a4aaa42016-09-20 17:58:14 -0400209 hc.cipher = nullCipher{}
David Benjaminf2b83632016-03-01 22:57:46 -0500210 hc.mac = nil
211 }
Adam Langley95c29f32014-06-20 12:00:00 -0700212 return nil
213}
214
David Benjamin21c00282016-07-18 21:56:23 +0200215// useTrafficSecret sets the current cipher state for TLS 1.3.
Steven Valdeza833c352016-11-01 13:39:36 -0400216func (hc *halfConn) useTrafficSecret(version uint16, suite *cipherSuite, secret []byte, side trafficDirection) {
Nick Harperb41d2e42016-07-01 17:50:32 -0400217 hc.version = version
Steven Valdeza833c352016-11-01 13:39:36 -0400218 hc.cipher = deriveTrafficAEAD(version, suite, secret, side)
David Benjamin7a4aaa42016-09-20 17:58:14 -0400219 if hc.config.Bugs.NullAllCiphers {
220 hc.cipher = nullCipher{}
221 }
David Benjamin21c00282016-07-18 21:56:23 +0200222 hc.trafficSecret = secret
Nick Harperb41d2e42016-07-01 17:50:32 -0400223 hc.incEpoch()
224}
225
Nick Harperf2511f12016-12-06 16:02:31 -0800226// resetCipher changes the cipher state back to no encryption to be able
227// to send an unencrypted ClientHello in response to HelloRetryRequest
228// after 0-RTT data was rejected.
229func (hc *halfConn) resetCipher() {
230 hc.cipher = nil
231 hc.incEpoch()
232}
233
David Benjamin21c00282016-07-18 21:56:23 +0200234func (hc *halfConn) doKeyUpdate(c *Conn, isOutgoing bool) {
235 side := serverWrite
236 if c.isClient == isOutgoing {
237 side = clientWrite
238 }
Steven Valdeza833c352016-11-01 13:39:36 -0400239 hc.useTrafficSecret(hc.version, c.cipherSuite, updateTrafficSecret(c.cipherSuite.hash(), hc.trafficSecret), side)
David Benjamin21c00282016-07-18 21:56:23 +0200240}
241
Adam Langley95c29f32014-06-20 12:00:00 -0700242// incSeq increments the sequence number.
David Benjamin5e961c12014-11-07 01:48:35 -0500243func (hc *halfConn) incSeq(isOutgoing bool) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400244 limit := 0
David Benjamin5e961c12014-11-07 01:48:35 -0500245 increment := uint64(1)
David Benjamin83c0bc92014-08-04 01:23:53 -0400246 if hc.isDTLS {
247 // Increment up to the epoch in DTLS.
248 limit = 2
249 }
250 for i := 7; i >= limit; i-- {
David Benjamin5e961c12014-11-07 01:48:35 -0500251 increment += uint64(hc.seq[i])
252 hc.seq[i] = byte(increment)
253 increment >>= 8
Adam Langley95c29f32014-06-20 12:00:00 -0700254 }
255
256 // Not allowed to let sequence number wrap.
257 // Instead, must renegotiate before it does.
258 // Not likely enough to bother.
David Benjamin5e961c12014-11-07 01:48:35 -0500259 if increment != 0 {
260 panic("TLS: sequence number wraparound")
261 }
David Benjamin8e6db492015-07-25 18:29:23 -0400262
263 hc.updateOutSeq()
Adam Langley95c29f32014-06-20 12:00:00 -0700264}
265
David Benjamin83f90402015-01-27 01:09:43 -0500266// incNextSeq increments the starting sequence number for the next epoch.
267func (hc *halfConn) incNextSeq() {
268 for i := len(hc.nextSeq) - 1; i >= 0; i-- {
269 hc.nextSeq[i]++
270 if hc.nextSeq[i] != 0 {
271 return
272 }
273 }
274 panic("TLS: sequence number wraparound")
275}
276
277// incEpoch resets the sequence number. In DTLS, it also increments the epoch
278// half of the sequence number.
David Benjamin83c0bc92014-08-04 01:23:53 -0400279func (hc *halfConn) incEpoch() {
David Benjamin83c0bc92014-08-04 01:23:53 -0400280 if hc.isDTLS {
281 for i := 1; i >= 0; i-- {
282 hc.seq[i]++
283 if hc.seq[i] != 0 {
284 break
285 }
286 if i == 0 {
287 panic("TLS: epoch number wraparound")
288 }
289 }
David Benjamin83f90402015-01-27 01:09:43 -0500290 copy(hc.seq[2:], hc.nextSeq[:])
291 for i := range hc.nextSeq {
292 hc.nextSeq[i] = 0
293 }
294 } else {
295 for i := range hc.seq {
296 hc.seq[i] = 0
297 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400298 }
David Benjamin8e6db492015-07-25 18:29:23 -0400299
300 hc.updateOutSeq()
301}
302
303func (hc *halfConn) updateOutSeq() {
304 if hc.config.Bugs.SequenceNumberMapping != nil {
305 seqU64 := binary.BigEndian.Uint64(hc.seq[:])
306 seqU64 = hc.config.Bugs.SequenceNumberMapping(seqU64)
307 binary.BigEndian.PutUint64(hc.outSeq[:], seqU64)
308
309 // The DTLS epoch cannot be changed.
310 copy(hc.outSeq[:2], hc.seq[:2])
311 return
312 }
313
314 copy(hc.outSeq[:], hc.seq[:])
David Benjamin83c0bc92014-08-04 01:23:53 -0400315}
316
317func (hc *halfConn) recordHeaderLen() int {
318 if hc.isDTLS {
319 return dtlsRecordHeaderLen
320 }
321 return tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700322}
323
324// removePadding returns an unpadded slice, in constant time, which is a prefix
325// of the input. It also returns a byte which is equal to 255 if the padding
326// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
327func removePadding(payload []byte) ([]byte, byte) {
328 if len(payload) < 1 {
329 return payload, 0
330 }
331
332 paddingLen := payload[len(payload)-1]
333 t := uint(len(payload)-1) - uint(paddingLen)
334 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
335 good := byte(int32(^t) >> 31)
336
337 toCheck := 255 // the maximum possible padding length
338 // The length of the padded data is public, so we can use an if here
339 if toCheck+1 > len(payload) {
340 toCheck = len(payload) - 1
341 }
342
343 for i := 0; i < toCheck; i++ {
344 t := uint(paddingLen) - uint(i)
345 // if i <= paddingLen then the MSB of t is zero
346 mask := byte(int32(^t) >> 31)
347 b := payload[len(payload)-1-i]
348 good &^= mask&paddingLen ^ mask&b
349 }
350
351 // We AND together the bits of good and replicate the result across
352 // all the bits.
353 good &= good << 4
354 good &= good << 2
355 good &= good << 1
356 good = uint8(int8(good) >> 7)
357
358 toRemove := good&paddingLen + 1
359 return payload[:len(payload)-int(toRemove)], good
360}
361
362// removePaddingSSL30 is a replacement for removePadding in the case that the
363// protocol version is SSLv3. In this version, the contents of the padding
364// are random and cannot be checked.
365func removePaddingSSL30(payload []byte) ([]byte, byte) {
366 if len(payload) < 1 {
367 return payload, 0
368 }
369
370 paddingLen := int(payload[len(payload)-1]) + 1
371 if paddingLen > len(payload) {
372 return payload, 0
373 }
374
375 return payload[:len(payload)-paddingLen], 255
376}
377
378func roundUp(a, b int) int {
379 return a + (b-a%b)%b
380}
381
382// cbcMode is an interface for block ciphers using cipher block chaining.
383type cbcMode interface {
384 cipher.BlockMode
385 SetIV([]byte)
386}
387
388// decrypt checks and strips the mac and decrypts the data in b. Returns a
389// success boolean, the number of bytes to skip from the start of the record in
Nick Harper1fd39d82016-06-14 18:14:35 -0700390// order to get the application payload, the encrypted record type (or 0
391// if there is none), and an optional alert value.
392func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, contentType recordType, alertValue alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400393 recordHeaderLen := hc.recordHeaderLen()
394
Adam Langley95c29f32014-06-20 12:00:00 -0700395 // pull out payload
396 payload := b.data[recordHeaderLen:]
397
398 macSize := 0
399 if hc.mac != nil {
400 macSize = hc.mac.Size()
401 }
402
403 paddingGood := byte(255)
404 explicitIVLen := 0
405
David Benjamin83c0bc92014-08-04 01:23:53 -0400406 seq := hc.seq[:]
407 if hc.isDTLS {
408 // DTLS sequence numbers are explicit.
409 seq = b.data[3:11]
410 }
411
Adam Langley95c29f32014-06-20 12:00:00 -0700412 // decrypt
413 if hc.cipher != nil {
414 switch c := hc.cipher.(type) {
415 case cipher.Stream:
416 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400417 case *tlsAead:
418 nonce := seq
419 if c.explicitNonce {
420 explicitIVLen = 8
421 if len(payload) < explicitIVLen {
Nick Harper1fd39d82016-06-14 18:14:35 -0700422 return false, 0, 0, alertBadRecordMAC
David Benjamine9a80ff2015-04-07 00:46:46 -0400423 }
424 nonce = payload[:8]
425 payload = payload[8:]
Adam Langley95c29f32014-06-20 12:00:00 -0700426 }
Adam Langley95c29f32014-06-20 12:00:00 -0700427
Nick Harper1fd39d82016-06-14 18:14:35 -0700428 var additionalData []byte
429 if hc.version < VersionTLS13 {
430 additionalData = make([]byte, 13)
431 copy(additionalData, seq)
432 copy(additionalData[8:], b.data[:3])
433 n := len(payload) - c.Overhead()
434 additionalData[11] = byte(n >> 8)
435 additionalData[12] = byte(n)
436 }
Adam Langley95c29f32014-06-20 12:00:00 -0700437 var err error
Nick Harper1fd39d82016-06-14 18:14:35 -0700438 payload, err = c.Open(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700439 if err != nil {
Nick Harper1fd39d82016-06-14 18:14:35 -0700440 return false, 0, 0, alertBadRecordMAC
441 }
Adam Langley95c29f32014-06-20 12:00:00 -0700442 b.resize(recordHeaderLen + explicitIVLen + len(payload))
443 case cbcMode:
444 blockSize := c.BlockSize()
David Benjamin83c0bc92014-08-04 01:23:53 -0400445 if hc.version >= VersionTLS11 || hc.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700446 explicitIVLen = blockSize
447 }
448
449 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
Nick Harper1fd39d82016-06-14 18:14:35 -0700450 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700451 }
452
453 if explicitIVLen > 0 {
454 c.SetIV(payload[:explicitIVLen])
455 payload = payload[explicitIVLen:]
456 }
457 c.CryptBlocks(payload, payload)
458 if hc.version == VersionSSL30 {
459 payload, paddingGood = removePaddingSSL30(payload)
460 } else {
461 payload, paddingGood = removePadding(payload)
462 }
463 b.resize(recordHeaderLen + explicitIVLen + len(payload))
464
465 // note that we still have a timing side-channel in the
466 // MAC check, below. An attacker can align the record
467 // so that a correct padding will cause one less hash
468 // block to be calculated. Then they can iteratively
469 // decrypt a record by breaking each byte. See
470 // "Password Interception in a SSL/TLS Channel", Brice
471 // Canvel et al.
472 //
473 // However, our behavior matches OpenSSL, so we leak
474 // only as much as they do.
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700475 case nullCipher:
476 break
Adam Langley95c29f32014-06-20 12:00:00 -0700477 default:
478 panic("unknown cipher type")
479 }
David Benjamin7a4aaa42016-09-20 17:58:14 -0400480
481 if hc.version >= VersionTLS13 {
482 i := len(payload)
483 for i > 0 && payload[i-1] == 0 {
484 i--
485 }
486 payload = payload[:i]
487 if len(payload) == 0 {
488 return false, 0, 0, alertUnexpectedMessage
489 }
490 contentType = recordType(payload[len(payload)-1])
491 payload = payload[:len(payload)-1]
492 b.resize(recordHeaderLen + len(payload))
493 }
Adam Langley95c29f32014-06-20 12:00:00 -0700494 }
495
496 // check, strip mac
497 if hc.mac != nil {
498 if len(payload) < macSize {
Nick Harper1fd39d82016-06-14 18:14:35 -0700499 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700500 }
501
502 // strip mac off payload, b.data
503 n := len(payload) - macSize
David Benjamin83c0bc92014-08-04 01:23:53 -0400504 b.data[recordHeaderLen-2] = byte(n >> 8)
505 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700506 b.resize(recordHeaderLen + explicitIVLen + n)
507 remoteMAC := payload[n:]
David Benjamin83c0bc92014-08-04 01:23:53 -0400508 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
Adam Langley95c29f32014-06-20 12:00:00 -0700509
510 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
Nick Harper1fd39d82016-06-14 18:14:35 -0700511 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700512 }
513 hc.inDigestBuf = localMAC
514 }
David Benjamin5e961c12014-11-07 01:48:35 -0500515 hc.incSeq(false)
Adam Langley95c29f32014-06-20 12:00:00 -0700516
Nick Harper1fd39d82016-06-14 18:14:35 -0700517 return true, recordHeaderLen + explicitIVLen, contentType, 0
Adam Langley95c29f32014-06-20 12:00:00 -0700518}
519
520// padToBlockSize calculates the needed padding block, if any, for a payload.
521// On exit, prefix aliases payload and extends to the end of the last full
522// block of payload. finalBlock is a fresh slice which contains the contents of
523// any suffix of payload as well as the needed padding to make finalBlock a
524// full block.
Adam Langley80842bd2014-06-20 12:00:00 -0700525func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
Adam Langley95c29f32014-06-20 12:00:00 -0700526 overrun := len(payload) % blockSize
Adam Langley95c29f32014-06-20 12:00:00 -0700527 prefix = payload[:len(payload)-overrun]
Adam Langley80842bd2014-06-20 12:00:00 -0700528
529 paddingLen := blockSize - overrun
530 finalSize := blockSize
531 if config.Bugs.MaxPadding {
532 for paddingLen+blockSize <= 256 {
533 paddingLen += blockSize
534 }
535 finalSize = 256
536 }
537 finalBlock = make([]byte, finalSize)
538 for i := range finalBlock {
Adam Langley95c29f32014-06-20 12:00:00 -0700539 finalBlock[i] = byte(paddingLen - 1)
540 }
Adam Langley80842bd2014-06-20 12:00:00 -0700541 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
542 finalBlock[overrun] ^= 0xff
543 }
544 copy(finalBlock, payload[len(payload)-overrun:])
Adam Langley95c29f32014-06-20 12:00:00 -0700545 return
546}
547
548// encrypt encrypts and macs the data in b.
Nick Harper1fd39d82016-06-14 18:14:35 -0700549func (hc *halfConn) encrypt(b *block, explicitIVLen int, typ recordType) (bool, alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400550 recordHeaderLen := hc.recordHeaderLen()
551
Adam Langley95c29f32014-06-20 12:00:00 -0700552 // mac
553 if hc.mac != nil {
David Benjamin8e6db492015-07-25 18:29:23 -0400554 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 -0700555
556 n := len(b.data)
557 b.resize(n + len(mac))
558 copy(b.data[n:], mac)
559 hc.outDigestBuf = mac
560 }
561
562 payload := b.data[recordHeaderLen:]
563
564 // encrypt
565 if hc.cipher != nil {
David Benjamin7a4aaa42016-09-20 17:58:14 -0400566 // Add TLS 1.3 padding.
567 if hc.version >= VersionTLS13 {
568 paddingLen := hc.config.Bugs.RecordPadding
569 if hc.config.Bugs.OmitRecordContents {
570 b.resize(recordHeaderLen + paddingLen)
571 } else {
572 b.resize(len(b.data) + 1 + paddingLen)
573 b.data[len(b.data)-paddingLen-1] = byte(typ)
574 }
575 for i := 0; i < paddingLen; i++ {
576 b.data[len(b.data)-paddingLen+i] = 0
577 }
578 }
579
Adam Langley95c29f32014-06-20 12:00:00 -0700580 switch c := hc.cipher.(type) {
581 case cipher.Stream:
582 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400583 case *tlsAead:
Adam Langley95c29f32014-06-20 12:00:00 -0700584 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
David Benjamin7a4aaa42016-09-20 17:58:14 -0400585 b.resize(len(b.data) + c.Overhead())
David Benjamin8e6db492015-07-25 18:29:23 -0400586 nonce := hc.outSeq[:]
David Benjamine9a80ff2015-04-07 00:46:46 -0400587 if c.explicitNonce {
588 nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
589 }
Adam Langley95c29f32014-06-20 12:00:00 -0700590 payload := b.data[recordHeaderLen+explicitIVLen:]
591 payload = payload[:payloadLen]
592
Nick Harper1fd39d82016-06-14 18:14:35 -0700593 var additionalData []byte
594 if hc.version < VersionTLS13 {
595 additionalData = make([]byte, 13)
596 copy(additionalData, hc.outSeq[:])
597 copy(additionalData[8:], b.data[:3])
598 additionalData[11] = byte(payloadLen >> 8)
599 additionalData[12] = byte(payloadLen)
600 }
Adam Langley95c29f32014-06-20 12:00:00 -0700601
Nick Harper1fd39d82016-06-14 18:14:35 -0700602 c.Seal(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700603 case cbcMode:
604 blockSize := c.BlockSize()
605 if explicitIVLen > 0 {
606 c.SetIV(payload[:explicitIVLen])
607 payload = payload[explicitIVLen:]
608 }
Adam Langley80842bd2014-06-20 12:00:00 -0700609 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700610 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
611 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
612 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700613 case nullCipher:
614 break
Adam Langley95c29f32014-06-20 12:00:00 -0700615 default:
616 panic("unknown cipher type")
617 }
618 }
619
620 // update length to include MAC and any block padding needed.
621 n := len(b.data) - recordHeaderLen
David Benjamin83c0bc92014-08-04 01:23:53 -0400622 b.data[recordHeaderLen-2] = byte(n >> 8)
623 b.data[recordHeaderLen-1] = byte(n)
David Benjamin5e961c12014-11-07 01:48:35 -0500624 hc.incSeq(true)
Adam Langley95c29f32014-06-20 12:00:00 -0700625
626 return true, 0
627}
628
629// A block is a simple data buffer.
630type block struct {
631 data []byte
632 off int // index for Read
633 link *block
634}
635
636// resize resizes block to be n bytes, growing if necessary.
637func (b *block) resize(n int) {
638 if n > cap(b.data) {
639 b.reserve(n)
640 }
641 b.data = b.data[0:n]
642}
643
644// reserve makes sure that block contains a capacity of at least n bytes.
645func (b *block) reserve(n int) {
646 if cap(b.data) >= n {
647 return
648 }
649 m := cap(b.data)
650 if m == 0 {
651 m = 1024
652 }
653 for m < n {
654 m *= 2
655 }
656 data := make([]byte, len(b.data), m)
657 copy(data, b.data)
658 b.data = data
659}
660
661// readFromUntil reads from r into b until b contains at least n bytes
662// or else returns an error.
663func (b *block) readFromUntil(r io.Reader, n int) error {
664 // quick case
665 if len(b.data) >= n {
666 return nil
667 }
668
669 // read until have enough.
670 b.reserve(n)
671 for {
672 m, err := r.Read(b.data[len(b.data):cap(b.data)])
673 b.data = b.data[0 : len(b.data)+m]
674 if len(b.data) >= n {
675 // TODO(bradfitz,agl): slightly suspicious
676 // that we're throwing away r.Read's err here.
677 break
678 }
679 if err != nil {
680 return err
681 }
682 }
683 return nil
684}
685
686func (b *block) Read(p []byte) (n int, err error) {
687 n = copy(p, b.data[b.off:])
688 b.off += n
689 return
690}
691
692// newBlock allocates a new block, from hc's free list if possible.
693func (hc *halfConn) newBlock() *block {
694 b := hc.bfree
695 if b == nil {
696 return new(block)
697 }
698 hc.bfree = b.link
699 b.link = nil
700 b.resize(0)
701 return b
702}
703
704// freeBlock returns a block to hc's free list.
705// The protocol is such that each side only has a block or two on
706// its free list at a time, so there's no need to worry about
707// trimming the list, etc.
708func (hc *halfConn) freeBlock(b *block) {
709 b.link = hc.bfree
710 hc.bfree = b
711}
712
713// splitBlock splits a block after the first n bytes,
714// returning a block with those n bytes and a
715// block with the remainder. the latter may be nil.
716func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
717 if len(b.data) <= n {
718 return b, nil
719 }
720 bb := hc.newBlock()
721 bb.resize(len(b.data) - n)
722 copy(bb.data, b.data[n:])
723 b.data = b.data[0:n]
724 return b, bb
725}
726
David Benjamin83c0bc92014-08-04 01:23:53 -0400727func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
Nick Harper47383aa2016-11-30 12:50:43 -0800728RestartReadRecord:
David Benjamin83c0bc92014-08-04 01:23:53 -0400729 if c.isDTLS {
730 return c.dtlsDoReadRecord(want)
731 }
732
David Benjamin6f600d62016-12-21 16:06:54 -0500733 recordHeaderLen := c.in.recordHeaderLen()
David Benjamin83c0bc92014-08-04 01:23:53 -0400734
735 if c.rawInput == nil {
736 c.rawInput = c.in.newBlock()
737 }
738 b := c.rawInput
739
740 // Read header, payload.
741 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
742 // RFC suggests that EOF without an alertCloseNotify is
743 // an error, but popular web sites seem to do this,
David Benjamin30789da2015-08-29 22:56:45 -0400744 // so we can't make it an error, outside of tests.
745 if err == io.EOF && c.config.Bugs.ExpectCloseNotify {
746 err = io.ErrUnexpectedEOF
747 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400748 if e, ok := err.(net.Error); !ok || !e.Temporary() {
749 c.in.setErrorLocked(err)
750 }
751 return 0, nil, err
752 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400753
Steven Valdez924a3522017-03-02 16:05:03 -0500754 typ := recordType(b.data[0])
David Benjamin6f600d62016-12-21 16:06:54 -0500755
Steven Valdez924a3522017-03-02 16:05:03 -0500756 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
757 // start with a uint16 length where the MSB is set and the first record
758 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
759 // an SSLv2 client.
760 if want == recordTypeHandshake && typ == 0x80 {
761 c.sendAlert(alertProtocolVersion)
762 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
David Benjamin83c0bc92014-08-04 01:23:53 -0400763 }
764
Steven Valdezdbe01582017-07-14 10:39:28 -0400765 // Accept server_plaintext_handshake records when the content type TLS 1.3 variant is enabled.
766 if c.isClient && c.in.cipher == nil && c.config.TLS13Variant == TLS13RecordTypeExperiment && want == recordTypeHandshake && typ == recordTypePlaintextHandshake {
767 typ = recordTypeHandshake
768 }
769
Steven Valdez924a3522017-03-02 16:05:03 -0500770 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
771 n := int(b.data[3])<<8 | int(b.data[4])
772
David Benjaminbde00392016-06-21 12:19:28 -0400773 // Alerts sent near version negotiation do not have a well-defined
774 // record-layer version prior to TLS 1.3. (In TLS 1.3, the record-layer
775 // version is irrelevant.)
776 if typ != recordTypeAlert {
David Benjamine6f22212016-11-08 14:28:24 -0500777 var expect uint16
David Benjaminbde00392016-06-21 12:19:28 -0400778 if c.haveVers {
David Benjamine6f22212016-11-08 14:28:24 -0500779 expect = c.vers
780 if c.vers >= VersionTLS13 {
781 expect = VersionTLS10
David Benjaminbde00392016-06-21 12:19:28 -0400782 }
783 } else {
David Benjamine6f22212016-11-08 14:28:24 -0500784 expect = c.config.Bugs.ExpectInitialRecordVersion
785 }
786 if expect != 0 && vers != expect {
787 c.sendAlert(alertProtocolVersion)
788 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
David Benjamin1e29a6b2014-12-10 02:27:24 -0500789 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400790 }
791 if n > maxCiphertext {
792 c.sendAlert(alertRecordOverflow)
793 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
794 }
795 if !c.haveVers {
796 // First message, be extra suspicious:
797 // this might not be a TLS client.
798 // Bail out before reading a full 'body', if possible.
799 // The current max version is 3.1.
800 // If the version is >= 16.0, it's probably not real.
801 // Similarly, a clientHello message encodes in
802 // well under a kilobyte. If the length is >= 12 kB,
803 // it's probably not real.
804 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
805 c.sendAlert(alertUnexpectedMessage)
806 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
807 }
808 }
809 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
810 if err == io.EOF {
811 err = io.ErrUnexpectedEOF
812 }
813 if e, ok := err.(net.Error); !ok || !e.Temporary() {
814 c.in.setErrorLocked(err)
815 }
816 return 0, nil, err
817 }
818
819 // Process message.
820 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
David Benjaminff26f092016-07-01 16:13:42 -0400821 ok, off, encTyp, alertValue := c.in.decrypt(b)
Nick Harper47383aa2016-11-30 12:50:43 -0800822
823 // Handle skipping over early data.
824 if !ok && c.skipEarlyData {
825 goto RestartReadRecord
826 }
827
828 // If the server is expecting a second ClientHello (in response to
829 // a HelloRetryRequest) and the client sends early data, there
830 // won't be a decryption failure but it still needs to be skipped.
831 if c.in.cipher == nil && typ == recordTypeApplicationData && c.skipEarlyData {
832 goto RestartReadRecord
833 }
834
David Benjaminff26f092016-07-01 16:13:42 -0400835 if !ok {
836 return 0, nil, c.in.setErrorLocked(c.sendAlert(alertValue))
837 }
838 b.off = off
Nick Harper47383aa2016-11-30 12:50:43 -0800839 c.skipEarlyData = false
David Benjaminff26f092016-07-01 16:13:42 -0400840
Nick Harper1fd39d82016-06-14 18:14:35 -0700841 if c.vers >= VersionTLS13 && c.in.cipher != nil {
David Benjaminc9ae27c2016-06-24 22:56:37 -0400842 if typ != recordTypeApplicationData {
843 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: outer record type is not application data"))
844 }
Nick Harper1fd39d82016-06-14 18:14:35 -0700845 typ = encTyp
846 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400847 return typ, b, nil
848}
849
Adam Langley95c29f32014-06-20 12:00:00 -0700850// readRecord reads the next TLS record from the connection
851// and updates the record layer state.
852// c.in.Mutex <= L; c.input == nil.
853func (c *Conn) readRecord(want recordType) error {
854 // Caller must be in sync with connection:
855 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700856 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700857 switch want {
858 default:
859 c.sendAlert(alertInternalError)
860 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
David Benjaminbbba9392017-04-06 12:54:12 -0400861 case recordTypeChangeCipherSpec:
Adam Langley95c29f32014-06-20 12:00:00 -0700862 if c.handshakeComplete {
863 c.sendAlert(alertInternalError)
David Benjaminbbba9392017-04-06 12:54:12 -0400864 return c.in.setErrorLocked(errors.New("tls: ChangeCipherSpec requested after handshake complete"))
Adam Langley95c29f32014-06-20 12:00:00 -0700865 }
Steven Valdeze831a812017-03-09 14:56:07 -0500866 case recordTypeApplicationData, recordTypeAlert, recordTypeHandshake:
867 break
Adam Langley95c29f32014-06-20 12:00:00 -0700868 }
869
870Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400871 typ, b, err := c.doReadRecord(want)
872 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700873 return err
874 }
Adam Langley95c29f32014-06-20 12:00:00 -0700875 data := b.data[b.off:]
David Benjamine3fbb362017-01-06 16:19:28 -0500876 max := maxPlaintext
877 if c.config.Bugs.MaxReceivePlaintext != 0 {
878 max = c.config.Bugs.MaxReceivePlaintext
879 }
880 if len(data) > max {
Adam Langley95c29f32014-06-20 12:00:00 -0700881 err := c.sendAlert(alertRecordOverflow)
882 c.in.freeBlock(b)
883 return c.in.setErrorLocked(err)
884 }
885
886 switch typ {
887 default:
888 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
889
890 case recordTypeAlert:
891 if len(data) != 2 {
892 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
893 break
894 }
895 if alert(data[1]) == alertCloseNotify {
896 c.in.setErrorLocked(io.EOF)
897 break
898 }
899 switch data[0] {
900 case alertLevelWarning:
David Benjamin053fee92017-01-02 08:30:36 -0500901 if alert(data[1]) == alertNoCertificate {
902 c.in.freeBlock(b)
903 return errNoCertificateAlert
904 }
Nick Harperab20cec2016-12-19 17:38:41 -0800905 if alert(data[1]) == alertEndOfEarlyData {
906 c.in.freeBlock(b)
907 return errEndOfEarlyDataAlert
908 }
David Benjamin053fee92017-01-02 08:30:36 -0500909
Adam Langley95c29f32014-06-20 12:00:00 -0700910 // drop on the floor
911 c.in.freeBlock(b)
912 goto Again
913 case alertLevelError:
914 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
915 default:
916 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
917 }
918
919 case recordTypeChangeCipherSpec:
920 if typ != want || len(data) != 1 || data[0] != 1 {
921 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
922 break
923 }
Steven Valdez520e1222017-06-13 12:45:25 -0400924 if c.wireVersion != tls13ExperimentVersion {
925 err := c.in.changeCipherSpec(c.config)
926 if err != nil {
927 c.in.setErrorLocked(c.sendAlert(err.(alert)))
928 }
Adam Langley95c29f32014-06-20 12:00:00 -0700929 }
930
931 case recordTypeApplicationData:
932 if typ != want {
933 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
934 break
935 }
936 c.input = b
937 b = nil
938
939 case recordTypeHandshake:
David Benjamind5a4ecb2016-07-18 01:17:13 +0200940 // Allow handshake data while reading application data to
941 // trigger post-handshake messages.
Adam Langley95c29f32014-06-20 12:00:00 -0700942 // TODO(rsc): Should at least pick off connection close.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200943 if typ != want && want != recordTypeApplicationData {
944 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
Adam Langley95c29f32014-06-20 12:00:00 -0700945 }
946 c.hand.Write(data)
947 }
948
949 if b != nil {
950 c.in.freeBlock(b)
951 }
952 return c.in.err
953}
954
955// sendAlert sends a TLS alert message.
956// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400957func (c *Conn) sendAlertLocked(level byte, err alert) error {
958 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700959 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400960 if c.config.Bugs.FragmentAlert {
961 c.writeRecord(recordTypeAlert, c.tmp[0:1])
962 c.writeRecord(recordTypeAlert, c.tmp[1:2])
David Benjamin0d3a8c62016-03-11 22:25:18 -0500963 } else if c.config.Bugs.DoubleAlert {
964 copy(c.tmp[2:4], c.tmp[0:2])
965 c.writeRecord(recordTypeAlert, c.tmp[0:4])
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400966 } else {
967 c.writeRecord(recordTypeAlert, c.tmp[0:2])
968 }
David Benjamin24f346d2015-06-06 03:28:08 -0400969 // Error alerts are fatal to the connection.
970 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700971 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
972 }
973 return nil
974}
975
976// sendAlert sends a TLS alert message.
977// L < c.out.Mutex.
978func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400979 level := byte(alertLevelError)
Nick Harperf2511f12016-12-06 16:02:31 -0800980 if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertificate || err == alertEndOfEarlyData {
David Benjamin24f346d2015-06-06 03:28:08 -0400981 level = alertLevelWarning
982 }
983 return c.SendAlert(level, err)
984}
985
986func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700987 c.out.Lock()
988 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -0400989 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -0700990}
991
David Benjamind86c7672014-08-02 04:07:12 -0400992// writeV2Record writes a record for a V2ClientHello.
993func (c *Conn) writeV2Record(data []byte) (n int, err error) {
994 record := make([]byte, 2+len(data))
995 record[0] = uint8(len(data)>>8) | 0x80
996 record[1] = uint8(len(data))
997 copy(record[2:], data)
998 return c.conn.Write(record)
999}
1000
Adam Langley95c29f32014-06-20 12:00:00 -07001001// writeRecord writes a TLS record with the given type and payload
1002// to the connection and updates the record layer state.
1003// c.out.Mutex <= L.
1004func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjaminebacdee2017-04-08 11:00:45 -04001005 if typ == recordTypeHandshake {
1006 msgType := data[0]
1007 if c.config.Bugs.SendWrongMessageType != 0 && msgType == c.config.Bugs.SendWrongMessageType {
1008 msgType += 42
1009 } else if msgType == typeServerHello && c.config.Bugs.SendServerHelloAsHelloRetryRequest {
1010 msgType = typeHelloRetryRequest
1011 }
1012 if msgType != data[0] {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001013 newData := make([]byte, len(data))
1014 copy(newData, data)
David Benjaminebacdee2017-04-08 11:00:45 -04001015 newData[0] = msgType
David Benjamin0b8d5da2016-07-15 00:39:56 -04001016 data = newData
1017 }
1018 }
1019
David Benjamin639846e2016-09-09 11:41:18 -04001020 if msgType := c.config.Bugs.SendTrailingMessageData; msgType != 0 {
1021 if typ == recordTypeHandshake && data[0] == msgType {
1022 newData := make([]byte, len(data))
1023 copy(newData, data)
1024
1025 // Add a 0 to the body.
1026 newData = append(newData, 0)
1027 // Fix the header.
1028 newLen := len(newData) - 4
1029 newData[1] = byte(newLen >> 16)
1030 newData[2] = byte(newLen >> 8)
1031 newData[3] = byte(newLen)
1032
1033 data = newData
1034 }
1035 }
1036
David Benjamin83c0bc92014-08-04 01:23:53 -04001037 if c.isDTLS {
1038 return c.dtlsWriteRecord(typ, data)
1039 }
1040
David Benjamin71dd6662016-07-08 14:10:48 -07001041 if typ == recordTypeHandshake {
1042 if c.config.Bugs.SendHelloRequestBeforeEveryHandshakeMessage {
1043 newData := make([]byte, 0, 4+len(data))
1044 newData = append(newData, typeHelloRequest, 0, 0, 0)
1045 newData = append(newData, data...)
1046 data = newData
1047 }
1048
1049 if c.config.Bugs.PackHandshakeFlight {
1050 c.pendingFlight.Write(data)
1051 return len(data), nil
1052 }
David Benjamin582ba042016-07-07 12:33:25 -07001053 }
1054
1055 return c.doWriteRecord(typ, data)
1056}
1057
1058func (c *Conn) doWriteRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin6f600d62016-12-21 16:06:54 -05001059 recordHeaderLen := c.out.recordHeaderLen()
Adam Langley95c29f32014-06-20 12:00:00 -07001060 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -04001061 first := true
1062 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -04001063 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -07001064 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -04001065 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -07001066 m = maxPlaintext
1067 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001068 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
1069 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -04001070 // By default, do not fragment the client_version or
1071 // server_version, which are located in the first 6
1072 // bytes.
1073 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
1074 m = 6
1075 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001076 }
Adam Langley95c29f32014-06-20 12:00:00 -07001077 explicitIVLen := 0
1078 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -04001079 first = false
Adam Langley95c29f32014-06-20 12:00:00 -07001080
1081 var cbc cbcMode
1082 if c.out.version >= VersionTLS11 {
1083 var ok bool
1084 if cbc, ok = c.out.cipher.(cbcMode); ok {
1085 explicitIVLen = cbc.BlockSize()
1086 }
1087 }
1088 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -04001089 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -07001090 explicitIVLen = 8
1091 // The AES-GCM construction in TLS has an
1092 // explicit nonce so that the nonce can be
1093 // random. However, the nonce is only 8 bytes
1094 // which is too small for a secure, random
1095 // nonce. Therefore we use the sequence number
1096 // as the nonce.
1097 explicitIVIsSeq = true
1098 }
1099 }
1100 b.resize(recordHeaderLen + explicitIVLen + m)
Steven Valdez924a3522017-03-02 16:05:03 -05001101 b.data[0] = byte(typ)
1102 if c.vers >= VersionTLS13 && c.out.cipher != nil {
1103 b.data[0] = byte(recordTypeApplicationData)
1104 if outerType := c.config.Bugs.OuterRecordType; outerType != 0 {
1105 b.data[0] = byte(outerType)
David Benjaminc9ae27c2016-06-24 22:56:37 -04001106 }
Nick Harper1fd39d82016-06-14 18:14:35 -07001107 }
Steven Valdez924a3522017-03-02 16:05:03 -05001108 vers := c.vers
1109 if vers == 0 || vers >= VersionTLS13 {
1110 // Some TLS servers fail if the record version is
1111 // greater than TLS 1.0 for the initial ClientHello.
1112 //
1113 // TLS 1.3 fixes the version number in the record
1114 // layer to {3, 1}.
1115 vers = VersionTLS10
1116 }
1117 if c.config.Bugs.SendRecordVersion != 0 {
1118 vers = c.config.Bugs.SendRecordVersion
1119 }
1120 if c.vers == 0 && c.config.Bugs.SendInitialRecordVersion != 0 {
1121 vers = c.config.Bugs.SendInitialRecordVersion
1122 }
1123 b.data[1] = byte(vers >> 8)
1124 b.data[2] = byte(vers)
1125 b.data[3] = byte(m >> 8)
1126 b.data[4] = byte(m)
Adam Langley95c29f32014-06-20 12:00:00 -07001127 if explicitIVLen > 0 {
1128 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
1129 if explicitIVIsSeq {
1130 copy(explicitIV, c.out.seq[:])
1131 } else {
1132 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
1133 break
1134 }
1135 }
1136 }
1137 copy(b.data[recordHeaderLen+explicitIVLen:], data)
Nick Harper1fd39d82016-06-14 18:14:35 -07001138 c.out.encrypt(b, explicitIVLen, typ)
Adam Langley95c29f32014-06-20 12:00:00 -07001139 _, err = c.conn.Write(b.data)
1140 if err != nil {
1141 break
1142 }
1143 n += m
1144 data = data[m:]
1145 }
1146 c.out.freeBlock(b)
1147
Steven Valdez520e1222017-06-13 12:45:25 -04001148 if typ == recordTypeChangeCipherSpec && c.wireVersion != tls13ExperimentVersion {
Adam Langley80842bd2014-06-20 12:00:00 -07001149 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -07001150 if err != nil {
David Benjamina8181342017-07-07 18:10:57 -04001151 return n, c.sendAlertLocked(alertLevelError, err.(alert))
Adam Langley95c29f32014-06-20 12:00:00 -07001152 }
1153 }
1154 return
1155}
1156
David Benjamin582ba042016-07-07 12:33:25 -07001157func (c *Conn) flushHandshake() error {
1158 if c.isDTLS {
1159 return c.dtlsFlushHandshake()
1160 }
1161
1162 for c.pendingFlight.Len() > 0 {
1163 var buf [maxPlaintext]byte
1164 n, _ := c.pendingFlight.Read(buf[:])
1165 if _, err := c.doWriteRecord(recordTypeHandshake, buf[:n]); err != nil {
1166 return err
1167 }
1168 }
1169
1170 c.pendingFlight.Reset()
1171 return nil
1172}
1173
David Benjamin83c0bc92014-08-04 01:23:53 -04001174func (c *Conn) doReadHandshake() ([]byte, error) {
1175 if c.isDTLS {
1176 return c.dtlsDoReadHandshake()
1177 }
1178
Adam Langley95c29f32014-06-20 12:00:00 -07001179 for c.hand.Len() < 4 {
1180 if err := c.in.err; err != nil {
1181 return nil, err
1182 }
1183 if err := c.readRecord(recordTypeHandshake); err != nil {
1184 return nil, err
1185 }
1186 }
1187
1188 data := c.hand.Bytes()
1189 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1190 if n > maxHandshake {
1191 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
1192 }
1193 for c.hand.Len() < 4+n {
1194 if err := c.in.err; err != nil {
1195 return nil, err
1196 }
1197 if err := c.readRecord(recordTypeHandshake); err != nil {
1198 return nil, err
1199 }
1200 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001201 return c.hand.Next(4 + n), nil
1202}
1203
1204// readHandshake reads the next handshake message from
1205// the record layer.
1206// c.in.Mutex < L; c.out.Mutex < L.
1207func (c *Conn) readHandshake() (interface{}, error) {
1208 data, err := c.doReadHandshake()
David Benjamin053fee92017-01-02 08:30:36 -05001209 if err == errNoCertificateAlert {
1210 if c.hand.Len() != 0 {
1211 // The warning alert may not interleave with a handshake message.
1212 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1213 }
1214 return new(ssl3NoCertificateMsg), nil
1215 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001216 if err != nil {
1217 return nil, err
1218 }
1219
Adam Langley95c29f32014-06-20 12:00:00 -07001220 var m handshakeMessage
1221 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001222 case typeHelloRequest:
1223 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001224 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001225 m = &clientHelloMsg{
1226 isDTLS: c.isDTLS,
1227 }
Adam Langley95c29f32014-06-20 12:00:00 -07001228 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001229 m = &serverHelloMsg{
1230 isDTLS: c.isDTLS,
1231 }
Nick Harperdcfbc672016-07-16 17:47:31 +02001232 case typeHelloRetryRequest:
1233 m = new(helloRetryRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001234 case typeNewSessionTicket:
David Benjamin58104882016-07-18 01:25:41 +02001235 m = &newSessionTicketMsg{
1236 version: c.vers,
1237 }
Nick Harperb41d2e42016-07-01 17:50:32 -04001238 case typeEncryptedExtensions:
1239 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001240 case typeCertificate:
Nick Harperb41d2e42016-07-01 17:50:32 -04001241 m = &certificateMsg{
David Benjamin8d315d72016-07-18 01:03:18 +02001242 hasRequestContext: c.vers >= VersionTLS13,
Nick Harperb41d2e42016-07-01 17:50:32 -04001243 }
Adam Langley95c29f32014-06-20 12:00:00 -07001244 case typeCertificateRequest:
1245 m = &certificateRequestMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001246 hasSignatureAlgorithm: c.vers >= VersionTLS12,
David Benjamin8d315d72016-07-18 01:03:18 +02001247 hasRequestContext: c.vers >= VersionTLS13,
Adam Langley95c29f32014-06-20 12:00:00 -07001248 }
1249 case typeCertificateStatus:
1250 m = new(certificateStatusMsg)
1251 case typeServerKeyExchange:
1252 m = new(serverKeyExchangeMsg)
1253 case typeServerHelloDone:
1254 m = new(serverHelloDoneMsg)
1255 case typeClientKeyExchange:
1256 m = new(clientKeyExchangeMsg)
1257 case typeCertificateVerify:
1258 m = &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001259 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001260 }
1261 case typeNextProtocol:
1262 m = new(nextProtoMsg)
1263 case typeFinished:
1264 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001265 case typeHelloVerifyRequest:
1266 m = new(helloVerifyRequestMsg)
David Benjamin24599a82016-06-30 18:56:53 -04001267 case typeChannelID:
1268 m = new(channelIDMsg)
David Benjamin21c00282016-07-18 21:56:23 +02001269 case typeKeyUpdate:
1270 m = new(keyUpdateMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001271 default:
1272 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1273 }
1274
1275 // The handshake message unmarshallers
1276 // expect to be able to keep references to data,
1277 // so pass in a fresh copy that won't be overwritten.
1278 data = append([]byte(nil), data...)
1279
1280 if !m.unmarshal(data) {
1281 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1282 }
1283 return m, nil
1284}
1285
David Benjamin83f90402015-01-27 01:09:43 -05001286// skipPacket processes all the DTLS records in packet. It updates
1287// sequence number expectations but otherwise ignores them.
1288func (c *Conn) skipPacket(packet []byte) error {
1289 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001290 if len(packet) < 13 {
1291 return errors.New("tls: bad packet")
1292 }
David Benjamin83f90402015-01-27 01:09:43 -05001293 // Dropped packets are completely ignored save to update
1294 // expected sequence numbers for this and the next epoch. (We
1295 // don't assert on the contents of the packets both for
1296 // simplicity and because a previous test with one shorter
1297 // timeout schedule would have done so.)
1298 epoch := packet[3:5]
1299 seq := packet[5:11]
1300 length := uint16(packet[11])<<8 | uint16(packet[12])
1301 if bytes.Equal(c.in.seq[:2], epoch) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001302 if bytes.Compare(seq, c.in.seq[2:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001303 return errors.New("tls: sequence mismatch")
1304 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001305 copy(c.in.seq[2:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001306 c.in.incSeq(false)
1307 } else {
David Benjamin13e81fc2015-11-02 17:16:13 -05001308 if bytes.Compare(seq, c.in.nextSeq[:]) < 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.nextSeq[:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001312 c.in.incNextSeq()
1313 }
David Benjamin6ca93552015-08-28 16:16:25 -04001314 if len(packet) < 13+int(length) {
1315 return errors.New("tls: bad packet")
1316 }
David Benjamin83f90402015-01-27 01:09:43 -05001317 packet = packet[13+length:]
1318 }
1319 return nil
1320}
1321
1322// simulatePacketLoss simulates the loss of a handshake leg from the
1323// peer based on the schedule in c.config.Bugs. If resendFunc is
1324// non-nil, it is called after each simulated timeout to retransmit
1325// handshake messages from the local end. This is used in cases where
1326// the peer retransmits on a stale Finished rather than a timeout.
1327func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1328 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1329 return nil
1330 }
1331 if !c.isDTLS {
1332 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1333 }
1334 if c.config.Bugs.PacketAdaptor == nil {
1335 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1336 }
1337 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1338 // Simulate a timeout.
1339 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1340 if err != nil {
1341 return err
1342 }
1343 for _, packet := range packets {
1344 if err := c.skipPacket(packet); err != nil {
1345 return err
1346 }
1347 }
1348 if resendFunc != nil {
1349 resendFunc()
1350 }
1351 }
1352 return nil
1353}
1354
David Benjamin47921102016-07-28 11:29:18 -04001355func (c *Conn) SendHalfHelloRequest() error {
1356 if err := c.Handshake(); err != nil {
1357 return err
1358 }
1359
1360 c.out.Lock()
1361 defer c.out.Unlock()
1362
1363 if _, err := c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0}); err != nil {
1364 return err
1365 }
1366 return c.flushHandshake()
1367}
1368
Adam Langley95c29f32014-06-20 12:00:00 -07001369// Write writes data to the connection.
1370func (c *Conn) Write(b []byte) (int, error) {
1371 if err := c.Handshake(); err != nil {
1372 return 0, err
1373 }
1374
1375 c.out.Lock()
1376 defer c.out.Unlock()
1377
David Benjamin12d2c482016-07-24 10:56:51 -04001378 // Flush any pending handshake data. PackHelloRequestWithFinished may
1379 // have been set and the handshake not followed by Renegotiate.
1380 c.flushHandshake()
1381
Adam Langley95c29f32014-06-20 12:00:00 -07001382 if err := c.out.err; err != nil {
1383 return 0, err
1384 }
1385
1386 if !c.handshakeComplete {
1387 return 0, alertInternalError
1388 }
1389
Steven Valdezc4aa7272016-10-03 12:25:56 -04001390 if c.keyUpdateRequested {
1391 if err := c.sendKeyUpdateLocked(keyUpdateNotRequested); err != nil {
David Benjamin21c00282016-07-18 21:56:23 +02001392 return 0, err
1393 }
Steven Valdezc4aa7272016-10-03 12:25:56 -04001394 c.keyUpdateRequested = false
David Benjamin21c00282016-07-18 21:56:23 +02001395 }
1396
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001397 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001398 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001399 }
1400
Adam Langley27a0d082015-11-03 13:34:10 -08001401 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1402 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
David Benjamin582ba042016-07-07 12:33:25 -07001403 c.flushHandshake()
Adam Langley27a0d082015-11-03 13:34:10 -08001404 }
1405
Adam Langley95c29f32014-06-20 12:00:00 -07001406 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1407 // attack when using block mode ciphers due to predictable IVs.
1408 // This can be prevented by splitting each Application Data
1409 // record into two records, effectively randomizing the IV.
1410 //
1411 // http://www.openssl.org/~bodo/tls-cbc.txt
1412 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1413 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1414
1415 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001416 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001417 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1418 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1419 if err != nil {
1420 return n, c.out.setErrorLocked(err)
1421 }
1422 m, b = 1, b[1:]
1423 }
1424 }
1425
1426 n, err := c.writeRecord(recordTypeApplicationData, b)
1427 return n + m, c.out.setErrorLocked(err)
1428}
1429
David Benjamin794cc592017-03-25 22:24:23 -05001430func (c *Conn) processTLS13NewSessionTicket(newSessionTicket *newSessionTicketMsg, cipherSuite *cipherSuite) error {
1431 if c.config.Bugs.ExpectGREASE && !newSessionTicket.hasGREASEExtension {
1432 return errors.New("tls: no GREASE ticket extension found")
1433 }
1434
1435 if c.config.Bugs.ExpectTicketEarlyDataInfo && newSessionTicket.maxEarlyDataSize == 0 {
1436 return errors.New("tls: no ticket_early_data_info extension found")
1437 }
1438
1439 if c.config.Bugs.ExpectNoNewSessionTicket {
1440 return errors.New("tls: received unexpected NewSessionTicket")
1441 }
1442
1443 if c.config.ClientSessionCache == nil || newSessionTicket.ticketLifetime == 0 {
1444 return nil
1445 }
1446
1447 session := &ClientSessionState{
1448 sessionTicket: newSessionTicket.ticket,
1449 vers: c.vers,
1450 cipherSuite: cipherSuite.id,
1451 masterSecret: c.resumptionSecret,
1452 serverCertificates: c.peerCertificates,
1453 sctList: c.sctList,
1454 ocspResponse: c.ocspResponse,
1455 ticketCreationTime: c.config.time(),
1456 ticketExpiration: c.config.time().Add(time.Duration(newSessionTicket.ticketLifetime) * time.Second),
1457 ticketAgeAdd: newSessionTicket.ticketAgeAdd,
1458 maxEarlyDataSize: newSessionTicket.maxEarlyDataSize,
1459 earlyALPN: c.clientProtocol,
1460 }
1461
1462 cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
1463 c.config.ClientSessionCache.Put(cacheKey, session)
1464 return nil
1465}
1466
David Benjamind5a4ecb2016-07-18 01:17:13 +02001467func (c *Conn) handlePostHandshakeMessage() error {
Adam Langley2ae77d22014-10-28 17:29:33 -07001468 msg, err := c.readHandshake()
1469 if err != nil {
1470 return err
1471 }
David Benjamind5a4ecb2016-07-18 01:17:13 +02001472
1473 if c.vers < VersionTLS13 {
1474 if !c.isClient {
1475 c.sendAlert(alertUnexpectedMessage)
1476 return errors.New("tls: unexpected post-handshake message")
1477 }
1478
1479 _, ok := msg.(*helloRequestMsg)
1480 if !ok {
1481 c.sendAlert(alertUnexpectedMessage)
1482 return alertUnexpectedMessage
1483 }
1484
1485 c.handshakeComplete = false
1486 return c.Handshake()
Adam Langley2ae77d22014-10-28 17:29:33 -07001487 }
1488
David Benjamind5a4ecb2016-07-18 01:17:13 +02001489 if c.isClient {
1490 if newSessionTicket, ok := msg.(*newSessionTicketMsg); ok {
David Benjamin794cc592017-03-25 22:24:23 -05001491 return c.processTLS13NewSessionTicket(newSessionTicket, c.cipherSuite)
David Benjamind5a4ecb2016-07-18 01:17:13 +02001492 }
1493 }
1494
Steven Valdezc4aa7272016-10-03 12:25:56 -04001495 if keyUpdate, ok := msg.(*keyUpdateMsg); ok {
David Benjaminbbba9392017-04-06 12:54:12 -04001496 if c.config.Bugs.RejectUnsolicitedKeyUpdate {
1497 return errors.New("tls: unexpected KeyUpdate message")
1498 }
Steven Valdez1dc53d22016-07-26 12:27:38 -04001499 c.in.doKeyUpdate(c, false)
Steven Valdezc4aa7272016-10-03 12:25:56 -04001500 if keyUpdate.keyUpdateRequest == keyUpdateRequested {
1501 c.keyUpdateRequested = true
1502 }
David Benjamin21c00282016-07-18 21:56:23 +02001503 return nil
1504 }
1505
David Benjamind5a4ecb2016-07-18 01:17:13 +02001506 c.sendAlert(alertUnexpectedMessage)
David Benjaminbbba9392017-04-06 12:54:12 -04001507 return errors.New("tls: unexpected post-handshake message")
1508}
1509
1510// Reads a KeyUpdate acknowledgment from the peer. There may not be any
1511// application data records before the message.
1512func (c *Conn) ReadKeyUpdateACK() error {
1513 c.in.Lock()
1514 defer c.in.Unlock()
1515
1516 msg, err := c.readHandshake()
1517 if err != nil {
1518 return err
1519 }
1520
1521 keyUpdate, ok := msg.(*keyUpdateMsg)
1522 if !ok {
1523 c.sendAlert(alertUnexpectedMessage)
1524 return errors.New("tls: unexpected message when reading KeyUpdate")
1525 }
1526
1527 if keyUpdate.keyUpdateRequest != keyUpdateNotRequested {
1528 return errors.New("tls: received invalid KeyUpdate message")
1529 }
1530
1531 c.in.doKeyUpdate(c, false)
1532 return nil
Adam Langley2ae77d22014-10-28 17:29:33 -07001533}
1534
Adam Langleycf2d4f42014-10-28 19:06:14 -07001535func (c *Conn) Renegotiate() error {
1536 if !c.isClient {
David Benjaminef5dfd22015-12-06 13:17:07 -05001537 helloReq := new(helloRequestMsg).marshal()
1538 if c.config.Bugs.BadHelloRequest != nil {
1539 helloReq = c.config.Bugs.BadHelloRequest
1540 }
1541 c.writeRecord(recordTypeHandshake, helloReq)
David Benjamin582ba042016-07-07 12:33:25 -07001542 c.flushHandshake()
Adam Langleycf2d4f42014-10-28 19:06:14 -07001543 }
1544
1545 c.handshakeComplete = false
1546 return c.Handshake()
1547}
1548
Adam Langley95c29f32014-06-20 12:00:00 -07001549// Read can be made to time out and return a net.Error with Timeout() == true
1550// after a fixed time limit; see SetDeadline and SetReadDeadline.
1551func (c *Conn) Read(b []byte) (n int, err error) {
1552 if err = c.Handshake(); err != nil {
1553 return
1554 }
1555
1556 c.in.Lock()
1557 defer c.in.Unlock()
1558
1559 // Some OpenSSL servers send empty records in order to randomize the
1560 // CBC IV. So this loop ignores a limited number of empty records.
1561 const maxConsecutiveEmptyRecords = 100
1562 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1563 for c.input == nil && c.in.err == nil {
1564 if err := c.readRecord(recordTypeApplicationData); err != nil {
1565 // Soft error, like EAGAIN
1566 return 0, err
1567 }
David Benjamind9b091b2015-01-27 01:10:54 -05001568 if c.hand.Len() > 0 {
David Benjamind5a4ecb2016-07-18 01:17:13 +02001569 // We received handshake bytes, indicating a
1570 // post-handshake message.
1571 if err := c.handlePostHandshakeMessage(); err != nil {
Adam Langley2ae77d22014-10-28 17:29:33 -07001572 return 0, err
1573 }
1574 continue
1575 }
Adam Langley95c29f32014-06-20 12:00:00 -07001576 }
1577 if err := c.in.err; err != nil {
1578 return 0, err
1579 }
1580
1581 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001582 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001583 c.in.freeBlock(c.input)
1584 c.input = nil
1585 }
1586
1587 // If a close-notify alert is waiting, read it so that
1588 // we can return (n, EOF) instead of (n, nil), to signal
1589 // to the HTTP response reading goroutine that the
1590 // connection is now closed. This eliminates a race
1591 // where the HTTP response reading goroutine would
1592 // otherwise not observe the EOF until its next read,
1593 // by which time a client goroutine might have already
1594 // tried to reuse the HTTP connection for a new
1595 // request.
1596 // See https://codereview.appspot.com/76400046
1597 // and http://golang.org/issue/3514
1598 if ri := c.rawInput; ri != nil &&
1599 n != 0 && err == nil &&
1600 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1601 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1602 err = recErr // will be io.EOF on closeNotify
1603 }
1604 }
1605
1606 if n != 0 || err != nil {
1607 return n, err
1608 }
1609 }
1610
1611 return 0, io.ErrNoProgress
1612}
1613
1614// Close closes the connection.
1615func (c *Conn) Close() error {
1616 var alertErr error
1617
1618 c.handshakeMutex.Lock()
1619 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001620 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
David Benjaminfa214e42016-05-10 17:03:10 -04001621 alert := alertCloseNotify
1622 if c.config.Bugs.SendAlertOnShutdown != 0 {
1623 alert = c.config.Bugs.SendAlertOnShutdown
1624 }
1625 alertErr = c.sendAlert(alert)
David Benjamin4d559612016-05-18 14:31:51 -04001626 // Clear local alerts when sending alerts so we continue to wait
1627 // for the peer rather than closing the socket early.
1628 if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1629 alertErr = nil
1630 }
Adam Langley95c29f32014-06-20 12:00:00 -07001631 }
1632
David Benjamin30789da2015-08-29 22:56:45 -04001633 // Consume a close_notify from the peer if one hasn't been received
1634 // already. This avoids the peer from failing |SSL_shutdown| due to a
1635 // write failing.
1636 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1637 for c.in.error() == nil {
1638 c.readRecord(recordTypeAlert)
1639 }
1640 if c.in.error() != io.EOF {
1641 alertErr = c.in.error()
1642 }
1643 }
1644
Adam Langley95c29f32014-06-20 12:00:00 -07001645 if err := c.conn.Close(); err != nil {
1646 return err
1647 }
1648 return alertErr
1649}
1650
1651// Handshake runs the client or server handshake
1652// protocol if it has not yet been run.
1653// Most uses of this package need not call Handshake
1654// explicitly: the first Read or Write will call it automatically.
1655func (c *Conn) Handshake() error {
1656 c.handshakeMutex.Lock()
1657 defer c.handshakeMutex.Unlock()
1658 if err := c.handshakeErr; err != nil {
1659 return err
1660 }
1661 if c.handshakeComplete {
1662 return nil
1663 }
1664
David Benjamin9a41d1b2015-05-16 01:30:09 -04001665 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1666 c.conn.Write([]byte{
1667 byte(recordTypeAlert), // type
1668 0xfe, 0xff, // version
1669 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1670 0x0, 0x2, // length
1671 })
1672 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1673 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001674 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1675 c.writeRecord(recordTypeApplicationData, data)
1676 }
Adam Langley95c29f32014-06-20 12:00:00 -07001677 if c.isClient {
1678 c.handshakeErr = c.clientHandshake()
1679 } else {
1680 c.handshakeErr = c.serverHandshake()
1681 }
David Benjaminddb9f152015-02-03 15:44:39 -05001682 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1683 c.writeRecord(recordType(42), []byte("invalid record"))
1684 }
Adam Langley95c29f32014-06-20 12:00:00 -07001685 return c.handshakeErr
1686}
1687
1688// ConnectionState returns basic TLS details about the connection.
1689func (c *Conn) ConnectionState() ConnectionState {
1690 c.handshakeMutex.Lock()
1691 defer c.handshakeMutex.Unlock()
1692
1693 var state ConnectionState
1694 state.HandshakeComplete = c.handshakeComplete
1695 if c.handshakeComplete {
1696 state.Version = c.vers
1697 state.NegotiatedProtocol = c.clientProtocol
1698 state.DidResume = c.didResume
1699 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001700 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001701 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001702 state.PeerCertificates = c.peerCertificates
1703 state.VerifiedChains = c.verifiedChains
1704 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001705 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001706 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001707 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001708 state.SCTList = c.sctList
Nick Harper60edffd2016-06-21 15:19:24 -07001709 state.PeerSignatureAlgorithm = c.peerSignatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -04001710 state.CurveID = c.curveID
Adam Langley95c29f32014-06-20 12:00:00 -07001711 }
1712
1713 return state
1714}
1715
1716// OCSPResponse returns the stapled OCSP response from the TLS server, if
1717// any. (Only valid for client connections.)
1718func (c *Conn) OCSPResponse() []byte {
1719 c.handshakeMutex.Lock()
1720 defer c.handshakeMutex.Unlock()
1721
1722 return c.ocspResponse
1723}
1724
1725// VerifyHostname checks that the peer certificate chain is valid for
1726// connecting to host. If so, it returns nil; if not, it returns an error
1727// describing the problem.
1728func (c *Conn) VerifyHostname(host string) error {
1729 c.handshakeMutex.Lock()
1730 defer c.handshakeMutex.Unlock()
1731 if !c.isClient {
1732 return errors.New("tls: VerifyHostname called on TLS server connection")
1733 }
1734 if !c.handshakeComplete {
1735 return errors.New("tls: handshake has not yet been performed")
1736 }
1737 return c.peerCertificates[0].VerifyHostname(host)
1738}
David Benjaminc565ebb2015-04-03 04:06:36 -04001739
1740// ExportKeyingMaterial exports keying material from the current connection
1741// state, as per RFC 5705.
1742func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1743 c.handshakeMutex.Lock()
1744 defer c.handshakeMutex.Unlock()
1745 if !c.handshakeComplete {
1746 return nil, errors.New("tls: handshake has not yet been performed")
1747 }
1748
David Benjamin8d315d72016-07-18 01:03:18 +02001749 if c.vers >= VersionTLS13 {
David Benjamin97a0a082016-07-13 17:57:35 -04001750 // TODO(davidben): What should we do with useContext? See
1751 // https://github.com/tlswg/tls13-spec/issues/546
1752 return hkdfExpandLabel(c.cipherSuite.hash(), c.exporterSecret, label, context, length), nil
1753 }
1754
David Benjaminc565ebb2015-04-03 04:06:36 -04001755 seedLen := len(c.clientRandom) + len(c.serverRandom)
1756 if useContext {
1757 seedLen += 2 + len(context)
1758 }
1759 seed := make([]byte, 0, seedLen)
1760 seed = append(seed, c.clientRandom[:]...)
1761 seed = append(seed, c.serverRandom[:]...)
1762 if useContext {
1763 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1764 seed = append(seed, context...)
1765 }
1766 result := make([]byte, length)
David Benjamin97a0a082016-07-13 17:57:35 -04001767 prfForVersion(c.vers, c.cipherSuite)(result, c.exporterSecret, label, seed)
David Benjaminc565ebb2015-04-03 04:06:36 -04001768 return result, nil
1769}
David Benjamin3e052de2015-11-25 20:10:31 -05001770
1771// noRenegotiationInfo returns true if the renegotiation info extension
1772// should be supported in the current handshake.
1773func (c *Conn) noRenegotiationInfo() bool {
1774 if c.config.Bugs.NoRenegotiationInfo {
1775 return true
1776 }
1777 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1778 return true
1779 }
1780 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1781 return true
1782 }
1783 return false
1784}
David Benjamin58104882016-07-18 01:25:41 +02001785
1786func (c *Conn) SendNewSessionTicket() error {
1787 if c.isClient || c.vers < VersionTLS13 {
1788 return errors.New("tls: cannot send post-handshake NewSessionTicket")
1789 }
1790
1791 var peerCertificatesRaw [][]byte
1792 for _, cert := range c.peerCertificates {
1793 peerCertificatesRaw = append(peerCertificatesRaw, cert.Raw)
1794 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001795
Steven Valdeza833c352016-11-01 13:39:36 -04001796 addBuffer := make([]byte, 4)
1797 _, err := io.ReadFull(c.config.rand(), addBuffer)
1798 if err != nil {
1799 c.sendAlert(alertInternalError)
1800 return errors.New("tls: short read from Rand: " + err.Error())
1801 }
1802 ticketAgeAdd := uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0])
1803
David Benjamin58104882016-07-18 01:25:41 +02001804 // TODO(davidben): Allow configuring these values.
1805 m := &newSessionTicketMsg{
David Benjamin9c33ae82017-01-08 06:04:43 -05001806 version: c.vers,
1807 ticketLifetime: uint32(24 * time.Hour / time.Second),
David Benjamin9c33ae82017-01-08 06:04:43 -05001808 duplicateEarlyDataInfo: c.config.Bugs.DuplicateTicketEarlyDataInfo,
1809 customExtension: c.config.Bugs.CustomTicketExtension,
1810 ticketAgeAdd: ticketAgeAdd,
Nick Harperab20cec2016-12-19 17:38:41 -08001811 maxEarlyDataSize: c.config.MaxEarlyDataSize,
David Benjamin58104882016-07-18 01:25:41 +02001812 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001813
David Benjamin17b30832017-01-28 14:00:32 -05001814 if c.config.Bugs.SendTicketLifetime != 0 {
1815 m.ticketLifetime = uint32(c.config.Bugs.SendTicketLifetime / time.Second)
1816 }
1817
Nick Harper0b3625b2016-07-25 16:16:28 -07001818 state := sessionState{
1819 vers: c.vers,
1820 cipherSuite: c.cipherSuite.id,
1821 masterSecret: c.resumptionSecret,
1822 certificates: peerCertificatesRaw,
1823 ticketCreationTime: c.config.time(),
1824 ticketExpiration: c.config.time().Add(time.Duration(m.ticketLifetime) * time.Second),
Steven Valdeza833c352016-11-01 13:39:36 -04001825 ticketAgeAdd: uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0]),
Steven Valdez2d850622017-01-11 11:34:52 -05001826 earlyALPN: []byte(c.clientProtocol),
Nick Harper0b3625b2016-07-25 16:16:28 -07001827 }
1828
David Benjamin58104882016-07-18 01:25:41 +02001829 if !c.config.Bugs.SendEmptySessionTicket {
1830 var err error
1831 m.ticket, err = c.encryptTicket(&state)
1832 if err != nil {
1833 return err
1834 }
1835 }
David Benjamin58104882016-07-18 01:25:41 +02001836 c.out.Lock()
1837 defer c.out.Unlock()
Steven Valdeza833c352016-11-01 13:39:36 -04001838 _, err = c.writeRecord(recordTypeHandshake, m.marshal())
David Benjamin58104882016-07-18 01:25:41 +02001839 return err
1840}
David Benjamin21c00282016-07-18 21:56:23 +02001841
Steven Valdezc4aa7272016-10-03 12:25:56 -04001842func (c *Conn) SendKeyUpdate(keyUpdateRequest byte) error {
David Benjamin21c00282016-07-18 21:56:23 +02001843 c.out.Lock()
1844 defer c.out.Unlock()
Steven Valdezc4aa7272016-10-03 12:25:56 -04001845 return c.sendKeyUpdateLocked(keyUpdateRequest)
David Benjamin21c00282016-07-18 21:56:23 +02001846}
1847
Steven Valdezc4aa7272016-10-03 12:25:56 -04001848func (c *Conn) sendKeyUpdateLocked(keyUpdateRequest byte) error {
David Benjamin7f0965a2016-09-30 15:14:01 -04001849 if c.vers < VersionTLS13 {
1850 return errors.New("tls: attempted to send KeyUpdate before TLS 1.3")
1851 }
1852
Steven Valdezc4aa7272016-10-03 12:25:56 -04001853 m := keyUpdateMsg{
1854 keyUpdateRequest: keyUpdateRequest,
1855 }
David Benjamin21c00282016-07-18 21:56:23 +02001856 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
1857 return err
1858 }
1859 if err := c.flushHandshake(); err != nil {
1860 return err
1861 }
Steven Valdez1dc53d22016-07-26 12:27:38 -04001862 c.out.doKeyUpdate(c, true)
David Benjamin21c00282016-07-18 21:56:23 +02001863 return nil
1864}
Steven Valdeza4ee74d2016-11-29 13:36:45 -05001865
1866func (c *Conn) sendFakeEarlyData(len int) error {
1867 // Assemble a fake early data record. This does not use writeRecord
1868 // because the record layer may be using different keys at this point.
1869 payload := make([]byte, 5+len)
1870 payload[0] = byte(recordTypeApplicationData)
1871 payload[1] = 3
1872 payload[2] = 1
1873 payload[3] = byte(len >> 8)
1874 payload[4] = byte(len)
1875 _, err := c.conn.Write(payload)
1876 return err
1877}