blob: 510bcf761469e36253e199196914e9ad093b97b6 [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
24// A Conn represents a secured connection.
25// It implements the net.Conn interface.
26type Conn struct {
27 // constant
28 conn net.Conn
David Benjamin83c0bc92014-08-04 01:23:53 -040029 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -070030 isClient bool
31
32 // constant after handshake; protected by handshakeMutex
Adam Langley75712922014-10-10 16:23:43 -070033 handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
34 handshakeErr error // error resulting from handshake
35 vers uint16 // TLS version
36 haveVers bool // version has been negotiated
37 config *Config // configuration passed to constructor
38 handshakeComplete bool
39 didResume bool // whether this connection was a session resumption
40 extendedMasterSecret bool // whether this session used an extended master secret
David Benjaminc565ebb2015-04-03 04:06:36 -040041 cipherSuite *cipherSuite
Adam Langley75712922014-10-10 16:23:43 -070042 ocspResponse []byte // stapled OCSP response
Paul Lietar4fac72e2015-09-09 13:44:55 +010043 sctList []byte // signed certificate timestamp list
Adam Langley75712922014-10-10 16:23:43 -070044 peerCertificates []*x509.Certificate
Adam Langley95c29f32014-06-20 12:00:00 -070045 // verifiedChains contains the certificate chains that we built, as
46 // opposed to the ones presented by the server.
47 verifiedChains [][]*x509.Certificate
48 // serverName contains the server name indicated by the client, if any.
Adam Langleyaf0e32c2015-06-03 09:57:23 -070049 serverName string
50 // firstFinished contains the first Finished hash sent during the
51 // handshake. This is the "tls-unique" channel binding value.
52 firstFinished [12]byte
Nick Harper60edffd2016-06-21 15:19:24 -070053 // peerSignatureAlgorithm contains the signature algorithm that was used
54 // by the peer in the handshake, or zero if not applicable.
55 peerSignatureAlgorithm signatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -040056 // curveID contains the curve that was used in the handshake, or zero if
57 // not applicable.
58 curveID CurveID
Adam Langleyaf0e32c2015-06-03 09:57:23 -070059
David Benjaminc565ebb2015-04-03 04:06:36 -040060 clientRandom, serverRandom [32]byte
David Benjamin97a0a082016-07-13 17:57:35 -040061 exporterSecret []byte
David Benjamin58104882016-07-18 01:25:41 +020062 resumptionSecret []byte
Adam Langley95c29f32014-06-20 12:00:00 -070063
64 clientProtocol string
65 clientProtocolFallback bool
David Benjaminfc7b0862014-09-06 13:21:53 -040066 usedALPN bool
Adam Langley95c29f32014-06-20 12:00:00 -070067
Adam Langley2ae77d22014-10-28 17:29:33 -070068 // verify_data values for the renegotiation extension.
69 clientVerify []byte
70 serverVerify []byte
71
David Benjamind30a9902014-08-24 01:44:23 -040072 channelID *ecdsa.PublicKey
73
David Benjaminca6c8262014-11-15 19:06:08 -050074 srtpProtectionProfile uint16
75
David Benjaminc44b1df2014-11-23 12:11:01 -050076 clientVersion uint16
77
Adam Langley95c29f32014-06-20 12:00:00 -070078 // input/output
79 in, out halfConn // in.Mutex < out.Mutex
80 rawInput *block // raw input, right off the wire
David Benjamin83c0bc92014-08-04 01:23:53 -040081 input *block // application record waiting to be read
82 hand bytes.Buffer // handshake record waiting to be read
83
David Benjamin582ba042016-07-07 12:33:25 -070084 // pendingFlight, if PackHandshakeFlight is enabled, is the buffer of
85 // handshake data to be split into records at the end of the flight.
86 pendingFlight bytes.Buffer
87
David Benjamin83c0bc92014-08-04 01:23:53 -040088 // DTLS state
89 sendHandshakeSeq uint16
90 recvHandshakeSeq uint16
David Benjaminb3774b92015-01-31 17:16:01 -050091 handMsg []byte // pending assembled handshake message
92 handMsgLen int // handshake message length, not including the header
93 pendingFragments [][]byte // pending outgoing handshake fragments.
Adam Langley95c29f32014-06-20 12:00:00 -070094
Steven Valdezc4aa7272016-10-03 12:25:56 -040095 keyUpdateRequested bool
96
Adam Langley95c29f32014-06-20 12:00:00 -070097 tmp [16]byte
98}
99
David Benjamin5e961c12014-11-07 01:48:35 -0500100func (c *Conn) init() {
101 c.in.isDTLS = c.isDTLS
102 c.out.isDTLS = c.isDTLS
103 c.in.config = c.config
104 c.out.config = c.config
David Benjamin8e6db492015-07-25 18:29:23 -0400105
106 c.out.updateOutSeq()
David Benjamin5e961c12014-11-07 01:48:35 -0500107}
108
Adam Langley95c29f32014-06-20 12:00:00 -0700109// Access to net.Conn methods.
110// Cannot just embed net.Conn because that would
111// export the struct field too.
112
113// LocalAddr returns the local network address.
114func (c *Conn) LocalAddr() net.Addr {
115 return c.conn.LocalAddr()
116}
117
118// RemoteAddr returns the remote network address.
119func (c *Conn) RemoteAddr() net.Addr {
120 return c.conn.RemoteAddr()
121}
122
123// SetDeadline sets the read and write deadlines associated with the connection.
124// A zero value for t means Read and Write will not time out.
125// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
126func (c *Conn) SetDeadline(t time.Time) error {
127 return c.conn.SetDeadline(t)
128}
129
130// SetReadDeadline sets the read deadline on the underlying connection.
131// A zero value for t means Read will not time out.
132func (c *Conn) SetReadDeadline(t time.Time) error {
133 return c.conn.SetReadDeadline(t)
134}
135
136// SetWriteDeadline sets the write deadline on the underlying conneciton.
137// A zero value for t means Write will not time out.
138// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
139func (c *Conn) SetWriteDeadline(t time.Time) error {
140 return c.conn.SetWriteDeadline(t)
141}
142
143// A halfConn represents one direction of the record layer
144// connection, either sending or receiving.
145type halfConn struct {
146 sync.Mutex
147
David Benjamin83c0bc92014-08-04 01:23:53 -0400148 err error // first permanent error
149 version uint16 // protocol version
150 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -0700151 cipher interface{} // cipher algorithm
152 mac macFunction
153 seq [8]byte // 64-bit sequence number
David Benjamin8e6db492015-07-25 18:29:23 -0400154 outSeq [8]byte // Mapped sequence number
Adam Langley95c29f32014-06-20 12:00:00 -0700155 bfree *block // list of free blocks
156
157 nextCipher interface{} // next encryption state
158 nextMac macFunction // next MAC algorithm
David Benjamin83f90402015-01-27 01:09:43 -0500159 nextSeq [6]byte // next epoch's starting sequence number in DTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700160
161 // used to save allocating a new buffer for each MAC.
162 inDigestBuf, outDigestBuf []byte
Adam Langley80842bd2014-06-20 12:00:00 -0700163
Steven Valdezc4aa7272016-10-03 12:25:56 -0400164 trafficSecret []byte
David Benjamin21c00282016-07-18 21:56:23 +0200165
David Benjamin6f600d62016-12-21 16:06:54 -0500166 shortHeader bool
167
Adam Langley80842bd2014-06-20 12:00:00 -0700168 config *Config
Adam Langley95c29f32014-06-20 12:00:00 -0700169}
170
171func (hc *halfConn) setErrorLocked(err error) error {
172 hc.err = err
173 return err
174}
175
176func (hc *halfConn) error() error {
Adam Langley2ae77d22014-10-28 17:29:33 -0700177 // This should be locked, but I've removed it for the renegotiation
178 // tests since we don't concurrently read and write the same tls.Conn
179 // in any case during testing.
Adam Langley95c29f32014-06-20 12:00:00 -0700180 err := hc.err
Adam Langley95c29f32014-06-20 12:00:00 -0700181 return err
182}
183
184// prepareCipherSpec sets the encryption and MAC states
185// that a subsequent changeCipherSpec will use.
186func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
187 hc.version = version
188 hc.nextCipher = cipher
189 hc.nextMac = mac
190}
191
192// changeCipherSpec changes the encryption and MAC states
193// to the ones previously passed to prepareCipherSpec.
Adam Langley80842bd2014-06-20 12:00:00 -0700194func (hc *halfConn) changeCipherSpec(config *Config) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700195 if hc.nextCipher == nil {
196 return alertInternalError
197 }
198 hc.cipher = hc.nextCipher
199 hc.mac = hc.nextMac
200 hc.nextCipher = nil
201 hc.nextMac = nil
Adam Langley80842bd2014-06-20 12:00:00 -0700202 hc.config = config
David Benjamin83c0bc92014-08-04 01:23:53 -0400203 hc.incEpoch()
David Benjaminf2b83632016-03-01 22:57:46 -0500204
205 if config.Bugs.NullAllCiphers {
David Benjamin7a4aaa42016-09-20 17:58:14 -0400206 hc.cipher = nullCipher{}
David Benjaminf2b83632016-03-01 22:57:46 -0500207 hc.mac = nil
208 }
Adam Langley95c29f32014-06-20 12:00:00 -0700209 return nil
210}
211
David Benjamin21c00282016-07-18 21:56:23 +0200212// useTrafficSecret sets the current cipher state for TLS 1.3.
Steven Valdeza833c352016-11-01 13:39:36 -0400213func (hc *halfConn) useTrafficSecret(version uint16, suite *cipherSuite, secret []byte, side trafficDirection) {
Nick Harperb41d2e42016-07-01 17:50:32 -0400214 hc.version = version
Steven Valdeza833c352016-11-01 13:39:36 -0400215 hc.cipher = deriveTrafficAEAD(version, suite, secret, side)
David Benjamin7a4aaa42016-09-20 17:58:14 -0400216 if hc.config.Bugs.NullAllCiphers {
217 hc.cipher = nullCipher{}
218 }
David Benjamin21c00282016-07-18 21:56:23 +0200219 hc.trafficSecret = secret
Nick Harperb41d2e42016-07-01 17:50:32 -0400220 hc.incEpoch()
221}
222
David Benjamin21c00282016-07-18 21:56:23 +0200223func (hc *halfConn) doKeyUpdate(c *Conn, isOutgoing bool) {
224 side := serverWrite
225 if c.isClient == isOutgoing {
226 side = clientWrite
227 }
Steven Valdeza833c352016-11-01 13:39:36 -0400228 hc.useTrafficSecret(hc.version, c.cipherSuite, updateTrafficSecret(c.cipherSuite.hash(), hc.trafficSecret), side)
David Benjamin21c00282016-07-18 21:56:23 +0200229}
230
Adam Langley95c29f32014-06-20 12:00:00 -0700231// incSeq increments the sequence number.
David Benjamin5e961c12014-11-07 01:48:35 -0500232func (hc *halfConn) incSeq(isOutgoing bool) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400233 limit := 0
David Benjamin5e961c12014-11-07 01:48:35 -0500234 increment := uint64(1)
David Benjamin83c0bc92014-08-04 01:23:53 -0400235 if hc.isDTLS {
236 // Increment up to the epoch in DTLS.
237 limit = 2
238 }
239 for i := 7; i >= limit; i-- {
David Benjamin5e961c12014-11-07 01:48:35 -0500240 increment += uint64(hc.seq[i])
241 hc.seq[i] = byte(increment)
242 increment >>= 8
Adam Langley95c29f32014-06-20 12:00:00 -0700243 }
244
245 // Not allowed to let sequence number wrap.
246 // Instead, must renegotiate before it does.
247 // Not likely enough to bother.
David Benjamin5e961c12014-11-07 01:48:35 -0500248 if increment != 0 {
249 panic("TLS: sequence number wraparound")
250 }
David Benjamin8e6db492015-07-25 18:29:23 -0400251
252 hc.updateOutSeq()
Adam Langley95c29f32014-06-20 12:00:00 -0700253}
254
David Benjamin83f90402015-01-27 01:09:43 -0500255// incNextSeq increments the starting sequence number for the next epoch.
256func (hc *halfConn) incNextSeq() {
257 for i := len(hc.nextSeq) - 1; i >= 0; i-- {
258 hc.nextSeq[i]++
259 if hc.nextSeq[i] != 0 {
260 return
261 }
262 }
263 panic("TLS: sequence number wraparound")
264}
265
266// incEpoch resets the sequence number. In DTLS, it also increments the epoch
267// half of the sequence number.
David Benjamin83c0bc92014-08-04 01:23:53 -0400268func (hc *halfConn) incEpoch() {
David Benjamin83c0bc92014-08-04 01:23:53 -0400269 if hc.isDTLS {
270 for i := 1; i >= 0; i-- {
271 hc.seq[i]++
272 if hc.seq[i] != 0 {
273 break
274 }
275 if i == 0 {
276 panic("TLS: epoch number wraparound")
277 }
278 }
David Benjamin83f90402015-01-27 01:09:43 -0500279 copy(hc.seq[2:], hc.nextSeq[:])
280 for i := range hc.nextSeq {
281 hc.nextSeq[i] = 0
282 }
283 } else {
284 for i := range hc.seq {
285 hc.seq[i] = 0
286 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400287 }
David Benjamin8e6db492015-07-25 18:29:23 -0400288
289 hc.updateOutSeq()
290}
291
292func (hc *halfConn) updateOutSeq() {
293 if hc.config.Bugs.SequenceNumberMapping != nil {
294 seqU64 := binary.BigEndian.Uint64(hc.seq[:])
295 seqU64 = hc.config.Bugs.SequenceNumberMapping(seqU64)
296 binary.BigEndian.PutUint64(hc.outSeq[:], seqU64)
297
298 // The DTLS epoch cannot be changed.
299 copy(hc.outSeq[:2], hc.seq[:2])
300 return
301 }
302
303 copy(hc.outSeq[:], hc.seq[:])
David Benjamin83c0bc92014-08-04 01:23:53 -0400304}
305
David Benjamin6f600d62016-12-21 16:06:54 -0500306func (hc *halfConn) isShortHeader() bool {
307 return hc.shortHeader && hc.cipher != nil
308}
309
David Benjamin83c0bc92014-08-04 01:23:53 -0400310func (hc *halfConn) recordHeaderLen() int {
311 if hc.isDTLS {
312 return dtlsRecordHeaderLen
313 }
David Benjamin6f600d62016-12-21 16:06:54 -0500314 if hc.isShortHeader() {
315 return 2
316 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400317 return tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700318}
319
320// removePadding returns an unpadded slice, in constant time, which is a prefix
321// of the input. It also returns a byte which is equal to 255 if the padding
322// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
323func removePadding(payload []byte) ([]byte, byte) {
324 if len(payload) < 1 {
325 return payload, 0
326 }
327
328 paddingLen := payload[len(payload)-1]
329 t := uint(len(payload)-1) - uint(paddingLen)
330 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
331 good := byte(int32(^t) >> 31)
332
333 toCheck := 255 // the maximum possible padding length
334 // The length of the padded data is public, so we can use an if here
335 if toCheck+1 > len(payload) {
336 toCheck = len(payload) - 1
337 }
338
339 for i := 0; i < toCheck; i++ {
340 t := uint(paddingLen) - uint(i)
341 // if i <= paddingLen then the MSB of t is zero
342 mask := byte(int32(^t) >> 31)
343 b := payload[len(payload)-1-i]
344 good &^= mask&paddingLen ^ mask&b
345 }
346
347 // We AND together the bits of good and replicate the result across
348 // all the bits.
349 good &= good << 4
350 good &= good << 2
351 good &= good << 1
352 good = uint8(int8(good) >> 7)
353
354 toRemove := good&paddingLen + 1
355 return payload[:len(payload)-int(toRemove)], good
356}
357
358// removePaddingSSL30 is a replacement for removePadding in the case that the
359// protocol version is SSLv3. In this version, the contents of the padding
360// are random and cannot be checked.
361func removePaddingSSL30(payload []byte) ([]byte, byte) {
362 if len(payload) < 1 {
363 return payload, 0
364 }
365
366 paddingLen := int(payload[len(payload)-1]) + 1
367 if paddingLen > len(payload) {
368 return payload, 0
369 }
370
371 return payload[:len(payload)-paddingLen], 255
372}
373
374func roundUp(a, b int) int {
375 return a + (b-a%b)%b
376}
377
378// cbcMode is an interface for block ciphers using cipher block chaining.
379type cbcMode interface {
380 cipher.BlockMode
381 SetIV([]byte)
382}
383
384// decrypt checks and strips the mac and decrypts the data in b. Returns a
385// success boolean, the number of bytes to skip from the start of the record in
Nick Harper1fd39d82016-06-14 18:14:35 -0700386// order to get the application payload, the encrypted record type (or 0
387// if there is none), and an optional alert value.
388func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, contentType recordType, alertValue alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400389 recordHeaderLen := hc.recordHeaderLen()
390
Adam Langley95c29f32014-06-20 12:00:00 -0700391 // pull out payload
392 payload := b.data[recordHeaderLen:]
393
394 macSize := 0
395 if hc.mac != nil {
396 macSize = hc.mac.Size()
397 }
398
399 paddingGood := byte(255)
400 explicitIVLen := 0
401
David Benjamin83c0bc92014-08-04 01:23:53 -0400402 seq := hc.seq[:]
403 if hc.isDTLS {
404 // DTLS sequence numbers are explicit.
405 seq = b.data[3:11]
406 }
407
Adam Langley95c29f32014-06-20 12:00:00 -0700408 // decrypt
409 if hc.cipher != nil {
410 switch c := hc.cipher.(type) {
411 case cipher.Stream:
412 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400413 case *tlsAead:
414 nonce := seq
415 if c.explicitNonce {
416 explicitIVLen = 8
417 if len(payload) < explicitIVLen {
Nick Harper1fd39d82016-06-14 18:14:35 -0700418 return false, 0, 0, alertBadRecordMAC
David Benjamine9a80ff2015-04-07 00:46:46 -0400419 }
420 nonce = payload[:8]
421 payload = payload[8:]
Adam Langley95c29f32014-06-20 12:00:00 -0700422 }
Adam Langley95c29f32014-06-20 12:00:00 -0700423
Nick Harper1fd39d82016-06-14 18:14:35 -0700424 var additionalData []byte
425 if hc.version < VersionTLS13 {
426 additionalData = make([]byte, 13)
427 copy(additionalData, seq)
428 copy(additionalData[8:], b.data[:3])
429 n := len(payload) - c.Overhead()
430 additionalData[11] = byte(n >> 8)
431 additionalData[12] = byte(n)
432 }
Adam Langley95c29f32014-06-20 12:00:00 -0700433 var err error
Nick Harper1fd39d82016-06-14 18:14:35 -0700434 payload, err = c.Open(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700435 if err != nil {
Nick Harper1fd39d82016-06-14 18:14:35 -0700436 return false, 0, 0, alertBadRecordMAC
437 }
Adam Langley95c29f32014-06-20 12:00:00 -0700438 b.resize(recordHeaderLen + explicitIVLen + len(payload))
439 case cbcMode:
440 blockSize := c.BlockSize()
David Benjamin83c0bc92014-08-04 01:23:53 -0400441 if hc.version >= VersionTLS11 || hc.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700442 explicitIVLen = blockSize
443 }
444
445 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
Nick Harper1fd39d82016-06-14 18:14:35 -0700446 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700447 }
448
449 if explicitIVLen > 0 {
450 c.SetIV(payload[:explicitIVLen])
451 payload = payload[explicitIVLen:]
452 }
453 c.CryptBlocks(payload, payload)
454 if hc.version == VersionSSL30 {
455 payload, paddingGood = removePaddingSSL30(payload)
456 } else {
457 payload, paddingGood = removePadding(payload)
458 }
459 b.resize(recordHeaderLen + explicitIVLen + len(payload))
460
461 // note that we still have a timing side-channel in the
462 // MAC check, below. An attacker can align the record
463 // so that a correct padding will cause one less hash
464 // block to be calculated. Then they can iteratively
465 // decrypt a record by breaking each byte. See
466 // "Password Interception in a SSL/TLS Channel", Brice
467 // Canvel et al.
468 //
469 // However, our behavior matches OpenSSL, so we leak
470 // only as much as they do.
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700471 case nullCipher:
472 break
Adam Langley95c29f32014-06-20 12:00:00 -0700473 default:
474 panic("unknown cipher type")
475 }
David Benjamin7a4aaa42016-09-20 17:58:14 -0400476
477 if hc.version >= VersionTLS13 {
478 i := len(payload)
479 for i > 0 && payload[i-1] == 0 {
480 i--
481 }
482 payload = payload[:i]
483 if len(payload) == 0 {
484 return false, 0, 0, alertUnexpectedMessage
485 }
486 contentType = recordType(payload[len(payload)-1])
487 payload = payload[:len(payload)-1]
488 b.resize(recordHeaderLen + len(payload))
489 }
Adam Langley95c29f32014-06-20 12:00:00 -0700490 }
491
492 // check, strip mac
493 if hc.mac != nil {
494 if len(payload) < macSize {
Nick Harper1fd39d82016-06-14 18:14:35 -0700495 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700496 }
497
498 // strip mac off payload, b.data
499 n := len(payload) - macSize
David Benjamin83c0bc92014-08-04 01:23:53 -0400500 b.data[recordHeaderLen-2] = byte(n >> 8)
501 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700502 b.resize(recordHeaderLen + explicitIVLen + n)
503 remoteMAC := payload[n:]
David Benjamin83c0bc92014-08-04 01:23:53 -0400504 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
Adam Langley95c29f32014-06-20 12:00:00 -0700505
506 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
Nick Harper1fd39d82016-06-14 18:14:35 -0700507 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700508 }
509 hc.inDigestBuf = localMAC
510 }
David Benjamin5e961c12014-11-07 01:48:35 -0500511 hc.incSeq(false)
Adam Langley95c29f32014-06-20 12:00:00 -0700512
Nick Harper1fd39d82016-06-14 18:14:35 -0700513 return true, recordHeaderLen + explicitIVLen, contentType, 0
Adam Langley95c29f32014-06-20 12:00:00 -0700514}
515
516// padToBlockSize calculates the needed padding block, if any, for a payload.
517// On exit, prefix aliases payload and extends to the end of the last full
518// block of payload. finalBlock is a fresh slice which contains the contents of
519// any suffix of payload as well as the needed padding to make finalBlock a
520// full block.
Adam Langley80842bd2014-06-20 12:00:00 -0700521func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
Adam Langley95c29f32014-06-20 12:00:00 -0700522 overrun := len(payload) % blockSize
Adam Langley95c29f32014-06-20 12:00:00 -0700523 prefix = payload[:len(payload)-overrun]
Adam Langley80842bd2014-06-20 12:00:00 -0700524
525 paddingLen := blockSize - overrun
526 finalSize := blockSize
527 if config.Bugs.MaxPadding {
528 for paddingLen+blockSize <= 256 {
529 paddingLen += blockSize
530 }
531 finalSize = 256
532 }
533 finalBlock = make([]byte, finalSize)
534 for i := range finalBlock {
Adam Langley95c29f32014-06-20 12:00:00 -0700535 finalBlock[i] = byte(paddingLen - 1)
536 }
Adam Langley80842bd2014-06-20 12:00:00 -0700537 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
538 finalBlock[overrun] ^= 0xff
539 }
540 copy(finalBlock, payload[len(payload)-overrun:])
Adam Langley95c29f32014-06-20 12:00:00 -0700541 return
542}
543
544// encrypt encrypts and macs the data in b.
Nick Harper1fd39d82016-06-14 18:14:35 -0700545func (hc *halfConn) encrypt(b *block, explicitIVLen int, typ recordType) (bool, alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400546 recordHeaderLen := hc.recordHeaderLen()
547
Adam Langley95c29f32014-06-20 12:00:00 -0700548 // mac
549 if hc.mac != nil {
David Benjamin8e6db492015-07-25 18:29:23 -0400550 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 -0700551
552 n := len(b.data)
553 b.resize(n + len(mac))
554 copy(b.data[n:], mac)
555 hc.outDigestBuf = mac
556 }
557
558 payload := b.data[recordHeaderLen:]
559
560 // encrypt
561 if hc.cipher != nil {
David Benjamin7a4aaa42016-09-20 17:58:14 -0400562 // Add TLS 1.3 padding.
563 if hc.version >= VersionTLS13 {
564 paddingLen := hc.config.Bugs.RecordPadding
565 if hc.config.Bugs.OmitRecordContents {
566 b.resize(recordHeaderLen + paddingLen)
567 } else {
568 b.resize(len(b.data) + 1 + paddingLen)
569 b.data[len(b.data)-paddingLen-1] = byte(typ)
570 }
571 for i := 0; i < paddingLen; i++ {
572 b.data[len(b.data)-paddingLen+i] = 0
573 }
574 }
575
Adam Langley95c29f32014-06-20 12:00:00 -0700576 switch c := hc.cipher.(type) {
577 case cipher.Stream:
578 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400579 case *tlsAead:
Adam Langley95c29f32014-06-20 12:00:00 -0700580 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
David Benjamin7a4aaa42016-09-20 17:58:14 -0400581 b.resize(len(b.data) + c.Overhead())
David Benjamin8e6db492015-07-25 18:29:23 -0400582 nonce := hc.outSeq[:]
David Benjamine9a80ff2015-04-07 00:46:46 -0400583 if c.explicitNonce {
584 nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
585 }
Adam Langley95c29f32014-06-20 12:00:00 -0700586 payload := b.data[recordHeaderLen+explicitIVLen:]
587 payload = payload[:payloadLen]
588
Nick Harper1fd39d82016-06-14 18:14:35 -0700589 var additionalData []byte
590 if hc.version < VersionTLS13 {
591 additionalData = make([]byte, 13)
592 copy(additionalData, hc.outSeq[:])
593 copy(additionalData[8:], b.data[:3])
594 additionalData[11] = byte(payloadLen >> 8)
595 additionalData[12] = byte(payloadLen)
596 }
Adam Langley95c29f32014-06-20 12:00:00 -0700597
Nick Harper1fd39d82016-06-14 18:14:35 -0700598 c.Seal(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700599 case cbcMode:
600 blockSize := c.BlockSize()
601 if explicitIVLen > 0 {
602 c.SetIV(payload[:explicitIVLen])
603 payload = payload[explicitIVLen:]
604 }
Adam Langley80842bd2014-06-20 12:00:00 -0700605 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700606 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
607 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
608 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700609 case nullCipher:
610 break
Adam Langley95c29f32014-06-20 12:00:00 -0700611 default:
612 panic("unknown cipher type")
613 }
614 }
615
616 // update length to include MAC and any block padding needed.
617 n := len(b.data) - recordHeaderLen
David Benjamin83c0bc92014-08-04 01:23:53 -0400618 b.data[recordHeaderLen-2] = byte(n >> 8)
619 b.data[recordHeaderLen-1] = byte(n)
David Benjamin6f600d62016-12-21 16:06:54 -0500620 if hc.isShortHeader() && !hc.config.Bugs.ClearShortHeaderBit {
621 b.data[0] |= 0x80
622 }
David Benjamin5e961c12014-11-07 01:48:35 -0500623 hc.incSeq(true)
Adam Langley95c29f32014-06-20 12:00:00 -0700624
625 return true, 0
626}
627
628// A block is a simple data buffer.
629type block struct {
630 data []byte
631 off int // index for Read
632 link *block
633}
634
635// resize resizes block to be n bytes, growing if necessary.
636func (b *block) resize(n int) {
637 if n > cap(b.data) {
638 b.reserve(n)
639 }
640 b.data = b.data[0:n]
641}
642
643// reserve makes sure that block contains a capacity of at least n bytes.
644func (b *block) reserve(n int) {
645 if cap(b.data) >= n {
646 return
647 }
648 m := cap(b.data)
649 if m == 0 {
650 m = 1024
651 }
652 for m < n {
653 m *= 2
654 }
655 data := make([]byte, len(b.data), m)
656 copy(data, b.data)
657 b.data = data
658}
659
660// readFromUntil reads from r into b until b contains at least n bytes
661// or else returns an error.
662func (b *block) readFromUntil(r io.Reader, n int) error {
663 // quick case
664 if len(b.data) >= n {
665 return nil
666 }
667
668 // read until have enough.
669 b.reserve(n)
670 for {
671 m, err := r.Read(b.data[len(b.data):cap(b.data)])
672 b.data = b.data[0 : len(b.data)+m]
673 if len(b.data) >= n {
674 // TODO(bradfitz,agl): slightly suspicious
675 // that we're throwing away r.Read's err here.
676 break
677 }
678 if err != nil {
679 return err
680 }
681 }
682 return nil
683}
684
685func (b *block) Read(p []byte) (n int, err error) {
686 n = copy(p, b.data[b.off:])
687 b.off += n
688 return
689}
690
691// newBlock allocates a new block, from hc's free list if possible.
692func (hc *halfConn) newBlock() *block {
693 b := hc.bfree
694 if b == nil {
695 return new(block)
696 }
697 hc.bfree = b.link
698 b.link = nil
699 b.resize(0)
700 return b
701}
702
703// freeBlock returns a block to hc's free list.
704// The protocol is such that each side only has a block or two on
705// its free list at a time, so there's no need to worry about
706// trimming the list, etc.
707func (hc *halfConn) freeBlock(b *block) {
708 b.link = hc.bfree
709 hc.bfree = b
710}
711
712// splitBlock splits a block after the first n bytes,
713// returning a block with those n bytes and a
714// block with the remainder. the latter may be nil.
715func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
716 if len(b.data) <= n {
717 return b, nil
718 }
719 bb := hc.newBlock()
720 bb.resize(len(b.data) - n)
721 copy(bb.data, b.data[n:])
722 b.data = b.data[0:n]
723 return b, bb
724}
725
David Benjamin83c0bc92014-08-04 01:23:53 -0400726func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
727 if c.isDTLS {
728 return c.dtlsDoReadRecord(want)
729 }
730
David Benjamin6f600d62016-12-21 16:06:54 -0500731 recordHeaderLen := c.in.recordHeaderLen()
David Benjamin83c0bc92014-08-04 01:23:53 -0400732
733 if c.rawInput == nil {
734 c.rawInput = c.in.newBlock()
735 }
736 b := c.rawInput
737
738 // Read header, payload.
739 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
740 // RFC suggests that EOF without an alertCloseNotify is
741 // an error, but popular web sites seem to do this,
David Benjamin30789da2015-08-29 22:56:45 -0400742 // so we can't make it an error, outside of tests.
743 if err == io.EOF && c.config.Bugs.ExpectCloseNotify {
744 err = io.ErrUnexpectedEOF
745 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400746 if e, ok := err.(net.Error); !ok || !e.Temporary() {
747 c.in.setErrorLocked(err)
748 }
749 return 0, nil, err
750 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400751
David Benjamin6f600d62016-12-21 16:06:54 -0500752 var typ recordType
753 var vers uint16
754 var n int
755 if c.in.isShortHeader() {
756 typ = recordTypeApplicationData
757 vers = VersionTLS10
758 n = int(b.data[0])<<8 | int(b.data[1])
759 if n&0x8000 == 0 {
760 c.sendAlert(alertDecodeError)
761 return 0, nil, c.in.setErrorLocked(errors.New("tls: length did not have high bit set"))
762 }
763
764 n = n & 0x7fff
765 } else {
766 typ = recordType(b.data[0])
767
768 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
769 // start with a uint16 length where the MSB is set and the first record
770 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
771 // an SSLv2 client.
772 if want == recordTypeHandshake && typ == 0x80 {
773 c.sendAlert(alertProtocolVersion)
774 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
775 }
776
777 vers = uint16(b.data[1])<<8 | uint16(b.data[2])
778 n = int(b.data[3])<<8 | int(b.data[4])
David Benjamin83c0bc92014-08-04 01:23:53 -0400779 }
780
David Benjaminbde00392016-06-21 12:19:28 -0400781 // Alerts sent near version negotiation do not have a well-defined
782 // record-layer version prior to TLS 1.3. (In TLS 1.3, the record-layer
783 // version is irrelevant.)
784 if typ != recordTypeAlert {
David Benjamine6f22212016-11-08 14:28:24 -0500785 var expect uint16
David Benjaminbde00392016-06-21 12:19:28 -0400786 if c.haveVers {
David Benjamine6f22212016-11-08 14:28:24 -0500787 expect = c.vers
788 if c.vers >= VersionTLS13 {
789 expect = VersionTLS10
David Benjaminbde00392016-06-21 12:19:28 -0400790 }
791 } else {
David Benjamine6f22212016-11-08 14:28:24 -0500792 expect = c.config.Bugs.ExpectInitialRecordVersion
793 }
794 if expect != 0 && vers != expect {
795 c.sendAlert(alertProtocolVersion)
796 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 -0500797 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400798 }
799 if n > maxCiphertext {
800 c.sendAlert(alertRecordOverflow)
801 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
802 }
803 if !c.haveVers {
804 // First message, be extra suspicious:
805 // this might not be a TLS client.
806 // Bail out before reading a full 'body', if possible.
807 // The current max version is 3.1.
808 // If the version is >= 16.0, it's probably not real.
809 // Similarly, a clientHello message encodes in
810 // well under a kilobyte. If the length is >= 12 kB,
811 // it's probably not real.
812 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
813 c.sendAlert(alertUnexpectedMessage)
814 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
815 }
816 }
817 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
818 if err == io.EOF {
819 err = io.ErrUnexpectedEOF
820 }
821 if e, ok := err.(net.Error); !ok || !e.Temporary() {
822 c.in.setErrorLocked(err)
823 }
824 return 0, nil, err
825 }
826
827 // Process message.
828 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
David Benjaminff26f092016-07-01 16:13:42 -0400829 ok, off, encTyp, alertValue := c.in.decrypt(b)
830 if !ok {
831 return 0, nil, c.in.setErrorLocked(c.sendAlert(alertValue))
832 }
833 b.off = off
834
Nick Harper1fd39d82016-06-14 18:14:35 -0700835 if c.vers >= VersionTLS13 && c.in.cipher != nil {
David Benjaminc9ae27c2016-06-24 22:56:37 -0400836 if typ != recordTypeApplicationData {
837 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: outer record type is not application data"))
838 }
Nick Harper1fd39d82016-06-14 18:14:35 -0700839 typ = encTyp
840 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400841 return typ, b, nil
842}
843
Adam Langley95c29f32014-06-20 12:00:00 -0700844// readRecord reads the next TLS record from the connection
845// and updates the record layer state.
846// c.in.Mutex <= L; c.input == nil.
847func (c *Conn) readRecord(want recordType) error {
848 // Caller must be in sync with connection:
849 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700850 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700851 switch want {
852 default:
853 c.sendAlert(alertInternalError)
854 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
855 case recordTypeHandshake, recordTypeChangeCipherSpec:
856 if c.handshakeComplete {
857 c.sendAlert(alertInternalError)
858 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
859 }
860 case recordTypeApplicationData:
David Benjamine58c4f52014-08-24 03:47:07 -0400861 if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart {
Adam Langley95c29f32014-06-20 12:00:00 -0700862 c.sendAlert(alertInternalError)
863 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
864 }
David Benjamin30789da2015-08-29 22:56:45 -0400865 case recordTypeAlert:
866 // Looking for a close_notify. Note: unlike a real
867 // implementation, this is not tolerant of additional records.
868 // See the documentation for ExpectCloseNotify.
Adam Langley95c29f32014-06-20 12:00:00 -0700869 }
870
871Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400872 typ, b, err := c.doReadRecord(want)
873 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700874 return err
875 }
Adam Langley95c29f32014-06-20 12:00:00 -0700876 data := b.data[b.off:]
877 if len(data) > maxPlaintext {
878 err := c.sendAlert(alertRecordOverflow)
879 c.in.freeBlock(b)
880 return c.in.setErrorLocked(err)
881 }
882
883 switch typ {
884 default:
885 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
886
887 case recordTypeAlert:
888 if len(data) != 2 {
889 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
890 break
891 }
892 if alert(data[1]) == alertCloseNotify {
893 c.in.setErrorLocked(io.EOF)
894 break
895 }
896 switch data[0] {
897 case alertLevelWarning:
898 // drop on the floor
899 c.in.freeBlock(b)
900 goto Again
901 case alertLevelError:
902 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
903 default:
904 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
905 }
906
907 case recordTypeChangeCipherSpec:
908 if typ != want || len(data) != 1 || data[0] != 1 {
909 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
910 break
911 }
Adam Langley80842bd2014-06-20 12:00:00 -0700912 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700913 if err != nil {
914 c.in.setErrorLocked(c.sendAlert(err.(alert)))
915 }
916
917 case recordTypeApplicationData:
918 if typ != want {
919 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
920 break
921 }
922 c.input = b
923 b = nil
924
925 case recordTypeHandshake:
David Benjamind5a4ecb2016-07-18 01:17:13 +0200926 // Allow handshake data while reading application data to
927 // trigger post-handshake messages.
Adam Langley95c29f32014-06-20 12:00:00 -0700928 // TODO(rsc): Should at least pick off connection close.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200929 if typ != want && want != recordTypeApplicationData {
930 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
Adam Langley95c29f32014-06-20 12:00:00 -0700931 }
932 c.hand.Write(data)
933 }
934
935 if b != nil {
936 c.in.freeBlock(b)
937 }
938 return c.in.err
939}
940
941// sendAlert sends a TLS alert message.
942// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400943func (c *Conn) sendAlertLocked(level byte, err alert) error {
944 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700945 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400946 if c.config.Bugs.FragmentAlert {
947 c.writeRecord(recordTypeAlert, c.tmp[0:1])
948 c.writeRecord(recordTypeAlert, c.tmp[1:2])
David Benjamin0d3a8c62016-03-11 22:25:18 -0500949 } else if c.config.Bugs.DoubleAlert {
950 copy(c.tmp[2:4], c.tmp[0:2])
951 c.writeRecord(recordTypeAlert, c.tmp[0:4])
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400952 } else {
953 c.writeRecord(recordTypeAlert, c.tmp[0:2])
954 }
David Benjamin24f346d2015-06-06 03:28:08 -0400955 // Error alerts are fatal to the connection.
956 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700957 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
958 }
959 return nil
960}
961
962// sendAlert sends a TLS alert message.
963// L < c.out.Mutex.
964func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400965 level := byte(alertLevelError)
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500966 if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertficate {
David Benjamin24f346d2015-06-06 03:28:08 -0400967 level = alertLevelWarning
968 }
969 return c.SendAlert(level, err)
970}
971
972func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700973 c.out.Lock()
974 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -0400975 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -0700976}
977
David Benjamind86c7672014-08-02 04:07:12 -0400978// writeV2Record writes a record for a V2ClientHello.
979func (c *Conn) writeV2Record(data []byte) (n int, err error) {
980 record := make([]byte, 2+len(data))
981 record[0] = uint8(len(data)>>8) | 0x80
982 record[1] = uint8(len(data))
983 copy(record[2:], data)
984 return c.conn.Write(record)
985}
986
Adam Langley95c29f32014-06-20 12:00:00 -0700987// writeRecord writes a TLS record with the given type and payload
988// to the connection and updates the record layer state.
989// c.out.Mutex <= L.
990func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin639846e2016-09-09 11:41:18 -0400991 if msgType := c.config.Bugs.SendWrongMessageType; msgType != 0 {
992 if typ == recordTypeHandshake && data[0] == msgType {
David Benjamin0b8d5da2016-07-15 00:39:56 -0400993 newData := make([]byte, len(data))
994 copy(newData, data)
995 newData[0] += 42
996 data = newData
997 }
998 }
999
David Benjamin639846e2016-09-09 11:41:18 -04001000 if msgType := c.config.Bugs.SendTrailingMessageData; msgType != 0 {
1001 if typ == recordTypeHandshake && data[0] == msgType {
1002 newData := make([]byte, len(data))
1003 copy(newData, data)
1004
1005 // Add a 0 to the body.
1006 newData = append(newData, 0)
1007 // Fix the header.
1008 newLen := len(newData) - 4
1009 newData[1] = byte(newLen >> 16)
1010 newData[2] = byte(newLen >> 8)
1011 newData[3] = byte(newLen)
1012
1013 data = newData
1014 }
1015 }
1016
David Benjamin83c0bc92014-08-04 01:23:53 -04001017 if c.isDTLS {
1018 return c.dtlsWriteRecord(typ, data)
1019 }
1020
David Benjamin71dd6662016-07-08 14:10:48 -07001021 if typ == recordTypeHandshake {
1022 if c.config.Bugs.SendHelloRequestBeforeEveryHandshakeMessage {
1023 newData := make([]byte, 0, 4+len(data))
1024 newData = append(newData, typeHelloRequest, 0, 0, 0)
1025 newData = append(newData, data...)
1026 data = newData
1027 }
1028
1029 if c.config.Bugs.PackHandshakeFlight {
1030 c.pendingFlight.Write(data)
1031 return len(data), nil
1032 }
David Benjamin582ba042016-07-07 12:33:25 -07001033 }
1034
1035 return c.doWriteRecord(typ, data)
1036}
1037
1038func (c *Conn) doWriteRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin6f600d62016-12-21 16:06:54 -05001039 recordHeaderLen := c.out.recordHeaderLen()
Adam Langley95c29f32014-06-20 12:00:00 -07001040 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -04001041 first := true
1042 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -04001043 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -07001044 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -04001045 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -07001046 m = maxPlaintext
1047 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001048 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
1049 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -04001050 // By default, do not fragment the client_version or
1051 // server_version, which are located in the first 6
1052 // bytes.
1053 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
1054 m = 6
1055 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001056 }
Adam Langley95c29f32014-06-20 12:00:00 -07001057 explicitIVLen := 0
1058 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -04001059 first = false
Adam Langley95c29f32014-06-20 12:00:00 -07001060
1061 var cbc cbcMode
1062 if c.out.version >= VersionTLS11 {
1063 var ok bool
1064 if cbc, ok = c.out.cipher.(cbcMode); ok {
1065 explicitIVLen = cbc.BlockSize()
1066 }
1067 }
1068 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -04001069 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -07001070 explicitIVLen = 8
1071 // The AES-GCM construction in TLS has an
1072 // explicit nonce so that the nonce can be
1073 // random. However, the nonce is only 8 bytes
1074 // which is too small for a secure, random
1075 // nonce. Therefore we use the sequence number
1076 // as the nonce.
1077 explicitIVIsSeq = true
1078 }
1079 }
1080 b.resize(recordHeaderLen + explicitIVLen + m)
David Benjamin6f600d62016-12-21 16:06:54 -05001081 // If using a short record header, the length will be filled in
1082 // by encrypt.
1083 if !c.out.isShortHeader() {
1084 b.data[0] = byte(typ)
1085 if c.vers >= VersionTLS13 && c.out.cipher != nil {
1086 b.data[0] = byte(recordTypeApplicationData)
1087 if outerType := c.config.Bugs.OuterRecordType; outerType != 0 {
1088 b.data[0] = byte(outerType)
1089 }
David Benjaminc9ae27c2016-06-24 22:56:37 -04001090 }
David Benjamin6f600d62016-12-21 16:06:54 -05001091 vers := c.vers
1092 if vers == 0 || vers >= VersionTLS13 {
1093 // Some TLS servers fail if the record version is
1094 // greater than TLS 1.0 for the initial ClientHello.
1095 //
1096 // TLS 1.3 fixes the version number in the record
1097 // layer to {3, 1}.
1098 vers = VersionTLS10
1099 }
1100 if c.config.Bugs.SendRecordVersion != 0 {
1101 vers = c.config.Bugs.SendRecordVersion
1102 }
1103 if c.vers == 0 && c.config.Bugs.SendInitialRecordVersion != 0 {
1104 vers = c.config.Bugs.SendInitialRecordVersion
1105 }
1106 b.data[1] = byte(vers >> 8)
1107 b.data[2] = byte(vers)
1108 b.data[3] = byte(m >> 8)
1109 b.data[4] = byte(m)
Nick Harper1fd39d82016-06-14 18:14:35 -07001110 }
Adam Langley95c29f32014-06-20 12:00:00 -07001111 if explicitIVLen > 0 {
1112 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
1113 if explicitIVIsSeq {
1114 copy(explicitIV, c.out.seq[:])
1115 } else {
1116 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
1117 break
1118 }
1119 }
1120 }
1121 copy(b.data[recordHeaderLen+explicitIVLen:], data)
Nick Harper1fd39d82016-06-14 18:14:35 -07001122 c.out.encrypt(b, explicitIVLen, typ)
Adam Langley95c29f32014-06-20 12:00:00 -07001123 _, err = c.conn.Write(b.data)
1124 if err != nil {
1125 break
1126 }
1127 n += m
1128 data = data[m:]
1129 }
1130 c.out.freeBlock(b)
1131
1132 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -07001133 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -07001134 if err != nil {
1135 // Cannot call sendAlert directly,
1136 // because we already hold c.out.Mutex.
1137 c.tmp[0] = alertLevelError
1138 c.tmp[1] = byte(err.(alert))
1139 c.writeRecord(recordTypeAlert, c.tmp[0:2])
1140 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
1141 }
1142 }
1143 return
1144}
1145
David Benjamin582ba042016-07-07 12:33:25 -07001146func (c *Conn) flushHandshake() error {
1147 if c.isDTLS {
1148 return c.dtlsFlushHandshake()
1149 }
1150
1151 for c.pendingFlight.Len() > 0 {
1152 var buf [maxPlaintext]byte
1153 n, _ := c.pendingFlight.Read(buf[:])
1154 if _, err := c.doWriteRecord(recordTypeHandshake, buf[:n]); err != nil {
1155 return err
1156 }
1157 }
1158
1159 c.pendingFlight.Reset()
1160 return nil
1161}
1162
David Benjamin83c0bc92014-08-04 01:23:53 -04001163func (c *Conn) doReadHandshake() ([]byte, error) {
1164 if c.isDTLS {
1165 return c.dtlsDoReadHandshake()
1166 }
1167
Adam Langley95c29f32014-06-20 12:00:00 -07001168 for c.hand.Len() < 4 {
1169 if err := c.in.err; err != nil {
1170 return nil, err
1171 }
1172 if err := c.readRecord(recordTypeHandshake); err != nil {
1173 return nil, err
1174 }
1175 }
1176
1177 data := c.hand.Bytes()
1178 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1179 if n > maxHandshake {
1180 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
1181 }
1182 for c.hand.Len() < 4+n {
1183 if err := c.in.err; err != nil {
1184 return nil, err
1185 }
1186 if err := c.readRecord(recordTypeHandshake); err != nil {
1187 return nil, err
1188 }
1189 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001190 return c.hand.Next(4 + n), nil
1191}
1192
1193// readHandshake reads the next handshake message from
1194// the record layer.
1195// c.in.Mutex < L; c.out.Mutex < L.
1196func (c *Conn) readHandshake() (interface{}, error) {
1197 data, err := c.doReadHandshake()
1198 if err != nil {
1199 return nil, err
1200 }
1201
Adam Langley95c29f32014-06-20 12:00:00 -07001202 var m handshakeMessage
1203 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001204 case typeHelloRequest:
1205 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001206 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001207 m = &clientHelloMsg{
1208 isDTLS: c.isDTLS,
1209 }
Adam Langley95c29f32014-06-20 12:00:00 -07001210 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001211 m = &serverHelloMsg{
1212 isDTLS: c.isDTLS,
1213 }
Nick Harperdcfbc672016-07-16 17:47:31 +02001214 case typeHelloRetryRequest:
1215 m = new(helloRetryRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001216 case typeNewSessionTicket:
David Benjamin58104882016-07-18 01:25:41 +02001217 m = &newSessionTicketMsg{
1218 version: c.vers,
1219 }
Nick Harperb41d2e42016-07-01 17:50:32 -04001220 case typeEncryptedExtensions:
1221 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001222 case typeCertificate:
Nick Harperb41d2e42016-07-01 17:50:32 -04001223 m = &certificateMsg{
David Benjamin8d315d72016-07-18 01:03:18 +02001224 hasRequestContext: c.vers >= VersionTLS13,
Nick Harperb41d2e42016-07-01 17:50:32 -04001225 }
Adam Langley95c29f32014-06-20 12:00:00 -07001226 case typeCertificateRequest:
1227 m = &certificateRequestMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001228 hasSignatureAlgorithm: c.vers >= VersionTLS12,
David Benjamin8d315d72016-07-18 01:03:18 +02001229 hasRequestContext: c.vers >= VersionTLS13,
Adam Langley95c29f32014-06-20 12:00:00 -07001230 }
1231 case typeCertificateStatus:
1232 m = new(certificateStatusMsg)
1233 case typeServerKeyExchange:
1234 m = new(serverKeyExchangeMsg)
1235 case typeServerHelloDone:
1236 m = new(serverHelloDoneMsg)
1237 case typeClientKeyExchange:
1238 m = new(clientKeyExchangeMsg)
1239 case typeCertificateVerify:
1240 m = &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001241 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001242 }
1243 case typeNextProtocol:
1244 m = new(nextProtoMsg)
1245 case typeFinished:
1246 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001247 case typeHelloVerifyRequest:
1248 m = new(helloVerifyRequestMsg)
David Benjamin24599a82016-06-30 18:56:53 -04001249 case typeChannelID:
1250 m = new(channelIDMsg)
David Benjamin21c00282016-07-18 21:56:23 +02001251 case typeKeyUpdate:
1252 m = new(keyUpdateMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001253 default:
1254 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1255 }
1256
1257 // The handshake message unmarshallers
1258 // expect to be able to keep references to data,
1259 // so pass in a fresh copy that won't be overwritten.
1260 data = append([]byte(nil), data...)
1261
1262 if !m.unmarshal(data) {
1263 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1264 }
1265 return m, nil
1266}
1267
David Benjamin83f90402015-01-27 01:09:43 -05001268// skipPacket processes all the DTLS records in packet. It updates
1269// sequence number expectations but otherwise ignores them.
1270func (c *Conn) skipPacket(packet []byte) error {
1271 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001272 if len(packet) < 13 {
1273 return errors.New("tls: bad packet")
1274 }
David Benjamin83f90402015-01-27 01:09:43 -05001275 // Dropped packets are completely ignored save to update
1276 // expected sequence numbers for this and the next epoch. (We
1277 // don't assert on the contents of the packets both for
1278 // simplicity and because a previous test with one shorter
1279 // timeout schedule would have done so.)
1280 epoch := packet[3:5]
1281 seq := packet[5:11]
1282 length := uint16(packet[11])<<8 | uint16(packet[12])
1283 if bytes.Equal(c.in.seq[:2], epoch) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001284 if bytes.Compare(seq, c.in.seq[2:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001285 return errors.New("tls: sequence mismatch")
1286 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001287 copy(c.in.seq[2:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001288 c.in.incSeq(false)
1289 } else {
David Benjamin13e81fc2015-11-02 17:16:13 -05001290 if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001291 return errors.New("tls: sequence mismatch")
1292 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001293 copy(c.in.nextSeq[:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001294 c.in.incNextSeq()
1295 }
David Benjamin6ca93552015-08-28 16:16:25 -04001296 if len(packet) < 13+int(length) {
1297 return errors.New("tls: bad packet")
1298 }
David Benjamin83f90402015-01-27 01:09:43 -05001299 packet = packet[13+length:]
1300 }
1301 return nil
1302}
1303
1304// simulatePacketLoss simulates the loss of a handshake leg from the
1305// peer based on the schedule in c.config.Bugs. If resendFunc is
1306// non-nil, it is called after each simulated timeout to retransmit
1307// handshake messages from the local end. This is used in cases where
1308// the peer retransmits on a stale Finished rather than a timeout.
1309func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1310 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1311 return nil
1312 }
1313 if !c.isDTLS {
1314 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1315 }
1316 if c.config.Bugs.PacketAdaptor == nil {
1317 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1318 }
1319 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1320 // Simulate a timeout.
1321 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1322 if err != nil {
1323 return err
1324 }
1325 for _, packet := range packets {
1326 if err := c.skipPacket(packet); err != nil {
1327 return err
1328 }
1329 }
1330 if resendFunc != nil {
1331 resendFunc()
1332 }
1333 }
1334 return nil
1335}
1336
David Benjamin47921102016-07-28 11:29:18 -04001337func (c *Conn) SendHalfHelloRequest() error {
1338 if err := c.Handshake(); err != nil {
1339 return err
1340 }
1341
1342 c.out.Lock()
1343 defer c.out.Unlock()
1344
1345 if _, err := c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0}); err != nil {
1346 return err
1347 }
1348 return c.flushHandshake()
1349}
1350
Adam Langley95c29f32014-06-20 12:00:00 -07001351// Write writes data to the connection.
1352func (c *Conn) Write(b []byte) (int, error) {
1353 if err := c.Handshake(); err != nil {
1354 return 0, err
1355 }
1356
1357 c.out.Lock()
1358 defer c.out.Unlock()
1359
David Benjamin12d2c482016-07-24 10:56:51 -04001360 // Flush any pending handshake data. PackHelloRequestWithFinished may
1361 // have been set and the handshake not followed by Renegotiate.
1362 c.flushHandshake()
1363
Adam Langley95c29f32014-06-20 12:00:00 -07001364 if err := c.out.err; err != nil {
1365 return 0, err
1366 }
1367
1368 if !c.handshakeComplete {
1369 return 0, alertInternalError
1370 }
1371
Steven Valdezc4aa7272016-10-03 12:25:56 -04001372 if c.keyUpdateRequested {
1373 if err := c.sendKeyUpdateLocked(keyUpdateNotRequested); err != nil {
David Benjamin21c00282016-07-18 21:56:23 +02001374 return 0, err
1375 }
Steven Valdezc4aa7272016-10-03 12:25:56 -04001376 c.keyUpdateRequested = false
David Benjamin21c00282016-07-18 21:56:23 +02001377 }
1378
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001379 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001380 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001381 }
1382
Adam Langley27a0d082015-11-03 13:34:10 -08001383 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1384 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
David Benjamin582ba042016-07-07 12:33:25 -07001385 c.flushHandshake()
Adam Langley27a0d082015-11-03 13:34:10 -08001386 }
1387
Adam Langley95c29f32014-06-20 12:00:00 -07001388 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1389 // attack when using block mode ciphers due to predictable IVs.
1390 // This can be prevented by splitting each Application Data
1391 // record into two records, effectively randomizing the IV.
1392 //
1393 // http://www.openssl.org/~bodo/tls-cbc.txt
1394 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1395 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1396
1397 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001398 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001399 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1400 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1401 if err != nil {
1402 return n, c.out.setErrorLocked(err)
1403 }
1404 m, b = 1, b[1:]
1405 }
1406 }
1407
1408 n, err := c.writeRecord(recordTypeApplicationData, b)
1409 return n + m, c.out.setErrorLocked(err)
1410}
1411
David Benjamind5a4ecb2016-07-18 01:17:13 +02001412func (c *Conn) handlePostHandshakeMessage() error {
Adam Langley2ae77d22014-10-28 17:29:33 -07001413 msg, err := c.readHandshake()
1414 if err != nil {
1415 return err
1416 }
David Benjamind5a4ecb2016-07-18 01:17:13 +02001417
1418 if c.vers < VersionTLS13 {
1419 if !c.isClient {
1420 c.sendAlert(alertUnexpectedMessage)
1421 return errors.New("tls: unexpected post-handshake message")
1422 }
1423
1424 _, ok := msg.(*helloRequestMsg)
1425 if !ok {
1426 c.sendAlert(alertUnexpectedMessage)
1427 return alertUnexpectedMessage
1428 }
1429
1430 c.handshakeComplete = false
1431 return c.Handshake()
Adam Langley2ae77d22014-10-28 17:29:33 -07001432 }
1433
David Benjamind5a4ecb2016-07-18 01:17:13 +02001434 if c.isClient {
1435 if newSessionTicket, ok := msg.(*newSessionTicketMsg); ok {
David Benjamin1a5e8ec2016-10-07 15:19:18 -04001436 if c.config.Bugs.ExpectGREASE && !newSessionTicket.hasGREASEExtension {
1437 return errors.New("tls: no GREASE ticket extension found")
1438 }
1439
Steven Valdeza833c352016-11-01 13:39:36 -04001440 if c.config.Bugs.ExpectNoNewSessionTicket {
1441 return errors.New("tls: received unexpected NewSessionTicket")
1442 }
1443
David Benjamind5a4ecb2016-07-18 01:17:13 +02001444 if c.config.ClientSessionCache == nil || newSessionTicket.ticketLifetime == 0 {
1445 return nil
1446 }
1447
1448 session := &ClientSessionState{
1449 sessionTicket: newSessionTicket.ticket,
1450 vers: c.vers,
1451 cipherSuite: c.cipherSuite.id,
1452 masterSecret: c.resumptionSecret,
1453 serverCertificates: c.peerCertificates,
1454 sctList: c.sctList,
1455 ocspResponse: c.ocspResponse,
Nick Harper0b3625b2016-07-25 16:16:28 -07001456 ticketCreationTime: c.config.time(),
1457 ticketExpiration: c.config.time().Add(time.Duration(newSessionTicket.ticketLifetime) * time.Second),
Steven Valdeza833c352016-11-01 13:39:36 -04001458 ticketAgeAdd: newSessionTicket.ticketAgeAdd,
David Benjamind5a4ecb2016-07-18 01:17:13 +02001459 }
1460
1461 cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
1462 c.config.ClientSessionCache.Put(cacheKey, session)
1463 return nil
1464 }
1465 }
1466
Steven Valdezc4aa7272016-10-03 12:25:56 -04001467 if keyUpdate, ok := msg.(*keyUpdateMsg); ok {
Steven Valdez1dc53d22016-07-26 12:27:38 -04001468 c.in.doKeyUpdate(c, false)
Steven Valdezc4aa7272016-10-03 12:25:56 -04001469 if keyUpdate.keyUpdateRequest == keyUpdateRequested {
1470 c.keyUpdateRequested = true
1471 }
David Benjamin21c00282016-07-18 21:56:23 +02001472 return nil
1473 }
1474
David Benjamind5a4ecb2016-07-18 01:17:13 +02001475 // TODO(davidben): Add support for KeyUpdate.
1476 c.sendAlert(alertUnexpectedMessage)
1477 return alertUnexpectedMessage
Adam Langley2ae77d22014-10-28 17:29:33 -07001478}
1479
Adam Langleycf2d4f42014-10-28 19:06:14 -07001480func (c *Conn) Renegotiate() error {
1481 if !c.isClient {
David Benjaminef5dfd22015-12-06 13:17:07 -05001482 helloReq := new(helloRequestMsg).marshal()
1483 if c.config.Bugs.BadHelloRequest != nil {
1484 helloReq = c.config.Bugs.BadHelloRequest
1485 }
1486 c.writeRecord(recordTypeHandshake, helloReq)
David Benjamin582ba042016-07-07 12:33:25 -07001487 c.flushHandshake()
Adam Langleycf2d4f42014-10-28 19:06:14 -07001488 }
1489
1490 c.handshakeComplete = false
1491 return c.Handshake()
1492}
1493
Adam Langley95c29f32014-06-20 12:00:00 -07001494// Read can be made to time out and return a net.Error with Timeout() == true
1495// after a fixed time limit; see SetDeadline and SetReadDeadline.
1496func (c *Conn) Read(b []byte) (n int, err error) {
1497 if err = c.Handshake(); err != nil {
1498 return
1499 }
1500
1501 c.in.Lock()
1502 defer c.in.Unlock()
1503
1504 // Some OpenSSL servers send empty records in order to randomize the
1505 // CBC IV. So this loop ignores a limited number of empty records.
1506 const maxConsecutiveEmptyRecords = 100
1507 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1508 for c.input == nil && c.in.err == nil {
1509 if err := c.readRecord(recordTypeApplicationData); err != nil {
1510 // Soft error, like EAGAIN
1511 return 0, err
1512 }
David Benjamind9b091b2015-01-27 01:10:54 -05001513 if c.hand.Len() > 0 {
David Benjamind5a4ecb2016-07-18 01:17:13 +02001514 // We received handshake bytes, indicating a
1515 // post-handshake message.
1516 if err := c.handlePostHandshakeMessage(); err != nil {
Adam Langley2ae77d22014-10-28 17:29:33 -07001517 return 0, err
1518 }
1519 continue
1520 }
Adam Langley95c29f32014-06-20 12:00:00 -07001521 }
1522 if err := c.in.err; err != nil {
1523 return 0, err
1524 }
1525
1526 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001527 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001528 c.in.freeBlock(c.input)
1529 c.input = nil
1530 }
1531
1532 // If a close-notify alert is waiting, read it so that
1533 // we can return (n, EOF) instead of (n, nil), to signal
1534 // to the HTTP response reading goroutine that the
1535 // connection is now closed. This eliminates a race
1536 // where the HTTP response reading goroutine would
1537 // otherwise not observe the EOF until its next read,
1538 // by which time a client goroutine might have already
1539 // tried to reuse the HTTP connection for a new
1540 // request.
1541 // See https://codereview.appspot.com/76400046
1542 // and http://golang.org/issue/3514
1543 if ri := c.rawInput; ri != nil &&
1544 n != 0 && err == nil &&
1545 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1546 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1547 err = recErr // will be io.EOF on closeNotify
1548 }
1549 }
1550
1551 if n != 0 || err != nil {
1552 return n, err
1553 }
1554 }
1555
1556 return 0, io.ErrNoProgress
1557}
1558
1559// Close closes the connection.
1560func (c *Conn) Close() error {
1561 var alertErr error
1562
1563 c.handshakeMutex.Lock()
1564 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001565 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
David Benjaminfa214e42016-05-10 17:03:10 -04001566 alert := alertCloseNotify
1567 if c.config.Bugs.SendAlertOnShutdown != 0 {
1568 alert = c.config.Bugs.SendAlertOnShutdown
1569 }
1570 alertErr = c.sendAlert(alert)
David Benjamin4d559612016-05-18 14:31:51 -04001571 // Clear local alerts when sending alerts so we continue to wait
1572 // for the peer rather than closing the socket early.
1573 if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1574 alertErr = nil
1575 }
Adam Langley95c29f32014-06-20 12:00:00 -07001576 }
1577
David Benjamin30789da2015-08-29 22:56:45 -04001578 // Consume a close_notify from the peer if one hasn't been received
1579 // already. This avoids the peer from failing |SSL_shutdown| due to a
1580 // write failing.
1581 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1582 for c.in.error() == nil {
1583 c.readRecord(recordTypeAlert)
1584 }
1585 if c.in.error() != io.EOF {
1586 alertErr = c.in.error()
1587 }
1588 }
1589
Adam Langley95c29f32014-06-20 12:00:00 -07001590 if err := c.conn.Close(); err != nil {
1591 return err
1592 }
1593 return alertErr
1594}
1595
1596// Handshake runs the client or server handshake
1597// protocol if it has not yet been run.
1598// Most uses of this package need not call Handshake
1599// explicitly: the first Read or Write will call it automatically.
1600func (c *Conn) Handshake() error {
1601 c.handshakeMutex.Lock()
1602 defer c.handshakeMutex.Unlock()
1603 if err := c.handshakeErr; err != nil {
1604 return err
1605 }
1606 if c.handshakeComplete {
1607 return nil
1608 }
1609
David Benjamin9a41d1b2015-05-16 01:30:09 -04001610 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1611 c.conn.Write([]byte{
1612 byte(recordTypeAlert), // type
1613 0xfe, 0xff, // version
1614 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1615 0x0, 0x2, // length
1616 })
1617 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1618 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001619 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1620 c.writeRecord(recordTypeApplicationData, data)
1621 }
Adam Langley95c29f32014-06-20 12:00:00 -07001622 if c.isClient {
1623 c.handshakeErr = c.clientHandshake()
1624 } else {
1625 c.handshakeErr = c.serverHandshake()
1626 }
David Benjaminddb9f152015-02-03 15:44:39 -05001627 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1628 c.writeRecord(recordType(42), []byte("invalid record"))
1629 }
Adam Langley95c29f32014-06-20 12:00:00 -07001630 return c.handshakeErr
1631}
1632
1633// ConnectionState returns basic TLS details about the connection.
1634func (c *Conn) ConnectionState() ConnectionState {
1635 c.handshakeMutex.Lock()
1636 defer c.handshakeMutex.Unlock()
1637
1638 var state ConnectionState
1639 state.HandshakeComplete = c.handshakeComplete
1640 if c.handshakeComplete {
1641 state.Version = c.vers
1642 state.NegotiatedProtocol = c.clientProtocol
1643 state.DidResume = c.didResume
1644 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001645 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001646 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001647 state.PeerCertificates = c.peerCertificates
1648 state.VerifiedChains = c.verifiedChains
1649 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001650 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001651 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001652 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001653 state.SCTList = c.sctList
Nick Harper60edffd2016-06-21 15:19:24 -07001654 state.PeerSignatureAlgorithm = c.peerSignatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -04001655 state.CurveID = c.curveID
David Benjamin6f600d62016-12-21 16:06:54 -05001656 state.ShortHeader = c.in.shortHeader
Adam Langley95c29f32014-06-20 12:00:00 -07001657 }
1658
1659 return state
1660}
1661
1662// OCSPResponse returns the stapled OCSP response from the TLS server, if
1663// any. (Only valid for client connections.)
1664func (c *Conn) OCSPResponse() []byte {
1665 c.handshakeMutex.Lock()
1666 defer c.handshakeMutex.Unlock()
1667
1668 return c.ocspResponse
1669}
1670
1671// VerifyHostname checks that the peer certificate chain is valid for
1672// connecting to host. If so, it returns nil; if not, it returns an error
1673// describing the problem.
1674func (c *Conn) VerifyHostname(host string) error {
1675 c.handshakeMutex.Lock()
1676 defer c.handshakeMutex.Unlock()
1677 if !c.isClient {
1678 return errors.New("tls: VerifyHostname called on TLS server connection")
1679 }
1680 if !c.handshakeComplete {
1681 return errors.New("tls: handshake has not yet been performed")
1682 }
1683 return c.peerCertificates[0].VerifyHostname(host)
1684}
David Benjaminc565ebb2015-04-03 04:06:36 -04001685
1686// ExportKeyingMaterial exports keying material from the current connection
1687// state, as per RFC 5705.
1688func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1689 c.handshakeMutex.Lock()
1690 defer c.handshakeMutex.Unlock()
1691 if !c.handshakeComplete {
1692 return nil, errors.New("tls: handshake has not yet been performed")
1693 }
1694
David Benjamin8d315d72016-07-18 01:03:18 +02001695 if c.vers >= VersionTLS13 {
David Benjamin97a0a082016-07-13 17:57:35 -04001696 // TODO(davidben): What should we do with useContext? See
1697 // https://github.com/tlswg/tls13-spec/issues/546
1698 return hkdfExpandLabel(c.cipherSuite.hash(), c.exporterSecret, label, context, length), nil
1699 }
1700
David Benjaminc565ebb2015-04-03 04:06:36 -04001701 seedLen := len(c.clientRandom) + len(c.serverRandom)
1702 if useContext {
1703 seedLen += 2 + len(context)
1704 }
1705 seed := make([]byte, 0, seedLen)
1706 seed = append(seed, c.clientRandom[:]...)
1707 seed = append(seed, c.serverRandom[:]...)
1708 if useContext {
1709 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1710 seed = append(seed, context...)
1711 }
1712 result := make([]byte, length)
David Benjamin97a0a082016-07-13 17:57:35 -04001713 prfForVersion(c.vers, c.cipherSuite)(result, c.exporterSecret, label, seed)
David Benjaminc565ebb2015-04-03 04:06:36 -04001714 return result, nil
1715}
David Benjamin3e052de2015-11-25 20:10:31 -05001716
1717// noRenegotiationInfo returns true if the renegotiation info extension
1718// should be supported in the current handshake.
1719func (c *Conn) noRenegotiationInfo() bool {
1720 if c.config.Bugs.NoRenegotiationInfo {
1721 return true
1722 }
1723 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1724 return true
1725 }
1726 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1727 return true
1728 }
1729 return false
1730}
David Benjamin58104882016-07-18 01:25:41 +02001731
1732func (c *Conn) SendNewSessionTicket() error {
1733 if c.isClient || c.vers < VersionTLS13 {
1734 return errors.New("tls: cannot send post-handshake NewSessionTicket")
1735 }
1736
1737 var peerCertificatesRaw [][]byte
1738 for _, cert := range c.peerCertificates {
1739 peerCertificatesRaw = append(peerCertificatesRaw, cert.Raw)
1740 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001741
Steven Valdeza833c352016-11-01 13:39:36 -04001742 addBuffer := make([]byte, 4)
1743 _, err := io.ReadFull(c.config.rand(), addBuffer)
1744 if err != nil {
1745 c.sendAlert(alertInternalError)
1746 return errors.New("tls: short read from Rand: " + err.Error())
1747 }
1748 ticketAgeAdd := uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0])
1749
David Benjamin58104882016-07-18 01:25:41 +02001750 // TODO(davidben): Allow configuring these values.
1751 m := &newSessionTicketMsg{
David Benjamin1286bee2016-10-07 15:25:06 -04001752 version: c.vers,
1753 ticketLifetime: uint32(24 * time.Hour / time.Second),
David Benjamin1286bee2016-10-07 15:25:06 -04001754 customExtension: c.config.Bugs.CustomTicketExtension,
Steven Valdeza833c352016-11-01 13:39:36 -04001755 ticketAgeAdd: ticketAgeAdd,
David Benjamin58104882016-07-18 01:25:41 +02001756 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001757
1758 state := sessionState{
1759 vers: c.vers,
1760 cipherSuite: c.cipherSuite.id,
1761 masterSecret: c.resumptionSecret,
1762 certificates: peerCertificatesRaw,
1763 ticketCreationTime: c.config.time(),
1764 ticketExpiration: c.config.time().Add(time.Duration(m.ticketLifetime) * time.Second),
Steven Valdeza833c352016-11-01 13:39:36 -04001765 ticketAgeAdd: uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0]),
Nick Harper0b3625b2016-07-25 16:16:28 -07001766 }
1767
David Benjamin58104882016-07-18 01:25:41 +02001768 if !c.config.Bugs.SendEmptySessionTicket {
1769 var err error
1770 m.ticket, err = c.encryptTicket(&state)
1771 if err != nil {
1772 return err
1773 }
1774 }
1775
1776 c.out.Lock()
1777 defer c.out.Unlock()
Steven Valdeza833c352016-11-01 13:39:36 -04001778 _, err = c.writeRecord(recordTypeHandshake, m.marshal())
David Benjamin58104882016-07-18 01:25:41 +02001779 return err
1780}
David Benjamin21c00282016-07-18 21:56:23 +02001781
Steven Valdezc4aa7272016-10-03 12:25:56 -04001782func (c *Conn) SendKeyUpdate(keyUpdateRequest byte) error {
David Benjamin21c00282016-07-18 21:56:23 +02001783 c.out.Lock()
1784 defer c.out.Unlock()
Steven Valdezc4aa7272016-10-03 12:25:56 -04001785 return c.sendKeyUpdateLocked(keyUpdateRequest)
David Benjamin21c00282016-07-18 21:56:23 +02001786}
1787
Steven Valdezc4aa7272016-10-03 12:25:56 -04001788func (c *Conn) sendKeyUpdateLocked(keyUpdateRequest byte) error {
David Benjamin7f0965a2016-09-30 15:14:01 -04001789 if c.vers < VersionTLS13 {
1790 return errors.New("tls: attempted to send KeyUpdate before TLS 1.3")
1791 }
1792
Steven Valdezc4aa7272016-10-03 12:25:56 -04001793 m := keyUpdateMsg{
1794 keyUpdateRequest: keyUpdateRequest,
1795 }
David Benjamin21c00282016-07-18 21:56:23 +02001796 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
1797 return err
1798 }
1799 if err := c.flushHandshake(); err != nil {
1800 return err
1801 }
Steven Valdez1dc53d22016-07-26 12:27:38 -04001802 c.out.doKeyUpdate(c, true)
David Benjamin21c00282016-07-18 21:56:23 +02001803 return nil
1804}
Steven Valdeza4ee74d2016-11-29 13:36:45 -05001805
1806func (c *Conn) sendFakeEarlyData(len int) error {
1807 // Assemble a fake early data record. This does not use writeRecord
1808 // because the record layer may be using different keys at this point.
1809 payload := make([]byte, 5+len)
1810 payload[0] = byte(recordTypeApplicationData)
1811 payload[1] = 3
1812 payload[2] = 1
1813 payload[3] = byte(len >> 8)
1814 payload[4] = byte(len)
1815 _, err := c.conn.Write(payload)
1816 return err
1817}
David Benjamin6f600d62016-12-21 16:06:54 -05001818
1819func (c *Conn) setShortHeader() {
1820 c.in.shortHeader = true
1821 c.out.shortHeader = true
1822}