blob: 615e2248e8eeab2fb5e49f7b728238f373d75947 [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
David Benjamin09ed1192017-07-14 20:11:07 -0400101 seenOneByteRecord bool
Steven Valdezc4aa7272016-10-03 12:25:56 -0400102
Adam Langley95c29f32014-06-20 12:00:00 -0700103 tmp [16]byte
104}
105
David Benjamin5e961c12014-11-07 01:48:35 -0500106func (c *Conn) init() {
107 c.in.isDTLS = c.isDTLS
108 c.out.isDTLS = c.isDTLS
109 c.in.config = c.config
110 c.out.config = c.config
David Benjamin8e6db492015-07-25 18:29:23 -0400111
112 c.out.updateOutSeq()
David Benjamin5e961c12014-11-07 01:48:35 -0500113}
114
Adam Langley95c29f32014-06-20 12:00:00 -0700115// Access to net.Conn methods.
116// Cannot just embed net.Conn because that would
117// export the struct field too.
118
119// LocalAddr returns the local network address.
120func (c *Conn) LocalAddr() net.Addr {
121 return c.conn.LocalAddr()
122}
123
124// RemoteAddr returns the remote network address.
125func (c *Conn) RemoteAddr() net.Addr {
126 return c.conn.RemoteAddr()
127}
128
129// SetDeadline sets the read and write deadlines associated with the connection.
130// A zero value for t means Read and Write will not time out.
131// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
132func (c *Conn) SetDeadline(t time.Time) error {
133 return c.conn.SetDeadline(t)
134}
135
136// SetReadDeadline sets the read deadline on the underlying connection.
137// A zero value for t means Read will not time out.
138func (c *Conn) SetReadDeadline(t time.Time) error {
139 return c.conn.SetReadDeadline(t)
140}
141
142// SetWriteDeadline sets the write deadline on the underlying conneciton.
143// A zero value for t means Write will not time out.
144// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
145func (c *Conn) SetWriteDeadline(t time.Time) error {
146 return c.conn.SetWriteDeadline(t)
147}
148
149// A halfConn represents one direction of the record layer
150// connection, either sending or receiving.
151type halfConn struct {
152 sync.Mutex
153
David Benjamin83c0bc92014-08-04 01:23:53 -0400154 err error // first permanent error
155 version uint16 // protocol version
156 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -0700157 cipher interface{} // cipher algorithm
158 mac macFunction
159 seq [8]byte // 64-bit sequence number
David Benjamin8e6db492015-07-25 18:29:23 -0400160 outSeq [8]byte // Mapped sequence number
Adam Langley95c29f32014-06-20 12:00:00 -0700161 bfree *block // list of free blocks
162
163 nextCipher interface{} // next encryption state
164 nextMac macFunction // next MAC algorithm
David Benjamin83f90402015-01-27 01:09:43 -0500165 nextSeq [6]byte // next epoch's starting sequence number in DTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700166
167 // used to save allocating a new buffer for each MAC.
168 inDigestBuf, outDigestBuf []byte
Adam Langley80842bd2014-06-20 12:00:00 -0700169
Steven Valdezc4aa7272016-10-03 12:25:56 -0400170 trafficSecret []byte
David Benjamin21c00282016-07-18 21:56:23 +0200171
Adam Langley80842bd2014-06-20 12:00:00 -0700172 config *Config
Adam Langley95c29f32014-06-20 12:00:00 -0700173}
174
175func (hc *halfConn) setErrorLocked(err error) error {
176 hc.err = err
177 return err
178}
179
180func (hc *halfConn) error() error {
Adam Langley2ae77d22014-10-28 17:29:33 -0700181 // This should be locked, but I've removed it for the renegotiation
182 // tests since we don't concurrently read and write the same tls.Conn
183 // in any case during testing.
Adam Langley95c29f32014-06-20 12:00:00 -0700184 err := hc.err
Adam Langley95c29f32014-06-20 12:00:00 -0700185 return err
186}
187
188// prepareCipherSpec sets the encryption and MAC states
189// that a subsequent changeCipherSpec will use.
190func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
191 hc.version = version
192 hc.nextCipher = cipher
193 hc.nextMac = mac
194}
195
196// changeCipherSpec changes the encryption and MAC states
197// to the ones previously passed to prepareCipherSpec.
Adam Langley80842bd2014-06-20 12:00:00 -0700198func (hc *halfConn) changeCipherSpec(config *Config) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700199 if hc.nextCipher == nil {
200 return alertInternalError
201 }
202 hc.cipher = hc.nextCipher
203 hc.mac = hc.nextMac
204 hc.nextCipher = nil
205 hc.nextMac = nil
Adam Langley80842bd2014-06-20 12:00:00 -0700206 hc.config = config
David Benjamin83c0bc92014-08-04 01:23:53 -0400207 hc.incEpoch()
David Benjaminf2b83632016-03-01 22:57:46 -0500208
209 if config.Bugs.NullAllCiphers {
David Benjamin7a4aaa42016-09-20 17:58:14 -0400210 hc.cipher = nullCipher{}
David Benjaminf2b83632016-03-01 22:57:46 -0500211 hc.mac = nil
212 }
Adam Langley95c29f32014-06-20 12:00:00 -0700213 return nil
214}
215
David Benjamin21c00282016-07-18 21:56:23 +0200216// useTrafficSecret sets the current cipher state for TLS 1.3.
Steven Valdeza833c352016-11-01 13:39:36 -0400217func (hc *halfConn) useTrafficSecret(version uint16, suite *cipherSuite, secret []byte, side trafficDirection) {
Nick Harperb41d2e42016-07-01 17:50:32 -0400218 hc.version = version
Steven Valdeza833c352016-11-01 13:39:36 -0400219 hc.cipher = deriveTrafficAEAD(version, suite, secret, side)
David Benjamin7a4aaa42016-09-20 17:58:14 -0400220 if hc.config.Bugs.NullAllCiphers {
221 hc.cipher = nullCipher{}
222 }
David Benjamin21c00282016-07-18 21:56:23 +0200223 hc.trafficSecret = secret
Nick Harperb41d2e42016-07-01 17:50:32 -0400224 hc.incEpoch()
225}
226
Nick Harperf2511f12016-12-06 16:02:31 -0800227// resetCipher changes the cipher state back to no encryption to be able
228// to send an unencrypted ClientHello in response to HelloRetryRequest
229// after 0-RTT data was rejected.
230func (hc *halfConn) resetCipher() {
231 hc.cipher = nil
232 hc.incEpoch()
233}
234
David Benjamin21c00282016-07-18 21:56:23 +0200235func (hc *halfConn) doKeyUpdate(c *Conn, isOutgoing bool) {
236 side := serverWrite
237 if c.isClient == isOutgoing {
238 side = clientWrite
239 }
Steven Valdeza833c352016-11-01 13:39:36 -0400240 hc.useTrafficSecret(hc.version, c.cipherSuite, updateTrafficSecret(c.cipherSuite.hash(), hc.trafficSecret), side)
David Benjamin21c00282016-07-18 21:56:23 +0200241}
242
Adam Langley95c29f32014-06-20 12:00:00 -0700243// incSeq increments the sequence number.
David Benjamin5e961c12014-11-07 01:48:35 -0500244func (hc *halfConn) incSeq(isOutgoing bool) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400245 limit := 0
David Benjamin5e961c12014-11-07 01:48:35 -0500246 increment := uint64(1)
David Benjamin83c0bc92014-08-04 01:23:53 -0400247 if hc.isDTLS {
248 // Increment up to the epoch in DTLS.
249 limit = 2
250 }
251 for i := 7; i >= limit; i-- {
David Benjamin5e961c12014-11-07 01:48:35 -0500252 increment += uint64(hc.seq[i])
253 hc.seq[i] = byte(increment)
254 increment >>= 8
Adam Langley95c29f32014-06-20 12:00:00 -0700255 }
256
257 // Not allowed to let sequence number wrap.
258 // Instead, must renegotiate before it does.
259 // Not likely enough to bother.
David Benjamin5e961c12014-11-07 01:48:35 -0500260 if increment != 0 {
261 panic("TLS: sequence number wraparound")
262 }
David Benjamin8e6db492015-07-25 18:29:23 -0400263
264 hc.updateOutSeq()
Adam Langley95c29f32014-06-20 12:00:00 -0700265}
266
David Benjamin83f90402015-01-27 01:09:43 -0500267// incNextSeq increments the starting sequence number for the next epoch.
268func (hc *halfConn) incNextSeq() {
269 for i := len(hc.nextSeq) - 1; i >= 0; i-- {
270 hc.nextSeq[i]++
271 if hc.nextSeq[i] != 0 {
272 return
273 }
274 }
275 panic("TLS: sequence number wraparound")
276}
277
278// incEpoch resets the sequence number. In DTLS, it also increments the epoch
279// half of the sequence number.
David Benjamin83c0bc92014-08-04 01:23:53 -0400280func (hc *halfConn) incEpoch() {
David Benjamin83c0bc92014-08-04 01:23:53 -0400281 if hc.isDTLS {
282 for i := 1; i >= 0; i-- {
283 hc.seq[i]++
284 if hc.seq[i] != 0 {
285 break
286 }
287 if i == 0 {
288 panic("TLS: epoch number wraparound")
289 }
290 }
David Benjamin83f90402015-01-27 01:09:43 -0500291 copy(hc.seq[2:], hc.nextSeq[:])
292 for i := range hc.nextSeq {
293 hc.nextSeq[i] = 0
294 }
295 } else {
296 for i := range hc.seq {
297 hc.seq[i] = 0
298 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400299 }
David Benjamin8e6db492015-07-25 18:29:23 -0400300
301 hc.updateOutSeq()
302}
303
304func (hc *halfConn) updateOutSeq() {
305 if hc.config.Bugs.SequenceNumberMapping != nil {
306 seqU64 := binary.BigEndian.Uint64(hc.seq[:])
307 seqU64 = hc.config.Bugs.SequenceNumberMapping(seqU64)
308 binary.BigEndian.PutUint64(hc.outSeq[:], seqU64)
309
310 // The DTLS epoch cannot be changed.
311 copy(hc.outSeq[:2], hc.seq[:2])
312 return
313 }
314
315 copy(hc.outSeq[:], hc.seq[:])
David Benjamin83c0bc92014-08-04 01:23:53 -0400316}
317
318func (hc *halfConn) recordHeaderLen() int {
319 if hc.isDTLS {
320 return dtlsRecordHeaderLen
321 }
322 return tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700323}
324
325// removePadding returns an unpadded slice, in constant time, which is a prefix
326// of the input. It also returns a byte which is equal to 255 if the padding
327// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
328func removePadding(payload []byte) ([]byte, byte) {
329 if len(payload) < 1 {
330 return payload, 0
331 }
332
333 paddingLen := payload[len(payload)-1]
334 t := uint(len(payload)-1) - uint(paddingLen)
335 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
336 good := byte(int32(^t) >> 31)
337
338 toCheck := 255 // the maximum possible padding length
339 // The length of the padded data is public, so we can use an if here
340 if toCheck+1 > len(payload) {
341 toCheck = len(payload) - 1
342 }
343
344 for i := 0; i < toCheck; i++ {
345 t := uint(paddingLen) - uint(i)
346 // if i <= paddingLen then the MSB of t is zero
347 mask := byte(int32(^t) >> 31)
348 b := payload[len(payload)-1-i]
349 good &^= mask&paddingLen ^ mask&b
350 }
351
352 // We AND together the bits of good and replicate the result across
353 // all the bits.
354 good &= good << 4
355 good &= good << 2
356 good &= good << 1
357 good = uint8(int8(good) >> 7)
358
359 toRemove := good&paddingLen + 1
360 return payload[:len(payload)-int(toRemove)], good
361}
362
363// removePaddingSSL30 is a replacement for removePadding in the case that the
364// protocol version is SSLv3. In this version, the contents of the padding
365// are random and cannot be checked.
366func removePaddingSSL30(payload []byte) ([]byte, byte) {
367 if len(payload) < 1 {
368 return payload, 0
369 }
370
371 paddingLen := int(payload[len(payload)-1]) + 1
372 if paddingLen > len(payload) {
373 return payload, 0
374 }
375
376 return payload[:len(payload)-paddingLen], 255
377}
378
379func roundUp(a, b int) int {
380 return a + (b-a%b)%b
381}
382
383// cbcMode is an interface for block ciphers using cipher block chaining.
384type cbcMode interface {
385 cipher.BlockMode
386 SetIV([]byte)
387}
388
389// decrypt checks and strips the mac and decrypts the data in b. Returns a
390// success boolean, the number of bytes to skip from the start of the record in
Nick Harper1fd39d82016-06-14 18:14:35 -0700391// order to get the application payload, the encrypted record type (or 0
392// if there is none), and an optional alert value.
393func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, contentType recordType, alertValue alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400394 recordHeaderLen := hc.recordHeaderLen()
395
Adam Langley95c29f32014-06-20 12:00:00 -0700396 // pull out payload
397 payload := b.data[recordHeaderLen:]
398
399 macSize := 0
400 if hc.mac != nil {
401 macSize = hc.mac.Size()
402 }
403
404 paddingGood := byte(255)
405 explicitIVLen := 0
406
David Benjamin83c0bc92014-08-04 01:23:53 -0400407 seq := hc.seq[:]
408 if hc.isDTLS {
409 // DTLS sequence numbers are explicit.
410 seq = b.data[3:11]
411 }
412
Adam Langley95c29f32014-06-20 12:00:00 -0700413 // decrypt
414 if hc.cipher != nil {
415 switch c := hc.cipher.(type) {
416 case cipher.Stream:
417 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400418 case *tlsAead:
419 nonce := seq
420 if c.explicitNonce {
421 explicitIVLen = 8
422 if len(payload) < explicitIVLen {
Nick Harper1fd39d82016-06-14 18:14:35 -0700423 return false, 0, 0, alertBadRecordMAC
David Benjamine9a80ff2015-04-07 00:46:46 -0400424 }
425 nonce = payload[:8]
426 payload = payload[8:]
Adam Langley95c29f32014-06-20 12:00:00 -0700427 }
Adam Langley95c29f32014-06-20 12:00:00 -0700428
Nick Harper1fd39d82016-06-14 18:14:35 -0700429 var additionalData []byte
430 if hc.version < VersionTLS13 {
431 additionalData = make([]byte, 13)
432 copy(additionalData, seq)
433 copy(additionalData[8:], b.data[:3])
434 n := len(payload) - c.Overhead()
435 additionalData[11] = byte(n >> 8)
436 additionalData[12] = byte(n)
437 }
Adam Langley95c29f32014-06-20 12:00:00 -0700438 var err error
Nick Harper1fd39d82016-06-14 18:14:35 -0700439 payload, err = c.Open(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700440 if err != nil {
Nick Harper1fd39d82016-06-14 18:14:35 -0700441 return false, 0, 0, alertBadRecordMAC
442 }
Adam Langley95c29f32014-06-20 12:00:00 -0700443 b.resize(recordHeaderLen + explicitIVLen + len(payload))
444 case cbcMode:
445 blockSize := c.BlockSize()
David Benjamin83c0bc92014-08-04 01:23:53 -0400446 if hc.version >= VersionTLS11 || hc.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700447 explicitIVLen = blockSize
448 }
449
450 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
Nick Harper1fd39d82016-06-14 18:14:35 -0700451 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700452 }
453
454 if explicitIVLen > 0 {
455 c.SetIV(payload[:explicitIVLen])
456 payload = payload[explicitIVLen:]
457 }
458 c.CryptBlocks(payload, payload)
459 if hc.version == VersionSSL30 {
460 payload, paddingGood = removePaddingSSL30(payload)
461 } else {
462 payload, paddingGood = removePadding(payload)
463 }
464 b.resize(recordHeaderLen + explicitIVLen + len(payload))
465
466 // note that we still have a timing side-channel in the
467 // MAC check, below. An attacker can align the record
468 // so that a correct padding will cause one less hash
469 // block to be calculated. Then they can iteratively
470 // decrypt a record by breaking each byte. See
471 // "Password Interception in a SSL/TLS Channel", Brice
472 // Canvel et al.
473 //
474 // However, our behavior matches OpenSSL, so we leak
475 // only as much as they do.
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700476 case nullCipher:
477 break
Adam Langley95c29f32014-06-20 12:00:00 -0700478 default:
479 panic("unknown cipher type")
480 }
David Benjamin7a4aaa42016-09-20 17:58:14 -0400481
482 if hc.version >= VersionTLS13 {
483 i := len(payload)
484 for i > 0 && payload[i-1] == 0 {
485 i--
486 }
487 payload = payload[:i]
488 if len(payload) == 0 {
489 return false, 0, 0, alertUnexpectedMessage
490 }
491 contentType = recordType(payload[len(payload)-1])
492 payload = payload[:len(payload)-1]
493 b.resize(recordHeaderLen + len(payload))
494 }
Adam Langley95c29f32014-06-20 12:00:00 -0700495 }
496
497 // check, strip mac
498 if hc.mac != nil {
499 if len(payload) < macSize {
Nick Harper1fd39d82016-06-14 18:14:35 -0700500 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700501 }
502
503 // strip mac off payload, b.data
504 n := len(payload) - macSize
David Benjamin83c0bc92014-08-04 01:23:53 -0400505 b.data[recordHeaderLen-2] = byte(n >> 8)
506 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700507 b.resize(recordHeaderLen + explicitIVLen + n)
508 remoteMAC := payload[n:]
David Benjamin83c0bc92014-08-04 01:23:53 -0400509 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
Adam Langley95c29f32014-06-20 12:00:00 -0700510
511 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
Nick Harper1fd39d82016-06-14 18:14:35 -0700512 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700513 }
514 hc.inDigestBuf = localMAC
515 }
David Benjamin5e961c12014-11-07 01:48:35 -0500516 hc.incSeq(false)
Adam Langley95c29f32014-06-20 12:00:00 -0700517
Nick Harper1fd39d82016-06-14 18:14:35 -0700518 return true, recordHeaderLen + explicitIVLen, contentType, 0
Adam Langley95c29f32014-06-20 12:00:00 -0700519}
520
521// padToBlockSize calculates the needed padding block, if any, for a payload.
522// On exit, prefix aliases payload and extends to the end of the last full
523// block of payload. finalBlock is a fresh slice which contains the contents of
524// any suffix of payload as well as the needed padding to make finalBlock a
525// full block.
Adam Langley80842bd2014-06-20 12:00:00 -0700526func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
Adam Langley95c29f32014-06-20 12:00:00 -0700527 overrun := len(payload) % blockSize
Adam Langley95c29f32014-06-20 12:00:00 -0700528 prefix = payload[:len(payload)-overrun]
Adam Langley80842bd2014-06-20 12:00:00 -0700529
530 paddingLen := blockSize - overrun
531 finalSize := blockSize
532 if config.Bugs.MaxPadding {
533 for paddingLen+blockSize <= 256 {
534 paddingLen += blockSize
535 }
536 finalSize = 256
537 }
538 finalBlock = make([]byte, finalSize)
539 for i := range finalBlock {
Adam Langley95c29f32014-06-20 12:00:00 -0700540 finalBlock[i] = byte(paddingLen - 1)
541 }
Adam Langley80842bd2014-06-20 12:00:00 -0700542 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
543 finalBlock[overrun] ^= 0xff
544 }
545 copy(finalBlock, payload[len(payload)-overrun:])
Adam Langley95c29f32014-06-20 12:00:00 -0700546 return
547}
548
549// encrypt encrypts and macs the data in b.
Nick Harper1fd39d82016-06-14 18:14:35 -0700550func (hc *halfConn) encrypt(b *block, explicitIVLen int, typ recordType) (bool, alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400551 recordHeaderLen := hc.recordHeaderLen()
552
Adam Langley95c29f32014-06-20 12:00:00 -0700553 // mac
554 if hc.mac != nil {
David Benjamin8e6db492015-07-25 18:29:23 -0400555 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 -0700556
557 n := len(b.data)
558 b.resize(n + len(mac))
559 copy(b.data[n:], mac)
560 hc.outDigestBuf = mac
561 }
562
563 payload := b.data[recordHeaderLen:]
564
565 // encrypt
566 if hc.cipher != nil {
David Benjamin7a4aaa42016-09-20 17:58:14 -0400567 // Add TLS 1.3 padding.
568 if hc.version >= VersionTLS13 {
569 paddingLen := hc.config.Bugs.RecordPadding
570 if hc.config.Bugs.OmitRecordContents {
571 b.resize(recordHeaderLen + paddingLen)
572 } else {
573 b.resize(len(b.data) + 1 + paddingLen)
574 b.data[len(b.data)-paddingLen-1] = byte(typ)
575 }
576 for i := 0; i < paddingLen; i++ {
577 b.data[len(b.data)-paddingLen+i] = 0
578 }
579 }
580
Adam Langley95c29f32014-06-20 12:00:00 -0700581 switch c := hc.cipher.(type) {
582 case cipher.Stream:
583 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400584 case *tlsAead:
Adam Langley95c29f32014-06-20 12:00:00 -0700585 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
David Benjamin7a4aaa42016-09-20 17:58:14 -0400586 b.resize(len(b.data) + c.Overhead())
David Benjamin8e6db492015-07-25 18:29:23 -0400587 nonce := hc.outSeq[:]
David Benjamine9a80ff2015-04-07 00:46:46 -0400588 if c.explicitNonce {
589 nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
590 }
Adam Langley95c29f32014-06-20 12:00:00 -0700591 payload := b.data[recordHeaderLen+explicitIVLen:]
592 payload = payload[:payloadLen]
593
Nick Harper1fd39d82016-06-14 18:14:35 -0700594 var additionalData []byte
595 if hc.version < VersionTLS13 {
596 additionalData = make([]byte, 13)
597 copy(additionalData, hc.outSeq[:])
598 copy(additionalData[8:], b.data[:3])
599 additionalData[11] = byte(payloadLen >> 8)
600 additionalData[12] = byte(payloadLen)
601 }
Adam Langley95c29f32014-06-20 12:00:00 -0700602
Nick Harper1fd39d82016-06-14 18:14:35 -0700603 c.Seal(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700604 case cbcMode:
605 blockSize := c.BlockSize()
606 if explicitIVLen > 0 {
607 c.SetIV(payload[:explicitIVLen])
608 payload = payload[explicitIVLen:]
609 }
Adam Langley80842bd2014-06-20 12:00:00 -0700610 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700611 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
612 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
613 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700614 case nullCipher:
615 break
Adam Langley95c29f32014-06-20 12:00:00 -0700616 default:
617 panic("unknown cipher type")
618 }
619 }
620
621 // update length to include MAC and any block padding needed.
622 n := len(b.data) - recordHeaderLen
David Benjamin83c0bc92014-08-04 01:23:53 -0400623 b.data[recordHeaderLen-2] = byte(n >> 8)
624 b.data[recordHeaderLen-1] = byte(n)
David Benjamin5e961c12014-11-07 01:48:35 -0500625 hc.incSeq(true)
Adam Langley95c29f32014-06-20 12:00:00 -0700626
627 return true, 0
628}
629
630// A block is a simple data buffer.
631type block struct {
632 data []byte
633 off int // index for Read
634 link *block
635}
636
637// resize resizes block to be n bytes, growing if necessary.
638func (b *block) resize(n int) {
639 if n > cap(b.data) {
640 b.reserve(n)
641 }
642 b.data = b.data[0:n]
643}
644
645// reserve makes sure that block contains a capacity of at least n bytes.
646func (b *block) reserve(n int) {
647 if cap(b.data) >= n {
648 return
649 }
650 m := cap(b.data)
651 if m == 0 {
652 m = 1024
653 }
654 for m < n {
655 m *= 2
656 }
657 data := make([]byte, len(b.data), m)
658 copy(data, b.data)
659 b.data = data
660}
661
662// readFromUntil reads from r into b until b contains at least n bytes
663// or else returns an error.
664func (b *block) readFromUntil(r io.Reader, n int) error {
665 // quick case
666 if len(b.data) >= n {
667 return nil
668 }
669
670 // read until have enough.
671 b.reserve(n)
672 for {
673 m, err := r.Read(b.data[len(b.data):cap(b.data)])
674 b.data = b.data[0 : len(b.data)+m]
675 if len(b.data) >= n {
676 // TODO(bradfitz,agl): slightly suspicious
677 // that we're throwing away r.Read's err here.
678 break
679 }
680 if err != nil {
681 return err
682 }
683 }
684 return nil
685}
686
687func (b *block) Read(p []byte) (n int, err error) {
688 n = copy(p, b.data[b.off:])
689 b.off += n
690 return
691}
692
693// newBlock allocates a new block, from hc's free list if possible.
694func (hc *halfConn) newBlock() *block {
695 b := hc.bfree
696 if b == nil {
697 return new(block)
698 }
699 hc.bfree = b.link
700 b.link = nil
701 b.resize(0)
702 return b
703}
704
705// freeBlock returns a block to hc's free list.
706// The protocol is such that each side only has a block or two on
707// its free list at a time, so there's no need to worry about
708// trimming the list, etc.
709func (hc *halfConn) freeBlock(b *block) {
710 b.link = hc.bfree
711 hc.bfree = b
712}
713
714// splitBlock splits a block after the first n bytes,
715// returning a block with those n bytes and a
716// block with the remainder. the latter may be nil.
717func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
718 if len(b.data) <= n {
719 return b, nil
720 }
721 bb := hc.newBlock()
722 bb.resize(len(b.data) - n)
723 copy(bb.data, b.data[n:])
724 b.data = b.data[0:n]
725 return b, bb
726}
727
David Benjamin83c0bc92014-08-04 01:23:53 -0400728func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
Nick Harper47383aa2016-11-30 12:50:43 -0800729RestartReadRecord:
David Benjamin83c0bc92014-08-04 01:23:53 -0400730 if c.isDTLS {
731 return c.dtlsDoReadRecord(want)
732 }
733
David Benjamin6f600d62016-12-21 16:06:54 -0500734 recordHeaderLen := c.in.recordHeaderLen()
David Benjamin83c0bc92014-08-04 01:23:53 -0400735
736 if c.rawInput == nil {
737 c.rawInput = c.in.newBlock()
738 }
739 b := c.rawInput
740
741 // Read header, payload.
742 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
743 // RFC suggests that EOF without an alertCloseNotify is
744 // an error, but popular web sites seem to do this,
David Benjamin30789da2015-08-29 22:56:45 -0400745 // so we can't make it an error, outside of tests.
746 if err == io.EOF && c.config.Bugs.ExpectCloseNotify {
747 err = io.ErrUnexpectedEOF
748 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400749 if e, ok := err.(net.Error); !ok || !e.Temporary() {
750 c.in.setErrorLocked(err)
751 }
752 return 0, nil, err
753 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400754
Steven Valdez924a3522017-03-02 16:05:03 -0500755 typ := recordType(b.data[0])
David Benjamin6f600d62016-12-21 16:06:54 -0500756
Steven Valdez924a3522017-03-02 16:05:03 -0500757 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
758 // start with a uint16 length where the MSB is set and the first record
759 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
760 // an SSLv2 client.
761 if want == recordTypeHandshake && typ == 0x80 {
762 c.sendAlert(alertProtocolVersion)
763 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
David Benjamin83c0bc92014-08-04 01:23:53 -0400764 }
765
Steven Valdezdbe01582017-07-14 10:39:28 -0400766 // Accept server_plaintext_handshake records when the content type TLS 1.3 variant is enabled.
767 if c.isClient && c.in.cipher == nil && c.config.TLS13Variant == TLS13RecordTypeExperiment && want == recordTypeHandshake && typ == recordTypePlaintextHandshake {
768 typ = recordTypeHandshake
769 }
770
Steven Valdez924a3522017-03-02 16:05:03 -0500771 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
772 n := int(b.data[3])<<8 | int(b.data[4])
773
David Benjaminbde00392016-06-21 12:19:28 -0400774 // Alerts sent near version negotiation do not have a well-defined
775 // record-layer version prior to TLS 1.3. (In TLS 1.3, the record-layer
776 // version is irrelevant.)
777 if typ != recordTypeAlert {
David Benjamine6f22212016-11-08 14:28:24 -0500778 var expect uint16
David Benjaminbde00392016-06-21 12:19:28 -0400779 if c.haveVers {
David Benjamine6f22212016-11-08 14:28:24 -0500780 expect = c.vers
781 if c.vers >= VersionTLS13 {
782 expect = VersionTLS10
David Benjaminbde00392016-06-21 12:19:28 -0400783 }
Steven Valdez16821262017-09-08 17:03:42 -0400784 if c.wireVersion == tls13Experiment2Version {
785 expect = VersionTLS12
786 }
David Benjaminbde00392016-06-21 12:19:28 -0400787 } else {
David Benjamine6f22212016-11-08 14:28:24 -0500788 expect = c.config.Bugs.ExpectInitialRecordVersion
789 }
790 if expect != 0 && vers != expect {
791 c.sendAlert(alertProtocolVersion)
792 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 -0500793 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400794 }
795 if n > maxCiphertext {
796 c.sendAlert(alertRecordOverflow)
797 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
798 }
799 if !c.haveVers {
800 // First message, be extra suspicious:
801 // this might not be a TLS client.
802 // Bail out before reading a full 'body', if possible.
803 // The current max version is 3.1.
804 // If the version is >= 16.0, it's probably not real.
805 // Similarly, a clientHello message encodes in
806 // well under a kilobyte. If the length is >= 12 kB,
807 // it's probably not real.
808 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
809 c.sendAlert(alertUnexpectedMessage)
810 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
811 }
812 }
813 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
814 if err == io.EOF {
815 err = io.ErrUnexpectedEOF
816 }
817 if e, ok := err.(net.Error); !ok || !e.Temporary() {
818 c.in.setErrorLocked(err)
819 }
820 return 0, nil, err
821 }
822
823 // Process message.
824 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
David Benjaminff26f092016-07-01 16:13:42 -0400825 ok, off, encTyp, alertValue := c.in.decrypt(b)
Nick Harper47383aa2016-11-30 12:50:43 -0800826
827 // Handle skipping over early data.
828 if !ok && c.skipEarlyData {
829 goto RestartReadRecord
830 }
831
832 // If the server is expecting a second ClientHello (in response to
833 // a HelloRetryRequest) and the client sends early data, there
834 // won't be a decryption failure but it still needs to be skipped.
835 if c.in.cipher == nil && typ == recordTypeApplicationData && c.skipEarlyData {
836 goto RestartReadRecord
837 }
838
David Benjaminff26f092016-07-01 16:13:42 -0400839 if !ok {
840 return 0, nil, c.in.setErrorLocked(c.sendAlert(alertValue))
841 }
842 b.off = off
Nick Harper47383aa2016-11-30 12:50:43 -0800843 c.skipEarlyData = false
David Benjaminff26f092016-07-01 16:13:42 -0400844
Nick Harper1fd39d82016-06-14 18:14:35 -0700845 if c.vers >= VersionTLS13 && c.in.cipher != nil {
David Benjaminc9ae27c2016-06-24 22:56:37 -0400846 if typ != recordTypeApplicationData {
847 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: outer record type is not application data"))
848 }
Nick Harper1fd39d82016-06-14 18:14:35 -0700849 typ = encTyp
850 }
David Benjamin09ed1192017-07-14 20:11:07 -0400851
852 length := len(b.data[b.off:])
853 if c.config.Bugs.ExpectRecordSplitting && typ == recordTypeApplicationData && length != 1 && !c.seenOneByteRecord {
854 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: application data records were not split"))
855 }
856
857 c.seenOneByteRecord = typ == recordTypeApplicationData && length == 1
David Benjamin83c0bc92014-08-04 01:23:53 -0400858 return typ, b, nil
859}
860
Adam Langley95c29f32014-06-20 12:00:00 -0700861// readRecord reads the next TLS record from the connection
862// and updates the record layer state.
863// c.in.Mutex <= L; c.input == nil.
864func (c *Conn) readRecord(want recordType) error {
865 // Caller must be in sync with connection:
866 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700867 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700868 switch want {
869 default:
870 c.sendAlert(alertInternalError)
871 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
David Benjaminbbba9392017-04-06 12:54:12 -0400872 case recordTypeChangeCipherSpec:
Adam Langley95c29f32014-06-20 12:00:00 -0700873 if c.handshakeComplete {
874 c.sendAlert(alertInternalError)
David Benjaminbbba9392017-04-06 12:54:12 -0400875 return c.in.setErrorLocked(errors.New("tls: ChangeCipherSpec requested after handshake complete"))
Adam Langley95c29f32014-06-20 12:00:00 -0700876 }
Steven Valdeze831a812017-03-09 14:56:07 -0500877 case recordTypeApplicationData, recordTypeAlert, recordTypeHandshake:
878 break
Adam Langley95c29f32014-06-20 12:00:00 -0700879 }
880
881Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400882 typ, b, err := c.doReadRecord(want)
883 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700884 return err
885 }
Adam Langley95c29f32014-06-20 12:00:00 -0700886 data := b.data[b.off:]
David Benjamine3fbb362017-01-06 16:19:28 -0500887 max := maxPlaintext
888 if c.config.Bugs.MaxReceivePlaintext != 0 {
889 max = c.config.Bugs.MaxReceivePlaintext
890 }
891 if len(data) > max {
Adam Langley95c29f32014-06-20 12:00:00 -0700892 err := c.sendAlert(alertRecordOverflow)
893 c.in.freeBlock(b)
894 return c.in.setErrorLocked(err)
895 }
896
897 switch typ {
898 default:
899 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
900
901 case recordTypeAlert:
902 if len(data) != 2 {
903 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
904 break
905 }
906 if alert(data[1]) == alertCloseNotify {
907 c.in.setErrorLocked(io.EOF)
908 break
909 }
910 switch data[0] {
911 case alertLevelWarning:
David Benjamin053fee92017-01-02 08:30:36 -0500912 if alert(data[1]) == alertNoCertificate {
913 c.in.freeBlock(b)
914 return errNoCertificateAlert
915 }
Nick Harperab20cec2016-12-19 17:38:41 -0800916 if alert(data[1]) == alertEndOfEarlyData {
917 c.in.freeBlock(b)
918 return errEndOfEarlyDataAlert
919 }
David Benjamin053fee92017-01-02 08:30:36 -0500920
Adam Langley95c29f32014-06-20 12:00:00 -0700921 // drop on the floor
922 c.in.freeBlock(b)
923 goto Again
924 case alertLevelError:
925 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
926 default:
927 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
928 }
929
930 case recordTypeChangeCipherSpec:
931 if typ != want || len(data) != 1 || data[0] != 1 {
932 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
933 break
934 }
Steven Valdez16821262017-09-08 17:03:42 -0400935 if !isResumptionExperiment(c.wireVersion) {
Steven Valdez520e1222017-06-13 12:45:25 -0400936 err := c.in.changeCipherSpec(c.config)
937 if err != nil {
938 c.in.setErrorLocked(c.sendAlert(err.(alert)))
939 }
Adam Langley95c29f32014-06-20 12:00:00 -0700940 }
941
942 case recordTypeApplicationData:
943 if typ != want {
944 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
945 break
946 }
947 c.input = b
948 b = nil
949
950 case recordTypeHandshake:
David Benjamind5a4ecb2016-07-18 01:17:13 +0200951 // Allow handshake data while reading application data to
952 // trigger post-handshake messages.
Adam Langley95c29f32014-06-20 12:00:00 -0700953 // TODO(rsc): Should at least pick off connection close.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200954 if typ != want && want != recordTypeApplicationData {
955 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
Adam Langley95c29f32014-06-20 12:00:00 -0700956 }
957 c.hand.Write(data)
958 }
959
960 if b != nil {
961 c.in.freeBlock(b)
962 }
963 return c.in.err
964}
965
966// sendAlert sends a TLS alert message.
967// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400968func (c *Conn) sendAlertLocked(level byte, err alert) error {
969 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700970 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400971 if c.config.Bugs.FragmentAlert {
972 c.writeRecord(recordTypeAlert, c.tmp[0:1])
973 c.writeRecord(recordTypeAlert, c.tmp[1:2])
David Benjamin0d3a8c62016-03-11 22:25:18 -0500974 } else if c.config.Bugs.DoubleAlert {
975 copy(c.tmp[2:4], c.tmp[0:2])
976 c.writeRecord(recordTypeAlert, c.tmp[0:4])
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400977 } else {
978 c.writeRecord(recordTypeAlert, c.tmp[0:2])
979 }
David Benjamin24f346d2015-06-06 03:28:08 -0400980 // Error alerts are fatal to the connection.
981 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700982 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
983 }
984 return nil
985}
986
987// sendAlert sends a TLS alert message.
988// L < c.out.Mutex.
989func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400990 level := byte(alertLevelError)
Nick Harperf2511f12016-12-06 16:02:31 -0800991 if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertificate || err == alertEndOfEarlyData {
David Benjamin24f346d2015-06-06 03:28:08 -0400992 level = alertLevelWarning
993 }
994 return c.SendAlert(level, err)
995}
996
997func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700998 c.out.Lock()
999 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -04001000 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -07001001}
1002
David Benjamind86c7672014-08-02 04:07:12 -04001003// writeV2Record writes a record for a V2ClientHello.
1004func (c *Conn) writeV2Record(data []byte) (n int, err error) {
1005 record := make([]byte, 2+len(data))
1006 record[0] = uint8(len(data)>>8) | 0x80
1007 record[1] = uint8(len(data))
1008 copy(record[2:], data)
1009 return c.conn.Write(record)
1010}
1011
Adam Langley95c29f32014-06-20 12:00:00 -07001012// writeRecord writes a TLS record with the given type and payload
1013// to the connection and updates the record layer state.
1014// c.out.Mutex <= L.
1015func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjaminebacdee2017-04-08 11:00:45 -04001016 if typ == recordTypeHandshake {
1017 msgType := data[0]
1018 if c.config.Bugs.SendWrongMessageType != 0 && msgType == c.config.Bugs.SendWrongMessageType {
1019 msgType += 42
1020 } else if msgType == typeServerHello && c.config.Bugs.SendServerHelloAsHelloRetryRequest {
1021 msgType = typeHelloRetryRequest
1022 }
1023 if msgType != data[0] {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001024 newData := make([]byte, len(data))
1025 copy(newData, data)
David Benjaminebacdee2017-04-08 11:00:45 -04001026 newData[0] = msgType
David Benjamin0b8d5da2016-07-15 00:39:56 -04001027 data = newData
1028 }
David Benjamin0b8d5da2016-07-15 00:39:56 -04001029
David Benjaminb0c761e2017-06-25 22:42:55 -04001030 if c.config.Bugs.SendTrailingMessageData != 0 && msgType == c.config.Bugs.SendTrailingMessageData {
David Benjamin639846e2016-09-09 11:41:18 -04001031 newData := make([]byte, len(data))
1032 copy(newData, data)
1033
1034 // Add a 0 to the body.
1035 newData = append(newData, 0)
1036 // Fix the header.
1037 newLen := len(newData) - 4
1038 newData[1] = byte(newLen >> 16)
1039 newData[2] = byte(newLen >> 8)
1040 newData[3] = byte(newLen)
1041
1042 data = newData
1043 }
1044 }
1045
David Benjamin83c0bc92014-08-04 01:23:53 -04001046 if c.isDTLS {
1047 return c.dtlsWriteRecord(typ, data)
1048 }
1049
David Benjamin71dd6662016-07-08 14:10:48 -07001050 if typ == recordTypeHandshake {
1051 if c.config.Bugs.SendHelloRequestBeforeEveryHandshakeMessage {
1052 newData := make([]byte, 0, 4+len(data))
1053 newData = append(newData, typeHelloRequest, 0, 0, 0)
1054 newData = append(newData, data...)
1055 data = newData
1056 }
1057
1058 if c.config.Bugs.PackHandshakeFlight {
1059 c.pendingFlight.Write(data)
1060 return len(data), nil
1061 }
David Benjamin582ba042016-07-07 12:33:25 -07001062 }
1063
David Benjaminb0c761e2017-06-25 22:42:55 -04001064 // Flush buffered data before writing anything.
1065 if err := c.flushHandshake(); err != nil {
1066 return 0, err
1067 }
1068
David Benjamin582ba042016-07-07 12:33:25 -07001069 return c.doWriteRecord(typ, data)
1070}
1071
1072func (c *Conn) doWriteRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin6f600d62016-12-21 16:06:54 -05001073 recordHeaderLen := c.out.recordHeaderLen()
Adam Langley95c29f32014-06-20 12:00:00 -07001074 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -04001075 first := true
1076 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -04001077 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -07001078 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -04001079 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -07001080 m = maxPlaintext
1081 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001082 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
1083 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -04001084 // By default, do not fragment the client_version or
1085 // server_version, which are located in the first 6
1086 // bytes.
1087 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
1088 m = 6
1089 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001090 }
Adam Langley95c29f32014-06-20 12:00:00 -07001091 explicitIVLen := 0
1092 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -04001093 first = false
Adam Langley95c29f32014-06-20 12:00:00 -07001094
1095 var cbc cbcMode
1096 if c.out.version >= VersionTLS11 {
1097 var ok bool
1098 if cbc, ok = c.out.cipher.(cbcMode); ok {
1099 explicitIVLen = cbc.BlockSize()
1100 }
1101 }
1102 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -04001103 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -07001104 explicitIVLen = 8
1105 // The AES-GCM construction in TLS has an
1106 // explicit nonce so that the nonce can be
1107 // random. However, the nonce is only 8 bytes
1108 // which is too small for a secure, random
1109 // nonce. Therefore we use the sequence number
1110 // as the nonce.
1111 explicitIVIsSeq = true
1112 }
1113 }
1114 b.resize(recordHeaderLen + explicitIVLen + m)
Steven Valdez924a3522017-03-02 16:05:03 -05001115 b.data[0] = byte(typ)
1116 if c.vers >= VersionTLS13 && c.out.cipher != nil {
1117 b.data[0] = byte(recordTypeApplicationData)
1118 if outerType := c.config.Bugs.OuterRecordType; outerType != 0 {
1119 b.data[0] = byte(outerType)
David Benjaminc9ae27c2016-06-24 22:56:37 -04001120 }
Nick Harper1fd39d82016-06-14 18:14:35 -07001121 }
Steven Valdez924a3522017-03-02 16:05:03 -05001122 vers := c.vers
1123 if vers == 0 || vers >= VersionTLS13 {
1124 // Some TLS servers fail if the record version is
1125 // greater than TLS 1.0 for the initial ClientHello.
1126 //
1127 // TLS 1.3 fixes the version number in the record
1128 // layer to {3, 1}.
1129 vers = VersionTLS10
1130 }
Steven Valdez16821262017-09-08 17:03:42 -04001131 if c.wireVersion == tls13Experiment2Version {
1132 vers = VersionTLS12
1133 }
1134
Steven Valdez924a3522017-03-02 16:05:03 -05001135 if c.config.Bugs.SendRecordVersion != 0 {
1136 vers = c.config.Bugs.SendRecordVersion
1137 }
1138 if c.vers == 0 && c.config.Bugs.SendInitialRecordVersion != 0 {
1139 vers = c.config.Bugs.SendInitialRecordVersion
1140 }
1141 b.data[1] = byte(vers >> 8)
1142 b.data[2] = byte(vers)
1143 b.data[3] = byte(m >> 8)
1144 b.data[4] = byte(m)
Adam Langley95c29f32014-06-20 12:00:00 -07001145 if explicitIVLen > 0 {
1146 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
1147 if explicitIVIsSeq {
1148 copy(explicitIV, c.out.seq[:])
1149 } else {
1150 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
1151 break
1152 }
1153 }
1154 }
1155 copy(b.data[recordHeaderLen+explicitIVLen:], data)
Nick Harper1fd39d82016-06-14 18:14:35 -07001156 c.out.encrypt(b, explicitIVLen, typ)
Adam Langley95c29f32014-06-20 12:00:00 -07001157 _, err = c.conn.Write(b.data)
1158 if err != nil {
1159 break
1160 }
1161 n += m
1162 data = data[m:]
1163 }
1164 c.out.freeBlock(b)
1165
Steven Valdez16821262017-09-08 17:03:42 -04001166 if typ == recordTypeChangeCipherSpec && !isResumptionExperiment(c.wireVersion) {
Adam Langley80842bd2014-06-20 12:00:00 -07001167 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -07001168 if err != nil {
David Benjamina8181342017-07-07 18:10:57 -04001169 return n, c.sendAlertLocked(alertLevelError, err.(alert))
Adam Langley95c29f32014-06-20 12:00:00 -07001170 }
1171 }
1172 return
1173}
1174
David Benjamin582ba042016-07-07 12:33:25 -07001175func (c *Conn) flushHandshake() error {
1176 if c.isDTLS {
1177 return c.dtlsFlushHandshake()
1178 }
1179
1180 for c.pendingFlight.Len() > 0 {
1181 var buf [maxPlaintext]byte
1182 n, _ := c.pendingFlight.Read(buf[:])
1183 if _, err := c.doWriteRecord(recordTypeHandshake, buf[:n]); err != nil {
1184 return err
1185 }
1186 }
1187
1188 c.pendingFlight.Reset()
1189 return nil
1190}
1191
David Benjamin83c0bc92014-08-04 01:23:53 -04001192func (c *Conn) doReadHandshake() ([]byte, error) {
1193 if c.isDTLS {
1194 return c.dtlsDoReadHandshake()
1195 }
1196
Adam Langley95c29f32014-06-20 12:00:00 -07001197 for c.hand.Len() < 4 {
1198 if err := c.in.err; err != nil {
1199 return nil, err
1200 }
1201 if err := c.readRecord(recordTypeHandshake); err != nil {
1202 return nil, err
1203 }
1204 }
1205
1206 data := c.hand.Bytes()
1207 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1208 if n > maxHandshake {
1209 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
1210 }
1211 for c.hand.Len() < 4+n {
1212 if err := c.in.err; err != nil {
1213 return nil, err
1214 }
1215 if err := c.readRecord(recordTypeHandshake); err != nil {
1216 return nil, err
1217 }
1218 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001219 return c.hand.Next(4 + n), nil
1220}
1221
1222// readHandshake reads the next handshake message from
1223// the record layer.
1224// c.in.Mutex < L; c.out.Mutex < L.
1225func (c *Conn) readHandshake() (interface{}, error) {
1226 data, err := c.doReadHandshake()
David Benjamin053fee92017-01-02 08:30:36 -05001227 if err == errNoCertificateAlert {
1228 if c.hand.Len() != 0 {
1229 // The warning alert may not interleave with a handshake message.
1230 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1231 }
1232 return new(ssl3NoCertificateMsg), nil
1233 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001234 if err != nil {
1235 return nil, err
1236 }
1237
Adam Langley95c29f32014-06-20 12:00:00 -07001238 var m handshakeMessage
1239 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001240 case typeHelloRequest:
1241 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001242 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001243 m = &clientHelloMsg{
1244 isDTLS: c.isDTLS,
1245 }
Adam Langley95c29f32014-06-20 12:00:00 -07001246 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001247 m = &serverHelloMsg{
1248 isDTLS: c.isDTLS,
1249 }
Nick Harperdcfbc672016-07-16 17:47:31 +02001250 case typeHelloRetryRequest:
1251 m = new(helloRetryRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001252 case typeNewSessionTicket:
David Benjamin58104882016-07-18 01:25:41 +02001253 m = &newSessionTicketMsg{
1254 version: c.vers,
1255 }
Nick Harperb41d2e42016-07-01 17:50:32 -04001256 case typeEncryptedExtensions:
1257 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001258 case typeCertificate:
Nick Harperb41d2e42016-07-01 17:50:32 -04001259 m = &certificateMsg{
David Benjamin8d315d72016-07-18 01:03:18 +02001260 hasRequestContext: c.vers >= VersionTLS13,
Nick Harperb41d2e42016-07-01 17:50:32 -04001261 }
Adam Langley95c29f32014-06-20 12:00:00 -07001262 case typeCertificateRequest:
1263 m = &certificateRequestMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001264 hasSignatureAlgorithm: c.vers >= VersionTLS12,
David Benjamin8d315d72016-07-18 01:03:18 +02001265 hasRequestContext: c.vers >= VersionTLS13,
Adam Langley95c29f32014-06-20 12:00:00 -07001266 }
1267 case typeCertificateStatus:
1268 m = new(certificateStatusMsg)
1269 case typeServerKeyExchange:
1270 m = new(serverKeyExchangeMsg)
1271 case typeServerHelloDone:
1272 m = new(serverHelloDoneMsg)
1273 case typeClientKeyExchange:
1274 m = new(clientKeyExchangeMsg)
1275 case typeCertificateVerify:
1276 m = &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001277 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001278 }
1279 case typeNextProtocol:
1280 m = new(nextProtoMsg)
1281 case typeFinished:
1282 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001283 case typeHelloVerifyRequest:
1284 m = new(helloVerifyRequestMsg)
David Benjamin24599a82016-06-30 18:56:53 -04001285 case typeChannelID:
1286 m = new(channelIDMsg)
David Benjamin21c00282016-07-18 21:56:23 +02001287 case typeKeyUpdate:
1288 m = new(keyUpdateMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001289 default:
1290 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1291 }
1292
1293 // The handshake message unmarshallers
1294 // expect to be able to keep references to data,
1295 // so pass in a fresh copy that won't be overwritten.
1296 data = append([]byte(nil), data...)
1297
1298 if !m.unmarshal(data) {
1299 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1300 }
1301 return m, nil
1302}
1303
David Benjamin83f90402015-01-27 01:09:43 -05001304// skipPacket processes all the DTLS records in packet. It updates
1305// sequence number expectations but otherwise ignores them.
1306func (c *Conn) skipPacket(packet []byte) error {
1307 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001308 if len(packet) < 13 {
1309 return errors.New("tls: bad packet")
1310 }
David Benjamin83f90402015-01-27 01:09:43 -05001311 // Dropped packets are completely ignored save to update
1312 // expected sequence numbers for this and the next epoch. (We
1313 // don't assert on the contents of the packets both for
1314 // simplicity and because a previous test with one shorter
1315 // timeout schedule would have done so.)
1316 epoch := packet[3:5]
1317 seq := packet[5:11]
1318 length := uint16(packet[11])<<8 | uint16(packet[12])
1319 if bytes.Equal(c.in.seq[:2], epoch) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001320 if bytes.Compare(seq, c.in.seq[2:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001321 return errors.New("tls: sequence mismatch")
1322 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001323 copy(c.in.seq[2:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001324 c.in.incSeq(false)
1325 } else {
David Benjamin13e81fc2015-11-02 17:16:13 -05001326 if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001327 return errors.New("tls: sequence mismatch")
1328 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001329 copy(c.in.nextSeq[:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001330 c.in.incNextSeq()
1331 }
David Benjamin6ca93552015-08-28 16:16:25 -04001332 if len(packet) < 13+int(length) {
1333 return errors.New("tls: bad packet")
1334 }
David Benjamin83f90402015-01-27 01:09:43 -05001335 packet = packet[13+length:]
1336 }
1337 return nil
1338}
1339
1340// simulatePacketLoss simulates the loss of a handshake leg from the
1341// peer based on the schedule in c.config.Bugs. If resendFunc is
1342// non-nil, it is called after each simulated timeout to retransmit
1343// handshake messages from the local end. This is used in cases where
1344// the peer retransmits on a stale Finished rather than a timeout.
1345func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1346 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1347 return nil
1348 }
1349 if !c.isDTLS {
1350 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1351 }
1352 if c.config.Bugs.PacketAdaptor == nil {
1353 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1354 }
1355 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1356 // Simulate a timeout.
1357 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1358 if err != nil {
1359 return err
1360 }
1361 for _, packet := range packets {
1362 if err := c.skipPacket(packet); err != nil {
1363 return err
1364 }
1365 }
1366 if resendFunc != nil {
1367 resendFunc()
1368 }
1369 }
1370 return nil
1371}
1372
David Benjamin47921102016-07-28 11:29:18 -04001373func (c *Conn) SendHalfHelloRequest() error {
1374 if err := c.Handshake(); err != nil {
1375 return err
1376 }
1377
1378 c.out.Lock()
1379 defer c.out.Unlock()
1380
1381 if _, err := c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0}); err != nil {
1382 return err
1383 }
1384 return c.flushHandshake()
1385}
1386
Adam Langley95c29f32014-06-20 12:00:00 -07001387// Write writes data to the connection.
1388func (c *Conn) Write(b []byte) (int, error) {
1389 if err := c.Handshake(); err != nil {
1390 return 0, err
1391 }
1392
1393 c.out.Lock()
1394 defer c.out.Unlock()
1395
David Benjamin12d2c482016-07-24 10:56:51 -04001396 // Flush any pending handshake data. PackHelloRequestWithFinished may
1397 // have been set and the handshake not followed by Renegotiate.
1398 c.flushHandshake()
1399
Adam Langley95c29f32014-06-20 12:00:00 -07001400 if err := c.out.err; err != nil {
1401 return 0, err
1402 }
1403
1404 if !c.handshakeComplete {
1405 return 0, alertInternalError
1406 }
1407
Steven Valdezc4aa7272016-10-03 12:25:56 -04001408 if c.keyUpdateRequested {
1409 if err := c.sendKeyUpdateLocked(keyUpdateNotRequested); err != nil {
David Benjamin21c00282016-07-18 21:56:23 +02001410 return 0, err
1411 }
Steven Valdezc4aa7272016-10-03 12:25:56 -04001412 c.keyUpdateRequested = false
David Benjamin21c00282016-07-18 21:56:23 +02001413 }
1414
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001415 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001416 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001417 }
1418
Adam Langley27a0d082015-11-03 13:34:10 -08001419 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1420 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
David Benjamin582ba042016-07-07 12:33:25 -07001421 c.flushHandshake()
Adam Langley27a0d082015-11-03 13:34:10 -08001422 }
1423
Adam Langley95c29f32014-06-20 12:00:00 -07001424 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1425 // attack when using block mode ciphers due to predictable IVs.
1426 // This can be prevented by splitting each Application Data
1427 // record into two records, effectively randomizing the IV.
1428 //
1429 // http://www.openssl.org/~bodo/tls-cbc.txt
1430 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1431 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1432
1433 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001434 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001435 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1436 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1437 if err != nil {
1438 return n, c.out.setErrorLocked(err)
1439 }
1440 m, b = 1, b[1:]
1441 }
1442 }
1443
1444 n, err := c.writeRecord(recordTypeApplicationData, b)
1445 return n + m, c.out.setErrorLocked(err)
1446}
1447
David Benjamin794cc592017-03-25 22:24:23 -05001448func (c *Conn) processTLS13NewSessionTicket(newSessionTicket *newSessionTicketMsg, cipherSuite *cipherSuite) error {
1449 if c.config.Bugs.ExpectGREASE && !newSessionTicket.hasGREASEExtension {
1450 return errors.New("tls: no GREASE ticket extension found")
1451 }
1452
1453 if c.config.Bugs.ExpectTicketEarlyDataInfo && newSessionTicket.maxEarlyDataSize == 0 {
1454 return errors.New("tls: no ticket_early_data_info extension found")
1455 }
1456
1457 if c.config.Bugs.ExpectNoNewSessionTicket {
1458 return errors.New("tls: received unexpected NewSessionTicket")
1459 }
1460
1461 if c.config.ClientSessionCache == nil || newSessionTicket.ticketLifetime == 0 {
1462 return nil
1463 }
1464
1465 session := &ClientSessionState{
1466 sessionTicket: newSessionTicket.ticket,
1467 vers: c.vers,
1468 cipherSuite: cipherSuite.id,
1469 masterSecret: c.resumptionSecret,
1470 serverCertificates: c.peerCertificates,
1471 sctList: c.sctList,
1472 ocspResponse: c.ocspResponse,
1473 ticketCreationTime: c.config.time(),
1474 ticketExpiration: c.config.time().Add(time.Duration(newSessionTicket.ticketLifetime) * time.Second),
1475 ticketAgeAdd: newSessionTicket.ticketAgeAdd,
1476 maxEarlyDataSize: newSessionTicket.maxEarlyDataSize,
1477 earlyALPN: c.clientProtocol,
1478 }
1479
1480 cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
1481 c.config.ClientSessionCache.Put(cacheKey, session)
1482 return nil
1483}
1484
David Benjamind5a4ecb2016-07-18 01:17:13 +02001485func (c *Conn) handlePostHandshakeMessage() error {
Adam Langley2ae77d22014-10-28 17:29:33 -07001486 msg, err := c.readHandshake()
1487 if err != nil {
1488 return err
1489 }
David Benjamind5a4ecb2016-07-18 01:17:13 +02001490
1491 if c.vers < VersionTLS13 {
1492 if !c.isClient {
1493 c.sendAlert(alertUnexpectedMessage)
1494 return errors.New("tls: unexpected post-handshake message")
1495 }
1496
1497 _, ok := msg.(*helloRequestMsg)
1498 if !ok {
1499 c.sendAlert(alertUnexpectedMessage)
1500 return alertUnexpectedMessage
1501 }
1502
1503 c.handshakeComplete = false
1504 return c.Handshake()
Adam Langley2ae77d22014-10-28 17:29:33 -07001505 }
1506
David Benjamind5a4ecb2016-07-18 01:17:13 +02001507 if c.isClient {
1508 if newSessionTicket, ok := msg.(*newSessionTicketMsg); ok {
David Benjamin794cc592017-03-25 22:24:23 -05001509 return c.processTLS13NewSessionTicket(newSessionTicket, c.cipherSuite)
David Benjamind5a4ecb2016-07-18 01:17:13 +02001510 }
1511 }
1512
Steven Valdezc4aa7272016-10-03 12:25:56 -04001513 if keyUpdate, ok := msg.(*keyUpdateMsg); ok {
David Benjaminbbba9392017-04-06 12:54:12 -04001514 if c.config.Bugs.RejectUnsolicitedKeyUpdate {
1515 return errors.New("tls: unexpected KeyUpdate message")
1516 }
Steven Valdez1dc53d22016-07-26 12:27:38 -04001517 c.in.doKeyUpdate(c, false)
Steven Valdezc4aa7272016-10-03 12:25:56 -04001518 if keyUpdate.keyUpdateRequest == keyUpdateRequested {
1519 c.keyUpdateRequested = true
1520 }
David Benjamin21c00282016-07-18 21:56:23 +02001521 return nil
1522 }
1523
David Benjamind5a4ecb2016-07-18 01:17:13 +02001524 c.sendAlert(alertUnexpectedMessage)
David Benjaminbbba9392017-04-06 12:54:12 -04001525 return errors.New("tls: unexpected post-handshake message")
1526}
1527
1528// Reads a KeyUpdate acknowledgment from the peer. There may not be any
1529// application data records before the message.
1530func (c *Conn) ReadKeyUpdateACK() error {
1531 c.in.Lock()
1532 defer c.in.Unlock()
1533
1534 msg, err := c.readHandshake()
1535 if err != nil {
1536 return err
1537 }
1538
1539 keyUpdate, ok := msg.(*keyUpdateMsg)
1540 if !ok {
1541 c.sendAlert(alertUnexpectedMessage)
1542 return errors.New("tls: unexpected message when reading KeyUpdate")
1543 }
1544
1545 if keyUpdate.keyUpdateRequest != keyUpdateNotRequested {
1546 return errors.New("tls: received invalid KeyUpdate message")
1547 }
1548
1549 c.in.doKeyUpdate(c, false)
1550 return nil
Adam Langley2ae77d22014-10-28 17:29:33 -07001551}
1552
Adam Langleycf2d4f42014-10-28 19:06:14 -07001553func (c *Conn) Renegotiate() error {
1554 if !c.isClient {
David Benjaminef5dfd22015-12-06 13:17:07 -05001555 helloReq := new(helloRequestMsg).marshal()
1556 if c.config.Bugs.BadHelloRequest != nil {
1557 helloReq = c.config.Bugs.BadHelloRequest
1558 }
1559 c.writeRecord(recordTypeHandshake, helloReq)
David Benjamin582ba042016-07-07 12:33:25 -07001560 c.flushHandshake()
Adam Langleycf2d4f42014-10-28 19:06:14 -07001561 }
1562
1563 c.handshakeComplete = false
1564 return c.Handshake()
1565}
1566
Adam Langley95c29f32014-06-20 12:00:00 -07001567// Read can be made to time out and return a net.Error with Timeout() == true
1568// after a fixed time limit; see SetDeadline and SetReadDeadline.
1569func (c *Conn) Read(b []byte) (n int, err error) {
1570 if err = c.Handshake(); err != nil {
1571 return
1572 }
1573
1574 c.in.Lock()
1575 defer c.in.Unlock()
1576
1577 // Some OpenSSL servers send empty records in order to randomize the
1578 // CBC IV. So this loop ignores a limited number of empty records.
1579 const maxConsecutiveEmptyRecords = 100
1580 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1581 for c.input == nil && c.in.err == nil {
1582 if err := c.readRecord(recordTypeApplicationData); err != nil {
1583 // Soft error, like EAGAIN
1584 return 0, err
1585 }
David Benjamind9b091b2015-01-27 01:10:54 -05001586 if c.hand.Len() > 0 {
David Benjamind5a4ecb2016-07-18 01:17:13 +02001587 // We received handshake bytes, indicating a
1588 // post-handshake message.
1589 if err := c.handlePostHandshakeMessage(); err != nil {
Adam Langley2ae77d22014-10-28 17:29:33 -07001590 return 0, err
1591 }
1592 continue
1593 }
Adam Langley95c29f32014-06-20 12:00:00 -07001594 }
1595 if err := c.in.err; err != nil {
1596 return 0, err
1597 }
1598
1599 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001600 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001601 c.in.freeBlock(c.input)
1602 c.input = nil
1603 }
1604
1605 // If a close-notify alert is waiting, read it so that
1606 // we can return (n, EOF) instead of (n, nil), to signal
1607 // to the HTTP response reading goroutine that the
1608 // connection is now closed. This eliminates a race
1609 // where the HTTP response reading goroutine would
1610 // otherwise not observe the EOF until its next read,
1611 // by which time a client goroutine might have already
1612 // tried to reuse the HTTP connection for a new
1613 // request.
1614 // See https://codereview.appspot.com/76400046
1615 // and http://golang.org/issue/3514
1616 if ri := c.rawInput; ri != nil &&
1617 n != 0 && err == nil &&
1618 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1619 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1620 err = recErr // will be io.EOF on closeNotify
1621 }
1622 }
1623
1624 if n != 0 || err != nil {
1625 return n, err
1626 }
1627 }
1628
1629 return 0, io.ErrNoProgress
1630}
1631
1632// Close closes the connection.
1633func (c *Conn) Close() error {
1634 var alertErr error
1635
1636 c.handshakeMutex.Lock()
1637 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001638 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
David Benjaminfa214e42016-05-10 17:03:10 -04001639 alert := alertCloseNotify
1640 if c.config.Bugs.SendAlertOnShutdown != 0 {
1641 alert = c.config.Bugs.SendAlertOnShutdown
1642 }
1643 alertErr = c.sendAlert(alert)
David Benjamin4d559612016-05-18 14:31:51 -04001644 // Clear local alerts when sending alerts so we continue to wait
1645 // for the peer rather than closing the socket early.
1646 if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1647 alertErr = nil
1648 }
Adam Langley95c29f32014-06-20 12:00:00 -07001649 }
1650
David Benjamin30789da2015-08-29 22:56:45 -04001651 // Consume a close_notify from the peer if one hasn't been received
1652 // already. This avoids the peer from failing |SSL_shutdown| due to a
1653 // write failing.
1654 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1655 for c.in.error() == nil {
1656 c.readRecord(recordTypeAlert)
1657 }
1658 if c.in.error() != io.EOF {
1659 alertErr = c.in.error()
1660 }
1661 }
1662
Adam Langley95c29f32014-06-20 12:00:00 -07001663 if err := c.conn.Close(); err != nil {
1664 return err
1665 }
1666 return alertErr
1667}
1668
1669// Handshake runs the client or server handshake
1670// protocol if it has not yet been run.
1671// Most uses of this package need not call Handshake
1672// explicitly: the first Read or Write will call it automatically.
1673func (c *Conn) Handshake() error {
1674 c.handshakeMutex.Lock()
1675 defer c.handshakeMutex.Unlock()
1676 if err := c.handshakeErr; err != nil {
1677 return err
1678 }
1679 if c.handshakeComplete {
1680 return nil
1681 }
1682
David Benjamin9a41d1b2015-05-16 01:30:09 -04001683 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1684 c.conn.Write([]byte{
1685 byte(recordTypeAlert), // type
1686 0xfe, 0xff, // version
1687 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1688 0x0, 0x2, // length
1689 })
1690 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1691 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001692 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1693 c.writeRecord(recordTypeApplicationData, data)
1694 }
Adam Langley95c29f32014-06-20 12:00:00 -07001695 if c.isClient {
1696 c.handshakeErr = c.clientHandshake()
1697 } else {
1698 c.handshakeErr = c.serverHandshake()
1699 }
David Benjaminddb9f152015-02-03 15:44:39 -05001700 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1701 c.writeRecord(recordType(42), []byte("invalid record"))
1702 }
Adam Langley95c29f32014-06-20 12:00:00 -07001703 return c.handshakeErr
1704}
1705
1706// ConnectionState returns basic TLS details about the connection.
1707func (c *Conn) ConnectionState() ConnectionState {
1708 c.handshakeMutex.Lock()
1709 defer c.handshakeMutex.Unlock()
1710
1711 var state ConnectionState
1712 state.HandshakeComplete = c.handshakeComplete
1713 if c.handshakeComplete {
1714 state.Version = c.vers
1715 state.NegotiatedProtocol = c.clientProtocol
1716 state.DidResume = c.didResume
1717 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001718 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001719 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001720 state.PeerCertificates = c.peerCertificates
1721 state.VerifiedChains = c.verifiedChains
1722 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001723 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001724 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001725 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001726 state.SCTList = c.sctList
Nick Harper60edffd2016-06-21 15:19:24 -07001727 state.PeerSignatureAlgorithm = c.peerSignatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -04001728 state.CurveID = c.curveID
Adam Langley95c29f32014-06-20 12:00:00 -07001729 }
1730
1731 return state
1732}
1733
1734// OCSPResponse returns the stapled OCSP response from the TLS server, if
1735// any. (Only valid for client connections.)
1736func (c *Conn) OCSPResponse() []byte {
1737 c.handshakeMutex.Lock()
1738 defer c.handshakeMutex.Unlock()
1739
1740 return c.ocspResponse
1741}
1742
1743// VerifyHostname checks that the peer certificate chain is valid for
1744// connecting to host. If so, it returns nil; if not, it returns an error
1745// describing the problem.
1746func (c *Conn) VerifyHostname(host string) error {
1747 c.handshakeMutex.Lock()
1748 defer c.handshakeMutex.Unlock()
1749 if !c.isClient {
1750 return errors.New("tls: VerifyHostname called on TLS server connection")
1751 }
1752 if !c.handshakeComplete {
1753 return errors.New("tls: handshake has not yet been performed")
1754 }
1755 return c.peerCertificates[0].VerifyHostname(host)
1756}
David Benjaminc565ebb2015-04-03 04:06:36 -04001757
1758// ExportKeyingMaterial exports keying material from the current connection
1759// state, as per RFC 5705.
1760func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1761 c.handshakeMutex.Lock()
1762 defer c.handshakeMutex.Unlock()
1763 if !c.handshakeComplete {
1764 return nil, errors.New("tls: handshake has not yet been performed")
1765 }
1766
David Benjamin8d315d72016-07-18 01:03:18 +02001767 if c.vers >= VersionTLS13 {
David Benjamin97a0a082016-07-13 17:57:35 -04001768 // TODO(davidben): What should we do with useContext? See
1769 // https://github.com/tlswg/tls13-spec/issues/546
1770 return hkdfExpandLabel(c.cipherSuite.hash(), c.exporterSecret, label, context, length), nil
1771 }
1772
David Benjaminc565ebb2015-04-03 04:06:36 -04001773 seedLen := len(c.clientRandom) + len(c.serverRandom)
1774 if useContext {
1775 seedLen += 2 + len(context)
1776 }
1777 seed := make([]byte, 0, seedLen)
1778 seed = append(seed, c.clientRandom[:]...)
1779 seed = append(seed, c.serverRandom[:]...)
1780 if useContext {
1781 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1782 seed = append(seed, context...)
1783 }
1784 result := make([]byte, length)
David Benjamin97a0a082016-07-13 17:57:35 -04001785 prfForVersion(c.vers, c.cipherSuite)(result, c.exporterSecret, label, seed)
David Benjaminc565ebb2015-04-03 04:06:36 -04001786 return result, nil
1787}
David Benjamin3e052de2015-11-25 20:10:31 -05001788
1789// noRenegotiationInfo returns true if the renegotiation info extension
1790// should be supported in the current handshake.
1791func (c *Conn) noRenegotiationInfo() bool {
1792 if c.config.Bugs.NoRenegotiationInfo {
1793 return true
1794 }
1795 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1796 return true
1797 }
1798 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1799 return true
1800 }
1801 return false
1802}
David Benjamin58104882016-07-18 01:25:41 +02001803
1804func (c *Conn) SendNewSessionTicket() error {
1805 if c.isClient || c.vers < VersionTLS13 {
1806 return errors.New("tls: cannot send post-handshake NewSessionTicket")
1807 }
1808
1809 var peerCertificatesRaw [][]byte
1810 for _, cert := range c.peerCertificates {
1811 peerCertificatesRaw = append(peerCertificatesRaw, cert.Raw)
1812 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001813
Steven Valdeza833c352016-11-01 13:39:36 -04001814 addBuffer := make([]byte, 4)
1815 _, err := io.ReadFull(c.config.rand(), addBuffer)
1816 if err != nil {
1817 c.sendAlert(alertInternalError)
1818 return errors.New("tls: short read from Rand: " + err.Error())
1819 }
1820 ticketAgeAdd := uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0])
1821
David Benjamin58104882016-07-18 01:25:41 +02001822 // TODO(davidben): Allow configuring these values.
1823 m := &newSessionTicketMsg{
David Benjamin9c33ae82017-01-08 06:04:43 -05001824 version: c.vers,
1825 ticketLifetime: uint32(24 * time.Hour / time.Second),
David Benjamin9c33ae82017-01-08 06:04:43 -05001826 duplicateEarlyDataInfo: c.config.Bugs.DuplicateTicketEarlyDataInfo,
1827 customExtension: c.config.Bugs.CustomTicketExtension,
1828 ticketAgeAdd: ticketAgeAdd,
Nick Harperab20cec2016-12-19 17:38:41 -08001829 maxEarlyDataSize: c.config.MaxEarlyDataSize,
David Benjamin58104882016-07-18 01:25:41 +02001830 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001831
David Benjamin17b30832017-01-28 14:00:32 -05001832 if c.config.Bugs.SendTicketLifetime != 0 {
1833 m.ticketLifetime = uint32(c.config.Bugs.SendTicketLifetime / time.Second)
1834 }
1835
Nick Harper0b3625b2016-07-25 16:16:28 -07001836 state := sessionState{
1837 vers: c.vers,
1838 cipherSuite: c.cipherSuite.id,
1839 masterSecret: c.resumptionSecret,
1840 certificates: peerCertificatesRaw,
1841 ticketCreationTime: c.config.time(),
1842 ticketExpiration: c.config.time().Add(time.Duration(m.ticketLifetime) * time.Second),
Steven Valdeza833c352016-11-01 13:39:36 -04001843 ticketAgeAdd: uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0]),
Steven Valdez2d850622017-01-11 11:34:52 -05001844 earlyALPN: []byte(c.clientProtocol),
Nick Harper0b3625b2016-07-25 16:16:28 -07001845 }
1846
David Benjamin58104882016-07-18 01:25:41 +02001847 if !c.config.Bugs.SendEmptySessionTicket {
1848 var err error
1849 m.ticket, err = c.encryptTicket(&state)
1850 if err != nil {
1851 return err
1852 }
1853 }
David Benjamin58104882016-07-18 01:25:41 +02001854 c.out.Lock()
1855 defer c.out.Unlock()
Steven Valdeza833c352016-11-01 13:39:36 -04001856 _, err = c.writeRecord(recordTypeHandshake, m.marshal())
David Benjamin58104882016-07-18 01:25:41 +02001857 return err
1858}
David Benjamin21c00282016-07-18 21:56:23 +02001859
Steven Valdezc4aa7272016-10-03 12:25:56 -04001860func (c *Conn) SendKeyUpdate(keyUpdateRequest byte) error {
David Benjamin21c00282016-07-18 21:56:23 +02001861 c.out.Lock()
1862 defer c.out.Unlock()
Steven Valdezc4aa7272016-10-03 12:25:56 -04001863 return c.sendKeyUpdateLocked(keyUpdateRequest)
David Benjamin21c00282016-07-18 21:56:23 +02001864}
1865
Steven Valdezc4aa7272016-10-03 12:25:56 -04001866func (c *Conn) sendKeyUpdateLocked(keyUpdateRequest byte) error {
David Benjamin7f0965a2016-09-30 15:14:01 -04001867 if c.vers < VersionTLS13 {
1868 return errors.New("tls: attempted to send KeyUpdate before TLS 1.3")
1869 }
1870
Steven Valdezc4aa7272016-10-03 12:25:56 -04001871 m := keyUpdateMsg{
1872 keyUpdateRequest: keyUpdateRequest,
1873 }
David Benjamin21c00282016-07-18 21:56:23 +02001874 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
1875 return err
1876 }
1877 if err := c.flushHandshake(); err != nil {
1878 return err
1879 }
Steven Valdez1dc53d22016-07-26 12:27:38 -04001880 c.out.doKeyUpdate(c, true)
David Benjamin21c00282016-07-18 21:56:23 +02001881 return nil
1882}
Steven Valdeza4ee74d2016-11-29 13:36:45 -05001883
1884func (c *Conn) sendFakeEarlyData(len int) error {
1885 // Assemble a fake early data record. This does not use writeRecord
1886 // because the record layer may be using different keys at this point.
1887 payload := make([]byte, 5+len)
1888 payload[0] = byte(recordTypeApplicationData)
1889 payload[1] = 3
1890 payload[2] = 1
1891 payload[3] = byte(len >> 8)
1892 payload[4] = byte(len)
1893 _, err := c.conn.Write(payload)
1894 return err
1895}