blob: 0235e42d184873ad9ac4f70d9ed173d57ccc6df4 [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")
25
Adam Langley95c29f32014-06-20 12:00:00 -070026// A Conn represents a secured connection.
27// It implements the net.Conn interface.
28type Conn struct {
29 // constant
30 conn net.Conn
David Benjamin83c0bc92014-08-04 01:23:53 -040031 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -070032 isClient bool
33
34 // constant after handshake; protected by handshakeMutex
Adam Langley75712922014-10-10 16:23:43 -070035 handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
36 handshakeErr error // error resulting from handshake
37 vers uint16 // TLS version
38 haveVers bool // version has been negotiated
39 config *Config // configuration passed to constructor
40 handshakeComplete bool
Nick Harper47383aa2016-11-30 12:50:43 -080041 skipEarlyData bool
Adam Langley75712922014-10-10 16:23:43 -070042 didResume bool // whether this connection was a session resumption
43 extendedMasterSecret bool // whether this session used an extended master secret
David Benjaminc565ebb2015-04-03 04:06:36 -040044 cipherSuite *cipherSuite
Adam Langley75712922014-10-10 16:23:43 -070045 ocspResponse []byte // stapled OCSP response
Paul Lietar4fac72e2015-09-09 13:44:55 +010046 sctList []byte // signed certificate timestamp list
Adam Langley75712922014-10-10 16:23:43 -070047 peerCertificates []*x509.Certificate
Adam Langley95c29f32014-06-20 12:00:00 -070048 // verifiedChains contains the certificate chains that we built, as
49 // opposed to the ones presented by the server.
50 verifiedChains [][]*x509.Certificate
51 // serverName contains the server name indicated by the client, if any.
Adam Langleyaf0e32c2015-06-03 09:57:23 -070052 serverName string
53 // firstFinished contains the first Finished hash sent during the
54 // handshake. This is the "tls-unique" channel binding value.
55 firstFinished [12]byte
Nick Harper60edffd2016-06-21 15:19:24 -070056 // peerSignatureAlgorithm contains the signature algorithm that was used
57 // by the peer in the handshake, or zero if not applicable.
58 peerSignatureAlgorithm signatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -040059 // curveID contains the curve that was used in the handshake, or zero if
60 // not applicable.
61 curveID CurveID
Adam Langleyaf0e32c2015-06-03 09:57:23 -070062
David Benjaminc565ebb2015-04-03 04:06:36 -040063 clientRandom, serverRandom [32]byte
David Benjamin97a0a082016-07-13 17:57:35 -040064 exporterSecret []byte
David Benjamin58104882016-07-18 01:25:41 +020065 resumptionSecret []byte
Adam Langley95c29f32014-06-20 12:00:00 -070066
67 clientProtocol string
68 clientProtocolFallback bool
David Benjaminfc7b0862014-09-06 13:21:53 -040069 usedALPN bool
Adam Langley95c29f32014-06-20 12:00:00 -070070
Adam Langley2ae77d22014-10-28 17:29:33 -070071 // verify_data values for the renegotiation extension.
72 clientVerify []byte
73 serverVerify []byte
74
David Benjamind30a9902014-08-24 01:44:23 -040075 channelID *ecdsa.PublicKey
76
David Benjaminca6c8262014-11-15 19:06:08 -050077 srtpProtectionProfile uint16
78
David Benjaminc44b1df2014-11-23 12:11:01 -050079 clientVersion uint16
80
Adam Langley95c29f32014-06-20 12:00:00 -070081 // input/output
82 in, out halfConn // in.Mutex < out.Mutex
83 rawInput *block // raw input, right off the wire
David Benjamin83c0bc92014-08-04 01:23:53 -040084 input *block // application record waiting to be read
85 hand bytes.Buffer // handshake record waiting to be read
86
David Benjamin582ba042016-07-07 12:33:25 -070087 // pendingFlight, if PackHandshakeFlight is enabled, is the buffer of
88 // handshake data to be split into records at the end of the flight.
89 pendingFlight bytes.Buffer
90
David Benjamin83c0bc92014-08-04 01:23:53 -040091 // DTLS state
92 sendHandshakeSeq uint16
93 recvHandshakeSeq uint16
David Benjaminb3774b92015-01-31 17:16:01 -050094 handMsg []byte // pending assembled handshake message
95 handMsgLen int // handshake message length, not including the header
96 pendingFragments [][]byte // pending outgoing handshake fragments.
Adam Langley95c29f32014-06-20 12:00:00 -070097
Steven Valdezc4aa7272016-10-03 12:25:56 -040098 keyUpdateRequested bool
99
Adam Langley95c29f32014-06-20 12:00:00 -0700100 tmp [16]byte
101}
102
David Benjamin5e961c12014-11-07 01:48:35 -0500103func (c *Conn) init() {
104 c.in.isDTLS = c.isDTLS
105 c.out.isDTLS = c.isDTLS
106 c.in.config = c.config
107 c.out.config = c.config
David Benjamin8e6db492015-07-25 18:29:23 -0400108
109 c.out.updateOutSeq()
David Benjamin5e961c12014-11-07 01:48:35 -0500110}
111
Adam Langley95c29f32014-06-20 12:00:00 -0700112// Access to net.Conn methods.
113// Cannot just embed net.Conn because that would
114// export the struct field too.
115
116// LocalAddr returns the local network address.
117func (c *Conn) LocalAddr() net.Addr {
118 return c.conn.LocalAddr()
119}
120
121// RemoteAddr returns the remote network address.
122func (c *Conn) RemoteAddr() net.Addr {
123 return c.conn.RemoteAddr()
124}
125
126// SetDeadline sets the read and write deadlines associated with the connection.
127// A zero value for t means Read and Write will not time out.
128// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
129func (c *Conn) SetDeadline(t time.Time) error {
130 return c.conn.SetDeadline(t)
131}
132
133// SetReadDeadline sets the read deadline on the underlying connection.
134// A zero value for t means Read will not time out.
135func (c *Conn) SetReadDeadline(t time.Time) error {
136 return c.conn.SetReadDeadline(t)
137}
138
139// SetWriteDeadline sets the write deadline on the underlying conneciton.
140// A zero value for t means Write will not time out.
141// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
142func (c *Conn) SetWriteDeadline(t time.Time) error {
143 return c.conn.SetWriteDeadline(t)
144}
145
146// A halfConn represents one direction of the record layer
147// connection, either sending or receiving.
148type halfConn struct {
149 sync.Mutex
150
David Benjamin83c0bc92014-08-04 01:23:53 -0400151 err error // first permanent error
152 version uint16 // protocol version
153 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -0700154 cipher interface{} // cipher algorithm
155 mac macFunction
156 seq [8]byte // 64-bit sequence number
David Benjamin8e6db492015-07-25 18:29:23 -0400157 outSeq [8]byte // Mapped sequence number
Adam Langley95c29f32014-06-20 12:00:00 -0700158 bfree *block // list of free blocks
159
160 nextCipher interface{} // next encryption state
161 nextMac macFunction // next MAC algorithm
David Benjamin83f90402015-01-27 01:09:43 -0500162 nextSeq [6]byte // next epoch's starting sequence number in DTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700163
164 // used to save allocating a new buffer for each MAC.
165 inDigestBuf, outDigestBuf []byte
Adam Langley80842bd2014-06-20 12:00:00 -0700166
Steven Valdezc4aa7272016-10-03 12:25:56 -0400167 trafficSecret []byte
David Benjamin21c00282016-07-18 21:56:23 +0200168
David Benjamin6f600d62016-12-21 16:06:54 -0500169 shortHeader bool
170
Adam Langley80842bd2014-06-20 12:00:00 -0700171 config *Config
Adam Langley95c29f32014-06-20 12:00:00 -0700172}
173
174func (hc *halfConn) setErrorLocked(err error) error {
175 hc.err = err
176 return err
177}
178
179func (hc *halfConn) error() error {
Adam Langley2ae77d22014-10-28 17:29:33 -0700180 // This should be locked, but I've removed it for the renegotiation
181 // tests since we don't concurrently read and write the same tls.Conn
182 // in any case during testing.
Adam Langley95c29f32014-06-20 12:00:00 -0700183 err := hc.err
Adam Langley95c29f32014-06-20 12:00:00 -0700184 return err
185}
186
187// prepareCipherSpec sets the encryption and MAC states
188// that a subsequent changeCipherSpec will use.
189func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
190 hc.version = version
191 hc.nextCipher = cipher
192 hc.nextMac = mac
193}
194
195// changeCipherSpec changes the encryption and MAC states
196// to the ones previously passed to prepareCipherSpec.
Adam Langley80842bd2014-06-20 12:00:00 -0700197func (hc *halfConn) changeCipherSpec(config *Config) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700198 if hc.nextCipher == nil {
199 return alertInternalError
200 }
201 hc.cipher = hc.nextCipher
202 hc.mac = hc.nextMac
203 hc.nextCipher = nil
204 hc.nextMac = nil
Adam Langley80842bd2014-06-20 12:00:00 -0700205 hc.config = config
David Benjamin83c0bc92014-08-04 01:23:53 -0400206 hc.incEpoch()
David Benjaminf2b83632016-03-01 22:57:46 -0500207
208 if config.Bugs.NullAllCiphers {
David Benjamin7a4aaa42016-09-20 17:58:14 -0400209 hc.cipher = nullCipher{}
David Benjaminf2b83632016-03-01 22:57:46 -0500210 hc.mac = nil
211 }
Adam Langley95c29f32014-06-20 12:00:00 -0700212 return nil
213}
214
David Benjamin21c00282016-07-18 21:56:23 +0200215// useTrafficSecret sets the current cipher state for TLS 1.3.
Steven Valdeza833c352016-11-01 13:39:36 -0400216func (hc *halfConn) useTrafficSecret(version uint16, suite *cipherSuite, secret []byte, side trafficDirection) {
Nick Harperb41d2e42016-07-01 17:50:32 -0400217 hc.version = version
Steven Valdeza833c352016-11-01 13:39:36 -0400218 hc.cipher = deriveTrafficAEAD(version, suite, secret, side)
David Benjamin7a4aaa42016-09-20 17:58:14 -0400219 if hc.config.Bugs.NullAllCiphers {
220 hc.cipher = nullCipher{}
221 }
David Benjamin21c00282016-07-18 21:56:23 +0200222 hc.trafficSecret = secret
Nick Harperb41d2e42016-07-01 17:50:32 -0400223 hc.incEpoch()
224}
225
Nick Harperf2511f12016-12-06 16:02:31 -0800226// resetCipher changes the cipher state back to no encryption to be able
227// to send an unencrypted ClientHello in response to HelloRetryRequest
228// after 0-RTT data was rejected.
229func (hc *halfConn) resetCipher() {
230 hc.cipher = nil
231 hc.incEpoch()
232}
233
David Benjamin21c00282016-07-18 21:56:23 +0200234func (hc *halfConn) doKeyUpdate(c *Conn, isOutgoing bool) {
235 side := serverWrite
236 if c.isClient == isOutgoing {
237 side = clientWrite
238 }
Steven Valdeza833c352016-11-01 13:39:36 -0400239 hc.useTrafficSecret(hc.version, c.cipherSuite, updateTrafficSecret(c.cipherSuite.hash(), hc.trafficSecret), side)
David Benjamin21c00282016-07-18 21:56:23 +0200240}
241
Adam Langley95c29f32014-06-20 12:00:00 -0700242// incSeq increments the sequence number.
David Benjamin5e961c12014-11-07 01:48:35 -0500243func (hc *halfConn) incSeq(isOutgoing bool) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400244 limit := 0
David Benjamin5e961c12014-11-07 01:48:35 -0500245 increment := uint64(1)
David Benjamin83c0bc92014-08-04 01:23:53 -0400246 if hc.isDTLS {
247 // Increment up to the epoch in DTLS.
248 limit = 2
249 }
250 for i := 7; i >= limit; i-- {
David Benjamin5e961c12014-11-07 01:48:35 -0500251 increment += uint64(hc.seq[i])
252 hc.seq[i] = byte(increment)
253 increment >>= 8
Adam Langley95c29f32014-06-20 12:00:00 -0700254 }
255
256 // Not allowed to let sequence number wrap.
257 // Instead, must renegotiate before it does.
258 // Not likely enough to bother.
David Benjamin5e961c12014-11-07 01:48:35 -0500259 if increment != 0 {
260 panic("TLS: sequence number wraparound")
261 }
David Benjamin8e6db492015-07-25 18:29:23 -0400262
263 hc.updateOutSeq()
Adam Langley95c29f32014-06-20 12:00:00 -0700264}
265
David Benjamin83f90402015-01-27 01:09:43 -0500266// incNextSeq increments the starting sequence number for the next epoch.
267func (hc *halfConn) incNextSeq() {
268 for i := len(hc.nextSeq) - 1; i >= 0; i-- {
269 hc.nextSeq[i]++
270 if hc.nextSeq[i] != 0 {
271 return
272 }
273 }
274 panic("TLS: sequence number wraparound")
275}
276
277// incEpoch resets the sequence number. In DTLS, it also increments the epoch
278// half of the sequence number.
David Benjamin83c0bc92014-08-04 01:23:53 -0400279func (hc *halfConn) incEpoch() {
David Benjamin83c0bc92014-08-04 01:23:53 -0400280 if hc.isDTLS {
281 for i := 1; i >= 0; i-- {
282 hc.seq[i]++
283 if hc.seq[i] != 0 {
284 break
285 }
286 if i == 0 {
287 panic("TLS: epoch number wraparound")
288 }
289 }
David Benjamin83f90402015-01-27 01:09:43 -0500290 copy(hc.seq[2:], hc.nextSeq[:])
291 for i := range hc.nextSeq {
292 hc.nextSeq[i] = 0
293 }
294 } else {
295 for i := range hc.seq {
296 hc.seq[i] = 0
297 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400298 }
David Benjamin8e6db492015-07-25 18:29:23 -0400299
300 hc.updateOutSeq()
301}
302
303func (hc *halfConn) updateOutSeq() {
304 if hc.config.Bugs.SequenceNumberMapping != nil {
305 seqU64 := binary.BigEndian.Uint64(hc.seq[:])
306 seqU64 = hc.config.Bugs.SequenceNumberMapping(seqU64)
307 binary.BigEndian.PutUint64(hc.outSeq[:], seqU64)
308
309 // The DTLS epoch cannot be changed.
310 copy(hc.outSeq[:2], hc.seq[:2])
311 return
312 }
313
314 copy(hc.outSeq[:], hc.seq[:])
David Benjamin83c0bc92014-08-04 01:23:53 -0400315}
316
David Benjamin6f600d62016-12-21 16:06:54 -0500317func (hc *halfConn) isShortHeader() bool {
318 return hc.shortHeader && hc.cipher != nil
319}
320
David Benjamin83c0bc92014-08-04 01:23:53 -0400321func (hc *halfConn) recordHeaderLen() int {
322 if hc.isDTLS {
323 return dtlsRecordHeaderLen
324 }
David Benjamin6f600d62016-12-21 16:06:54 -0500325 if hc.isShortHeader() {
326 return 2
327 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400328 return tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700329}
330
331// removePadding returns an unpadded slice, in constant time, which is a prefix
332// of the input. It also returns a byte which is equal to 255 if the padding
333// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
334func removePadding(payload []byte) ([]byte, byte) {
335 if len(payload) < 1 {
336 return payload, 0
337 }
338
339 paddingLen := payload[len(payload)-1]
340 t := uint(len(payload)-1) - uint(paddingLen)
341 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
342 good := byte(int32(^t) >> 31)
343
344 toCheck := 255 // the maximum possible padding length
345 // The length of the padded data is public, so we can use an if here
346 if toCheck+1 > len(payload) {
347 toCheck = len(payload) - 1
348 }
349
350 for i := 0; i < toCheck; i++ {
351 t := uint(paddingLen) - uint(i)
352 // if i <= paddingLen then the MSB of t is zero
353 mask := byte(int32(^t) >> 31)
354 b := payload[len(payload)-1-i]
355 good &^= mask&paddingLen ^ mask&b
356 }
357
358 // We AND together the bits of good and replicate the result across
359 // all the bits.
360 good &= good << 4
361 good &= good << 2
362 good &= good << 1
363 good = uint8(int8(good) >> 7)
364
365 toRemove := good&paddingLen + 1
366 return payload[:len(payload)-int(toRemove)], good
367}
368
369// removePaddingSSL30 is a replacement for removePadding in the case that the
370// protocol version is SSLv3. In this version, the contents of the padding
371// are random and cannot be checked.
372func removePaddingSSL30(payload []byte) ([]byte, byte) {
373 if len(payload) < 1 {
374 return payload, 0
375 }
376
377 paddingLen := int(payload[len(payload)-1]) + 1
378 if paddingLen > len(payload) {
379 return payload, 0
380 }
381
382 return payload[:len(payload)-paddingLen], 255
383}
384
385func roundUp(a, b int) int {
386 return a + (b-a%b)%b
387}
388
389// cbcMode is an interface for block ciphers using cipher block chaining.
390type cbcMode interface {
391 cipher.BlockMode
392 SetIV([]byte)
393}
394
395// decrypt checks and strips the mac and decrypts the data in b. Returns a
396// success boolean, the number of bytes to skip from the start of the record in
Nick Harper1fd39d82016-06-14 18:14:35 -0700397// order to get the application payload, the encrypted record type (or 0
398// if there is none), and an optional alert value.
399func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, contentType recordType, alertValue alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400400 recordHeaderLen := hc.recordHeaderLen()
401
Adam Langley95c29f32014-06-20 12:00:00 -0700402 // pull out payload
403 payload := b.data[recordHeaderLen:]
404
405 macSize := 0
406 if hc.mac != nil {
407 macSize = hc.mac.Size()
408 }
409
410 paddingGood := byte(255)
411 explicitIVLen := 0
412
David Benjamin83c0bc92014-08-04 01:23:53 -0400413 seq := hc.seq[:]
414 if hc.isDTLS {
415 // DTLS sequence numbers are explicit.
416 seq = b.data[3:11]
417 }
418
Adam Langley95c29f32014-06-20 12:00:00 -0700419 // decrypt
420 if hc.cipher != nil {
421 switch c := hc.cipher.(type) {
422 case cipher.Stream:
423 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400424 case *tlsAead:
425 nonce := seq
426 if c.explicitNonce {
427 explicitIVLen = 8
428 if len(payload) < explicitIVLen {
Nick Harper1fd39d82016-06-14 18:14:35 -0700429 return false, 0, 0, alertBadRecordMAC
David Benjamine9a80ff2015-04-07 00:46:46 -0400430 }
431 nonce = payload[:8]
432 payload = payload[8:]
Adam Langley95c29f32014-06-20 12:00:00 -0700433 }
Adam Langley95c29f32014-06-20 12:00:00 -0700434
Nick Harper1fd39d82016-06-14 18:14:35 -0700435 var additionalData []byte
436 if hc.version < VersionTLS13 {
437 additionalData = make([]byte, 13)
438 copy(additionalData, seq)
439 copy(additionalData[8:], b.data[:3])
440 n := len(payload) - c.Overhead()
441 additionalData[11] = byte(n >> 8)
442 additionalData[12] = byte(n)
443 }
Adam Langley95c29f32014-06-20 12:00:00 -0700444 var err error
Nick Harper1fd39d82016-06-14 18:14:35 -0700445 payload, err = c.Open(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700446 if err != nil {
Nick Harper1fd39d82016-06-14 18:14:35 -0700447 return false, 0, 0, alertBadRecordMAC
448 }
Adam Langley95c29f32014-06-20 12:00:00 -0700449 b.resize(recordHeaderLen + explicitIVLen + len(payload))
450 case cbcMode:
451 blockSize := c.BlockSize()
David Benjamin83c0bc92014-08-04 01:23:53 -0400452 if hc.version >= VersionTLS11 || hc.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700453 explicitIVLen = blockSize
454 }
455
456 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
Nick Harper1fd39d82016-06-14 18:14:35 -0700457 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700458 }
459
460 if explicitIVLen > 0 {
461 c.SetIV(payload[:explicitIVLen])
462 payload = payload[explicitIVLen:]
463 }
464 c.CryptBlocks(payload, payload)
465 if hc.version == VersionSSL30 {
466 payload, paddingGood = removePaddingSSL30(payload)
467 } else {
468 payload, paddingGood = removePadding(payload)
469 }
470 b.resize(recordHeaderLen + explicitIVLen + len(payload))
471
472 // note that we still have a timing side-channel in the
473 // MAC check, below. An attacker can align the record
474 // so that a correct padding will cause one less hash
475 // block to be calculated. Then they can iteratively
476 // decrypt a record by breaking each byte. See
477 // "Password Interception in a SSL/TLS Channel", Brice
478 // Canvel et al.
479 //
480 // However, our behavior matches OpenSSL, so we leak
481 // only as much as they do.
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700482 case nullCipher:
483 break
Adam Langley95c29f32014-06-20 12:00:00 -0700484 default:
485 panic("unknown cipher type")
486 }
David Benjamin7a4aaa42016-09-20 17:58:14 -0400487
488 if hc.version >= VersionTLS13 {
489 i := len(payload)
490 for i > 0 && payload[i-1] == 0 {
491 i--
492 }
493 payload = payload[:i]
494 if len(payload) == 0 {
495 return false, 0, 0, alertUnexpectedMessage
496 }
497 contentType = recordType(payload[len(payload)-1])
498 payload = payload[:len(payload)-1]
499 b.resize(recordHeaderLen + len(payload))
500 }
Adam Langley95c29f32014-06-20 12:00:00 -0700501 }
502
503 // check, strip mac
504 if hc.mac != nil {
505 if len(payload) < macSize {
Nick Harper1fd39d82016-06-14 18:14:35 -0700506 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700507 }
508
509 // strip mac off payload, b.data
510 n := len(payload) - macSize
David Benjamin83c0bc92014-08-04 01:23:53 -0400511 b.data[recordHeaderLen-2] = byte(n >> 8)
512 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700513 b.resize(recordHeaderLen + explicitIVLen + n)
514 remoteMAC := payload[n:]
David Benjamin83c0bc92014-08-04 01:23:53 -0400515 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
Adam Langley95c29f32014-06-20 12:00:00 -0700516
517 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
Nick Harper1fd39d82016-06-14 18:14:35 -0700518 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700519 }
520 hc.inDigestBuf = localMAC
521 }
David Benjamin5e961c12014-11-07 01:48:35 -0500522 hc.incSeq(false)
Adam Langley95c29f32014-06-20 12:00:00 -0700523
Nick Harper1fd39d82016-06-14 18:14:35 -0700524 return true, recordHeaderLen + explicitIVLen, contentType, 0
Adam Langley95c29f32014-06-20 12:00:00 -0700525}
526
527// padToBlockSize calculates the needed padding block, if any, for a payload.
528// On exit, prefix aliases payload and extends to the end of the last full
529// block of payload. finalBlock is a fresh slice which contains the contents of
530// any suffix of payload as well as the needed padding to make finalBlock a
531// full block.
Adam Langley80842bd2014-06-20 12:00:00 -0700532func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
Adam Langley95c29f32014-06-20 12:00:00 -0700533 overrun := len(payload) % blockSize
Adam Langley95c29f32014-06-20 12:00:00 -0700534 prefix = payload[:len(payload)-overrun]
Adam Langley80842bd2014-06-20 12:00:00 -0700535
536 paddingLen := blockSize - overrun
537 finalSize := blockSize
538 if config.Bugs.MaxPadding {
539 for paddingLen+blockSize <= 256 {
540 paddingLen += blockSize
541 }
542 finalSize = 256
543 }
544 finalBlock = make([]byte, finalSize)
545 for i := range finalBlock {
Adam Langley95c29f32014-06-20 12:00:00 -0700546 finalBlock[i] = byte(paddingLen - 1)
547 }
Adam Langley80842bd2014-06-20 12:00:00 -0700548 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
549 finalBlock[overrun] ^= 0xff
550 }
551 copy(finalBlock, payload[len(payload)-overrun:])
Adam Langley95c29f32014-06-20 12:00:00 -0700552 return
553}
554
555// encrypt encrypts and macs the data in b.
Nick Harper1fd39d82016-06-14 18:14:35 -0700556func (hc *halfConn) encrypt(b *block, explicitIVLen int, typ recordType) (bool, alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400557 recordHeaderLen := hc.recordHeaderLen()
558
Adam Langley95c29f32014-06-20 12:00:00 -0700559 // mac
560 if hc.mac != nil {
David Benjamin8e6db492015-07-25 18:29:23 -0400561 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 -0700562
563 n := len(b.data)
564 b.resize(n + len(mac))
565 copy(b.data[n:], mac)
566 hc.outDigestBuf = mac
567 }
568
569 payload := b.data[recordHeaderLen:]
570
571 // encrypt
572 if hc.cipher != nil {
David Benjamin7a4aaa42016-09-20 17:58:14 -0400573 // Add TLS 1.3 padding.
574 if hc.version >= VersionTLS13 {
575 paddingLen := hc.config.Bugs.RecordPadding
576 if hc.config.Bugs.OmitRecordContents {
577 b.resize(recordHeaderLen + paddingLen)
578 } else {
579 b.resize(len(b.data) + 1 + paddingLen)
580 b.data[len(b.data)-paddingLen-1] = byte(typ)
581 }
582 for i := 0; i < paddingLen; i++ {
583 b.data[len(b.data)-paddingLen+i] = 0
584 }
585 }
586
Adam Langley95c29f32014-06-20 12:00:00 -0700587 switch c := hc.cipher.(type) {
588 case cipher.Stream:
589 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400590 case *tlsAead:
Adam Langley95c29f32014-06-20 12:00:00 -0700591 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
David Benjamin7a4aaa42016-09-20 17:58:14 -0400592 b.resize(len(b.data) + c.Overhead())
David Benjamin8e6db492015-07-25 18:29:23 -0400593 nonce := hc.outSeq[:]
David Benjamine9a80ff2015-04-07 00:46:46 -0400594 if c.explicitNonce {
595 nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
596 }
Adam Langley95c29f32014-06-20 12:00:00 -0700597 payload := b.data[recordHeaderLen+explicitIVLen:]
598 payload = payload[:payloadLen]
599
Nick Harper1fd39d82016-06-14 18:14:35 -0700600 var additionalData []byte
601 if hc.version < VersionTLS13 {
602 additionalData = make([]byte, 13)
603 copy(additionalData, hc.outSeq[:])
604 copy(additionalData[8:], b.data[:3])
605 additionalData[11] = byte(payloadLen >> 8)
606 additionalData[12] = byte(payloadLen)
607 }
Adam Langley95c29f32014-06-20 12:00:00 -0700608
Nick Harper1fd39d82016-06-14 18:14:35 -0700609 c.Seal(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700610 case cbcMode:
611 blockSize := c.BlockSize()
612 if explicitIVLen > 0 {
613 c.SetIV(payload[:explicitIVLen])
614 payload = payload[explicitIVLen:]
615 }
Adam Langley80842bd2014-06-20 12:00:00 -0700616 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700617 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
618 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
619 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700620 case nullCipher:
621 break
Adam Langley95c29f32014-06-20 12:00:00 -0700622 default:
623 panic("unknown cipher type")
624 }
625 }
626
627 // update length to include MAC and any block padding needed.
628 n := len(b.data) - recordHeaderLen
David Benjamin83c0bc92014-08-04 01:23:53 -0400629 b.data[recordHeaderLen-2] = byte(n >> 8)
630 b.data[recordHeaderLen-1] = byte(n)
David Benjamin6f600d62016-12-21 16:06:54 -0500631 if hc.isShortHeader() && !hc.config.Bugs.ClearShortHeaderBit {
632 b.data[0] |= 0x80
633 }
David Benjamin5e961c12014-11-07 01:48:35 -0500634 hc.incSeq(true)
Adam Langley95c29f32014-06-20 12:00:00 -0700635
636 return true, 0
637}
638
639// A block is a simple data buffer.
640type block struct {
641 data []byte
642 off int // index for Read
643 link *block
644}
645
646// resize resizes block to be n bytes, growing if necessary.
647func (b *block) resize(n int) {
648 if n > cap(b.data) {
649 b.reserve(n)
650 }
651 b.data = b.data[0:n]
652}
653
654// reserve makes sure that block contains a capacity of at least n bytes.
655func (b *block) reserve(n int) {
656 if cap(b.data) >= n {
657 return
658 }
659 m := cap(b.data)
660 if m == 0 {
661 m = 1024
662 }
663 for m < n {
664 m *= 2
665 }
666 data := make([]byte, len(b.data), m)
667 copy(data, b.data)
668 b.data = data
669}
670
671// readFromUntil reads from r into b until b contains at least n bytes
672// or else returns an error.
673func (b *block) readFromUntil(r io.Reader, n int) error {
674 // quick case
675 if len(b.data) >= n {
676 return nil
677 }
678
679 // read until have enough.
680 b.reserve(n)
681 for {
682 m, err := r.Read(b.data[len(b.data):cap(b.data)])
683 b.data = b.data[0 : len(b.data)+m]
684 if len(b.data) >= n {
685 // TODO(bradfitz,agl): slightly suspicious
686 // that we're throwing away r.Read's err here.
687 break
688 }
689 if err != nil {
690 return err
691 }
692 }
693 return nil
694}
695
696func (b *block) Read(p []byte) (n int, err error) {
697 n = copy(p, b.data[b.off:])
698 b.off += n
699 return
700}
701
702// newBlock allocates a new block, from hc's free list if possible.
703func (hc *halfConn) newBlock() *block {
704 b := hc.bfree
705 if b == nil {
706 return new(block)
707 }
708 hc.bfree = b.link
709 b.link = nil
710 b.resize(0)
711 return b
712}
713
714// freeBlock returns a block to hc's free list.
715// The protocol is such that each side only has a block or two on
716// its free list at a time, so there's no need to worry about
717// trimming the list, etc.
718func (hc *halfConn) freeBlock(b *block) {
719 b.link = hc.bfree
720 hc.bfree = b
721}
722
723// splitBlock splits a block after the first n bytes,
724// returning a block with those n bytes and a
725// block with the remainder. the latter may be nil.
726func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
727 if len(b.data) <= n {
728 return b, nil
729 }
730 bb := hc.newBlock()
731 bb.resize(len(b.data) - n)
732 copy(bb.data, b.data[n:])
733 b.data = b.data[0:n]
734 return b, bb
735}
736
David Benjamin83c0bc92014-08-04 01:23:53 -0400737func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
Nick Harper47383aa2016-11-30 12:50:43 -0800738RestartReadRecord:
David Benjamin83c0bc92014-08-04 01:23:53 -0400739 if c.isDTLS {
740 return c.dtlsDoReadRecord(want)
741 }
742
David Benjamin6f600d62016-12-21 16:06:54 -0500743 recordHeaderLen := c.in.recordHeaderLen()
David Benjamin83c0bc92014-08-04 01:23:53 -0400744
745 if c.rawInput == nil {
746 c.rawInput = c.in.newBlock()
747 }
748 b := c.rawInput
749
750 // Read header, payload.
751 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
752 // RFC suggests that EOF without an alertCloseNotify is
753 // an error, but popular web sites seem to do this,
David Benjamin30789da2015-08-29 22:56:45 -0400754 // so we can't make it an error, outside of tests.
755 if err == io.EOF && c.config.Bugs.ExpectCloseNotify {
756 err = io.ErrUnexpectedEOF
757 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400758 if e, ok := err.(net.Error); !ok || !e.Temporary() {
759 c.in.setErrorLocked(err)
760 }
761 return 0, nil, err
762 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400763
David Benjamin6f600d62016-12-21 16:06:54 -0500764 var typ recordType
765 var vers uint16
766 var n int
767 if c.in.isShortHeader() {
768 typ = recordTypeApplicationData
769 vers = VersionTLS10
770 n = int(b.data[0])<<8 | int(b.data[1])
771 if n&0x8000 == 0 {
772 c.sendAlert(alertDecodeError)
773 return 0, nil, c.in.setErrorLocked(errors.New("tls: length did not have high bit set"))
774 }
775
776 n = n & 0x7fff
777 } else {
778 typ = recordType(b.data[0])
779
780 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
781 // start with a uint16 length where the MSB is set and the first record
782 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
783 // an SSLv2 client.
784 if want == recordTypeHandshake && typ == 0x80 {
785 c.sendAlert(alertProtocolVersion)
786 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
787 }
788
789 vers = uint16(b.data[1])<<8 | uint16(b.data[2])
790 n = int(b.data[3])<<8 | int(b.data[4])
David Benjamin83c0bc92014-08-04 01:23:53 -0400791 }
792
David Benjaminbde00392016-06-21 12:19:28 -0400793 // Alerts sent near version negotiation do not have a well-defined
794 // record-layer version prior to TLS 1.3. (In TLS 1.3, the record-layer
795 // version is irrelevant.)
796 if typ != recordTypeAlert {
David Benjamine6f22212016-11-08 14:28:24 -0500797 var expect uint16
David Benjaminbde00392016-06-21 12:19:28 -0400798 if c.haveVers {
David Benjamine6f22212016-11-08 14:28:24 -0500799 expect = c.vers
800 if c.vers >= VersionTLS13 {
801 expect = VersionTLS10
David Benjaminbde00392016-06-21 12:19:28 -0400802 }
803 } else {
David Benjamine6f22212016-11-08 14:28:24 -0500804 expect = c.config.Bugs.ExpectInitialRecordVersion
805 }
806 if expect != 0 && vers != expect {
807 c.sendAlert(alertProtocolVersion)
808 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 -0500809 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400810 }
811 if n > maxCiphertext {
812 c.sendAlert(alertRecordOverflow)
813 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
814 }
815 if !c.haveVers {
816 // First message, be extra suspicious:
817 // this might not be a TLS client.
818 // Bail out before reading a full 'body', if possible.
819 // The current max version is 3.1.
820 // If the version is >= 16.0, it's probably not real.
821 // Similarly, a clientHello message encodes in
822 // well under a kilobyte. If the length is >= 12 kB,
823 // it's probably not real.
824 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
825 c.sendAlert(alertUnexpectedMessage)
826 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
827 }
828 }
829 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
830 if err == io.EOF {
831 err = io.ErrUnexpectedEOF
832 }
833 if e, ok := err.(net.Error); !ok || !e.Temporary() {
834 c.in.setErrorLocked(err)
835 }
836 return 0, nil, err
837 }
838
839 // Process message.
840 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
David Benjaminff26f092016-07-01 16:13:42 -0400841 ok, off, encTyp, alertValue := c.in.decrypt(b)
Nick Harper47383aa2016-11-30 12:50:43 -0800842
843 // Handle skipping over early data.
844 if !ok && c.skipEarlyData {
845 goto RestartReadRecord
846 }
847
848 // If the server is expecting a second ClientHello (in response to
849 // a HelloRetryRequest) and the client sends early data, there
850 // won't be a decryption failure but it still needs to be skipped.
851 if c.in.cipher == nil && typ == recordTypeApplicationData && c.skipEarlyData {
852 goto RestartReadRecord
853 }
854
David Benjaminff26f092016-07-01 16:13:42 -0400855 if !ok {
856 return 0, nil, c.in.setErrorLocked(c.sendAlert(alertValue))
857 }
858 b.off = off
Nick Harper47383aa2016-11-30 12:50:43 -0800859 c.skipEarlyData = false
David Benjaminff26f092016-07-01 16:13:42 -0400860
Nick Harper1fd39d82016-06-14 18:14:35 -0700861 if c.vers >= VersionTLS13 && c.in.cipher != nil {
David Benjaminc9ae27c2016-06-24 22:56:37 -0400862 if typ != recordTypeApplicationData {
863 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: outer record type is not application data"))
864 }
Nick Harper1fd39d82016-06-14 18:14:35 -0700865 typ = encTyp
866 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400867 return typ, b, nil
868}
869
Adam Langley95c29f32014-06-20 12:00:00 -0700870// readRecord reads the next TLS record from the connection
871// and updates the record layer state.
872// c.in.Mutex <= L; c.input == nil.
873func (c *Conn) readRecord(want recordType) error {
874 // Caller must be in sync with connection:
875 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700876 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700877 switch want {
878 default:
879 c.sendAlert(alertInternalError)
880 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
881 case recordTypeHandshake, recordTypeChangeCipherSpec:
882 if c.handshakeComplete {
883 c.sendAlert(alertInternalError)
884 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
885 }
886 case recordTypeApplicationData:
Nick Harper7cd0a972016-12-02 11:08:40 -0800887 if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart && len(c.config.Bugs.ExpectHalfRTTData) == 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700888 c.sendAlert(alertInternalError)
889 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
890 }
David Benjamin30789da2015-08-29 22:56:45 -0400891 case recordTypeAlert:
892 // Looking for a close_notify. Note: unlike a real
893 // implementation, this is not tolerant of additional records.
894 // See the documentation for ExpectCloseNotify.
Adam Langley95c29f32014-06-20 12:00:00 -0700895 }
896
897Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400898 typ, b, err := c.doReadRecord(want)
899 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700900 return err
901 }
Adam Langley95c29f32014-06-20 12:00:00 -0700902 data := b.data[b.off:]
David Benjamine3fbb362017-01-06 16:19:28 -0500903 max := maxPlaintext
904 if c.config.Bugs.MaxReceivePlaintext != 0 {
905 max = c.config.Bugs.MaxReceivePlaintext
906 }
907 if len(data) > max {
Adam Langley95c29f32014-06-20 12:00:00 -0700908 err := c.sendAlert(alertRecordOverflow)
909 c.in.freeBlock(b)
910 return c.in.setErrorLocked(err)
911 }
912
913 switch typ {
914 default:
915 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
916
917 case recordTypeAlert:
918 if len(data) != 2 {
919 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
920 break
921 }
922 if alert(data[1]) == alertCloseNotify {
923 c.in.setErrorLocked(io.EOF)
924 break
925 }
926 switch data[0] {
927 case alertLevelWarning:
David Benjamin053fee92017-01-02 08:30:36 -0500928 if alert(data[1]) == alertNoCertificate {
929 c.in.freeBlock(b)
930 return errNoCertificateAlert
931 }
932
Adam Langley95c29f32014-06-20 12:00:00 -0700933 // drop on the floor
934 c.in.freeBlock(b)
935 goto Again
936 case alertLevelError:
937 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
938 default:
939 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
940 }
941
942 case recordTypeChangeCipherSpec:
943 if typ != want || len(data) != 1 || data[0] != 1 {
944 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
945 break
946 }
Adam Langley80842bd2014-06-20 12:00:00 -0700947 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700948 if err != nil {
949 c.in.setErrorLocked(c.sendAlert(err.(alert)))
950 }
951
952 case recordTypeApplicationData:
953 if typ != want {
954 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
955 break
956 }
957 c.input = b
958 b = nil
959
960 case recordTypeHandshake:
David Benjamind5a4ecb2016-07-18 01:17:13 +0200961 // Allow handshake data while reading application data to
962 // trigger post-handshake messages.
Adam Langley95c29f32014-06-20 12:00:00 -0700963 // TODO(rsc): Should at least pick off connection close.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200964 if typ != want && want != recordTypeApplicationData {
965 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
Adam Langley95c29f32014-06-20 12:00:00 -0700966 }
967 c.hand.Write(data)
968 }
969
970 if b != nil {
971 c.in.freeBlock(b)
972 }
973 return c.in.err
974}
975
976// sendAlert sends a TLS alert message.
977// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400978func (c *Conn) sendAlertLocked(level byte, err alert) error {
979 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700980 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400981 if c.config.Bugs.FragmentAlert {
982 c.writeRecord(recordTypeAlert, c.tmp[0:1])
983 c.writeRecord(recordTypeAlert, c.tmp[1:2])
David Benjamin0d3a8c62016-03-11 22:25:18 -0500984 } else if c.config.Bugs.DoubleAlert {
985 copy(c.tmp[2:4], c.tmp[0:2])
986 c.writeRecord(recordTypeAlert, c.tmp[0:4])
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400987 } else {
988 c.writeRecord(recordTypeAlert, c.tmp[0:2])
989 }
David Benjamin24f346d2015-06-06 03:28:08 -0400990 // Error alerts are fatal to the connection.
991 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700992 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
993 }
994 return nil
995}
996
997// sendAlert sends a TLS alert message.
998// L < c.out.Mutex.
999func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -04001000 level := byte(alertLevelError)
Nick Harperf2511f12016-12-06 16:02:31 -08001001 if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertificate || err == alertEndOfEarlyData {
David Benjamin24f346d2015-06-06 03:28:08 -04001002 level = alertLevelWarning
1003 }
1004 return c.SendAlert(level, err)
1005}
1006
1007func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001008 c.out.Lock()
1009 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -04001010 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -07001011}
1012
David Benjamind86c7672014-08-02 04:07:12 -04001013// writeV2Record writes a record for a V2ClientHello.
1014func (c *Conn) writeV2Record(data []byte) (n int, err error) {
1015 record := make([]byte, 2+len(data))
1016 record[0] = uint8(len(data)>>8) | 0x80
1017 record[1] = uint8(len(data))
1018 copy(record[2:], data)
1019 return c.conn.Write(record)
1020}
1021
Adam Langley95c29f32014-06-20 12:00:00 -07001022// writeRecord writes a TLS record with the given type and payload
1023// to the connection and updates the record layer state.
1024// c.out.Mutex <= L.
1025func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin639846e2016-09-09 11:41:18 -04001026 if msgType := c.config.Bugs.SendWrongMessageType; msgType != 0 {
1027 if typ == recordTypeHandshake && data[0] == msgType {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001028 newData := make([]byte, len(data))
1029 copy(newData, data)
1030 newData[0] += 42
1031 data = newData
1032 }
1033 }
1034
David Benjamin639846e2016-09-09 11:41:18 -04001035 if msgType := c.config.Bugs.SendTrailingMessageData; msgType != 0 {
1036 if typ == recordTypeHandshake && data[0] == msgType {
1037 newData := make([]byte, len(data))
1038 copy(newData, data)
1039
1040 // Add a 0 to the body.
1041 newData = append(newData, 0)
1042 // Fix the header.
1043 newLen := len(newData) - 4
1044 newData[1] = byte(newLen >> 16)
1045 newData[2] = byte(newLen >> 8)
1046 newData[3] = byte(newLen)
1047
1048 data = newData
1049 }
1050 }
1051
David Benjamin83c0bc92014-08-04 01:23:53 -04001052 if c.isDTLS {
1053 return c.dtlsWriteRecord(typ, data)
1054 }
1055
David Benjamin71dd6662016-07-08 14:10:48 -07001056 if typ == recordTypeHandshake {
1057 if c.config.Bugs.SendHelloRequestBeforeEveryHandshakeMessage {
1058 newData := make([]byte, 0, 4+len(data))
1059 newData = append(newData, typeHelloRequest, 0, 0, 0)
1060 newData = append(newData, data...)
1061 data = newData
1062 }
1063
1064 if c.config.Bugs.PackHandshakeFlight {
1065 c.pendingFlight.Write(data)
1066 return len(data), nil
1067 }
David Benjamin582ba042016-07-07 12:33:25 -07001068 }
1069
1070 return c.doWriteRecord(typ, data)
1071}
1072
1073func (c *Conn) doWriteRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin6f600d62016-12-21 16:06:54 -05001074 recordHeaderLen := c.out.recordHeaderLen()
Adam Langley95c29f32014-06-20 12:00:00 -07001075 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -04001076 first := true
1077 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -04001078 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -07001079 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -04001080 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -07001081 m = maxPlaintext
1082 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001083 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
1084 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -04001085 // By default, do not fragment the client_version or
1086 // server_version, which are located in the first 6
1087 // bytes.
1088 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
1089 m = 6
1090 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001091 }
Adam Langley95c29f32014-06-20 12:00:00 -07001092 explicitIVLen := 0
1093 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -04001094 first = false
Adam Langley95c29f32014-06-20 12:00:00 -07001095
1096 var cbc cbcMode
1097 if c.out.version >= VersionTLS11 {
1098 var ok bool
1099 if cbc, ok = c.out.cipher.(cbcMode); ok {
1100 explicitIVLen = cbc.BlockSize()
1101 }
1102 }
1103 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -04001104 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -07001105 explicitIVLen = 8
1106 // The AES-GCM construction in TLS has an
1107 // explicit nonce so that the nonce can be
1108 // random. However, the nonce is only 8 bytes
1109 // which is too small for a secure, random
1110 // nonce. Therefore we use the sequence number
1111 // as the nonce.
1112 explicitIVIsSeq = true
1113 }
1114 }
1115 b.resize(recordHeaderLen + explicitIVLen + m)
David Benjamin6f600d62016-12-21 16:06:54 -05001116 // If using a short record header, the length will be filled in
1117 // by encrypt.
1118 if !c.out.isShortHeader() {
1119 b.data[0] = byte(typ)
1120 if c.vers >= VersionTLS13 && c.out.cipher != nil {
1121 b.data[0] = byte(recordTypeApplicationData)
1122 if outerType := c.config.Bugs.OuterRecordType; outerType != 0 {
1123 b.data[0] = byte(outerType)
1124 }
David Benjaminc9ae27c2016-06-24 22:56:37 -04001125 }
David Benjamin6f600d62016-12-21 16:06:54 -05001126 vers := c.vers
1127 if vers == 0 || vers >= VersionTLS13 {
1128 // Some TLS servers fail if the record version is
1129 // greater than TLS 1.0 for the initial ClientHello.
1130 //
1131 // TLS 1.3 fixes the version number in the record
1132 // layer to {3, 1}.
1133 vers = VersionTLS10
1134 }
1135 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)
Nick Harper1fd39d82016-06-14 18:14:35 -07001145 }
Adam Langley95c29f32014-06-20 12:00:00 -07001146 if explicitIVLen > 0 {
1147 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
1148 if explicitIVIsSeq {
1149 copy(explicitIV, c.out.seq[:])
1150 } else {
1151 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
1152 break
1153 }
1154 }
1155 }
1156 copy(b.data[recordHeaderLen+explicitIVLen:], data)
Nick Harper1fd39d82016-06-14 18:14:35 -07001157 c.out.encrypt(b, explicitIVLen, typ)
Adam Langley95c29f32014-06-20 12:00:00 -07001158 _, err = c.conn.Write(b.data)
1159 if err != nil {
1160 break
1161 }
1162 n += m
1163 data = data[m:]
1164 }
1165 c.out.freeBlock(b)
1166
1167 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -07001168 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -07001169 if err != nil {
1170 // Cannot call sendAlert directly,
1171 // because we already hold c.out.Mutex.
1172 c.tmp[0] = alertLevelError
1173 c.tmp[1] = byte(err.(alert))
1174 c.writeRecord(recordTypeAlert, c.tmp[0:2])
1175 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
1176 }
1177 }
1178 return
1179}
1180
David Benjamin582ba042016-07-07 12:33:25 -07001181func (c *Conn) flushHandshake() error {
1182 if c.isDTLS {
1183 return c.dtlsFlushHandshake()
1184 }
1185
1186 for c.pendingFlight.Len() > 0 {
1187 var buf [maxPlaintext]byte
1188 n, _ := c.pendingFlight.Read(buf[:])
1189 if _, err := c.doWriteRecord(recordTypeHandshake, buf[:n]); err != nil {
1190 return err
1191 }
1192 }
1193
1194 c.pendingFlight.Reset()
1195 return nil
1196}
1197
David Benjamin83c0bc92014-08-04 01:23:53 -04001198func (c *Conn) doReadHandshake() ([]byte, error) {
1199 if c.isDTLS {
1200 return c.dtlsDoReadHandshake()
1201 }
1202
Adam Langley95c29f32014-06-20 12:00:00 -07001203 for c.hand.Len() < 4 {
1204 if err := c.in.err; err != nil {
1205 return nil, err
1206 }
1207 if err := c.readRecord(recordTypeHandshake); err != nil {
1208 return nil, err
1209 }
1210 }
1211
1212 data := c.hand.Bytes()
1213 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1214 if n > maxHandshake {
1215 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
1216 }
1217 for c.hand.Len() < 4+n {
1218 if err := c.in.err; err != nil {
1219 return nil, err
1220 }
1221 if err := c.readRecord(recordTypeHandshake); err != nil {
1222 return nil, err
1223 }
1224 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001225 return c.hand.Next(4 + n), nil
1226}
1227
1228// readHandshake reads the next handshake message from
1229// the record layer.
1230// c.in.Mutex < L; c.out.Mutex < L.
1231func (c *Conn) readHandshake() (interface{}, error) {
1232 data, err := c.doReadHandshake()
David Benjamin053fee92017-01-02 08:30:36 -05001233 if err == errNoCertificateAlert {
1234 if c.hand.Len() != 0 {
1235 // The warning alert may not interleave with a handshake message.
1236 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1237 }
1238 return new(ssl3NoCertificateMsg), nil
1239 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001240 if err != nil {
1241 return nil, err
1242 }
1243
Adam Langley95c29f32014-06-20 12:00:00 -07001244 var m handshakeMessage
1245 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001246 case typeHelloRequest:
1247 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001248 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001249 m = &clientHelloMsg{
1250 isDTLS: c.isDTLS,
1251 }
Adam Langley95c29f32014-06-20 12:00:00 -07001252 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001253 m = &serverHelloMsg{
1254 isDTLS: c.isDTLS,
1255 }
Nick Harperdcfbc672016-07-16 17:47:31 +02001256 case typeHelloRetryRequest:
1257 m = new(helloRetryRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001258 case typeNewSessionTicket:
David Benjamin58104882016-07-18 01:25:41 +02001259 m = &newSessionTicketMsg{
1260 version: c.vers,
1261 }
Nick Harperb41d2e42016-07-01 17:50:32 -04001262 case typeEncryptedExtensions:
1263 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001264 case typeCertificate:
Nick Harperb41d2e42016-07-01 17:50:32 -04001265 m = &certificateMsg{
David Benjamin8d315d72016-07-18 01:03:18 +02001266 hasRequestContext: c.vers >= VersionTLS13,
Nick Harperb41d2e42016-07-01 17:50:32 -04001267 }
Adam Langley95c29f32014-06-20 12:00:00 -07001268 case typeCertificateRequest:
1269 m = &certificateRequestMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001270 hasSignatureAlgorithm: c.vers >= VersionTLS12,
David Benjamin8d315d72016-07-18 01:03:18 +02001271 hasRequestContext: c.vers >= VersionTLS13,
Adam Langley95c29f32014-06-20 12:00:00 -07001272 }
1273 case typeCertificateStatus:
1274 m = new(certificateStatusMsg)
1275 case typeServerKeyExchange:
1276 m = new(serverKeyExchangeMsg)
1277 case typeServerHelloDone:
1278 m = new(serverHelloDoneMsg)
1279 case typeClientKeyExchange:
1280 m = new(clientKeyExchangeMsg)
1281 case typeCertificateVerify:
1282 m = &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001283 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001284 }
1285 case typeNextProtocol:
1286 m = new(nextProtoMsg)
1287 case typeFinished:
1288 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001289 case typeHelloVerifyRequest:
1290 m = new(helloVerifyRequestMsg)
David Benjamin24599a82016-06-30 18:56:53 -04001291 case typeChannelID:
1292 m = new(channelIDMsg)
David Benjamin21c00282016-07-18 21:56:23 +02001293 case typeKeyUpdate:
1294 m = new(keyUpdateMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001295 default:
1296 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1297 }
1298
1299 // The handshake message unmarshallers
1300 // expect to be able to keep references to data,
1301 // so pass in a fresh copy that won't be overwritten.
1302 data = append([]byte(nil), data...)
1303
1304 if !m.unmarshal(data) {
1305 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1306 }
1307 return m, nil
1308}
1309
David Benjamin83f90402015-01-27 01:09:43 -05001310// skipPacket processes all the DTLS records in packet. It updates
1311// sequence number expectations but otherwise ignores them.
1312func (c *Conn) skipPacket(packet []byte) error {
1313 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001314 if len(packet) < 13 {
1315 return errors.New("tls: bad packet")
1316 }
David Benjamin83f90402015-01-27 01:09:43 -05001317 // Dropped packets are completely ignored save to update
1318 // expected sequence numbers for this and the next epoch. (We
1319 // don't assert on the contents of the packets both for
1320 // simplicity and because a previous test with one shorter
1321 // timeout schedule would have done so.)
1322 epoch := packet[3:5]
1323 seq := packet[5:11]
1324 length := uint16(packet[11])<<8 | uint16(packet[12])
1325 if bytes.Equal(c.in.seq[:2], epoch) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001326 if bytes.Compare(seq, c.in.seq[2:]) < 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.seq[2:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001330 c.in.incSeq(false)
1331 } else {
David Benjamin13e81fc2015-11-02 17:16:13 -05001332 if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001333 return errors.New("tls: sequence mismatch")
1334 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001335 copy(c.in.nextSeq[:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001336 c.in.incNextSeq()
1337 }
David Benjamin6ca93552015-08-28 16:16:25 -04001338 if len(packet) < 13+int(length) {
1339 return errors.New("tls: bad packet")
1340 }
David Benjamin83f90402015-01-27 01:09:43 -05001341 packet = packet[13+length:]
1342 }
1343 return nil
1344}
1345
1346// simulatePacketLoss simulates the loss of a handshake leg from the
1347// peer based on the schedule in c.config.Bugs. If resendFunc is
1348// non-nil, it is called after each simulated timeout to retransmit
1349// handshake messages from the local end. This is used in cases where
1350// the peer retransmits on a stale Finished rather than a timeout.
1351func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1352 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1353 return nil
1354 }
1355 if !c.isDTLS {
1356 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1357 }
1358 if c.config.Bugs.PacketAdaptor == nil {
1359 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1360 }
1361 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1362 // Simulate a timeout.
1363 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1364 if err != nil {
1365 return err
1366 }
1367 for _, packet := range packets {
1368 if err := c.skipPacket(packet); err != nil {
1369 return err
1370 }
1371 }
1372 if resendFunc != nil {
1373 resendFunc()
1374 }
1375 }
1376 return nil
1377}
1378
David Benjamin47921102016-07-28 11:29:18 -04001379func (c *Conn) SendHalfHelloRequest() error {
1380 if err := c.Handshake(); err != nil {
1381 return err
1382 }
1383
1384 c.out.Lock()
1385 defer c.out.Unlock()
1386
1387 if _, err := c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0}); err != nil {
1388 return err
1389 }
1390 return c.flushHandshake()
1391}
1392
Adam Langley95c29f32014-06-20 12:00:00 -07001393// Write writes data to the connection.
1394func (c *Conn) Write(b []byte) (int, error) {
1395 if err := c.Handshake(); err != nil {
1396 return 0, err
1397 }
1398
1399 c.out.Lock()
1400 defer c.out.Unlock()
1401
David Benjamin12d2c482016-07-24 10:56:51 -04001402 // Flush any pending handshake data. PackHelloRequestWithFinished may
1403 // have been set and the handshake not followed by Renegotiate.
1404 c.flushHandshake()
1405
Adam Langley95c29f32014-06-20 12:00:00 -07001406 if err := c.out.err; err != nil {
1407 return 0, err
1408 }
1409
1410 if !c.handshakeComplete {
1411 return 0, alertInternalError
1412 }
1413
Steven Valdezc4aa7272016-10-03 12:25:56 -04001414 if c.keyUpdateRequested {
1415 if err := c.sendKeyUpdateLocked(keyUpdateNotRequested); err != nil {
David Benjamin21c00282016-07-18 21:56:23 +02001416 return 0, err
1417 }
Steven Valdezc4aa7272016-10-03 12:25:56 -04001418 c.keyUpdateRequested = false
David Benjamin21c00282016-07-18 21:56:23 +02001419 }
1420
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001421 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001422 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001423 }
1424
Adam Langley27a0d082015-11-03 13:34:10 -08001425 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1426 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
David Benjamin582ba042016-07-07 12:33:25 -07001427 c.flushHandshake()
Adam Langley27a0d082015-11-03 13:34:10 -08001428 }
1429
Adam Langley95c29f32014-06-20 12:00:00 -07001430 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1431 // attack when using block mode ciphers due to predictable IVs.
1432 // This can be prevented by splitting each Application Data
1433 // record into two records, effectively randomizing the IV.
1434 //
1435 // http://www.openssl.org/~bodo/tls-cbc.txt
1436 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1437 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1438
1439 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001440 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001441 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1442 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1443 if err != nil {
1444 return n, c.out.setErrorLocked(err)
1445 }
1446 m, b = 1, b[1:]
1447 }
1448 }
1449
1450 n, err := c.writeRecord(recordTypeApplicationData, b)
1451 return n + m, c.out.setErrorLocked(err)
1452}
1453
David Benjamind5a4ecb2016-07-18 01:17:13 +02001454func (c *Conn) handlePostHandshakeMessage() error {
Adam Langley2ae77d22014-10-28 17:29:33 -07001455 msg, err := c.readHandshake()
1456 if err != nil {
1457 return err
1458 }
David Benjamind5a4ecb2016-07-18 01:17:13 +02001459
1460 if c.vers < VersionTLS13 {
1461 if !c.isClient {
1462 c.sendAlert(alertUnexpectedMessage)
1463 return errors.New("tls: unexpected post-handshake message")
1464 }
1465
1466 _, ok := msg.(*helloRequestMsg)
1467 if !ok {
1468 c.sendAlert(alertUnexpectedMessage)
1469 return alertUnexpectedMessage
1470 }
1471
1472 c.handshakeComplete = false
1473 return c.Handshake()
Adam Langley2ae77d22014-10-28 17:29:33 -07001474 }
1475
David Benjamind5a4ecb2016-07-18 01:17:13 +02001476 if c.isClient {
1477 if newSessionTicket, ok := msg.(*newSessionTicketMsg); ok {
David Benjamin1a5e8ec2016-10-07 15:19:18 -04001478 if c.config.Bugs.ExpectGREASE && !newSessionTicket.hasGREASEExtension {
1479 return errors.New("tls: no GREASE ticket extension found")
1480 }
1481
Nick Harperf2511f12016-12-06 16:02:31 -08001482 if c.config.Bugs.ExpectTicketEarlyDataInfo && newSessionTicket.maxEarlyDataSize == 0 {
Steven Valdez08b65f42016-12-07 15:29:45 -05001483 return errors.New("tls: no ticket_early_data_info extension found")
1484 }
1485
Steven Valdeza833c352016-11-01 13:39:36 -04001486 if c.config.Bugs.ExpectNoNewSessionTicket {
1487 return errors.New("tls: received unexpected NewSessionTicket")
1488 }
1489
David Benjamind5a4ecb2016-07-18 01:17:13 +02001490 if c.config.ClientSessionCache == nil || newSessionTicket.ticketLifetime == 0 {
1491 return nil
1492 }
1493
1494 session := &ClientSessionState{
1495 sessionTicket: newSessionTicket.ticket,
1496 vers: c.vers,
1497 cipherSuite: c.cipherSuite.id,
1498 masterSecret: c.resumptionSecret,
1499 serverCertificates: c.peerCertificates,
1500 sctList: c.sctList,
1501 ocspResponse: c.ocspResponse,
Nick Harper0b3625b2016-07-25 16:16:28 -07001502 ticketCreationTime: c.config.time(),
1503 ticketExpiration: c.config.time().Add(time.Duration(newSessionTicket.ticketLifetime) * time.Second),
Steven Valdeza833c352016-11-01 13:39:36 -04001504 ticketAgeAdd: newSessionTicket.ticketAgeAdd,
Nick Harperf2511f12016-12-06 16:02:31 -08001505 maxEarlyDataSize: newSessionTicket.maxEarlyDataSize,
David Benjamind5a4ecb2016-07-18 01:17:13 +02001506 }
1507
1508 cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
1509 c.config.ClientSessionCache.Put(cacheKey, session)
1510 return nil
1511 }
1512 }
1513
Steven Valdezc4aa7272016-10-03 12:25:56 -04001514 if keyUpdate, ok := msg.(*keyUpdateMsg); ok {
Steven Valdez1dc53d22016-07-26 12:27:38 -04001515 c.in.doKeyUpdate(c, false)
Steven Valdezc4aa7272016-10-03 12:25:56 -04001516 if keyUpdate.keyUpdateRequest == keyUpdateRequested {
1517 c.keyUpdateRequested = true
1518 }
David Benjamin21c00282016-07-18 21:56:23 +02001519 return nil
1520 }
1521
David Benjamind5a4ecb2016-07-18 01:17:13 +02001522 // TODO(davidben): Add support for KeyUpdate.
1523 c.sendAlert(alertUnexpectedMessage)
1524 return alertUnexpectedMessage
Adam Langley2ae77d22014-10-28 17:29:33 -07001525}
1526
Adam Langleycf2d4f42014-10-28 19:06:14 -07001527func (c *Conn) Renegotiate() error {
1528 if !c.isClient {
David Benjaminef5dfd22015-12-06 13:17:07 -05001529 helloReq := new(helloRequestMsg).marshal()
1530 if c.config.Bugs.BadHelloRequest != nil {
1531 helloReq = c.config.Bugs.BadHelloRequest
1532 }
1533 c.writeRecord(recordTypeHandshake, helloReq)
David Benjamin582ba042016-07-07 12:33:25 -07001534 c.flushHandshake()
Adam Langleycf2d4f42014-10-28 19:06:14 -07001535 }
1536
1537 c.handshakeComplete = false
1538 return c.Handshake()
1539}
1540
Adam Langley95c29f32014-06-20 12:00:00 -07001541// Read can be made to time out and return a net.Error with Timeout() == true
1542// after a fixed time limit; see SetDeadline and SetReadDeadline.
1543func (c *Conn) Read(b []byte) (n int, err error) {
1544 if err = c.Handshake(); err != nil {
1545 return
1546 }
1547
1548 c.in.Lock()
1549 defer c.in.Unlock()
1550
1551 // Some OpenSSL servers send empty records in order to randomize the
1552 // CBC IV. So this loop ignores a limited number of empty records.
1553 const maxConsecutiveEmptyRecords = 100
1554 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1555 for c.input == nil && c.in.err == nil {
1556 if err := c.readRecord(recordTypeApplicationData); err != nil {
1557 // Soft error, like EAGAIN
1558 return 0, err
1559 }
David Benjamind9b091b2015-01-27 01:10:54 -05001560 if c.hand.Len() > 0 {
David Benjamind5a4ecb2016-07-18 01:17:13 +02001561 // We received handshake bytes, indicating a
1562 // post-handshake message.
1563 if err := c.handlePostHandshakeMessage(); err != nil {
Adam Langley2ae77d22014-10-28 17:29:33 -07001564 return 0, err
1565 }
1566 continue
1567 }
Adam Langley95c29f32014-06-20 12:00:00 -07001568 }
1569 if err := c.in.err; err != nil {
1570 return 0, err
1571 }
1572
1573 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001574 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001575 c.in.freeBlock(c.input)
1576 c.input = nil
1577 }
1578
1579 // If a close-notify alert is waiting, read it so that
1580 // we can return (n, EOF) instead of (n, nil), to signal
1581 // to the HTTP response reading goroutine that the
1582 // connection is now closed. This eliminates a race
1583 // where the HTTP response reading goroutine would
1584 // otherwise not observe the EOF until its next read,
1585 // by which time a client goroutine might have already
1586 // tried to reuse the HTTP connection for a new
1587 // request.
1588 // See https://codereview.appspot.com/76400046
1589 // and http://golang.org/issue/3514
1590 if ri := c.rawInput; ri != nil &&
1591 n != 0 && err == nil &&
1592 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1593 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1594 err = recErr // will be io.EOF on closeNotify
1595 }
1596 }
1597
1598 if n != 0 || err != nil {
1599 return n, err
1600 }
1601 }
1602
1603 return 0, io.ErrNoProgress
1604}
1605
1606// Close closes the connection.
1607func (c *Conn) Close() error {
1608 var alertErr error
1609
1610 c.handshakeMutex.Lock()
1611 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001612 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
David Benjaminfa214e42016-05-10 17:03:10 -04001613 alert := alertCloseNotify
1614 if c.config.Bugs.SendAlertOnShutdown != 0 {
1615 alert = c.config.Bugs.SendAlertOnShutdown
1616 }
1617 alertErr = c.sendAlert(alert)
David Benjamin4d559612016-05-18 14:31:51 -04001618 // Clear local alerts when sending alerts so we continue to wait
1619 // for the peer rather than closing the socket early.
1620 if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1621 alertErr = nil
1622 }
Adam Langley95c29f32014-06-20 12:00:00 -07001623 }
1624
David Benjamin30789da2015-08-29 22:56:45 -04001625 // Consume a close_notify from the peer if one hasn't been received
1626 // already. This avoids the peer from failing |SSL_shutdown| due to a
1627 // write failing.
1628 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1629 for c.in.error() == nil {
1630 c.readRecord(recordTypeAlert)
1631 }
1632 if c.in.error() != io.EOF {
1633 alertErr = c.in.error()
1634 }
1635 }
1636
Adam Langley95c29f32014-06-20 12:00:00 -07001637 if err := c.conn.Close(); err != nil {
1638 return err
1639 }
1640 return alertErr
1641}
1642
1643// Handshake runs the client or server handshake
1644// protocol if it has not yet been run.
1645// Most uses of this package need not call Handshake
1646// explicitly: the first Read or Write will call it automatically.
1647func (c *Conn) Handshake() error {
1648 c.handshakeMutex.Lock()
1649 defer c.handshakeMutex.Unlock()
1650 if err := c.handshakeErr; err != nil {
1651 return err
1652 }
1653 if c.handshakeComplete {
1654 return nil
1655 }
1656
David Benjamin9a41d1b2015-05-16 01:30:09 -04001657 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1658 c.conn.Write([]byte{
1659 byte(recordTypeAlert), // type
1660 0xfe, 0xff, // version
1661 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1662 0x0, 0x2, // length
1663 })
1664 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1665 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001666 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1667 c.writeRecord(recordTypeApplicationData, data)
1668 }
Adam Langley95c29f32014-06-20 12:00:00 -07001669 if c.isClient {
1670 c.handshakeErr = c.clientHandshake()
1671 } else {
1672 c.handshakeErr = c.serverHandshake()
1673 }
David Benjaminddb9f152015-02-03 15:44:39 -05001674 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1675 c.writeRecord(recordType(42), []byte("invalid record"))
1676 }
Adam Langley95c29f32014-06-20 12:00:00 -07001677 return c.handshakeErr
1678}
1679
1680// ConnectionState returns basic TLS details about the connection.
1681func (c *Conn) ConnectionState() ConnectionState {
1682 c.handshakeMutex.Lock()
1683 defer c.handshakeMutex.Unlock()
1684
1685 var state ConnectionState
1686 state.HandshakeComplete = c.handshakeComplete
1687 if c.handshakeComplete {
1688 state.Version = c.vers
1689 state.NegotiatedProtocol = c.clientProtocol
1690 state.DidResume = c.didResume
1691 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001692 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001693 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001694 state.PeerCertificates = c.peerCertificates
1695 state.VerifiedChains = c.verifiedChains
1696 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001697 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001698 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001699 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001700 state.SCTList = c.sctList
Nick Harper60edffd2016-06-21 15:19:24 -07001701 state.PeerSignatureAlgorithm = c.peerSignatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -04001702 state.CurveID = c.curveID
David Benjamin6f600d62016-12-21 16:06:54 -05001703 state.ShortHeader = c.in.shortHeader
Adam Langley95c29f32014-06-20 12:00:00 -07001704 }
1705
1706 return state
1707}
1708
1709// OCSPResponse returns the stapled OCSP response from the TLS server, if
1710// any. (Only valid for client connections.)
1711func (c *Conn) OCSPResponse() []byte {
1712 c.handshakeMutex.Lock()
1713 defer c.handshakeMutex.Unlock()
1714
1715 return c.ocspResponse
1716}
1717
1718// VerifyHostname checks that the peer certificate chain is valid for
1719// connecting to host. If so, it returns nil; if not, it returns an error
1720// describing the problem.
1721func (c *Conn) VerifyHostname(host string) error {
1722 c.handshakeMutex.Lock()
1723 defer c.handshakeMutex.Unlock()
1724 if !c.isClient {
1725 return errors.New("tls: VerifyHostname called on TLS server connection")
1726 }
1727 if !c.handshakeComplete {
1728 return errors.New("tls: handshake has not yet been performed")
1729 }
1730 return c.peerCertificates[0].VerifyHostname(host)
1731}
David Benjaminc565ebb2015-04-03 04:06:36 -04001732
1733// ExportKeyingMaterial exports keying material from the current connection
1734// state, as per RFC 5705.
1735func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1736 c.handshakeMutex.Lock()
1737 defer c.handshakeMutex.Unlock()
1738 if !c.handshakeComplete {
1739 return nil, errors.New("tls: handshake has not yet been performed")
1740 }
1741
David Benjamin8d315d72016-07-18 01:03:18 +02001742 if c.vers >= VersionTLS13 {
David Benjamin97a0a082016-07-13 17:57:35 -04001743 // TODO(davidben): What should we do with useContext? See
1744 // https://github.com/tlswg/tls13-spec/issues/546
1745 return hkdfExpandLabel(c.cipherSuite.hash(), c.exporterSecret, label, context, length), nil
1746 }
1747
David Benjaminc565ebb2015-04-03 04:06:36 -04001748 seedLen := len(c.clientRandom) + len(c.serverRandom)
1749 if useContext {
1750 seedLen += 2 + len(context)
1751 }
1752 seed := make([]byte, 0, seedLen)
1753 seed = append(seed, c.clientRandom[:]...)
1754 seed = append(seed, c.serverRandom[:]...)
1755 if useContext {
1756 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1757 seed = append(seed, context...)
1758 }
1759 result := make([]byte, length)
David Benjamin97a0a082016-07-13 17:57:35 -04001760 prfForVersion(c.vers, c.cipherSuite)(result, c.exporterSecret, label, seed)
David Benjaminc565ebb2015-04-03 04:06:36 -04001761 return result, nil
1762}
David Benjamin3e052de2015-11-25 20:10:31 -05001763
1764// noRenegotiationInfo returns true if the renegotiation info extension
1765// should be supported in the current handshake.
1766func (c *Conn) noRenegotiationInfo() bool {
1767 if c.config.Bugs.NoRenegotiationInfo {
1768 return true
1769 }
1770 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1771 return true
1772 }
1773 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1774 return true
1775 }
1776 return false
1777}
David Benjamin58104882016-07-18 01:25:41 +02001778
1779func (c *Conn) SendNewSessionTicket() error {
1780 if c.isClient || c.vers < VersionTLS13 {
1781 return errors.New("tls: cannot send post-handshake NewSessionTicket")
1782 }
1783
1784 var peerCertificatesRaw [][]byte
1785 for _, cert := range c.peerCertificates {
1786 peerCertificatesRaw = append(peerCertificatesRaw, cert.Raw)
1787 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001788
Steven Valdeza833c352016-11-01 13:39:36 -04001789 addBuffer := make([]byte, 4)
1790 _, err := io.ReadFull(c.config.rand(), addBuffer)
1791 if err != nil {
1792 c.sendAlert(alertInternalError)
1793 return errors.New("tls: short read from Rand: " + err.Error())
1794 }
1795 ticketAgeAdd := uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0])
1796
David Benjamin58104882016-07-18 01:25:41 +02001797 // TODO(davidben): Allow configuring these values.
1798 m := &newSessionTicketMsg{
David Benjamin9c33ae82017-01-08 06:04:43 -05001799 version: c.vers,
1800 ticketLifetime: uint32(24 * time.Hour / time.Second),
Nick Harperf2511f12016-12-06 16:02:31 -08001801 maxEarlyDataSize: c.config.Bugs.SendTicketEarlyDataInfo,
David Benjamin9c33ae82017-01-08 06:04:43 -05001802 duplicateEarlyDataInfo: c.config.Bugs.DuplicateTicketEarlyDataInfo,
1803 customExtension: c.config.Bugs.CustomTicketExtension,
1804 ticketAgeAdd: ticketAgeAdd,
David Benjamin58104882016-07-18 01:25:41 +02001805 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001806
David Benjamin17b30832017-01-28 14:00:32 -05001807 if c.config.Bugs.SendTicketLifetime != 0 {
1808 m.ticketLifetime = uint32(c.config.Bugs.SendTicketLifetime / time.Second)
1809 }
1810
Nick Harper0b3625b2016-07-25 16:16:28 -07001811 state := sessionState{
1812 vers: c.vers,
1813 cipherSuite: c.cipherSuite.id,
1814 masterSecret: c.resumptionSecret,
1815 certificates: peerCertificatesRaw,
1816 ticketCreationTime: c.config.time(),
1817 ticketExpiration: c.config.time().Add(time.Duration(m.ticketLifetime) * time.Second),
Steven Valdeza833c352016-11-01 13:39:36 -04001818 ticketAgeAdd: uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0]),
Nick Harper0b3625b2016-07-25 16:16:28 -07001819 }
1820
David Benjamin58104882016-07-18 01:25:41 +02001821 if !c.config.Bugs.SendEmptySessionTicket {
1822 var err error
1823 m.ticket, err = c.encryptTicket(&state)
1824 if err != nil {
1825 return err
1826 }
1827 }
1828
1829 c.out.Lock()
1830 defer c.out.Unlock()
Steven Valdeza833c352016-11-01 13:39:36 -04001831 _, err = c.writeRecord(recordTypeHandshake, m.marshal())
David Benjamin58104882016-07-18 01:25:41 +02001832 return err
1833}
David Benjamin21c00282016-07-18 21:56:23 +02001834
Steven Valdezc4aa7272016-10-03 12:25:56 -04001835func (c *Conn) SendKeyUpdate(keyUpdateRequest byte) error {
David Benjamin21c00282016-07-18 21:56:23 +02001836 c.out.Lock()
1837 defer c.out.Unlock()
Steven Valdezc4aa7272016-10-03 12:25:56 -04001838 return c.sendKeyUpdateLocked(keyUpdateRequest)
David Benjamin21c00282016-07-18 21:56:23 +02001839}
1840
Steven Valdezc4aa7272016-10-03 12:25:56 -04001841func (c *Conn) sendKeyUpdateLocked(keyUpdateRequest byte) error {
David Benjamin7f0965a2016-09-30 15:14:01 -04001842 if c.vers < VersionTLS13 {
1843 return errors.New("tls: attempted to send KeyUpdate before TLS 1.3")
1844 }
1845
Steven Valdezc4aa7272016-10-03 12:25:56 -04001846 m := keyUpdateMsg{
1847 keyUpdateRequest: keyUpdateRequest,
1848 }
David Benjamin21c00282016-07-18 21:56:23 +02001849 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
1850 return err
1851 }
1852 if err := c.flushHandshake(); err != nil {
1853 return err
1854 }
Steven Valdez1dc53d22016-07-26 12:27:38 -04001855 c.out.doKeyUpdate(c, true)
David Benjamin21c00282016-07-18 21:56:23 +02001856 return nil
1857}
Steven Valdeza4ee74d2016-11-29 13:36:45 -05001858
1859func (c *Conn) sendFakeEarlyData(len int) error {
1860 // Assemble a fake early data record. This does not use writeRecord
1861 // because the record layer may be using different keys at this point.
1862 payload := make([]byte, 5+len)
1863 payload[0] = byte(recordTypeApplicationData)
1864 payload[1] = 3
1865 payload[2] = 1
1866 payload[3] = byte(len >> 8)
1867 payload[4] = byte(len)
1868 _, err := c.conn.Write(payload)
1869 return err
1870}
David Benjamin6f600d62016-12-21 16:06:54 -05001871
1872func (c *Conn) setShortHeader() {
1873 c.in.shortHeader = true
1874 c.out.shortHeader = true
1875}