blob: a50029febccaa01eced109b681f0ff95aeeed1e8 [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 Valdez924a3522017-03-02 16:05:03 -0500765 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
766 n := int(b.data[3])<<8 | int(b.data[4])
767
David Benjaminbde00392016-06-21 12:19:28 -0400768 // Alerts sent near version negotiation do not have a well-defined
769 // record-layer version prior to TLS 1.3. (In TLS 1.3, the record-layer
770 // version is irrelevant.)
771 if typ != recordTypeAlert {
David Benjamine6f22212016-11-08 14:28:24 -0500772 var expect uint16
David Benjaminbde00392016-06-21 12:19:28 -0400773 if c.haveVers {
David Benjamine6f22212016-11-08 14:28:24 -0500774 expect = c.vers
775 if c.vers >= VersionTLS13 {
776 expect = VersionTLS10
David Benjaminbde00392016-06-21 12:19:28 -0400777 }
778 } else {
David Benjamine6f22212016-11-08 14:28:24 -0500779 expect = c.config.Bugs.ExpectInitialRecordVersion
780 }
781 if expect != 0 && vers != expect {
782 c.sendAlert(alertProtocolVersion)
783 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 -0500784 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400785 }
786 if n > maxCiphertext {
787 c.sendAlert(alertRecordOverflow)
788 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
789 }
790 if !c.haveVers {
791 // First message, be extra suspicious:
792 // this might not be a TLS client.
793 // Bail out before reading a full 'body', if possible.
794 // The current max version is 3.1.
795 // If the version is >= 16.0, it's probably not real.
796 // Similarly, a clientHello message encodes in
797 // well under a kilobyte. If the length is >= 12 kB,
798 // it's probably not real.
799 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
800 c.sendAlert(alertUnexpectedMessage)
801 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
802 }
803 }
804 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
805 if err == io.EOF {
806 err = io.ErrUnexpectedEOF
807 }
808 if e, ok := err.(net.Error); !ok || !e.Temporary() {
809 c.in.setErrorLocked(err)
810 }
811 return 0, nil, err
812 }
813
814 // Process message.
815 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
David Benjaminff26f092016-07-01 16:13:42 -0400816 ok, off, encTyp, alertValue := c.in.decrypt(b)
Nick Harper47383aa2016-11-30 12:50:43 -0800817
818 // Handle skipping over early data.
819 if !ok && c.skipEarlyData {
820 goto RestartReadRecord
821 }
822
823 // If the server is expecting a second ClientHello (in response to
824 // a HelloRetryRequest) and the client sends early data, there
825 // won't be a decryption failure but it still needs to be skipped.
826 if c.in.cipher == nil && typ == recordTypeApplicationData && c.skipEarlyData {
827 goto RestartReadRecord
828 }
829
David Benjaminff26f092016-07-01 16:13:42 -0400830 if !ok {
831 return 0, nil, c.in.setErrorLocked(c.sendAlert(alertValue))
832 }
833 b.off = off
Nick Harper47383aa2016-11-30 12:50:43 -0800834 c.skipEarlyData = false
David Benjaminff26f092016-07-01 16:13:42 -0400835
Nick Harper1fd39d82016-06-14 18:14:35 -0700836 if c.vers >= VersionTLS13 && c.in.cipher != nil {
David Benjaminc9ae27c2016-06-24 22:56:37 -0400837 if typ != recordTypeApplicationData {
838 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: outer record type is not application data"))
839 }
Nick Harper1fd39d82016-06-14 18:14:35 -0700840 typ = encTyp
841 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400842 return typ, b, nil
843}
844
Adam Langley95c29f32014-06-20 12:00:00 -0700845// readRecord reads the next TLS record from the connection
846// and updates the record layer state.
847// c.in.Mutex <= L; c.input == nil.
848func (c *Conn) readRecord(want recordType) error {
849 // Caller must be in sync with connection:
850 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700851 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700852 switch want {
853 default:
854 c.sendAlert(alertInternalError)
855 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
David Benjaminbbba9392017-04-06 12:54:12 -0400856 case recordTypeChangeCipherSpec:
Adam Langley95c29f32014-06-20 12:00:00 -0700857 if c.handshakeComplete {
858 c.sendAlert(alertInternalError)
David Benjaminbbba9392017-04-06 12:54:12 -0400859 return c.in.setErrorLocked(errors.New("tls: ChangeCipherSpec requested after handshake complete"))
Adam Langley95c29f32014-06-20 12:00:00 -0700860 }
Steven Valdeze831a812017-03-09 14:56:07 -0500861 case recordTypeApplicationData, recordTypeAlert, recordTypeHandshake:
862 break
Adam Langley95c29f32014-06-20 12:00:00 -0700863 }
864
865Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400866 typ, b, err := c.doReadRecord(want)
867 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700868 return err
869 }
Adam Langley95c29f32014-06-20 12:00:00 -0700870 data := b.data[b.off:]
David Benjamine3fbb362017-01-06 16:19:28 -0500871 max := maxPlaintext
872 if c.config.Bugs.MaxReceivePlaintext != 0 {
873 max = c.config.Bugs.MaxReceivePlaintext
874 }
875 if len(data) > max {
Adam Langley95c29f32014-06-20 12:00:00 -0700876 err := c.sendAlert(alertRecordOverflow)
877 c.in.freeBlock(b)
878 return c.in.setErrorLocked(err)
879 }
880
881 switch typ {
882 default:
883 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
884
885 case recordTypeAlert:
886 if len(data) != 2 {
887 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
888 break
889 }
890 if alert(data[1]) == alertCloseNotify {
891 c.in.setErrorLocked(io.EOF)
892 break
893 }
894 switch data[0] {
895 case alertLevelWarning:
David Benjamin053fee92017-01-02 08:30:36 -0500896 if alert(data[1]) == alertNoCertificate {
897 c.in.freeBlock(b)
898 return errNoCertificateAlert
899 }
Nick Harperab20cec2016-12-19 17:38:41 -0800900 if alert(data[1]) == alertEndOfEarlyData {
901 c.in.freeBlock(b)
902 return errEndOfEarlyDataAlert
903 }
David Benjamin053fee92017-01-02 08:30:36 -0500904
Adam Langley95c29f32014-06-20 12:00:00 -0700905 // drop on the floor
906 c.in.freeBlock(b)
907 goto Again
908 case alertLevelError:
909 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
910 default:
911 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
912 }
913
914 case recordTypeChangeCipherSpec:
915 if typ != want || len(data) != 1 || data[0] != 1 {
916 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
917 break
918 }
Steven Valdez520e1222017-06-13 12:45:25 -0400919 if c.wireVersion != tls13ExperimentVersion {
920 err := c.in.changeCipherSpec(c.config)
921 if err != nil {
922 c.in.setErrorLocked(c.sendAlert(err.(alert)))
923 }
Adam Langley95c29f32014-06-20 12:00:00 -0700924 }
925
926 case recordTypeApplicationData:
927 if typ != want {
928 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
929 break
930 }
931 c.input = b
932 b = nil
933
934 case recordTypeHandshake:
David Benjamind5a4ecb2016-07-18 01:17:13 +0200935 // Allow handshake data while reading application data to
936 // trigger post-handshake messages.
Adam Langley95c29f32014-06-20 12:00:00 -0700937 // TODO(rsc): Should at least pick off connection close.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200938 if typ != want && want != recordTypeApplicationData {
939 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
Adam Langley95c29f32014-06-20 12:00:00 -0700940 }
941 c.hand.Write(data)
942 }
943
944 if b != nil {
945 c.in.freeBlock(b)
946 }
947 return c.in.err
948}
949
950// sendAlert sends a TLS alert message.
951// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400952func (c *Conn) sendAlertLocked(level byte, err alert) error {
953 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700954 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400955 if c.config.Bugs.FragmentAlert {
956 c.writeRecord(recordTypeAlert, c.tmp[0:1])
957 c.writeRecord(recordTypeAlert, c.tmp[1:2])
David Benjamin0d3a8c62016-03-11 22:25:18 -0500958 } else if c.config.Bugs.DoubleAlert {
959 copy(c.tmp[2:4], c.tmp[0:2])
960 c.writeRecord(recordTypeAlert, c.tmp[0:4])
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400961 } else {
962 c.writeRecord(recordTypeAlert, c.tmp[0:2])
963 }
David Benjamin24f346d2015-06-06 03:28:08 -0400964 // Error alerts are fatal to the connection.
965 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700966 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
967 }
968 return nil
969}
970
971// sendAlert sends a TLS alert message.
972// L < c.out.Mutex.
973func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400974 level := byte(alertLevelError)
Nick Harperf2511f12016-12-06 16:02:31 -0800975 if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertificate || err == alertEndOfEarlyData {
David Benjamin24f346d2015-06-06 03:28:08 -0400976 level = alertLevelWarning
977 }
978 return c.SendAlert(level, err)
979}
980
981func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700982 c.out.Lock()
983 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -0400984 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -0700985}
986
David Benjamind86c7672014-08-02 04:07:12 -0400987// writeV2Record writes a record for a V2ClientHello.
988func (c *Conn) writeV2Record(data []byte) (n int, err error) {
989 record := make([]byte, 2+len(data))
990 record[0] = uint8(len(data)>>8) | 0x80
991 record[1] = uint8(len(data))
992 copy(record[2:], data)
993 return c.conn.Write(record)
994}
995
Adam Langley95c29f32014-06-20 12:00:00 -0700996// writeRecord writes a TLS record with the given type and payload
997// to the connection and updates the record layer state.
998// c.out.Mutex <= L.
999func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjaminebacdee2017-04-08 11:00:45 -04001000 if typ == recordTypeHandshake {
1001 msgType := data[0]
1002 if c.config.Bugs.SendWrongMessageType != 0 && msgType == c.config.Bugs.SendWrongMessageType {
1003 msgType += 42
1004 } else if msgType == typeServerHello && c.config.Bugs.SendServerHelloAsHelloRetryRequest {
1005 msgType = typeHelloRetryRequest
1006 }
1007 if msgType != data[0] {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001008 newData := make([]byte, len(data))
1009 copy(newData, data)
David Benjaminebacdee2017-04-08 11:00:45 -04001010 newData[0] = msgType
David Benjamin0b8d5da2016-07-15 00:39:56 -04001011 data = newData
1012 }
1013 }
1014
David Benjamin639846e2016-09-09 11:41:18 -04001015 if msgType := c.config.Bugs.SendTrailingMessageData; msgType != 0 {
1016 if typ == recordTypeHandshake && data[0] == msgType {
1017 newData := make([]byte, len(data))
1018 copy(newData, data)
1019
1020 // Add a 0 to the body.
1021 newData = append(newData, 0)
1022 // Fix the header.
1023 newLen := len(newData) - 4
1024 newData[1] = byte(newLen >> 16)
1025 newData[2] = byte(newLen >> 8)
1026 newData[3] = byte(newLen)
1027
1028 data = newData
1029 }
1030 }
1031
David Benjamin83c0bc92014-08-04 01:23:53 -04001032 if c.isDTLS {
1033 return c.dtlsWriteRecord(typ, data)
1034 }
1035
David Benjamin71dd6662016-07-08 14:10:48 -07001036 if typ == recordTypeHandshake {
1037 if c.config.Bugs.SendHelloRequestBeforeEveryHandshakeMessage {
1038 newData := make([]byte, 0, 4+len(data))
1039 newData = append(newData, typeHelloRequest, 0, 0, 0)
1040 newData = append(newData, data...)
1041 data = newData
1042 }
1043
1044 if c.config.Bugs.PackHandshakeFlight {
1045 c.pendingFlight.Write(data)
1046 return len(data), nil
1047 }
David Benjamin582ba042016-07-07 12:33:25 -07001048 }
1049
1050 return c.doWriteRecord(typ, data)
1051}
1052
1053func (c *Conn) doWriteRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin6f600d62016-12-21 16:06:54 -05001054 recordHeaderLen := c.out.recordHeaderLen()
Adam Langley95c29f32014-06-20 12:00:00 -07001055 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -04001056 first := true
1057 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -04001058 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -07001059 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -04001060 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -07001061 m = maxPlaintext
1062 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001063 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
1064 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -04001065 // By default, do not fragment the client_version or
1066 // server_version, which are located in the first 6
1067 // bytes.
1068 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
1069 m = 6
1070 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001071 }
Adam Langley95c29f32014-06-20 12:00:00 -07001072 explicitIVLen := 0
1073 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -04001074 first = false
Adam Langley95c29f32014-06-20 12:00:00 -07001075
1076 var cbc cbcMode
1077 if c.out.version >= VersionTLS11 {
1078 var ok bool
1079 if cbc, ok = c.out.cipher.(cbcMode); ok {
1080 explicitIVLen = cbc.BlockSize()
1081 }
1082 }
1083 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -04001084 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -07001085 explicitIVLen = 8
1086 // The AES-GCM construction in TLS has an
1087 // explicit nonce so that the nonce can be
1088 // random. However, the nonce is only 8 bytes
1089 // which is too small for a secure, random
1090 // nonce. Therefore we use the sequence number
1091 // as the nonce.
1092 explicitIVIsSeq = true
1093 }
1094 }
1095 b.resize(recordHeaderLen + explicitIVLen + m)
Steven Valdez924a3522017-03-02 16:05:03 -05001096 b.data[0] = byte(typ)
1097 if c.vers >= VersionTLS13 && c.out.cipher != nil {
1098 b.data[0] = byte(recordTypeApplicationData)
1099 if outerType := c.config.Bugs.OuterRecordType; outerType != 0 {
1100 b.data[0] = byte(outerType)
David Benjaminc9ae27c2016-06-24 22:56:37 -04001101 }
Nick Harper1fd39d82016-06-14 18:14:35 -07001102 }
Steven Valdez924a3522017-03-02 16:05:03 -05001103 vers := c.vers
1104 if vers == 0 || vers >= VersionTLS13 {
1105 // Some TLS servers fail if the record version is
1106 // greater than TLS 1.0 for the initial ClientHello.
1107 //
1108 // TLS 1.3 fixes the version number in the record
1109 // layer to {3, 1}.
1110 vers = VersionTLS10
1111 }
1112 if c.config.Bugs.SendRecordVersion != 0 {
1113 vers = c.config.Bugs.SendRecordVersion
1114 }
1115 if c.vers == 0 && c.config.Bugs.SendInitialRecordVersion != 0 {
1116 vers = c.config.Bugs.SendInitialRecordVersion
1117 }
1118 b.data[1] = byte(vers >> 8)
1119 b.data[2] = byte(vers)
1120 b.data[3] = byte(m >> 8)
1121 b.data[4] = byte(m)
Adam Langley95c29f32014-06-20 12:00:00 -07001122 if explicitIVLen > 0 {
1123 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
1124 if explicitIVIsSeq {
1125 copy(explicitIV, c.out.seq[:])
1126 } else {
1127 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
1128 break
1129 }
1130 }
1131 }
1132 copy(b.data[recordHeaderLen+explicitIVLen:], data)
Nick Harper1fd39d82016-06-14 18:14:35 -07001133 c.out.encrypt(b, explicitIVLen, typ)
Adam Langley95c29f32014-06-20 12:00:00 -07001134 _, err = c.conn.Write(b.data)
1135 if err != nil {
1136 break
1137 }
1138 n += m
1139 data = data[m:]
1140 }
1141 c.out.freeBlock(b)
1142
Steven Valdez520e1222017-06-13 12:45:25 -04001143 if typ == recordTypeChangeCipherSpec && c.wireVersion != tls13ExperimentVersion {
Adam Langley80842bd2014-06-20 12:00:00 -07001144 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -07001145 if err != nil {
David Benjamina8181342017-07-07 18:10:57 -04001146 return n, c.sendAlertLocked(alertLevelError, err.(alert))
Adam Langley95c29f32014-06-20 12:00:00 -07001147 }
1148 }
1149 return
1150}
1151
David Benjamin582ba042016-07-07 12:33:25 -07001152func (c *Conn) flushHandshake() error {
1153 if c.isDTLS {
1154 return c.dtlsFlushHandshake()
1155 }
1156
1157 for c.pendingFlight.Len() > 0 {
1158 var buf [maxPlaintext]byte
1159 n, _ := c.pendingFlight.Read(buf[:])
1160 if _, err := c.doWriteRecord(recordTypeHandshake, buf[:n]); err != nil {
1161 return err
1162 }
1163 }
1164
1165 c.pendingFlight.Reset()
1166 return nil
1167}
1168
David Benjamin83c0bc92014-08-04 01:23:53 -04001169func (c *Conn) doReadHandshake() ([]byte, error) {
1170 if c.isDTLS {
1171 return c.dtlsDoReadHandshake()
1172 }
1173
Adam Langley95c29f32014-06-20 12:00:00 -07001174 for c.hand.Len() < 4 {
1175 if err := c.in.err; err != nil {
1176 return nil, err
1177 }
1178 if err := c.readRecord(recordTypeHandshake); err != nil {
1179 return nil, err
1180 }
1181 }
1182
1183 data := c.hand.Bytes()
1184 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1185 if n > maxHandshake {
1186 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
1187 }
1188 for c.hand.Len() < 4+n {
1189 if err := c.in.err; err != nil {
1190 return nil, err
1191 }
1192 if err := c.readRecord(recordTypeHandshake); err != nil {
1193 return nil, err
1194 }
1195 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001196 return c.hand.Next(4 + n), nil
1197}
1198
1199// readHandshake reads the next handshake message from
1200// the record layer.
1201// c.in.Mutex < L; c.out.Mutex < L.
1202func (c *Conn) readHandshake() (interface{}, error) {
1203 data, err := c.doReadHandshake()
David Benjamin053fee92017-01-02 08:30:36 -05001204 if err == errNoCertificateAlert {
1205 if c.hand.Len() != 0 {
1206 // The warning alert may not interleave with a handshake message.
1207 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1208 }
1209 return new(ssl3NoCertificateMsg), nil
1210 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001211 if err != nil {
1212 return nil, err
1213 }
1214
Adam Langley95c29f32014-06-20 12:00:00 -07001215 var m handshakeMessage
1216 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001217 case typeHelloRequest:
1218 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001219 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001220 m = &clientHelloMsg{
1221 isDTLS: c.isDTLS,
1222 }
Adam Langley95c29f32014-06-20 12:00:00 -07001223 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001224 m = &serverHelloMsg{
1225 isDTLS: c.isDTLS,
1226 }
Nick Harperdcfbc672016-07-16 17:47:31 +02001227 case typeHelloRetryRequest:
1228 m = new(helloRetryRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001229 case typeNewSessionTicket:
David Benjamin58104882016-07-18 01:25:41 +02001230 m = &newSessionTicketMsg{
1231 version: c.vers,
1232 }
Nick Harperb41d2e42016-07-01 17:50:32 -04001233 case typeEncryptedExtensions:
1234 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001235 case typeCertificate:
Nick Harperb41d2e42016-07-01 17:50:32 -04001236 m = &certificateMsg{
David Benjamin8d315d72016-07-18 01:03:18 +02001237 hasRequestContext: c.vers >= VersionTLS13,
Nick Harperb41d2e42016-07-01 17:50:32 -04001238 }
Adam Langley95c29f32014-06-20 12:00:00 -07001239 case typeCertificateRequest:
1240 m = &certificateRequestMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001241 hasSignatureAlgorithm: c.vers >= VersionTLS12,
David Benjamin8d315d72016-07-18 01:03:18 +02001242 hasRequestContext: c.vers >= VersionTLS13,
Adam Langley95c29f32014-06-20 12:00:00 -07001243 }
1244 case typeCertificateStatus:
1245 m = new(certificateStatusMsg)
1246 case typeServerKeyExchange:
1247 m = new(serverKeyExchangeMsg)
1248 case typeServerHelloDone:
1249 m = new(serverHelloDoneMsg)
1250 case typeClientKeyExchange:
1251 m = new(clientKeyExchangeMsg)
1252 case typeCertificateVerify:
1253 m = &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001254 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001255 }
1256 case typeNextProtocol:
1257 m = new(nextProtoMsg)
1258 case typeFinished:
1259 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001260 case typeHelloVerifyRequest:
1261 m = new(helloVerifyRequestMsg)
David Benjamin24599a82016-06-30 18:56:53 -04001262 case typeChannelID:
1263 m = new(channelIDMsg)
David Benjamin21c00282016-07-18 21:56:23 +02001264 case typeKeyUpdate:
1265 m = new(keyUpdateMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001266 default:
1267 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1268 }
1269
1270 // The handshake message unmarshallers
1271 // expect to be able to keep references to data,
1272 // so pass in a fresh copy that won't be overwritten.
1273 data = append([]byte(nil), data...)
1274
1275 if !m.unmarshal(data) {
1276 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1277 }
1278 return m, nil
1279}
1280
David Benjamin83f90402015-01-27 01:09:43 -05001281// skipPacket processes all the DTLS records in packet. It updates
1282// sequence number expectations but otherwise ignores them.
1283func (c *Conn) skipPacket(packet []byte) error {
1284 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001285 if len(packet) < 13 {
1286 return errors.New("tls: bad packet")
1287 }
David Benjamin83f90402015-01-27 01:09:43 -05001288 // Dropped packets are completely ignored save to update
1289 // expected sequence numbers for this and the next epoch. (We
1290 // don't assert on the contents of the packets both for
1291 // simplicity and because a previous test with one shorter
1292 // timeout schedule would have done so.)
1293 epoch := packet[3:5]
1294 seq := packet[5:11]
1295 length := uint16(packet[11])<<8 | uint16(packet[12])
1296 if bytes.Equal(c.in.seq[:2], epoch) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001297 if bytes.Compare(seq, c.in.seq[2:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001298 return errors.New("tls: sequence mismatch")
1299 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001300 copy(c.in.seq[2:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001301 c.in.incSeq(false)
1302 } else {
David Benjamin13e81fc2015-11-02 17:16:13 -05001303 if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001304 return errors.New("tls: sequence mismatch")
1305 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001306 copy(c.in.nextSeq[:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001307 c.in.incNextSeq()
1308 }
David Benjamin6ca93552015-08-28 16:16:25 -04001309 if len(packet) < 13+int(length) {
1310 return errors.New("tls: bad packet")
1311 }
David Benjamin83f90402015-01-27 01:09:43 -05001312 packet = packet[13+length:]
1313 }
1314 return nil
1315}
1316
1317// simulatePacketLoss simulates the loss of a handshake leg from the
1318// peer based on the schedule in c.config.Bugs. If resendFunc is
1319// non-nil, it is called after each simulated timeout to retransmit
1320// handshake messages from the local end. This is used in cases where
1321// the peer retransmits on a stale Finished rather than a timeout.
1322func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1323 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1324 return nil
1325 }
1326 if !c.isDTLS {
1327 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1328 }
1329 if c.config.Bugs.PacketAdaptor == nil {
1330 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1331 }
1332 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1333 // Simulate a timeout.
1334 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1335 if err != nil {
1336 return err
1337 }
1338 for _, packet := range packets {
1339 if err := c.skipPacket(packet); err != nil {
1340 return err
1341 }
1342 }
1343 if resendFunc != nil {
1344 resendFunc()
1345 }
1346 }
1347 return nil
1348}
1349
David Benjamin47921102016-07-28 11:29:18 -04001350func (c *Conn) SendHalfHelloRequest() error {
1351 if err := c.Handshake(); err != nil {
1352 return err
1353 }
1354
1355 c.out.Lock()
1356 defer c.out.Unlock()
1357
1358 if _, err := c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0}); err != nil {
1359 return err
1360 }
1361 return c.flushHandshake()
1362}
1363
Adam Langley95c29f32014-06-20 12:00:00 -07001364// Write writes data to the connection.
1365func (c *Conn) Write(b []byte) (int, error) {
1366 if err := c.Handshake(); err != nil {
1367 return 0, err
1368 }
1369
1370 c.out.Lock()
1371 defer c.out.Unlock()
1372
David Benjamin12d2c482016-07-24 10:56:51 -04001373 // Flush any pending handshake data. PackHelloRequestWithFinished may
1374 // have been set and the handshake not followed by Renegotiate.
1375 c.flushHandshake()
1376
Adam Langley95c29f32014-06-20 12:00:00 -07001377 if err := c.out.err; err != nil {
1378 return 0, err
1379 }
1380
1381 if !c.handshakeComplete {
1382 return 0, alertInternalError
1383 }
1384
Steven Valdezc4aa7272016-10-03 12:25:56 -04001385 if c.keyUpdateRequested {
1386 if err := c.sendKeyUpdateLocked(keyUpdateNotRequested); err != nil {
David Benjamin21c00282016-07-18 21:56:23 +02001387 return 0, err
1388 }
Steven Valdezc4aa7272016-10-03 12:25:56 -04001389 c.keyUpdateRequested = false
David Benjamin21c00282016-07-18 21:56:23 +02001390 }
1391
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001392 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001393 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001394 }
1395
Adam Langley27a0d082015-11-03 13:34:10 -08001396 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1397 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
David Benjamin582ba042016-07-07 12:33:25 -07001398 c.flushHandshake()
Adam Langley27a0d082015-11-03 13:34:10 -08001399 }
1400
Adam Langley95c29f32014-06-20 12:00:00 -07001401 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1402 // attack when using block mode ciphers due to predictable IVs.
1403 // This can be prevented by splitting each Application Data
1404 // record into two records, effectively randomizing the IV.
1405 //
1406 // http://www.openssl.org/~bodo/tls-cbc.txt
1407 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1408 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1409
1410 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001411 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001412 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1413 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1414 if err != nil {
1415 return n, c.out.setErrorLocked(err)
1416 }
1417 m, b = 1, b[1:]
1418 }
1419 }
1420
1421 n, err := c.writeRecord(recordTypeApplicationData, b)
1422 return n + m, c.out.setErrorLocked(err)
1423}
1424
David Benjamin794cc592017-03-25 22:24:23 -05001425func (c *Conn) processTLS13NewSessionTicket(newSessionTicket *newSessionTicketMsg, cipherSuite *cipherSuite) error {
1426 if c.config.Bugs.ExpectGREASE && !newSessionTicket.hasGREASEExtension {
1427 return errors.New("tls: no GREASE ticket extension found")
1428 }
1429
1430 if c.config.Bugs.ExpectTicketEarlyDataInfo && newSessionTicket.maxEarlyDataSize == 0 {
1431 return errors.New("tls: no ticket_early_data_info extension found")
1432 }
1433
1434 if c.config.Bugs.ExpectNoNewSessionTicket {
1435 return errors.New("tls: received unexpected NewSessionTicket")
1436 }
1437
1438 if c.config.ClientSessionCache == nil || newSessionTicket.ticketLifetime == 0 {
1439 return nil
1440 }
1441
1442 session := &ClientSessionState{
1443 sessionTicket: newSessionTicket.ticket,
1444 vers: c.vers,
1445 cipherSuite: cipherSuite.id,
1446 masterSecret: c.resumptionSecret,
1447 serverCertificates: c.peerCertificates,
1448 sctList: c.sctList,
1449 ocspResponse: c.ocspResponse,
1450 ticketCreationTime: c.config.time(),
1451 ticketExpiration: c.config.time().Add(time.Duration(newSessionTicket.ticketLifetime) * time.Second),
1452 ticketAgeAdd: newSessionTicket.ticketAgeAdd,
1453 maxEarlyDataSize: newSessionTicket.maxEarlyDataSize,
1454 earlyALPN: c.clientProtocol,
1455 }
1456
1457 cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
1458 c.config.ClientSessionCache.Put(cacheKey, session)
1459 return nil
1460}
1461
David Benjamind5a4ecb2016-07-18 01:17:13 +02001462func (c *Conn) handlePostHandshakeMessage() error {
Adam Langley2ae77d22014-10-28 17:29:33 -07001463 msg, err := c.readHandshake()
1464 if err != nil {
1465 return err
1466 }
David Benjamind5a4ecb2016-07-18 01:17:13 +02001467
1468 if c.vers < VersionTLS13 {
1469 if !c.isClient {
1470 c.sendAlert(alertUnexpectedMessage)
1471 return errors.New("tls: unexpected post-handshake message")
1472 }
1473
1474 _, ok := msg.(*helloRequestMsg)
1475 if !ok {
1476 c.sendAlert(alertUnexpectedMessage)
1477 return alertUnexpectedMessage
1478 }
1479
1480 c.handshakeComplete = false
1481 return c.Handshake()
Adam Langley2ae77d22014-10-28 17:29:33 -07001482 }
1483
David Benjamind5a4ecb2016-07-18 01:17:13 +02001484 if c.isClient {
1485 if newSessionTicket, ok := msg.(*newSessionTicketMsg); ok {
David Benjamin794cc592017-03-25 22:24:23 -05001486 return c.processTLS13NewSessionTicket(newSessionTicket, c.cipherSuite)
David Benjamind5a4ecb2016-07-18 01:17:13 +02001487 }
1488 }
1489
Steven Valdezc4aa7272016-10-03 12:25:56 -04001490 if keyUpdate, ok := msg.(*keyUpdateMsg); ok {
David Benjaminbbba9392017-04-06 12:54:12 -04001491 if c.config.Bugs.RejectUnsolicitedKeyUpdate {
1492 return errors.New("tls: unexpected KeyUpdate message")
1493 }
Steven Valdez1dc53d22016-07-26 12:27:38 -04001494 c.in.doKeyUpdate(c, false)
Steven Valdezc4aa7272016-10-03 12:25:56 -04001495 if keyUpdate.keyUpdateRequest == keyUpdateRequested {
1496 c.keyUpdateRequested = true
1497 }
David Benjamin21c00282016-07-18 21:56:23 +02001498 return nil
1499 }
1500
David Benjamind5a4ecb2016-07-18 01:17:13 +02001501 c.sendAlert(alertUnexpectedMessage)
David Benjaminbbba9392017-04-06 12:54:12 -04001502 return errors.New("tls: unexpected post-handshake message")
1503}
1504
1505// Reads a KeyUpdate acknowledgment from the peer. There may not be any
1506// application data records before the message.
1507func (c *Conn) ReadKeyUpdateACK() error {
1508 c.in.Lock()
1509 defer c.in.Unlock()
1510
1511 msg, err := c.readHandshake()
1512 if err != nil {
1513 return err
1514 }
1515
1516 keyUpdate, ok := msg.(*keyUpdateMsg)
1517 if !ok {
1518 c.sendAlert(alertUnexpectedMessage)
1519 return errors.New("tls: unexpected message when reading KeyUpdate")
1520 }
1521
1522 if keyUpdate.keyUpdateRequest != keyUpdateNotRequested {
1523 return errors.New("tls: received invalid KeyUpdate message")
1524 }
1525
1526 c.in.doKeyUpdate(c, false)
1527 return nil
Adam Langley2ae77d22014-10-28 17:29:33 -07001528}
1529
Adam Langleycf2d4f42014-10-28 19:06:14 -07001530func (c *Conn) Renegotiate() error {
1531 if !c.isClient {
David Benjaminef5dfd22015-12-06 13:17:07 -05001532 helloReq := new(helloRequestMsg).marshal()
1533 if c.config.Bugs.BadHelloRequest != nil {
1534 helloReq = c.config.Bugs.BadHelloRequest
1535 }
1536 c.writeRecord(recordTypeHandshake, helloReq)
David Benjamin582ba042016-07-07 12:33:25 -07001537 c.flushHandshake()
Adam Langleycf2d4f42014-10-28 19:06:14 -07001538 }
1539
1540 c.handshakeComplete = false
1541 return c.Handshake()
1542}
1543
Adam Langley95c29f32014-06-20 12:00:00 -07001544// Read can be made to time out and return a net.Error with Timeout() == true
1545// after a fixed time limit; see SetDeadline and SetReadDeadline.
1546func (c *Conn) Read(b []byte) (n int, err error) {
1547 if err = c.Handshake(); err != nil {
1548 return
1549 }
1550
1551 c.in.Lock()
1552 defer c.in.Unlock()
1553
1554 // Some OpenSSL servers send empty records in order to randomize the
1555 // CBC IV. So this loop ignores a limited number of empty records.
1556 const maxConsecutiveEmptyRecords = 100
1557 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1558 for c.input == nil && c.in.err == nil {
1559 if err := c.readRecord(recordTypeApplicationData); err != nil {
1560 // Soft error, like EAGAIN
1561 return 0, err
1562 }
David Benjamind9b091b2015-01-27 01:10:54 -05001563 if c.hand.Len() > 0 {
David Benjamind5a4ecb2016-07-18 01:17:13 +02001564 // We received handshake bytes, indicating a
1565 // post-handshake message.
1566 if err := c.handlePostHandshakeMessage(); err != nil {
Adam Langley2ae77d22014-10-28 17:29:33 -07001567 return 0, err
1568 }
1569 continue
1570 }
Adam Langley95c29f32014-06-20 12:00:00 -07001571 }
1572 if err := c.in.err; err != nil {
1573 return 0, err
1574 }
1575
1576 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001577 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001578 c.in.freeBlock(c.input)
1579 c.input = nil
1580 }
1581
1582 // If a close-notify alert is waiting, read it so that
1583 // we can return (n, EOF) instead of (n, nil), to signal
1584 // to the HTTP response reading goroutine that the
1585 // connection is now closed. This eliminates a race
1586 // where the HTTP response reading goroutine would
1587 // otherwise not observe the EOF until its next read,
1588 // by which time a client goroutine might have already
1589 // tried to reuse the HTTP connection for a new
1590 // request.
1591 // See https://codereview.appspot.com/76400046
1592 // and http://golang.org/issue/3514
1593 if ri := c.rawInput; ri != nil &&
1594 n != 0 && err == nil &&
1595 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1596 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1597 err = recErr // will be io.EOF on closeNotify
1598 }
1599 }
1600
1601 if n != 0 || err != nil {
1602 return n, err
1603 }
1604 }
1605
1606 return 0, io.ErrNoProgress
1607}
1608
1609// Close closes the connection.
1610func (c *Conn) Close() error {
1611 var alertErr error
1612
1613 c.handshakeMutex.Lock()
1614 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001615 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
David Benjaminfa214e42016-05-10 17:03:10 -04001616 alert := alertCloseNotify
1617 if c.config.Bugs.SendAlertOnShutdown != 0 {
1618 alert = c.config.Bugs.SendAlertOnShutdown
1619 }
1620 alertErr = c.sendAlert(alert)
David Benjamin4d559612016-05-18 14:31:51 -04001621 // Clear local alerts when sending alerts so we continue to wait
1622 // for the peer rather than closing the socket early.
1623 if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1624 alertErr = nil
1625 }
Adam Langley95c29f32014-06-20 12:00:00 -07001626 }
1627
David Benjamin30789da2015-08-29 22:56:45 -04001628 // Consume a close_notify from the peer if one hasn't been received
1629 // already. This avoids the peer from failing |SSL_shutdown| due to a
1630 // write failing.
1631 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1632 for c.in.error() == nil {
1633 c.readRecord(recordTypeAlert)
1634 }
1635 if c.in.error() != io.EOF {
1636 alertErr = c.in.error()
1637 }
1638 }
1639
Adam Langley95c29f32014-06-20 12:00:00 -07001640 if err := c.conn.Close(); err != nil {
1641 return err
1642 }
1643 return alertErr
1644}
1645
1646// Handshake runs the client or server handshake
1647// protocol if it has not yet been run.
1648// Most uses of this package need not call Handshake
1649// explicitly: the first Read or Write will call it automatically.
1650func (c *Conn) Handshake() error {
1651 c.handshakeMutex.Lock()
1652 defer c.handshakeMutex.Unlock()
1653 if err := c.handshakeErr; err != nil {
1654 return err
1655 }
1656 if c.handshakeComplete {
1657 return nil
1658 }
1659
David Benjamin9a41d1b2015-05-16 01:30:09 -04001660 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1661 c.conn.Write([]byte{
1662 byte(recordTypeAlert), // type
1663 0xfe, 0xff, // version
1664 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1665 0x0, 0x2, // length
1666 })
1667 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1668 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001669 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1670 c.writeRecord(recordTypeApplicationData, data)
1671 }
Adam Langley95c29f32014-06-20 12:00:00 -07001672 if c.isClient {
1673 c.handshakeErr = c.clientHandshake()
1674 } else {
1675 c.handshakeErr = c.serverHandshake()
1676 }
David Benjaminddb9f152015-02-03 15:44:39 -05001677 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1678 c.writeRecord(recordType(42), []byte("invalid record"))
1679 }
Adam Langley95c29f32014-06-20 12:00:00 -07001680 return c.handshakeErr
1681}
1682
1683// ConnectionState returns basic TLS details about the connection.
1684func (c *Conn) ConnectionState() ConnectionState {
1685 c.handshakeMutex.Lock()
1686 defer c.handshakeMutex.Unlock()
1687
1688 var state ConnectionState
1689 state.HandshakeComplete = c.handshakeComplete
1690 if c.handshakeComplete {
1691 state.Version = c.vers
1692 state.NegotiatedProtocol = c.clientProtocol
1693 state.DidResume = c.didResume
1694 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001695 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001696 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001697 state.PeerCertificates = c.peerCertificates
1698 state.VerifiedChains = c.verifiedChains
1699 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001700 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001701 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001702 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001703 state.SCTList = c.sctList
Nick Harper60edffd2016-06-21 15:19:24 -07001704 state.PeerSignatureAlgorithm = c.peerSignatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -04001705 state.CurveID = c.curveID
Adam Langley95c29f32014-06-20 12:00:00 -07001706 }
1707
1708 return state
1709}
1710
1711// OCSPResponse returns the stapled OCSP response from the TLS server, if
1712// any. (Only valid for client connections.)
1713func (c *Conn) OCSPResponse() []byte {
1714 c.handshakeMutex.Lock()
1715 defer c.handshakeMutex.Unlock()
1716
1717 return c.ocspResponse
1718}
1719
1720// VerifyHostname checks that the peer certificate chain is valid for
1721// connecting to host. If so, it returns nil; if not, it returns an error
1722// describing the problem.
1723func (c *Conn) VerifyHostname(host string) error {
1724 c.handshakeMutex.Lock()
1725 defer c.handshakeMutex.Unlock()
1726 if !c.isClient {
1727 return errors.New("tls: VerifyHostname called on TLS server connection")
1728 }
1729 if !c.handshakeComplete {
1730 return errors.New("tls: handshake has not yet been performed")
1731 }
1732 return c.peerCertificates[0].VerifyHostname(host)
1733}
David Benjaminc565ebb2015-04-03 04:06:36 -04001734
1735// ExportKeyingMaterial exports keying material from the current connection
1736// state, as per RFC 5705.
1737func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1738 c.handshakeMutex.Lock()
1739 defer c.handshakeMutex.Unlock()
1740 if !c.handshakeComplete {
1741 return nil, errors.New("tls: handshake has not yet been performed")
1742 }
1743
David Benjamin8d315d72016-07-18 01:03:18 +02001744 if c.vers >= VersionTLS13 {
David Benjamin97a0a082016-07-13 17:57:35 -04001745 // TODO(davidben): What should we do with useContext? See
1746 // https://github.com/tlswg/tls13-spec/issues/546
1747 return hkdfExpandLabel(c.cipherSuite.hash(), c.exporterSecret, label, context, length), nil
1748 }
1749
David Benjaminc565ebb2015-04-03 04:06:36 -04001750 seedLen := len(c.clientRandom) + len(c.serverRandom)
1751 if useContext {
1752 seedLen += 2 + len(context)
1753 }
1754 seed := make([]byte, 0, seedLen)
1755 seed = append(seed, c.clientRandom[:]...)
1756 seed = append(seed, c.serverRandom[:]...)
1757 if useContext {
1758 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1759 seed = append(seed, context...)
1760 }
1761 result := make([]byte, length)
David Benjamin97a0a082016-07-13 17:57:35 -04001762 prfForVersion(c.vers, c.cipherSuite)(result, c.exporterSecret, label, seed)
David Benjaminc565ebb2015-04-03 04:06:36 -04001763 return result, nil
1764}
David Benjamin3e052de2015-11-25 20:10:31 -05001765
1766// noRenegotiationInfo returns true if the renegotiation info extension
1767// should be supported in the current handshake.
1768func (c *Conn) noRenegotiationInfo() bool {
1769 if c.config.Bugs.NoRenegotiationInfo {
1770 return true
1771 }
1772 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1773 return true
1774 }
1775 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1776 return true
1777 }
1778 return false
1779}
David Benjamin58104882016-07-18 01:25:41 +02001780
1781func (c *Conn) SendNewSessionTicket() error {
1782 if c.isClient || c.vers < VersionTLS13 {
1783 return errors.New("tls: cannot send post-handshake NewSessionTicket")
1784 }
1785
1786 var peerCertificatesRaw [][]byte
1787 for _, cert := range c.peerCertificates {
1788 peerCertificatesRaw = append(peerCertificatesRaw, cert.Raw)
1789 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001790
Steven Valdeza833c352016-11-01 13:39:36 -04001791 addBuffer := make([]byte, 4)
1792 _, err := io.ReadFull(c.config.rand(), addBuffer)
1793 if err != nil {
1794 c.sendAlert(alertInternalError)
1795 return errors.New("tls: short read from Rand: " + err.Error())
1796 }
1797 ticketAgeAdd := uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0])
1798
David Benjamin58104882016-07-18 01:25:41 +02001799 // TODO(davidben): Allow configuring these values.
1800 m := &newSessionTicketMsg{
David Benjamin9c33ae82017-01-08 06:04:43 -05001801 version: c.vers,
1802 ticketLifetime: uint32(24 * time.Hour / time.Second),
David Benjamin9c33ae82017-01-08 06:04:43 -05001803 duplicateEarlyDataInfo: c.config.Bugs.DuplicateTicketEarlyDataInfo,
1804 customExtension: c.config.Bugs.CustomTicketExtension,
1805 ticketAgeAdd: ticketAgeAdd,
Nick Harperab20cec2016-12-19 17:38:41 -08001806 maxEarlyDataSize: c.config.MaxEarlyDataSize,
David Benjamin58104882016-07-18 01:25:41 +02001807 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001808
David Benjamin17b30832017-01-28 14:00:32 -05001809 if c.config.Bugs.SendTicketLifetime != 0 {
1810 m.ticketLifetime = uint32(c.config.Bugs.SendTicketLifetime / time.Second)
1811 }
1812
Nick Harper0b3625b2016-07-25 16:16:28 -07001813 state := sessionState{
1814 vers: c.vers,
1815 cipherSuite: c.cipherSuite.id,
1816 masterSecret: c.resumptionSecret,
1817 certificates: peerCertificatesRaw,
1818 ticketCreationTime: c.config.time(),
1819 ticketExpiration: c.config.time().Add(time.Duration(m.ticketLifetime) * time.Second),
Steven Valdeza833c352016-11-01 13:39:36 -04001820 ticketAgeAdd: uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0]),
Steven Valdez2d850622017-01-11 11:34:52 -05001821 earlyALPN: []byte(c.clientProtocol),
Nick Harper0b3625b2016-07-25 16:16:28 -07001822 }
1823
David Benjamin58104882016-07-18 01:25:41 +02001824 if !c.config.Bugs.SendEmptySessionTicket {
1825 var err error
1826 m.ticket, err = c.encryptTicket(&state)
1827 if err != nil {
1828 return err
1829 }
1830 }
David Benjamin58104882016-07-18 01:25:41 +02001831 c.out.Lock()
1832 defer c.out.Unlock()
Steven Valdeza833c352016-11-01 13:39:36 -04001833 _, err = c.writeRecord(recordTypeHandshake, m.marshal())
David Benjamin58104882016-07-18 01:25:41 +02001834 return err
1835}
David Benjamin21c00282016-07-18 21:56:23 +02001836
Steven Valdezc4aa7272016-10-03 12:25:56 -04001837func (c *Conn) SendKeyUpdate(keyUpdateRequest byte) error {
David Benjamin21c00282016-07-18 21:56:23 +02001838 c.out.Lock()
1839 defer c.out.Unlock()
Steven Valdezc4aa7272016-10-03 12:25:56 -04001840 return c.sendKeyUpdateLocked(keyUpdateRequest)
David Benjamin21c00282016-07-18 21:56:23 +02001841}
1842
Steven Valdezc4aa7272016-10-03 12:25:56 -04001843func (c *Conn) sendKeyUpdateLocked(keyUpdateRequest byte) error {
David Benjamin7f0965a2016-09-30 15:14:01 -04001844 if c.vers < VersionTLS13 {
1845 return errors.New("tls: attempted to send KeyUpdate before TLS 1.3")
1846 }
1847
Steven Valdezc4aa7272016-10-03 12:25:56 -04001848 m := keyUpdateMsg{
1849 keyUpdateRequest: keyUpdateRequest,
1850 }
David Benjamin21c00282016-07-18 21:56:23 +02001851 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
1852 return err
1853 }
1854 if err := c.flushHandshake(); err != nil {
1855 return err
1856 }
Steven Valdez1dc53d22016-07-26 12:27:38 -04001857 c.out.doKeyUpdate(c, true)
David Benjamin21c00282016-07-18 21:56:23 +02001858 return nil
1859}
Steven Valdeza4ee74d2016-11-29 13:36:45 -05001860
1861func (c *Conn) sendFakeEarlyData(len int) error {
1862 // Assemble a fake early data record. This does not use writeRecord
1863 // because the record layer may be using different keys at this point.
1864 payload := make([]byte, 5+len)
1865 payload[0] = byte(recordTypeApplicationData)
1866 payload[1] = 3
1867 payload[2] = 1
1868 payload[3] = byte(len >> 8)
1869 payload[4] = byte(len)
1870 _, err := c.conn.Write(payload)
1871 return err
1872}