blob: 61fc9d3106df3acc9abef96446d711b5b267c3a1 [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 }
Adam Langley80842bd2014-06-20 12:00:00 -0700919 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700920 if err != nil {
921 c.in.setErrorLocked(c.sendAlert(err.(alert)))
922 }
923
924 case recordTypeApplicationData:
925 if typ != want {
926 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
927 break
928 }
929 c.input = b
930 b = nil
931
932 case recordTypeHandshake:
David Benjamind5a4ecb2016-07-18 01:17:13 +0200933 // Allow handshake data while reading application data to
934 // trigger post-handshake messages.
Adam Langley95c29f32014-06-20 12:00:00 -0700935 // TODO(rsc): Should at least pick off connection close.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200936 if typ != want && want != recordTypeApplicationData {
937 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
Adam Langley95c29f32014-06-20 12:00:00 -0700938 }
939 c.hand.Write(data)
940 }
941
942 if b != nil {
943 c.in.freeBlock(b)
944 }
945 return c.in.err
946}
947
948// sendAlert sends a TLS alert message.
949// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400950func (c *Conn) sendAlertLocked(level byte, err alert) error {
951 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700952 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400953 if c.config.Bugs.FragmentAlert {
954 c.writeRecord(recordTypeAlert, c.tmp[0:1])
955 c.writeRecord(recordTypeAlert, c.tmp[1:2])
David Benjamin0d3a8c62016-03-11 22:25:18 -0500956 } else if c.config.Bugs.DoubleAlert {
957 copy(c.tmp[2:4], c.tmp[0:2])
958 c.writeRecord(recordTypeAlert, c.tmp[0:4])
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400959 } else {
960 c.writeRecord(recordTypeAlert, c.tmp[0:2])
961 }
David Benjamin24f346d2015-06-06 03:28:08 -0400962 // Error alerts are fatal to the connection.
963 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700964 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
965 }
966 return nil
967}
968
969// sendAlert sends a TLS alert message.
970// L < c.out.Mutex.
971func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400972 level := byte(alertLevelError)
Nick Harperf2511f12016-12-06 16:02:31 -0800973 if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertificate || err == alertEndOfEarlyData {
David Benjamin24f346d2015-06-06 03:28:08 -0400974 level = alertLevelWarning
975 }
976 return c.SendAlert(level, err)
977}
978
979func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700980 c.out.Lock()
981 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -0400982 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -0700983}
984
David Benjamind86c7672014-08-02 04:07:12 -0400985// writeV2Record writes a record for a V2ClientHello.
986func (c *Conn) writeV2Record(data []byte) (n int, err error) {
987 record := make([]byte, 2+len(data))
988 record[0] = uint8(len(data)>>8) | 0x80
989 record[1] = uint8(len(data))
990 copy(record[2:], data)
991 return c.conn.Write(record)
992}
993
Adam Langley95c29f32014-06-20 12:00:00 -0700994// writeRecord writes a TLS record with the given type and payload
995// to the connection and updates the record layer state.
996// c.out.Mutex <= L.
997func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjaminebacdee2017-04-08 11:00:45 -0400998 if typ == recordTypeHandshake {
999 msgType := data[0]
1000 if c.config.Bugs.SendWrongMessageType != 0 && msgType == c.config.Bugs.SendWrongMessageType {
1001 msgType += 42
1002 } else if msgType == typeServerHello && c.config.Bugs.SendServerHelloAsHelloRetryRequest {
1003 msgType = typeHelloRetryRequest
1004 }
1005 if msgType != data[0] {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001006 newData := make([]byte, len(data))
1007 copy(newData, data)
David Benjaminebacdee2017-04-08 11:00:45 -04001008 newData[0] = msgType
David Benjamin0b8d5da2016-07-15 00:39:56 -04001009 data = newData
1010 }
1011 }
1012
David Benjamin639846e2016-09-09 11:41:18 -04001013 if msgType := c.config.Bugs.SendTrailingMessageData; msgType != 0 {
1014 if typ == recordTypeHandshake && data[0] == msgType {
1015 newData := make([]byte, len(data))
1016 copy(newData, data)
1017
1018 // Add a 0 to the body.
1019 newData = append(newData, 0)
1020 // Fix the header.
1021 newLen := len(newData) - 4
1022 newData[1] = byte(newLen >> 16)
1023 newData[2] = byte(newLen >> 8)
1024 newData[3] = byte(newLen)
1025
1026 data = newData
1027 }
1028 }
1029
David Benjamin83c0bc92014-08-04 01:23:53 -04001030 if c.isDTLS {
1031 return c.dtlsWriteRecord(typ, data)
1032 }
1033
David Benjamin71dd6662016-07-08 14:10:48 -07001034 if typ == recordTypeHandshake {
1035 if c.config.Bugs.SendHelloRequestBeforeEveryHandshakeMessage {
1036 newData := make([]byte, 0, 4+len(data))
1037 newData = append(newData, typeHelloRequest, 0, 0, 0)
1038 newData = append(newData, data...)
1039 data = newData
1040 }
1041
1042 if c.config.Bugs.PackHandshakeFlight {
1043 c.pendingFlight.Write(data)
1044 return len(data), nil
1045 }
David Benjamin582ba042016-07-07 12:33:25 -07001046 }
1047
1048 return c.doWriteRecord(typ, data)
1049}
1050
1051func (c *Conn) doWriteRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin6f600d62016-12-21 16:06:54 -05001052 recordHeaderLen := c.out.recordHeaderLen()
Adam Langley95c29f32014-06-20 12:00:00 -07001053 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -04001054 first := true
1055 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -04001056 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -07001057 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -04001058 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -07001059 m = maxPlaintext
1060 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001061 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
1062 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -04001063 // By default, do not fragment the client_version or
1064 // server_version, which are located in the first 6
1065 // bytes.
1066 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
1067 m = 6
1068 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001069 }
Adam Langley95c29f32014-06-20 12:00:00 -07001070 explicitIVLen := 0
1071 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -04001072 first = false
Adam Langley95c29f32014-06-20 12:00:00 -07001073
1074 var cbc cbcMode
1075 if c.out.version >= VersionTLS11 {
1076 var ok bool
1077 if cbc, ok = c.out.cipher.(cbcMode); ok {
1078 explicitIVLen = cbc.BlockSize()
1079 }
1080 }
1081 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -04001082 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -07001083 explicitIVLen = 8
1084 // The AES-GCM construction in TLS has an
1085 // explicit nonce so that the nonce can be
1086 // random. However, the nonce is only 8 bytes
1087 // which is too small for a secure, random
1088 // nonce. Therefore we use the sequence number
1089 // as the nonce.
1090 explicitIVIsSeq = true
1091 }
1092 }
1093 b.resize(recordHeaderLen + explicitIVLen + m)
Steven Valdez924a3522017-03-02 16:05:03 -05001094 b.data[0] = byte(typ)
1095 if c.vers >= VersionTLS13 && c.out.cipher != nil {
1096 b.data[0] = byte(recordTypeApplicationData)
1097 if outerType := c.config.Bugs.OuterRecordType; outerType != 0 {
1098 b.data[0] = byte(outerType)
David Benjaminc9ae27c2016-06-24 22:56:37 -04001099 }
Nick Harper1fd39d82016-06-14 18:14:35 -07001100 }
Steven Valdez924a3522017-03-02 16:05:03 -05001101 vers := c.vers
1102 if vers == 0 || vers >= VersionTLS13 {
1103 // Some TLS servers fail if the record version is
1104 // greater than TLS 1.0 for the initial ClientHello.
1105 //
1106 // TLS 1.3 fixes the version number in the record
1107 // layer to {3, 1}.
1108 vers = VersionTLS10
1109 }
1110 if c.config.Bugs.SendRecordVersion != 0 {
1111 vers = c.config.Bugs.SendRecordVersion
1112 }
1113 if c.vers == 0 && c.config.Bugs.SendInitialRecordVersion != 0 {
1114 vers = c.config.Bugs.SendInitialRecordVersion
1115 }
1116 b.data[1] = byte(vers >> 8)
1117 b.data[2] = byte(vers)
1118 b.data[3] = byte(m >> 8)
1119 b.data[4] = byte(m)
Adam Langley95c29f32014-06-20 12:00:00 -07001120 if explicitIVLen > 0 {
1121 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
1122 if explicitIVIsSeq {
1123 copy(explicitIV, c.out.seq[:])
1124 } else {
1125 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
1126 break
1127 }
1128 }
1129 }
1130 copy(b.data[recordHeaderLen+explicitIVLen:], data)
Nick Harper1fd39d82016-06-14 18:14:35 -07001131 c.out.encrypt(b, explicitIVLen, typ)
Adam Langley95c29f32014-06-20 12:00:00 -07001132 _, err = c.conn.Write(b.data)
1133 if err != nil {
1134 break
1135 }
1136 n += m
1137 data = data[m:]
1138 }
1139 c.out.freeBlock(b)
1140
1141 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -07001142 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -07001143 if err != nil {
1144 // Cannot call sendAlert directly,
1145 // because we already hold c.out.Mutex.
1146 c.tmp[0] = alertLevelError
1147 c.tmp[1] = byte(err.(alert))
1148 c.writeRecord(recordTypeAlert, c.tmp[0:2])
1149 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
1150 }
1151 }
1152 return
1153}
1154
David Benjamin582ba042016-07-07 12:33:25 -07001155func (c *Conn) flushHandshake() error {
1156 if c.isDTLS {
1157 return c.dtlsFlushHandshake()
1158 }
1159
1160 for c.pendingFlight.Len() > 0 {
1161 var buf [maxPlaintext]byte
1162 n, _ := c.pendingFlight.Read(buf[:])
1163 if _, err := c.doWriteRecord(recordTypeHandshake, buf[:n]); err != nil {
1164 return err
1165 }
1166 }
1167
1168 c.pendingFlight.Reset()
1169 return nil
1170}
1171
David Benjamin83c0bc92014-08-04 01:23:53 -04001172func (c *Conn) doReadHandshake() ([]byte, error) {
1173 if c.isDTLS {
1174 return c.dtlsDoReadHandshake()
1175 }
1176
Adam Langley95c29f32014-06-20 12:00:00 -07001177 for c.hand.Len() < 4 {
1178 if err := c.in.err; err != nil {
1179 return nil, err
1180 }
1181 if err := c.readRecord(recordTypeHandshake); err != nil {
1182 return nil, err
1183 }
1184 }
1185
1186 data := c.hand.Bytes()
1187 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1188 if n > maxHandshake {
1189 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
1190 }
1191 for c.hand.Len() < 4+n {
1192 if err := c.in.err; err != nil {
1193 return nil, err
1194 }
1195 if err := c.readRecord(recordTypeHandshake); err != nil {
1196 return nil, err
1197 }
1198 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001199 return c.hand.Next(4 + n), nil
1200}
1201
1202// readHandshake reads the next handshake message from
1203// the record layer.
1204// c.in.Mutex < L; c.out.Mutex < L.
1205func (c *Conn) readHandshake() (interface{}, error) {
1206 data, err := c.doReadHandshake()
David Benjamin053fee92017-01-02 08:30:36 -05001207 if err == errNoCertificateAlert {
1208 if c.hand.Len() != 0 {
1209 // The warning alert may not interleave with a handshake message.
1210 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1211 }
1212 return new(ssl3NoCertificateMsg), nil
1213 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001214 if err != nil {
1215 return nil, err
1216 }
1217
Adam Langley95c29f32014-06-20 12:00:00 -07001218 var m handshakeMessage
1219 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001220 case typeHelloRequest:
1221 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001222 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001223 m = &clientHelloMsg{
1224 isDTLS: c.isDTLS,
1225 }
Adam Langley95c29f32014-06-20 12:00:00 -07001226 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001227 m = &serverHelloMsg{
1228 isDTLS: c.isDTLS,
1229 }
Nick Harperdcfbc672016-07-16 17:47:31 +02001230 case typeHelloRetryRequest:
1231 m = new(helloRetryRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001232 case typeNewSessionTicket:
David Benjamin58104882016-07-18 01:25:41 +02001233 m = &newSessionTicketMsg{
1234 version: c.vers,
1235 }
Nick Harperb41d2e42016-07-01 17:50:32 -04001236 case typeEncryptedExtensions:
1237 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001238 case typeCertificate:
Nick Harperb41d2e42016-07-01 17:50:32 -04001239 m = &certificateMsg{
David Benjamin8d315d72016-07-18 01:03:18 +02001240 hasRequestContext: c.vers >= VersionTLS13,
Nick Harperb41d2e42016-07-01 17:50:32 -04001241 }
Adam Langley95c29f32014-06-20 12:00:00 -07001242 case typeCertificateRequest:
1243 m = &certificateRequestMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001244 hasSignatureAlgorithm: c.vers >= VersionTLS12,
David Benjamin8d315d72016-07-18 01:03:18 +02001245 hasRequestContext: c.vers >= VersionTLS13,
Adam Langley95c29f32014-06-20 12:00:00 -07001246 }
1247 case typeCertificateStatus:
1248 m = new(certificateStatusMsg)
1249 case typeServerKeyExchange:
1250 m = new(serverKeyExchangeMsg)
1251 case typeServerHelloDone:
1252 m = new(serverHelloDoneMsg)
1253 case typeClientKeyExchange:
1254 m = new(clientKeyExchangeMsg)
1255 case typeCertificateVerify:
1256 m = &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001257 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001258 }
1259 case typeNextProtocol:
1260 m = new(nextProtoMsg)
1261 case typeFinished:
1262 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001263 case typeHelloVerifyRequest:
1264 m = new(helloVerifyRequestMsg)
David Benjamin24599a82016-06-30 18:56:53 -04001265 case typeChannelID:
1266 m = new(channelIDMsg)
David Benjamin21c00282016-07-18 21:56:23 +02001267 case typeKeyUpdate:
1268 m = new(keyUpdateMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001269 default:
1270 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1271 }
1272
1273 // The handshake message unmarshallers
1274 // expect to be able to keep references to data,
1275 // so pass in a fresh copy that won't be overwritten.
1276 data = append([]byte(nil), data...)
1277
1278 if !m.unmarshal(data) {
1279 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1280 }
1281 return m, nil
1282}
1283
David Benjamin83f90402015-01-27 01:09:43 -05001284// skipPacket processes all the DTLS records in packet. It updates
1285// sequence number expectations but otherwise ignores them.
1286func (c *Conn) skipPacket(packet []byte) error {
1287 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001288 if len(packet) < 13 {
1289 return errors.New("tls: bad packet")
1290 }
David Benjamin83f90402015-01-27 01:09:43 -05001291 // Dropped packets are completely ignored save to update
1292 // expected sequence numbers for this and the next epoch. (We
1293 // don't assert on the contents of the packets both for
1294 // simplicity and because a previous test with one shorter
1295 // timeout schedule would have done so.)
1296 epoch := packet[3:5]
1297 seq := packet[5:11]
1298 length := uint16(packet[11])<<8 | uint16(packet[12])
1299 if bytes.Equal(c.in.seq[:2], epoch) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001300 if bytes.Compare(seq, c.in.seq[2:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001301 return errors.New("tls: sequence mismatch")
1302 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001303 copy(c.in.seq[2:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001304 c.in.incSeq(false)
1305 } else {
David Benjamin13e81fc2015-11-02 17:16:13 -05001306 if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001307 return errors.New("tls: sequence mismatch")
1308 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001309 copy(c.in.nextSeq[:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001310 c.in.incNextSeq()
1311 }
David Benjamin6ca93552015-08-28 16:16:25 -04001312 if len(packet) < 13+int(length) {
1313 return errors.New("tls: bad packet")
1314 }
David Benjamin83f90402015-01-27 01:09:43 -05001315 packet = packet[13+length:]
1316 }
1317 return nil
1318}
1319
1320// simulatePacketLoss simulates the loss of a handshake leg from the
1321// peer based on the schedule in c.config.Bugs. If resendFunc is
1322// non-nil, it is called after each simulated timeout to retransmit
1323// handshake messages from the local end. This is used in cases where
1324// the peer retransmits on a stale Finished rather than a timeout.
1325func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1326 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1327 return nil
1328 }
1329 if !c.isDTLS {
1330 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1331 }
1332 if c.config.Bugs.PacketAdaptor == nil {
1333 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1334 }
1335 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1336 // Simulate a timeout.
1337 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1338 if err != nil {
1339 return err
1340 }
1341 for _, packet := range packets {
1342 if err := c.skipPacket(packet); err != nil {
1343 return err
1344 }
1345 }
1346 if resendFunc != nil {
1347 resendFunc()
1348 }
1349 }
1350 return nil
1351}
1352
David Benjamin47921102016-07-28 11:29:18 -04001353func (c *Conn) SendHalfHelloRequest() error {
1354 if err := c.Handshake(); err != nil {
1355 return err
1356 }
1357
1358 c.out.Lock()
1359 defer c.out.Unlock()
1360
1361 if _, err := c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0}); err != nil {
1362 return err
1363 }
1364 return c.flushHandshake()
1365}
1366
Adam Langley95c29f32014-06-20 12:00:00 -07001367// Write writes data to the connection.
1368func (c *Conn) Write(b []byte) (int, error) {
1369 if err := c.Handshake(); err != nil {
1370 return 0, err
1371 }
1372
1373 c.out.Lock()
1374 defer c.out.Unlock()
1375
David Benjamin12d2c482016-07-24 10:56:51 -04001376 // Flush any pending handshake data. PackHelloRequestWithFinished may
1377 // have been set and the handshake not followed by Renegotiate.
1378 c.flushHandshake()
1379
Adam Langley95c29f32014-06-20 12:00:00 -07001380 if err := c.out.err; err != nil {
1381 return 0, err
1382 }
1383
1384 if !c.handshakeComplete {
1385 return 0, alertInternalError
1386 }
1387
Steven Valdezc4aa7272016-10-03 12:25:56 -04001388 if c.keyUpdateRequested {
1389 if err := c.sendKeyUpdateLocked(keyUpdateNotRequested); err != nil {
David Benjamin21c00282016-07-18 21:56:23 +02001390 return 0, err
1391 }
Steven Valdezc4aa7272016-10-03 12:25:56 -04001392 c.keyUpdateRequested = false
David Benjamin21c00282016-07-18 21:56:23 +02001393 }
1394
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001395 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001396 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001397 }
1398
Adam Langley27a0d082015-11-03 13:34:10 -08001399 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1400 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
David Benjamin582ba042016-07-07 12:33:25 -07001401 c.flushHandshake()
Adam Langley27a0d082015-11-03 13:34:10 -08001402 }
1403
Adam Langley95c29f32014-06-20 12:00:00 -07001404 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1405 // attack when using block mode ciphers due to predictable IVs.
1406 // This can be prevented by splitting each Application Data
1407 // record into two records, effectively randomizing the IV.
1408 //
1409 // http://www.openssl.org/~bodo/tls-cbc.txt
1410 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1411 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1412
1413 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001414 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001415 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1416 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1417 if err != nil {
1418 return n, c.out.setErrorLocked(err)
1419 }
1420 m, b = 1, b[1:]
1421 }
1422 }
1423
1424 n, err := c.writeRecord(recordTypeApplicationData, b)
1425 return n + m, c.out.setErrorLocked(err)
1426}
1427
David Benjamin794cc592017-03-25 22:24:23 -05001428func (c *Conn) processTLS13NewSessionTicket(newSessionTicket *newSessionTicketMsg, cipherSuite *cipherSuite) error {
1429 if c.config.Bugs.ExpectGREASE && !newSessionTicket.hasGREASEExtension {
1430 return errors.New("tls: no GREASE ticket extension found")
1431 }
1432
1433 if c.config.Bugs.ExpectTicketEarlyDataInfo && newSessionTicket.maxEarlyDataSize == 0 {
1434 return errors.New("tls: no ticket_early_data_info extension found")
1435 }
1436
1437 if c.config.Bugs.ExpectNoNewSessionTicket {
1438 return errors.New("tls: received unexpected NewSessionTicket")
1439 }
1440
1441 if c.config.ClientSessionCache == nil || newSessionTicket.ticketLifetime == 0 {
1442 return nil
1443 }
1444
1445 session := &ClientSessionState{
1446 sessionTicket: newSessionTicket.ticket,
1447 vers: c.vers,
1448 cipherSuite: cipherSuite.id,
1449 masterSecret: c.resumptionSecret,
1450 serverCertificates: c.peerCertificates,
1451 sctList: c.sctList,
1452 ocspResponse: c.ocspResponse,
1453 ticketCreationTime: c.config.time(),
1454 ticketExpiration: c.config.time().Add(time.Duration(newSessionTicket.ticketLifetime) * time.Second),
1455 ticketAgeAdd: newSessionTicket.ticketAgeAdd,
1456 maxEarlyDataSize: newSessionTicket.maxEarlyDataSize,
1457 earlyALPN: c.clientProtocol,
1458 }
1459
1460 cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
1461 c.config.ClientSessionCache.Put(cacheKey, session)
1462 return nil
1463}
1464
David Benjamind5a4ecb2016-07-18 01:17:13 +02001465func (c *Conn) handlePostHandshakeMessage() error {
Adam Langley2ae77d22014-10-28 17:29:33 -07001466 msg, err := c.readHandshake()
1467 if err != nil {
1468 return err
1469 }
David Benjamind5a4ecb2016-07-18 01:17:13 +02001470
1471 if c.vers < VersionTLS13 {
1472 if !c.isClient {
1473 c.sendAlert(alertUnexpectedMessage)
1474 return errors.New("tls: unexpected post-handshake message")
1475 }
1476
1477 _, ok := msg.(*helloRequestMsg)
1478 if !ok {
1479 c.sendAlert(alertUnexpectedMessage)
1480 return alertUnexpectedMessage
1481 }
1482
1483 c.handshakeComplete = false
1484 return c.Handshake()
Adam Langley2ae77d22014-10-28 17:29:33 -07001485 }
1486
David Benjamind5a4ecb2016-07-18 01:17:13 +02001487 if c.isClient {
1488 if newSessionTicket, ok := msg.(*newSessionTicketMsg); ok {
David Benjamin794cc592017-03-25 22:24:23 -05001489 return c.processTLS13NewSessionTicket(newSessionTicket, c.cipherSuite)
David Benjamind5a4ecb2016-07-18 01:17:13 +02001490 }
1491 }
1492
Steven Valdezc4aa7272016-10-03 12:25:56 -04001493 if keyUpdate, ok := msg.(*keyUpdateMsg); ok {
David Benjaminbbba9392017-04-06 12:54:12 -04001494 if c.config.Bugs.RejectUnsolicitedKeyUpdate {
1495 return errors.New("tls: unexpected KeyUpdate message")
1496 }
Steven Valdez1dc53d22016-07-26 12:27:38 -04001497 c.in.doKeyUpdate(c, false)
Steven Valdezc4aa7272016-10-03 12:25:56 -04001498 if keyUpdate.keyUpdateRequest == keyUpdateRequested {
1499 c.keyUpdateRequested = true
1500 }
David Benjamin21c00282016-07-18 21:56:23 +02001501 return nil
1502 }
1503
David Benjamind5a4ecb2016-07-18 01:17:13 +02001504 c.sendAlert(alertUnexpectedMessage)
David Benjaminbbba9392017-04-06 12:54:12 -04001505 return errors.New("tls: unexpected post-handshake message")
1506}
1507
1508// Reads a KeyUpdate acknowledgment from the peer. There may not be any
1509// application data records before the message.
1510func (c *Conn) ReadKeyUpdateACK() error {
1511 c.in.Lock()
1512 defer c.in.Unlock()
1513
1514 msg, err := c.readHandshake()
1515 if err != nil {
1516 return err
1517 }
1518
1519 keyUpdate, ok := msg.(*keyUpdateMsg)
1520 if !ok {
1521 c.sendAlert(alertUnexpectedMessage)
1522 return errors.New("tls: unexpected message when reading KeyUpdate")
1523 }
1524
1525 if keyUpdate.keyUpdateRequest != keyUpdateNotRequested {
1526 return errors.New("tls: received invalid KeyUpdate message")
1527 }
1528
1529 c.in.doKeyUpdate(c, false)
1530 return nil
Adam Langley2ae77d22014-10-28 17:29:33 -07001531}
1532
Adam Langleycf2d4f42014-10-28 19:06:14 -07001533func (c *Conn) Renegotiate() error {
1534 if !c.isClient {
David Benjaminef5dfd22015-12-06 13:17:07 -05001535 helloReq := new(helloRequestMsg).marshal()
1536 if c.config.Bugs.BadHelloRequest != nil {
1537 helloReq = c.config.Bugs.BadHelloRequest
1538 }
1539 c.writeRecord(recordTypeHandshake, helloReq)
David Benjamin582ba042016-07-07 12:33:25 -07001540 c.flushHandshake()
Adam Langleycf2d4f42014-10-28 19:06:14 -07001541 }
1542
1543 c.handshakeComplete = false
1544 return c.Handshake()
1545}
1546
Adam Langley95c29f32014-06-20 12:00:00 -07001547// Read can be made to time out and return a net.Error with Timeout() == true
1548// after a fixed time limit; see SetDeadline and SetReadDeadline.
1549func (c *Conn) Read(b []byte) (n int, err error) {
1550 if err = c.Handshake(); err != nil {
1551 return
1552 }
1553
1554 c.in.Lock()
1555 defer c.in.Unlock()
1556
1557 // Some OpenSSL servers send empty records in order to randomize the
1558 // CBC IV. So this loop ignores a limited number of empty records.
1559 const maxConsecutiveEmptyRecords = 100
1560 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1561 for c.input == nil && c.in.err == nil {
1562 if err := c.readRecord(recordTypeApplicationData); err != nil {
1563 // Soft error, like EAGAIN
1564 return 0, err
1565 }
David Benjamind9b091b2015-01-27 01:10:54 -05001566 if c.hand.Len() > 0 {
David Benjamind5a4ecb2016-07-18 01:17:13 +02001567 // We received handshake bytes, indicating a
1568 // post-handshake message.
1569 if err := c.handlePostHandshakeMessage(); err != nil {
Adam Langley2ae77d22014-10-28 17:29:33 -07001570 return 0, err
1571 }
1572 continue
1573 }
Adam Langley95c29f32014-06-20 12:00:00 -07001574 }
1575 if err := c.in.err; err != nil {
1576 return 0, err
1577 }
1578
1579 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001580 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001581 c.in.freeBlock(c.input)
1582 c.input = nil
1583 }
1584
1585 // If a close-notify alert is waiting, read it so that
1586 // we can return (n, EOF) instead of (n, nil), to signal
1587 // to the HTTP response reading goroutine that the
1588 // connection is now closed. This eliminates a race
1589 // where the HTTP response reading goroutine would
1590 // otherwise not observe the EOF until its next read,
1591 // by which time a client goroutine might have already
1592 // tried to reuse the HTTP connection for a new
1593 // request.
1594 // See https://codereview.appspot.com/76400046
1595 // and http://golang.org/issue/3514
1596 if ri := c.rawInput; ri != nil &&
1597 n != 0 && err == nil &&
1598 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1599 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1600 err = recErr // will be io.EOF on closeNotify
1601 }
1602 }
1603
1604 if n != 0 || err != nil {
1605 return n, err
1606 }
1607 }
1608
1609 return 0, io.ErrNoProgress
1610}
1611
1612// Close closes the connection.
1613func (c *Conn) Close() error {
1614 var alertErr error
1615
1616 c.handshakeMutex.Lock()
1617 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001618 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
David Benjaminfa214e42016-05-10 17:03:10 -04001619 alert := alertCloseNotify
1620 if c.config.Bugs.SendAlertOnShutdown != 0 {
1621 alert = c.config.Bugs.SendAlertOnShutdown
1622 }
1623 alertErr = c.sendAlert(alert)
David Benjamin4d559612016-05-18 14:31:51 -04001624 // Clear local alerts when sending alerts so we continue to wait
1625 // for the peer rather than closing the socket early.
1626 if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1627 alertErr = nil
1628 }
Adam Langley95c29f32014-06-20 12:00:00 -07001629 }
1630
David Benjamin30789da2015-08-29 22:56:45 -04001631 // Consume a close_notify from the peer if one hasn't been received
1632 // already. This avoids the peer from failing |SSL_shutdown| due to a
1633 // write failing.
1634 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1635 for c.in.error() == nil {
1636 c.readRecord(recordTypeAlert)
1637 }
1638 if c.in.error() != io.EOF {
1639 alertErr = c.in.error()
1640 }
1641 }
1642
Adam Langley95c29f32014-06-20 12:00:00 -07001643 if err := c.conn.Close(); err != nil {
1644 return err
1645 }
1646 return alertErr
1647}
1648
1649// Handshake runs the client or server handshake
1650// protocol if it has not yet been run.
1651// Most uses of this package need not call Handshake
1652// explicitly: the first Read or Write will call it automatically.
1653func (c *Conn) Handshake() error {
1654 c.handshakeMutex.Lock()
1655 defer c.handshakeMutex.Unlock()
1656 if err := c.handshakeErr; err != nil {
1657 return err
1658 }
1659 if c.handshakeComplete {
1660 return nil
1661 }
1662
David Benjamin9a41d1b2015-05-16 01:30:09 -04001663 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1664 c.conn.Write([]byte{
1665 byte(recordTypeAlert), // type
1666 0xfe, 0xff, // version
1667 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1668 0x0, 0x2, // length
1669 })
1670 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1671 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001672 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1673 c.writeRecord(recordTypeApplicationData, data)
1674 }
Adam Langley95c29f32014-06-20 12:00:00 -07001675 if c.isClient {
1676 c.handshakeErr = c.clientHandshake()
1677 } else {
1678 c.handshakeErr = c.serverHandshake()
1679 }
David Benjaminddb9f152015-02-03 15:44:39 -05001680 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1681 c.writeRecord(recordType(42), []byte("invalid record"))
1682 }
Adam Langley95c29f32014-06-20 12:00:00 -07001683 return c.handshakeErr
1684}
1685
1686// ConnectionState returns basic TLS details about the connection.
1687func (c *Conn) ConnectionState() ConnectionState {
1688 c.handshakeMutex.Lock()
1689 defer c.handshakeMutex.Unlock()
1690
1691 var state ConnectionState
1692 state.HandshakeComplete = c.handshakeComplete
1693 if c.handshakeComplete {
1694 state.Version = c.vers
1695 state.NegotiatedProtocol = c.clientProtocol
1696 state.DidResume = c.didResume
1697 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001698 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001699 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001700 state.PeerCertificates = c.peerCertificates
1701 state.VerifiedChains = c.verifiedChains
1702 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001703 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001704 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001705 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001706 state.SCTList = c.sctList
Nick Harper60edffd2016-06-21 15:19:24 -07001707 state.PeerSignatureAlgorithm = c.peerSignatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -04001708 state.CurveID = c.curveID
Adam Langley95c29f32014-06-20 12:00:00 -07001709 }
1710
1711 return state
1712}
1713
1714// OCSPResponse returns the stapled OCSP response from the TLS server, if
1715// any. (Only valid for client connections.)
1716func (c *Conn) OCSPResponse() []byte {
1717 c.handshakeMutex.Lock()
1718 defer c.handshakeMutex.Unlock()
1719
1720 return c.ocspResponse
1721}
1722
1723// VerifyHostname checks that the peer certificate chain is valid for
1724// connecting to host. If so, it returns nil; if not, it returns an error
1725// describing the problem.
1726func (c *Conn) VerifyHostname(host string) error {
1727 c.handshakeMutex.Lock()
1728 defer c.handshakeMutex.Unlock()
1729 if !c.isClient {
1730 return errors.New("tls: VerifyHostname called on TLS server connection")
1731 }
1732 if !c.handshakeComplete {
1733 return errors.New("tls: handshake has not yet been performed")
1734 }
1735 return c.peerCertificates[0].VerifyHostname(host)
1736}
David Benjaminc565ebb2015-04-03 04:06:36 -04001737
1738// ExportKeyingMaterial exports keying material from the current connection
1739// state, as per RFC 5705.
1740func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1741 c.handshakeMutex.Lock()
1742 defer c.handshakeMutex.Unlock()
1743 if !c.handshakeComplete {
1744 return nil, errors.New("tls: handshake has not yet been performed")
1745 }
1746
David Benjamin8d315d72016-07-18 01:03:18 +02001747 if c.vers >= VersionTLS13 {
David Benjamin97a0a082016-07-13 17:57:35 -04001748 // TODO(davidben): What should we do with useContext? See
1749 // https://github.com/tlswg/tls13-spec/issues/546
1750 return hkdfExpandLabel(c.cipherSuite.hash(), c.exporterSecret, label, context, length), nil
1751 }
1752
David Benjaminc565ebb2015-04-03 04:06:36 -04001753 seedLen := len(c.clientRandom) + len(c.serverRandom)
1754 if useContext {
1755 seedLen += 2 + len(context)
1756 }
1757 seed := make([]byte, 0, seedLen)
1758 seed = append(seed, c.clientRandom[:]...)
1759 seed = append(seed, c.serverRandom[:]...)
1760 if useContext {
1761 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1762 seed = append(seed, context...)
1763 }
1764 result := make([]byte, length)
David Benjamin97a0a082016-07-13 17:57:35 -04001765 prfForVersion(c.vers, c.cipherSuite)(result, c.exporterSecret, label, seed)
David Benjaminc565ebb2015-04-03 04:06:36 -04001766 return result, nil
1767}
David Benjamin3e052de2015-11-25 20:10:31 -05001768
1769// noRenegotiationInfo returns true if the renegotiation info extension
1770// should be supported in the current handshake.
1771func (c *Conn) noRenegotiationInfo() bool {
1772 if c.config.Bugs.NoRenegotiationInfo {
1773 return true
1774 }
1775 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1776 return true
1777 }
1778 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1779 return true
1780 }
1781 return false
1782}
David Benjamin58104882016-07-18 01:25:41 +02001783
1784func (c *Conn) SendNewSessionTicket() error {
1785 if c.isClient || c.vers < VersionTLS13 {
1786 return errors.New("tls: cannot send post-handshake NewSessionTicket")
1787 }
1788
1789 var peerCertificatesRaw [][]byte
1790 for _, cert := range c.peerCertificates {
1791 peerCertificatesRaw = append(peerCertificatesRaw, cert.Raw)
1792 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001793
Steven Valdeza833c352016-11-01 13:39:36 -04001794 addBuffer := make([]byte, 4)
1795 _, err := io.ReadFull(c.config.rand(), addBuffer)
1796 if err != nil {
1797 c.sendAlert(alertInternalError)
1798 return errors.New("tls: short read from Rand: " + err.Error())
1799 }
1800 ticketAgeAdd := uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0])
1801
David Benjamin58104882016-07-18 01:25:41 +02001802 // TODO(davidben): Allow configuring these values.
1803 m := &newSessionTicketMsg{
David Benjamin9c33ae82017-01-08 06:04:43 -05001804 version: c.vers,
1805 ticketLifetime: uint32(24 * time.Hour / time.Second),
David Benjamin9c33ae82017-01-08 06:04:43 -05001806 duplicateEarlyDataInfo: c.config.Bugs.DuplicateTicketEarlyDataInfo,
1807 customExtension: c.config.Bugs.CustomTicketExtension,
1808 ticketAgeAdd: ticketAgeAdd,
Nick Harperab20cec2016-12-19 17:38:41 -08001809 maxEarlyDataSize: c.config.MaxEarlyDataSize,
David Benjamin58104882016-07-18 01:25:41 +02001810 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001811
David Benjamin17b30832017-01-28 14:00:32 -05001812 if c.config.Bugs.SendTicketLifetime != 0 {
1813 m.ticketLifetime = uint32(c.config.Bugs.SendTicketLifetime / time.Second)
1814 }
1815
Nick Harper0b3625b2016-07-25 16:16:28 -07001816 state := sessionState{
1817 vers: c.vers,
1818 cipherSuite: c.cipherSuite.id,
1819 masterSecret: c.resumptionSecret,
1820 certificates: peerCertificatesRaw,
1821 ticketCreationTime: c.config.time(),
1822 ticketExpiration: c.config.time().Add(time.Duration(m.ticketLifetime) * time.Second),
Steven Valdeza833c352016-11-01 13:39:36 -04001823 ticketAgeAdd: uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0]),
Steven Valdez2d850622017-01-11 11:34:52 -05001824 earlyALPN: []byte(c.clientProtocol),
Nick Harper0b3625b2016-07-25 16:16:28 -07001825 }
1826
David Benjamin58104882016-07-18 01:25:41 +02001827 if !c.config.Bugs.SendEmptySessionTicket {
1828 var err error
1829 m.ticket, err = c.encryptTicket(&state)
1830 if err != nil {
1831 return err
1832 }
1833 }
David Benjamin58104882016-07-18 01:25:41 +02001834 c.out.Lock()
1835 defer c.out.Unlock()
Steven Valdeza833c352016-11-01 13:39:36 -04001836 _, err = c.writeRecord(recordTypeHandshake, m.marshal())
David Benjamin58104882016-07-18 01:25:41 +02001837 return err
1838}
David Benjamin21c00282016-07-18 21:56:23 +02001839
Steven Valdezc4aa7272016-10-03 12:25:56 -04001840func (c *Conn) SendKeyUpdate(keyUpdateRequest byte) error {
David Benjamin21c00282016-07-18 21:56:23 +02001841 c.out.Lock()
1842 defer c.out.Unlock()
Steven Valdezc4aa7272016-10-03 12:25:56 -04001843 return c.sendKeyUpdateLocked(keyUpdateRequest)
David Benjamin21c00282016-07-18 21:56:23 +02001844}
1845
Steven Valdezc4aa7272016-10-03 12:25:56 -04001846func (c *Conn) sendKeyUpdateLocked(keyUpdateRequest byte) error {
David Benjamin7f0965a2016-09-30 15:14:01 -04001847 if c.vers < VersionTLS13 {
1848 return errors.New("tls: attempted to send KeyUpdate before TLS 1.3")
1849 }
1850
Steven Valdezc4aa7272016-10-03 12:25:56 -04001851 m := keyUpdateMsg{
1852 keyUpdateRequest: keyUpdateRequest,
1853 }
David Benjamin21c00282016-07-18 21:56:23 +02001854 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
1855 return err
1856 }
1857 if err := c.flushHandshake(); err != nil {
1858 return err
1859 }
Steven Valdez1dc53d22016-07-26 12:27:38 -04001860 c.out.doKeyUpdate(c, true)
David Benjamin21c00282016-07-18 21:56:23 +02001861 return nil
1862}
Steven Valdeza4ee74d2016-11-29 13:36:45 -05001863
1864func (c *Conn) sendFakeEarlyData(len int) error {
1865 // Assemble a fake early data record. This does not use writeRecord
1866 // because the record layer may be using different keys at this point.
1867 payload := make([]byte, 5+len)
1868 payload[0] = byte(recordTypeApplicationData)
1869 payload[1] = 3
1870 payload[2] = 1
1871 payload[3] = byte(len >> 8)
1872 payload[4] = byte(len)
1873 _, err := c.conn.Write(payload)
1874 return err
1875}