blob: 2332e6bfc83872b60c5d2c4a41126a1bdb8041b8 [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 }
784 } else {
David Benjamine6f22212016-11-08 14:28:24 -0500785 expect = c.config.Bugs.ExpectInitialRecordVersion
786 }
787 if expect != 0 && vers != expect {
788 c.sendAlert(alertProtocolVersion)
789 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 -0500790 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400791 }
792 if n > maxCiphertext {
793 c.sendAlert(alertRecordOverflow)
794 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
795 }
796 if !c.haveVers {
797 // First message, be extra suspicious:
798 // this might not be a TLS client.
799 // Bail out before reading a full 'body', if possible.
800 // The current max version is 3.1.
801 // If the version is >= 16.0, it's probably not real.
802 // Similarly, a clientHello message encodes in
803 // well under a kilobyte. If the length is >= 12 kB,
804 // it's probably not real.
805 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
806 c.sendAlert(alertUnexpectedMessage)
807 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
808 }
809 }
810 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
811 if err == io.EOF {
812 err = io.ErrUnexpectedEOF
813 }
814 if e, ok := err.(net.Error); !ok || !e.Temporary() {
815 c.in.setErrorLocked(err)
816 }
817 return 0, nil, err
818 }
819
820 // Process message.
821 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
David Benjaminff26f092016-07-01 16:13:42 -0400822 ok, off, encTyp, alertValue := c.in.decrypt(b)
Nick Harper47383aa2016-11-30 12:50:43 -0800823
824 // Handle skipping over early data.
825 if !ok && c.skipEarlyData {
826 goto RestartReadRecord
827 }
828
829 // If the server is expecting a second ClientHello (in response to
830 // a HelloRetryRequest) and the client sends early data, there
831 // won't be a decryption failure but it still needs to be skipped.
832 if c.in.cipher == nil && typ == recordTypeApplicationData && c.skipEarlyData {
833 goto RestartReadRecord
834 }
835
David Benjaminff26f092016-07-01 16:13:42 -0400836 if !ok {
837 return 0, nil, c.in.setErrorLocked(c.sendAlert(alertValue))
838 }
839 b.off = off
Nick Harper47383aa2016-11-30 12:50:43 -0800840 c.skipEarlyData = false
David Benjaminff26f092016-07-01 16:13:42 -0400841
Nick Harper1fd39d82016-06-14 18:14:35 -0700842 if c.vers >= VersionTLS13 && c.in.cipher != nil {
David Benjaminc9ae27c2016-06-24 22:56:37 -0400843 if typ != recordTypeApplicationData {
844 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: outer record type is not application data"))
845 }
Nick Harper1fd39d82016-06-14 18:14:35 -0700846 typ = encTyp
847 }
David Benjamin09ed1192017-07-14 20:11:07 -0400848
849 length := len(b.data[b.off:])
850 if c.config.Bugs.ExpectRecordSplitting && typ == recordTypeApplicationData && length != 1 && !c.seenOneByteRecord {
851 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: application data records were not split"))
852 }
853
854 c.seenOneByteRecord = typ == recordTypeApplicationData && length == 1
David Benjamin83c0bc92014-08-04 01:23:53 -0400855 return typ, b, nil
856}
857
Adam Langley95c29f32014-06-20 12:00:00 -0700858// readRecord reads the next TLS record from the connection
859// and updates the record layer state.
860// c.in.Mutex <= L; c.input == nil.
861func (c *Conn) readRecord(want recordType) error {
862 // Caller must be in sync with connection:
863 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700864 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700865 switch want {
866 default:
867 c.sendAlert(alertInternalError)
868 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
David Benjaminbbba9392017-04-06 12:54:12 -0400869 case recordTypeChangeCipherSpec:
Adam Langley95c29f32014-06-20 12:00:00 -0700870 if c.handshakeComplete {
871 c.sendAlert(alertInternalError)
David Benjaminbbba9392017-04-06 12:54:12 -0400872 return c.in.setErrorLocked(errors.New("tls: ChangeCipherSpec requested after handshake complete"))
Adam Langley95c29f32014-06-20 12:00:00 -0700873 }
Steven Valdeze831a812017-03-09 14:56:07 -0500874 case recordTypeApplicationData, recordTypeAlert, recordTypeHandshake:
875 break
Adam Langley95c29f32014-06-20 12:00:00 -0700876 }
877
878Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400879 typ, b, err := c.doReadRecord(want)
880 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700881 return err
882 }
Adam Langley95c29f32014-06-20 12:00:00 -0700883 data := b.data[b.off:]
David Benjamine3fbb362017-01-06 16:19:28 -0500884 max := maxPlaintext
885 if c.config.Bugs.MaxReceivePlaintext != 0 {
886 max = c.config.Bugs.MaxReceivePlaintext
887 }
888 if len(data) > max {
Adam Langley95c29f32014-06-20 12:00:00 -0700889 err := c.sendAlert(alertRecordOverflow)
890 c.in.freeBlock(b)
891 return c.in.setErrorLocked(err)
892 }
893
894 switch typ {
895 default:
896 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
897
898 case recordTypeAlert:
899 if len(data) != 2 {
900 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
901 break
902 }
903 if alert(data[1]) == alertCloseNotify {
904 c.in.setErrorLocked(io.EOF)
905 break
906 }
907 switch data[0] {
908 case alertLevelWarning:
David Benjamin053fee92017-01-02 08:30:36 -0500909 if alert(data[1]) == alertNoCertificate {
910 c.in.freeBlock(b)
911 return errNoCertificateAlert
912 }
Nick Harperab20cec2016-12-19 17:38:41 -0800913 if alert(data[1]) == alertEndOfEarlyData {
914 c.in.freeBlock(b)
915 return errEndOfEarlyDataAlert
916 }
David Benjamin053fee92017-01-02 08:30:36 -0500917
Adam Langley95c29f32014-06-20 12:00:00 -0700918 // drop on the floor
919 c.in.freeBlock(b)
920 goto Again
921 case alertLevelError:
922 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
923 default:
924 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
925 }
926
927 case recordTypeChangeCipherSpec:
928 if typ != want || len(data) != 1 || data[0] != 1 {
929 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
930 break
931 }
Steven Valdez520e1222017-06-13 12:45:25 -0400932 if c.wireVersion != tls13ExperimentVersion {
933 err := c.in.changeCipherSpec(c.config)
934 if err != nil {
935 c.in.setErrorLocked(c.sendAlert(err.(alert)))
936 }
Adam Langley95c29f32014-06-20 12:00:00 -0700937 }
938
939 case recordTypeApplicationData:
940 if typ != want {
941 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
942 break
943 }
944 c.input = b
945 b = nil
946
947 case recordTypeHandshake:
David Benjamind5a4ecb2016-07-18 01:17:13 +0200948 // Allow handshake data while reading application data to
949 // trigger post-handshake messages.
Adam Langley95c29f32014-06-20 12:00:00 -0700950 // TODO(rsc): Should at least pick off connection close.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200951 if typ != want && want != recordTypeApplicationData {
952 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
Adam Langley95c29f32014-06-20 12:00:00 -0700953 }
954 c.hand.Write(data)
955 }
956
957 if b != nil {
958 c.in.freeBlock(b)
959 }
960 return c.in.err
961}
962
963// sendAlert sends a TLS alert message.
964// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400965func (c *Conn) sendAlertLocked(level byte, err alert) error {
966 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700967 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400968 if c.config.Bugs.FragmentAlert {
969 c.writeRecord(recordTypeAlert, c.tmp[0:1])
970 c.writeRecord(recordTypeAlert, c.tmp[1:2])
David Benjamin0d3a8c62016-03-11 22:25:18 -0500971 } else if c.config.Bugs.DoubleAlert {
972 copy(c.tmp[2:4], c.tmp[0:2])
973 c.writeRecord(recordTypeAlert, c.tmp[0:4])
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400974 } else {
975 c.writeRecord(recordTypeAlert, c.tmp[0:2])
976 }
David Benjamin24f346d2015-06-06 03:28:08 -0400977 // Error alerts are fatal to the connection.
978 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700979 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
980 }
981 return nil
982}
983
984// sendAlert sends a TLS alert message.
985// L < c.out.Mutex.
986func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400987 level := byte(alertLevelError)
Nick Harperf2511f12016-12-06 16:02:31 -0800988 if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertificate || err == alertEndOfEarlyData {
David Benjamin24f346d2015-06-06 03:28:08 -0400989 level = alertLevelWarning
990 }
991 return c.SendAlert(level, err)
992}
993
994func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700995 c.out.Lock()
996 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -0400997 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -0700998}
999
David Benjamind86c7672014-08-02 04:07:12 -04001000// writeV2Record writes a record for a V2ClientHello.
1001func (c *Conn) writeV2Record(data []byte) (n int, err error) {
1002 record := make([]byte, 2+len(data))
1003 record[0] = uint8(len(data)>>8) | 0x80
1004 record[1] = uint8(len(data))
1005 copy(record[2:], data)
1006 return c.conn.Write(record)
1007}
1008
Adam Langley95c29f32014-06-20 12:00:00 -07001009// writeRecord writes a TLS record with the given type and payload
1010// to the connection and updates the record layer state.
1011// c.out.Mutex <= L.
1012func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjaminebacdee2017-04-08 11:00:45 -04001013 if typ == recordTypeHandshake {
1014 msgType := data[0]
1015 if c.config.Bugs.SendWrongMessageType != 0 && msgType == c.config.Bugs.SendWrongMessageType {
1016 msgType += 42
1017 } else if msgType == typeServerHello && c.config.Bugs.SendServerHelloAsHelloRetryRequest {
1018 msgType = typeHelloRetryRequest
1019 }
1020 if msgType != data[0] {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001021 newData := make([]byte, len(data))
1022 copy(newData, data)
David Benjaminebacdee2017-04-08 11:00:45 -04001023 newData[0] = msgType
David Benjamin0b8d5da2016-07-15 00:39:56 -04001024 data = newData
1025 }
David Benjamin0b8d5da2016-07-15 00:39:56 -04001026
David Benjaminb0c761e2017-06-25 22:42:55 -04001027 if c.config.Bugs.SendTrailingMessageData != 0 && msgType == c.config.Bugs.SendTrailingMessageData {
David Benjamin639846e2016-09-09 11:41:18 -04001028 newData := make([]byte, len(data))
1029 copy(newData, data)
1030
1031 // Add a 0 to the body.
1032 newData = append(newData, 0)
1033 // Fix the header.
1034 newLen := len(newData) - 4
1035 newData[1] = byte(newLen >> 16)
1036 newData[2] = byte(newLen >> 8)
1037 newData[3] = byte(newLen)
1038
1039 data = newData
1040 }
1041 }
1042
David Benjamin83c0bc92014-08-04 01:23:53 -04001043 if c.isDTLS {
1044 return c.dtlsWriteRecord(typ, data)
1045 }
1046
David Benjamin71dd6662016-07-08 14:10:48 -07001047 if typ == recordTypeHandshake {
1048 if c.config.Bugs.SendHelloRequestBeforeEveryHandshakeMessage {
1049 newData := make([]byte, 0, 4+len(data))
1050 newData = append(newData, typeHelloRequest, 0, 0, 0)
1051 newData = append(newData, data...)
1052 data = newData
1053 }
1054
1055 if c.config.Bugs.PackHandshakeFlight {
1056 c.pendingFlight.Write(data)
1057 return len(data), nil
1058 }
David Benjamin582ba042016-07-07 12:33:25 -07001059 }
1060
David Benjaminb0c761e2017-06-25 22:42:55 -04001061 // Flush buffered data before writing anything.
1062 if err := c.flushHandshake(); err != nil {
1063 return 0, err
1064 }
1065
David Benjamin582ba042016-07-07 12:33:25 -07001066 return c.doWriteRecord(typ, data)
1067}
1068
1069func (c *Conn) doWriteRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin6f600d62016-12-21 16:06:54 -05001070 recordHeaderLen := c.out.recordHeaderLen()
Adam Langley95c29f32014-06-20 12:00:00 -07001071 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -04001072 first := true
1073 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -04001074 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -07001075 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -04001076 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -07001077 m = maxPlaintext
1078 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001079 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
1080 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -04001081 // By default, do not fragment the client_version or
1082 // server_version, which are located in the first 6
1083 // bytes.
1084 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
1085 m = 6
1086 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001087 }
Adam Langley95c29f32014-06-20 12:00:00 -07001088 explicitIVLen := 0
1089 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -04001090 first = false
Adam Langley95c29f32014-06-20 12:00:00 -07001091
1092 var cbc cbcMode
1093 if c.out.version >= VersionTLS11 {
1094 var ok bool
1095 if cbc, ok = c.out.cipher.(cbcMode); ok {
1096 explicitIVLen = cbc.BlockSize()
1097 }
1098 }
1099 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -04001100 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -07001101 explicitIVLen = 8
1102 // The AES-GCM construction in TLS has an
1103 // explicit nonce so that the nonce can be
1104 // random. However, the nonce is only 8 bytes
1105 // which is too small for a secure, random
1106 // nonce. Therefore we use the sequence number
1107 // as the nonce.
1108 explicitIVIsSeq = true
1109 }
1110 }
1111 b.resize(recordHeaderLen + explicitIVLen + m)
Steven Valdez924a3522017-03-02 16:05:03 -05001112 b.data[0] = byte(typ)
1113 if c.vers >= VersionTLS13 && c.out.cipher != nil {
1114 b.data[0] = byte(recordTypeApplicationData)
1115 if outerType := c.config.Bugs.OuterRecordType; outerType != 0 {
1116 b.data[0] = byte(outerType)
David Benjaminc9ae27c2016-06-24 22:56:37 -04001117 }
Nick Harper1fd39d82016-06-14 18:14:35 -07001118 }
Steven Valdez924a3522017-03-02 16:05:03 -05001119 vers := c.vers
1120 if vers == 0 || vers >= VersionTLS13 {
1121 // Some TLS servers fail if the record version is
1122 // greater than TLS 1.0 for the initial ClientHello.
1123 //
1124 // TLS 1.3 fixes the version number in the record
1125 // layer to {3, 1}.
1126 vers = VersionTLS10
1127 }
1128 if c.config.Bugs.SendRecordVersion != 0 {
1129 vers = c.config.Bugs.SendRecordVersion
1130 }
1131 if c.vers == 0 && c.config.Bugs.SendInitialRecordVersion != 0 {
1132 vers = c.config.Bugs.SendInitialRecordVersion
1133 }
1134 b.data[1] = byte(vers >> 8)
1135 b.data[2] = byte(vers)
1136 b.data[3] = byte(m >> 8)
1137 b.data[4] = byte(m)
Adam Langley95c29f32014-06-20 12:00:00 -07001138 if explicitIVLen > 0 {
1139 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
1140 if explicitIVIsSeq {
1141 copy(explicitIV, c.out.seq[:])
1142 } else {
1143 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
1144 break
1145 }
1146 }
1147 }
1148 copy(b.data[recordHeaderLen+explicitIVLen:], data)
Nick Harper1fd39d82016-06-14 18:14:35 -07001149 c.out.encrypt(b, explicitIVLen, typ)
Adam Langley95c29f32014-06-20 12:00:00 -07001150 _, err = c.conn.Write(b.data)
1151 if err != nil {
1152 break
1153 }
1154 n += m
1155 data = data[m:]
1156 }
1157 c.out.freeBlock(b)
1158
Steven Valdez520e1222017-06-13 12:45:25 -04001159 if typ == recordTypeChangeCipherSpec && c.wireVersion != tls13ExperimentVersion {
Adam Langley80842bd2014-06-20 12:00:00 -07001160 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -07001161 if err != nil {
David Benjamina8181342017-07-07 18:10:57 -04001162 return n, c.sendAlertLocked(alertLevelError, err.(alert))
Adam Langley95c29f32014-06-20 12:00:00 -07001163 }
1164 }
1165 return
1166}
1167
David Benjamin582ba042016-07-07 12:33:25 -07001168func (c *Conn) flushHandshake() error {
1169 if c.isDTLS {
1170 return c.dtlsFlushHandshake()
1171 }
1172
1173 for c.pendingFlight.Len() > 0 {
1174 var buf [maxPlaintext]byte
1175 n, _ := c.pendingFlight.Read(buf[:])
1176 if _, err := c.doWriteRecord(recordTypeHandshake, buf[:n]); err != nil {
1177 return err
1178 }
1179 }
1180
1181 c.pendingFlight.Reset()
1182 return nil
1183}
1184
David Benjamin83c0bc92014-08-04 01:23:53 -04001185func (c *Conn) doReadHandshake() ([]byte, error) {
1186 if c.isDTLS {
1187 return c.dtlsDoReadHandshake()
1188 }
1189
Adam Langley95c29f32014-06-20 12:00:00 -07001190 for c.hand.Len() < 4 {
1191 if err := c.in.err; err != nil {
1192 return nil, err
1193 }
1194 if err := c.readRecord(recordTypeHandshake); err != nil {
1195 return nil, err
1196 }
1197 }
1198
1199 data := c.hand.Bytes()
1200 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1201 if n > maxHandshake {
1202 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
1203 }
1204 for c.hand.Len() < 4+n {
1205 if err := c.in.err; err != nil {
1206 return nil, err
1207 }
1208 if err := c.readRecord(recordTypeHandshake); err != nil {
1209 return nil, err
1210 }
1211 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001212 return c.hand.Next(4 + n), nil
1213}
1214
1215// readHandshake reads the next handshake message from
1216// the record layer.
1217// c.in.Mutex < L; c.out.Mutex < L.
1218func (c *Conn) readHandshake() (interface{}, error) {
1219 data, err := c.doReadHandshake()
David Benjamin053fee92017-01-02 08:30:36 -05001220 if err == errNoCertificateAlert {
1221 if c.hand.Len() != 0 {
1222 // The warning alert may not interleave with a handshake message.
1223 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1224 }
1225 return new(ssl3NoCertificateMsg), nil
1226 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001227 if err != nil {
1228 return nil, err
1229 }
1230
Adam Langley95c29f32014-06-20 12:00:00 -07001231 var m handshakeMessage
1232 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001233 case typeHelloRequest:
1234 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001235 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001236 m = &clientHelloMsg{
1237 isDTLS: c.isDTLS,
1238 }
Adam Langley95c29f32014-06-20 12:00:00 -07001239 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001240 m = &serverHelloMsg{
1241 isDTLS: c.isDTLS,
1242 }
Nick Harperdcfbc672016-07-16 17:47:31 +02001243 case typeHelloRetryRequest:
1244 m = new(helloRetryRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001245 case typeNewSessionTicket:
David Benjamin58104882016-07-18 01:25:41 +02001246 m = &newSessionTicketMsg{
1247 version: c.vers,
1248 }
Nick Harperb41d2e42016-07-01 17:50:32 -04001249 case typeEncryptedExtensions:
1250 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001251 case typeCertificate:
Nick Harperb41d2e42016-07-01 17:50:32 -04001252 m = &certificateMsg{
David Benjamin8d315d72016-07-18 01:03:18 +02001253 hasRequestContext: c.vers >= VersionTLS13,
Nick Harperb41d2e42016-07-01 17:50:32 -04001254 }
Adam Langley95c29f32014-06-20 12:00:00 -07001255 case typeCertificateRequest:
1256 m = &certificateRequestMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001257 hasSignatureAlgorithm: c.vers >= VersionTLS12,
David Benjamin8d315d72016-07-18 01:03:18 +02001258 hasRequestContext: c.vers >= VersionTLS13,
Adam Langley95c29f32014-06-20 12:00:00 -07001259 }
1260 case typeCertificateStatus:
1261 m = new(certificateStatusMsg)
1262 case typeServerKeyExchange:
1263 m = new(serverKeyExchangeMsg)
1264 case typeServerHelloDone:
1265 m = new(serverHelloDoneMsg)
1266 case typeClientKeyExchange:
1267 m = new(clientKeyExchangeMsg)
1268 case typeCertificateVerify:
1269 m = &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001270 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001271 }
1272 case typeNextProtocol:
1273 m = new(nextProtoMsg)
1274 case typeFinished:
1275 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001276 case typeHelloVerifyRequest:
1277 m = new(helloVerifyRequestMsg)
David Benjamin24599a82016-06-30 18:56:53 -04001278 case typeChannelID:
1279 m = new(channelIDMsg)
David Benjamin21c00282016-07-18 21:56:23 +02001280 case typeKeyUpdate:
1281 m = new(keyUpdateMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001282 default:
1283 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1284 }
1285
1286 // The handshake message unmarshallers
1287 // expect to be able to keep references to data,
1288 // so pass in a fresh copy that won't be overwritten.
1289 data = append([]byte(nil), data...)
1290
1291 if !m.unmarshal(data) {
1292 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1293 }
1294 return m, nil
1295}
1296
David Benjamin83f90402015-01-27 01:09:43 -05001297// skipPacket processes all the DTLS records in packet. It updates
1298// sequence number expectations but otherwise ignores them.
1299func (c *Conn) skipPacket(packet []byte) error {
1300 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001301 if len(packet) < 13 {
1302 return errors.New("tls: bad packet")
1303 }
David Benjamin83f90402015-01-27 01:09:43 -05001304 // Dropped packets are completely ignored save to update
1305 // expected sequence numbers for this and the next epoch. (We
1306 // don't assert on the contents of the packets both for
1307 // simplicity and because a previous test with one shorter
1308 // timeout schedule would have done so.)
1309 epoch := packet[3:5]
1310 seq := packet[5:11]
1311 length := uint16(packet[11])<<8 | uint16(packet[12])
1312 if bytes.Equal(c.in.seq[:2], epoch) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001313 if bytes.Compare(seq, c.in.seq[2:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001314 return errors.New("tls: sequence mismatch")
1315 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001316 copy(c.in.seq[2:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001317 c.in.incSeq(false)
1318 } else {
David Benjamin13e81fc2015-11-02 17:16:13 -05001319 if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001320 return errors.New("tls: sequence mismatch")
1321 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001322 copy(c.in.nextSeq[:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001323 c.in.incNextSeq()
1324 }
David Benjamin6ca93552015-08-28 16:16:25 -04001325 if len(packet) < 13+int(length) {
1326 return errors.New("tls: bad packet")
1327 }
David Benjamin83f90402015-01-27 01:09:43 -05001328 packet = packet[13+length:]
1329 }
1330 return nil
1331}
1332
1333// simulatePacketLoss simulates the loss of a handshake leg from the
1334// peer based on the schedule in c.config.Bugs. If resendFunc is
1335// non-nil, it is called after each simulated timeout to retransmit
1336// handshake messages from the local end. This is used in cases where
1337// the peer retransmits on a stale Finished rather than a timeout.
1338func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1339 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1340 return nil
1341 }
1342 if !c.isDTLS {
1343 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1344 }
1345 if c.config.Bugs.PacketAdaptor == nil {
1346 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1347 }
1348 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1349 // Simulate a timeout.
1350 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1351 if err != nil {
1352 return err
1353 }
1354 for _, packet := range packets {
1355 if err := c.skipPacket(packet); err != nil {
1356 return err
1357 }
1358 }
1359 if resendFunc != nil {
1360 resendFunc()
1361 }
1362 }
1363 return nil
1364}
1365
David Benjamin47921102016-07-28 11:29:18 -04001366func (c *Conn) SendHalfHelloRequest() error {
1367 if err := c.Handshake(); err != nil {
1368 return err
1369 }
1370
1371 c.out.Lock()
1372 defer c.out.Unlock()
1373
1374 if _, err := c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0}); err != nil {
1375 return err
1376 }
1377 return c.flushHandshake()
1378}
1379
Adam Langley95c29f32014-06-20 12:00:00 -07001380// Write writes data to the connection.
1381func (c *Conn) Write(b []byte) (int, error) {
1382 if err := c.Handshake(); err != nil {
1383 return 0, err
1384 }
1385
1386 c.out.Lock()
1387 defer c.out.Unlock()
1388
David Benjamin12d2c482016-07-24 10:56:51 -04001389 // Flush any pending handshake data. PackHelloRequestWithFinished may
1390 // have been set and the handshake not followed by Renegotiate.
1391 c.flushHandshake()
1392
Adam Langley95c29f32014-06-20 12:00:00 -07001393 if err := c.out.err; err != nil {
1394 return 0, err
1395 }
1396
1397 if !c.handshakeComplete {
1398 return 0, alertInternalError
1399 }
1400
Steven Valdezc4aa7272016-10-03 12:25:56 -04001401 if c.keyUpdateRequested {
1402 if err := c.sendKeyUpdateLocked(keyUpdateNotRequested); err != nil {
David Benjamin21c00282016-07-18 21:56:23 +02001403 return 0, err
1404 }
Steven Valdezc4aa7272016-10-03 12:25:56 -04001405 c.keyUpdateRequested = false
David Benjamin21c00282016-07-18 21:56:23 +02001406 }
1407
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001408 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001409 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001410 }
1411
Adam Langley27a0d082015-11-03 13:34:10 -08001412 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1413 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
David Benjamin582ba042016-07-07 12:33:25 -07001414 c.flushHandshake()
Adam Langley27a0d082015-11-03 13:34:10 -08001415 }
1416
Adam Langley95c29f32014-06-20 12:00:00 -07001417 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1418 // attack when using block mode ciphers due to predictable IVs.
1419 // This can be prevented by splitting each Application Data
1420 // record into two records, effectively randomizing the IV.
1421 //
1422 // http://www.openssl.org/~bodo/tls-cbc.txt
1423 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1424 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1425
1426 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001427 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001428 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1429 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1430 if err != nil {
1431 return n, c.out.setErrorLocked(err)
1432 }
1433 m, b = 1, b[1:]
1434 }
1435 }
1436
1437 n, err := c.writeRecord(recordTypeApplicationData, b)
1438 return n + m, c.out.setErrorLocked(err)
1439}
1440
David Benjamin794cc592017-03-25 22:24:23 -05001441func (c *Conn) processTLS13NewSessionTicket(newSessionTicket *newSessionTicketMsg, cipherSuite *cipherSuite) error {
1442 if c.config.Bugs.ExpectGREASE && !newSessionTicket.hasGREASEExtension {
1443 return errors.New("tls: no GREASE ticket extension found")
1444 }
1445
1446 if c.config.Bugs.ExpectTicketEarlyDataInfo && newSessionTicket.maxEarlyDataSize == 0 {
1447 return errors.New("tls: no ticket_early_data_info extension found")
1448 }
1449
1450 if c.config.Bugs.ExpectNoNewSessionTicket {
1451 return errors.New("tls: received unexpected NewSessionTicket")
1452 }
1453
1454 if c.config.ClientSessionCache == nil || newSessionTicket.ticketLifetime == 0 {
1455 return nil
1456 }
1457
1458 session := &ClientSessionState{
1459 sessionTicket: newSessionTicket.ticket,
1460 vers: c.vers,
1461 cipherSuite: cipherSuite.id,
1462 masterSecret: c.resumptionSecret,
1463 serverCertificates: c.peerCertificates,
1464 sctList: c.sctList,
1465 ocspResponse: c.ocspResponse,
1466 ticketCreationTime: c.config.time(),
1467 ticketExpiration: c.config.time().Add(time.Duration(newSessionTicket.ticketLifetime) * time.Second),
1468 ticketAgeAdd: newSessionTicket.ticketAgeAdd,
1469 maxEarlyDataSize: newSessionTicket.maxEarlyDataSize,
1470 earlyALPN: c.clientProtocol,
1471 }
1472
1473 cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
1474 c.config.ClientSessionCache.Put(cacheKey, session)
1475 return nil
1476}
1477
David Benjamind5a4ecb2016-07-18 01:17:13 +02001478func (c *Conn) handlePostHandshakeMessage() error {
Adam Langley2ae77d22014-10-28 17:29:33 -07001479 msg, err := c.readHandshake()
1480 if err != nil {
1481 return err
1482 }
David Benjamind5a4ecb2016-07-18 01:17:13 +02001483
1484 if c.vers < VersionTLS13 {
1485 if !c.isClient {
1486 c.sendAlert(alertUnexpectedMessage)
1487 return errors.New("tls: unexpected post-handshake message")
1488 }
1489
1490 _, ok := msg.(*helloRequestMsg)
1491 if !ok {
1492 c.sendAlert(alertUnexpectedMessage)
1493 return alertUnexpectedMessage
1494 }
1495
1496 c.handshakeComplete = false
1497 return c.Handshake()
Adam Langley2ae77d22014-10-28 17:29:33 -07001498 }
1499
David Benjamind5a4ecb2016-07-18 01:17:13 +02001500 if c.isClient {
1501 if newSessionTicket, ok := msg.(*newSessionTicketMsg); ok {
David Benjamin794cc592017-03-25 22:24:23 -05001502 return c.processTLS13NewSessionTicket(newSessionTicket, c.cipherSuite)
David Benjamind5a4ecb2016-07-18 01:17:13 +02001503 }
1504 }
1505
Steven Valdezc4aa7272016-10-03 12:25:56 -04001506 if keyUpdate, ok := msg.(*keyUpdateMsg); ok {
David Benjaminbbba9392017-04-06 12:54:12 -04001507 if c.config.Bugs.RejectUnsolicitedKeyUpdate {
1508 return errors.New("tls: unexpected KeyUpdate message")
1509 }
Steven Valdez1dc53d22016-07-26 12:27:38 -04001510 c.in.doKeyUpdate(c, false)
Steven Valdezc4aa7272016-10-03 12:25:56 -04001511 if keyUpdate.keyUpdateRequest == keyUpdateRequested {
1512 c.keyUpdateRequested = true
1513 }
David Benjamin21c00282016-07-18 21:56:23 +02001514 return nil
1515 }
1516
David Benjamind5a4ecb2016-07-18 01:17:13 +02001517 c.sendAlert(alertUnexpectedMessage)
David Benjaminbbba9392017-04-06 12:54:12 -04001518 return errors.New("tls: unexpected post-handshake message")
1519}
1520
1521// Reads a KeyUpdate acknowledgment from the peer. There may not be any
1522// application data records before the message.
1523func (c *Conn) ReadKeyUpdateACK() error {
1524 c.in.Lock()
1525 defer c.in.Unlock()
1526
1527 msg, err := c.readHandshake()
1528 if err != nil {
1529 return err
1530 }
1531
1532 keyUpdate, ok := msg.(*keyUpdateMsg)
1533 if !ok {
1534 c.sendAlert(alertUnexpectedMessage)
1535 return errors.New("tls: unexpected message when reading KeyUpdate")
1536 }
1537
1538 if keyUpdate.keyUpdateRequest != keyUpdateNotRequested {
1539 return errors.New("tls: received invalid KeyUpdate message")
1540 }
1541
1542 c.in.doKeyUpdate(c, false)
1543 return nil
Adam Langley2ae77d22014-10-28 17:29:33 -07001544}
1545
Adam Langleycf2d4f42014-10-28 19:06:14 -07001546func (c *Conn) Renegotiate() error {
1547 if !c.isClient {
David Benjaminef5dfd22015-12-06 13:17:07 -05001548 helloReq := new(helloRequestMsg).marshal()
1549 if c.config.Bugs.BadHelloRequest != nil {
1550 helloReq = c.config.Bugs.BadHelloRequest
1551 }
1552 c.writeRecord(recordTypeHandshake, helloReq)
David Benjamin582ba042016-07-07 12:33:25 -07001553 c.flushHandshake()
Adam Langleycf2d4f42014-10-28 19:06:14 -07001554 }
1555
1556 c.handshakeComplete = false
1557 return c.Handshake()
1558}
1559
Adam Langley95c29f32014-06-20 12:00:00 -07001560// Read can be made to time out and return a net.Error with Timeout() == true
1561// after a fixed time limit; see SetDeadline and SetReadDeadline.
1562func (c *Conn) Read(b []byte) (n int, err error) {
1563 if err = c.Handshake(); err != nil {
1564 return
1565 }
1566
1567 c.in.Lock()
1568 defer c.in.Unlock()
1569
1570 // Some OpenSSL servers send empty records in order to randomize the
1571 // CBC IV. So this loop ignores a limited number of empty records.
1572 const maxConsecutiveEmptyRecords = 100
1573 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1574 for c.input == nil && c.in.err == nil {
1575 if err := c.readRecord(recordTypeApplicationData); err != nil {
1576 // Soft error, like EAGAIN
1577 return 0, err
1578 }
David Benjamind9b091b2015-01-27 01:10:54 -05001579 if c.hand.Len() > 0 {
David Benjamind5a4ecb2016-07-18 01:17:13 +02001580 // We received handshake bytes, indicating a
1581 // post-handshake message.
1582 if err := c.handlePostHandshakeMessage(); err != nil {
Adam Langley2ae77d22014-10-28 17:29:33 -07001583 return 0, err
1584 }
1585 continue
1586 }
Adam Langley95c29f32014-06-20 12:00:00 -07001587 }
1588 if err := c.in.err; err != nil {
1589 return 0, err
1590 }
1591
1592 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001593 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001594 c.in.freeBlock(c.input)
1595 c.input = nil
1596 }
1597
1598 // If a close-notify alert is waiting, read it so that
1599 // we can return (n, EOF) instead of (n, nil), to signal
1600 // to the HTTP response reading goroutine that the
1601 // connection is now closed. This eliminates a race
1602 // where the HTTP response reading goroutine would
1603 // otherwise not observe the EOF until its next read,
1604 // by which time a client goroutine might have already
1605 // tried to reuse the HTTP connection for a new
1606 // request.
1607 // See https://codereview.appspot.com/76400046
1608 // and http://golang.org/issue/3514
1609 if ri := c.rawInput; ri != nil &&
1610 n != 0 && err == nil &&
1611 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1612 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1613 err = recErr // will be io.EOF on closeNotify
1614 }
1615 }
1616
1617 if n != 0 || err != nil {
1618 return n, err
1619 }
1620 }
1621
1622 return 0, io.ErrNoProgress
1623}
1624
1625// Close closes the connection.
1626func (c *Conn) Close() error {
1627 var alertErr error
1628
1629 c.handshakeMutex.Lock()
1630 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001631 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
David Benjaminfa214e42016-05-10 17:03:10 -04001632 alert := alertCloseNotify
1633 if c.config.Bugs.SendAlertOnShutdown != 0 {
1634 alert = c.config.Bugs.SendAlertOnShutdown
1635 }
1636 alertErr = c.sendAlert(alert)
David Benjamin4d559612016-05-18 14:31:51 -04001637 // Clear local alerts when sending alerts so we continue to wait
1638 // for the peer rather than closing the socket early.
1639 if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1640 alertErr = nil
1641 }
Adam Langley95c29f32014-06-20 12:00:00 -07001642 }
1643
David Benjamin30789da2015-08-29 22:56:45 -04001644 // Consume a close_notify from the peer if one hasn't been received
1645 // already. This avoids the peer from failing |SSL_shutdown| due to a
1646 // write failing.
1647 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1648 for c.in.error() == nil {
1649 c.readRecord(recordTypeAlert)
1650 }
1651 if c.in.error() != io.EOF {
1652 alertErr = c.in.error()
1653 }
1654 }
1655
Adam Langley95c29f32014-06-20 12:00:00 -07001656 if err := c.conn.Close(); err != nil {
1657 return err
1658 }
1659 return alertErr
1660}
1661
1662// Handshake runs the client or server handshake
1663// protocol if it has not yet been run.
1664// Most uses of this package need not call Handshake
1665// explicitly: the first Read or Write will call it automatically.
1666func (c *Conn) Handshake() error {
1667 c.handshakeMutex.Lock()
1668 defer c.handshakeMutex.Unlock()
1669 if err := c.handshakeErr; err != nil {
1670 return err
1671 }
1672 if c.handshakeComplete {
1673 return nil
1674 }
1675
David Benjamin9a41d1b2015-05-16 01:30:09 -04001676 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1677 c.conn.Write([]byte{
1678 byte(recordTypeAlert), // type
1679 0xfe, 0xff, // version
1680 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1681 0x0, 0x2, // length
1682 })
1683 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1684 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001685 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1686 c.writeRecord(recordTypeApplicationData, data)
1687 }
Adam Langley95c29f32014-06-20 12:00:00 -07001688 if c.isClient {
1689 c.handshakeErr = c.clientHandshake()
1690 } else {
1691 c.handshakeErr = c.serverHandshake()
1692 }
David Benjaminddb9f152015-02-03 15:44:39 -05001693 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1694 c.writeRecord(recordType(42), []byte("invalid record"))
1695 }
Adam Langley95c29f32014-06-20 12:00:00 -07001696 return c.handshakeErr
1697}
1698
1699// ConnectionState returns basic TLS details about the connection.
1700func (c *Conn) ConnectionState() ConnectionState {
1701 c.handshakeMutex.Lock()
1702 defer c.handshakeMutex.Unlock()
1703
1704 var state ConnectionState
1705 state.HandshakeComplete = c.handshakeComplete
1706 if c.handshakeComplete {
1707 state.Version = c.vers
1708 state.NegotiatedProtocol = c.clientProtocol
1709 state.DidResume = c.didResume
1710 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001711 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001712 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001713 state.PeerCertificates = c.peerCertificates
1714 state.VerifiedChains = c.verifiedChains
1715 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001716 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001717 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001718 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001719 state.SCTList = c.sctList
Nick Harper60edffd2016-06-21 15:19:24 -07001720 state.PeerSignatureAlgorithm = c.peerSignatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -04001721 state.CurveID = c.curveID
Adam Langley95c29f32014-06-20 12:00:00 -07001722 }
1723
1724 return state
1725}
1726
1727// OCSPResponse returns the stapled OCSP response from the TLS server, if
1728// any. (Only valid for client connections.)
1729func (c *Conn) OCSPResponse() []byte {
1730 c.handshakeMutex.Lock()
1731 defer c.handshakeMutex.Unlock()
1732
1733 return c.ocspResponse
1734}
1735
1736// VerifyHostname checks that the peer certificate chain is valid for
1737// connecting to host. If so, it returns nil; if not, it returns an error
1738// describing the problem.
1739func (c *Conn) VerifyHostname(host string) error {
1740 c.handshakeMutex.Lock()
1741 defer c.handshakeMutex.Unlock()
1742 if !c.isClient {
1743 return errors.New("tls: VerifyHostname called on TLS server connection")
1744 }
1745 if !c.handshakeComplete {
1746 return errors.New("tls: handshake has not yet been performed")
1747 }
1748 return c.peerCertificates[0].VerifyHostname(host)
1749}
David Benjaminc565ebb2015-04-03 04:06:36 -04001750
1751// ExportKeyingMaterial exports keying material from the current connection
1752// state, as per RFC 5705.
1753func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1754 c.handshakeMutex.Lock()
1755 defer c.handshakeMutex.Unlock()
1756 if !c.handshakeComplete {
1757 return nil, errors.New("tls: handshake has not yet been performed")
1758 }
1759
David Benjamin8d315d72016-07-18 01:03:18 +02001760 if c.vers >= VersionTLS13 {
David Benjamin97a0a082016-07-13 17:57:35 -04001761 // TODO(davidben): What should we do with useContext? See
1762 // https://github.com/tlswg/tls13-spec/issues/546
1763 return hkdfExpandLabel(c.cipherSuite.hash(), c.exporterSecret, label, context, length), nil
1764 }
1765
David Benjaminc565ebb2015-04-03 04:06:36 -04001766 seedLen := len(c.clientRandom) + len(c.serverRandom)
1767 if useContext {
1768 seedLen += 2 + len(context)
1769 }
1770 seed := make([]byte, 0, seedLen)
1771 seed = append(seed, c.clientRandom[:]...)
1772 seed = append(seed, c.serverRandom[:]...)
1773 if useContext {
1774 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1775 seed = append(seed, context...)
1776 }
1777 result := make([]byte, length)
David Benjamin97a0a082016-07-13 17:57:35 -04001778 prfForVersion(c.vers, c.cipherSuite)(result, c.exporterSecret, label, seed)
David Benjaminc565ebb2015-04-03 04:06:36 -04001779 return result, nil
1780}
David Benjamin3e052de2015-11-25 20:10:31 -05001781
1782// noRenegotiationInfo returns true if the renegotiation info extension
1783// should be supported in the current handshake.
1784func (c *Conn) noRenegotiationInfo() bool {
1785 if c.config.Bugs.NoRenegotiationInfo {
1786 return true
1787 }
1788 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1789 return true
1790 }
1791 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1792 return true
1793 }
1794 return false
1795}
David Benjamin58104882016-07-18 01:25:41 +02001796
1797func (c *Conn) SendNewSessionTicket() error {
1798 if c.isClient || c.vers < VersionTLS13 {
1799 return errors.New("tls: cannot send post-handshake NewSessionTicket")
1800 }
1801
1802 var peerCertificatesRaw [][]byte
1803 for _, cert := range c.peerCertificates {
1804 peerCertificatesRaw = append(peerCertificatesRaw, cert.Raw)
1805 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001806
Steven Valdeza833c352016-11-01 13:39:36 -04001807 addBuffer := make([]byte, 4)
1808 _, err := io.ReadFull(c.config.rand(), addBuffer)
1809 if err != nil {
1810 c.sendAlert(alertInternalError)
1811 return errors.New("tls: short read from Rand: " + err.Error())
1812 }
1813 ticketAgeAdd := uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0])
1814
David Benjamin58104882016-07-18 01:25:41 +02001815 // TODO(davidben): Allow configuring these values.
1816 m := &newSessionTicketMsg{
David Benjamin9c33ae82017-01-08 06:04:43 -05001817 version: c.vers,
1818 ticketLifetime: uint32(24 * time.Hour / time.Second),
David Benjamin9c33ae82017-01-08 06:04:43 -05001819 duplicateEarlyDataInfo: c.config.Bugs.DuplicateTicketEarlyDataInfo,
1820 customExtension: c.config.Bugs.CustomTicketExtension,
1821 ticketAgeAdd: ticketAgeAdd,
Nick Harperab20cec2016-12-19 17:38:41 -08001822 maxEarlyDataSize: c.config.MaxEarlyDataSize,
David Benjamin58104882016-07-18 01:25:41 +02001823 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001824
David Benjamin17b30832017-01-28 14:00:32 -05001825 if c.config.Bugs.SendTicketLifetime != 0 {
1826 m.ticketLifetime = uint32(c.config.Bugs.SendTicketLifetime / time.Second)
1827 }
1828
Nick Harper0b3625b2016-07-25 16:16:28 -07001829 state := sessionState{
1830 vers: c.vers,
1831 cipherSuite: c.cipherSuite.id,
1832 masterSecret: c.resumptionSecret,
1833 certificates: peerCertificatesRaw,
1834 ticketCreationTime: c.config.time(),
1835 ticketExpiration: c.config.time().Add(time.Duration(m.ticketLifetime) * time.Second),
Steven Valdeza833c352016-11-01 13:39:36 -04001836 ticketAgeAdd: uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0]),
Steven Valdez2d850622017-01-11 11:34:52 -05001837 earlyALPN: []byte(c.clientProtocol),
Nick Harper0b3625b2016-07-25 16:16:28 -07001838 }
1839
David Benjamin58104882016-07-18 01:25:41 +02001840 if !c.config.Bugs.SendEmptySessionTicket {
1841 var err error
1842 m.ticket, err = c.encryptTicket(&state)
1843 if err != nil {
1844 return err
1845 }
1846 }
David Benjamin58104882016-07-18 01:25:41 +02001847 c.out.Lock()
1848 defer c.out.Unlock()
Steven Valdeza833c352016-11-01 13:39:36 -04001849 _, err = c.writeRecord(recordTypeHandshake, m.marshal())
David Benjamin58104882016-07-18 01:25:41 +02001850 return err
1851}
David Benjamin21c00282016-07-18 21:56:23 +02001852
Steven Valdezc4aa7272016-10-03 12:25:56 -04001853func (c *Conn) SendKeyUpdate(keyUpdateRequest byte) error {
David Benjamin21c00282016-07-18 21:56:23 +02001854 c.out.Lock()
1855 defer c.out.Unlock()
Steven Valdezc4aa7272016-10-03 12:25:56 -04001856 return c.sendKeyUpdateLocked(keyUpdateRequest)
David Benjamin21c00282016-07-18 21:56:23 +02001857}
1858
Steven Valdezc4aa7272016-10-03 12:25:56 -04001859func (c *Conn) sendKeyUpdateLocked(keyUpdateRequest byte) error {
David Benjamin7f0965a2016-09-30 15:14:01 -04001860 if c.vers < VersionTLS13 {
1861 return errors.New("tls: attempted to send KeyUpdate before TLS 1.3")
1862 }
1863
Steven Valdezc4aa7272016-10-03 12:25:56 -04001864 m := keyUpdateMsg{
1865 keyUpdateRequest: keyUpdateRequest,
1866 }
David Benjamin21c00282016-07-18 21:56:23 +02001867 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
1868 return err
1869 }
1870 if err := c.flushHandshake(); err != nil {
1871 return err
1872 }
Steven Valdez1dc53d22016-07-26 12:27:38 -04001873 c.out.doKeyUpdate(c, true)
David Benjamin21c00282016-07-18 21:56:23 +02001874 return nil
1875}
Steven Valdeza4ee74d2016-11-29 13:36:45 -05001876
1877func (c *Conn) sendFakeEarlyData(len int) error {
1878 // Assemble a fake early data record. This does not use writeRecord
1879 // because the record layer may be using different keys at this point.
1880 payload := make([]byte, 5+len)
1881 payload[0] = byte(recordTypeApplicationData)
1882 payload[1] = 3
1883 payload[2] = 1
1884 payload[3] = byte(len >> 8)
1885 payload[4] = byte(len)
1886 _, err := c.conn.Write(payload)
1887 return err
1888}