blob: fbd501a050b14b265780149569ada3c1c741191e [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
Adam Langley95c29f32014-06-20 12:00:00 -070062
63 clientProtocol string
64 clientProtocolFallback bool
David Benjaminfc7b0862014-09-06 13:21:53 -040065 usedALPN bool
Adam Langley95c29f32014-06-20 12:00:00 -070066
Adam Langley2ae77d22014-10-28 17:29:33 -070067 // verify_data values for the renegotiation extension.
68 clientVerify []byte
69 serverVerify []byte
70
David Benjamind30a9902014-08-24 01:44:23 -040071 channelID *ecdsa.PublicKey
72
David Benjaminca6c8262014-11-15 19:06:08 -050073 srtpProtectionProfile uint16
74
David Benjaminc44b1df2014-11-23 12:11:01 -050075 clientVersion uint16
76
Adam Langley95c29f32014-06-20 12:00:00 -070077 // input/output
78 in, out halfConn // in.Mutex < out.Mutex
79 rawInput *block // raw input, right off the wire
David Benjamin83c0bc92014-08-04 01:23:53 -040080 input *block // application record waiting to be read
81 hand bytes.Buffer // handshake record waiting to be read
82
David Benjamin582ba042016-07-07 12:33:25 -070083 // pendingFlight, if PackHandshakeFlight is enabled, is the buffer of
84 // handshake data to be split into records at the end of the flight.
85 pendingFlight bytes.Buffer
86
David Benjamin83c0bc92014-08-04 01:23:53 -040087 // DTLS state
88 sendHandshakeSeq uint16
89 recvHandshakeSeq uint16
David Benjaminb3774b92015-01-31 17:16:01 -050090 handMsg []byte // pending assembled handshake message
91 handMsgLen int // handshake message length, not including the header
92 pendingFragments [][]byte // pending outgoing handshake fragments.
Adam Langley95c29f32014-06-20 12:00:00 -070093
94 tmp [16]byte
95}
96
David Benjamin5e961c12014-11-07 01:48:35 -050097func (c *Conn) init() {
98 c.in.isDTLS = c.isDTLS
99 c.out.isDTLS = c.isDTLS
100 c.in.config = c.config
101 c.out.config = c.config
David Benjamin8e6db492015-07-25 18:29:23 -0400102
103 c.out.updateOutSeq()
David Benjamin5e961c12014-11-07 01:48:35 -0500104}
105
Adam Langley95c29f32014-06-20 12:00:00 -0700106// Access to net.Conn methods.
107// Cannot just embed net.Conn because that would
108// export the struct field too.
109
110// LocalAddr returns the local network address.
111func (c *Conn) LocalAddr() net.Addr {
112 return c.conn.LocalAddr()
113}
114
115// RemoteAddr returns the remote network address.
116func (c *Conn) RemoteAddr() net.Addr {
117 return c.conn.RemoteAddr()
118}
119
120// SetDeadline sets the read and write deadlines associated with the connection.
121// A zero value for t means Read and Write will not time out.
122// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
123func (c *Conn) SetDeadline(t time.Time) error {
124 return c.conn.SetDeadline(t)
125}
126
127// SetReadDeadline sets the read deadline on the underlying connection.
128// A zero value for t means Read will not time out.
129func (c *Conn) SetReadDeadline(t time.Time) error {
130 return c.conn.SetReadDeadline(t)
131}
132
133// SetWriteDeadline sets the write deadline on the underlying conneciton.
134// A zero value for t means Write will not time out.
135// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
136func (c *Conn) SetWriteDeadline(t time.Time) error {
137 return c.conn.SetWriteDeadline(t)
138}
139
140// A halfConn represents one direction of the record layer
141// connection, either sending or receiving.
142type halfConn struct {
143 sync.Mutex
144
David Benjamin83c0bc92014-08-04 01:23:53 -0400145 err error // first permanent error
146 version uint16 // protocol version
147 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -0700148 cipher interface{} // cipher algorithm
149 mac macFunction
150 seq [8]byte // 64-bit sequence number
David Benjamin8e6db492015-07-25 18:29:23 -0400151 outSeq [8]byte // Mapped sequence number
Adam Langley95c29f32014-06-20 12:00:00 -0700152 bfree *block // list of free blocks
153
154 nextCipher interface{} // next encryption state
155 nextMac macFunction // next MAC algorithm
David Benjamin83f90402015-01-27 01:09:43 -0500156 nextSeq [6]byte // next epoch's starting sequence number in DTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700157
158 // used to save allocating a new buffer for each MAC.
159 inDigestBuf, outDigestBuf []byte
Adam Langley80842bd2014-06-20 12:00:00 -0700160
161 config *Config
Adam Langley95c29f32014-06-20 12:00:00 -0700162}
163
164func (hc *halfConn) setErrorLocked(err error) error {
165 hc.err = err
166 return err
167}
168
169func (hc *halfConn) error() error {
Adam Langley2ae77d22014-10-28 17:29:33 -0700170 // This should be locked, but I've removed it for the renegotiation
171 // tests since we don't concurrently read and write the same tls.Conn
172 // in any case during testing.
Adam Langley95c29f32014-06-20 12:00:00 -0700173 err := hc.err
Adam Langley95c29f32014-06-20 12:00:00 -0700174 return err
175}
176
177// prepareCipherSpec sets the encryption and MAC states
178// that a subsequent changeCipherSpec will use.
179func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
180 hc.version = version
181 hc.nextCipher = cipher
182 hc.nextMac = mac
183}
184
185// changeCipherSpec changes the encryption and MAC states
186// to the ones previously passed to prepareCipherSpec.
Adam Langley80842bd2014-06-20 12:00:00 -0700187func (hc *halfConn) changeCipherSpec(config *Config) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700188 if hc.nextCipher == nil {
189 return alertInternalError
190 }
191 hc.cipher = hc.nextCipher
192 hc.mac = hc.nextMac
193 hc.nextCipher = nil
194 hc.nextMac = nil
Adam Langley80842bd2014-06-20 12:00:00 -0700195 hc.config = config
David Benjamin83c0bc92014-08-04 01:23:53 -0400196 hc.incEpoch()
David Benjaminf2b83632016-03-01 22:57:46 -0500197
198 if config.Bugs.NullAllCiphers {
199 hc.cipher = nil
200 hc.mac = nil
201 }
Adam Langley95c29f32014-06-20 12:00:00 -0700202 return nil
203}
204
Nick Harperb41d2e42016-07-01 17:50:32 -0400205// updateKeys sets the current cipher state.
206func (hc *halfConn) updateKeys(cipher interface{}, version uint16) {
207 hc.version = version
208 hc.cipher = cipher
209 hc.incEpoch()
210}
211
Adam Langley95c29f32014-06-20 12:00:00 -0700212// incSeq increments the sequence number.
David Benjamin5e961c12014-11-07 01:48:35 -0500213func (hc *halfConn) incSeq(isOutgoing bool) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400214 limit := 0
David Benjamin5e961c12014-11-07 01:48:35 -0500215 increment := uint64(1)
David Benjamin83c0bc92014-08-04 01:23:53 -0400216 if hc.isDTLS {
217 // Increment up to the epoch in DTLS.
218 limit = 2
219 }
220 for i := 7; i >= limit; i-- {
David Benjamin5e961c12014-11-07 01:48:35 -0500221 increment += uint64(hc.seq[i])
222 hc.seq[i] = byte(increment)
223 increment >>= 8
Adam Langley95c29f32014-06-20 12:00:00 -0700224 }
225
226 // Not allowed to let sequence number wrap.
227 // Instead, must renegotiate before it does.
228 // Not likely enough to bother.
David Benjamin5e961c12014-11-07 01:48:35 -0500229 if increment != 0 {
230 panic("TLS: sequence number wraparound")
231 }
David Benjamin8e6db492015-07-25 18:29:23 -0400232
233 hc.updateOutSeq()
Adam Langley95c29f32014-06-20 12:00:00 -0700234}
235
David Benjamin83f90402015-01-27 01:09:43 -0500236// incNextSeq increments the starting sequence number for the next epoch.
237func (hc *halfConn) incNextSeq() {
238 for i := len(hc.nextSeq) - 1; i >= 0; i-- {
239 hc.nextSeq[i]++
240 if hc.nextSeq[i] != 0 {
241 return
242 }
243 }
244 panic("TLS: sequence number wraparound")
245}
246
247// incEpoch resets the sequence number. In DTLS, it also increments the epoch
248// half of the sequence number.
David Benjamin83c0bc92014-08-04 01:23:53 -0400249func (hc *halfConn) incEpoch() {
David Benjamin83c0bc92014-08-04 01:23:53 -0400250 if hc.isDTLS {
251 for i := 1; i >= 0; i-- {
252 hc.seq[i]++
253 if hc.seq[i] != 0 {
254 break
255 }
256 if i == 0 {
257 panic("TLS: epoch number wraparound")
258 }
259 }
David Benjamin83f90402015-01-27 01:09:43 -0500260 copy(hc.seq[2:], hc.nextSeq[:])
261 for i := range hc.nextSeq {
262 hc.nextSeq[i] = 0
263 }
264 } else {
265 for i := range hc.seq {
266 hc.seq[i] = 0
267 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400268 }
David Benjamin8e6db492015-07-25 18:29:23 -0400269
270 hc.updateOutSeq()
271}
272
273func (hc *halfConn) updateOutSeq() {
274 if hc.config.Bugs.SequenceNumberMapping != nil {
275 seqU64 := binary.BigEndian.Uint64(hc.seq[:])
276 seqU64 = hc.config.Bugs.SequenceNumberMapping(seqU64)
277 binary.BigEndian.PutUint64(hc.outSeq[:], seqU64)
278
279 // The DTLS epoch cannot be changed.
280 copy(hc.outSeq[:2], hc.seq[:2])
281 return
282 }
283
284 copy(hc.outSeq[:], hc.seq[:])
David Benjamin83c0bc92014-08-04 01:23:53 -0400285}
286
287func (hc *halfConn) recordHeaderLen() int {
288 if hc.isDTLS {
289 return dtlsRecordHeaderLen
290 }
291 return tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700292}
293
294// removePadding returns an unpadded slice, in constant time, which is a prefix
295// of the input. It also returns a byte which is equal to 255 if the padding
296// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
297func removePadding(payload []byte) ([]byte, byte) {
298 if len(payload) < 1 {
299 return payload, 0
300 }
301
302 paddingLen := payload[len(payload)-1]
303 t := uint(len(payload)-1) - uint(paddingLen)
304 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
305 good := byte(int32(^t) >> 31)
306
307 toCheck := 255 // the maximum possible padding length
308 // The length of the padded data is public, so we can use an if here
309 if toCheck+1 > len(payload) {
310 toCheck = len(payload) - 1
311 }
312
313 for i := 0; i < toCheck; i++ {
314 t := uint(paddingLen) - uint(i)
315 // if i <= paddingLen then the MSB of t is zero
316 mask := byte(int32(^t) >> 31)
317 b := payload[len(payload)-1-i]
318 good &^= mask&paddingLen ^ mask&b
319 }
320
321 // We AND together the bits of good and replicate the result across
322 // all the bits.
323 good &= good << 4
324 good &= good << 2
325 good &= good << 1
326 good = uint8(int8(good) >> 7)
327
328 toRemove := good&paddingLen + 1
329 return payload[:len(payload)-int(toRemove)], good
330}
331
332// removePaddingSSL30 is a replacement for removePadding in the case that the
333// protocol version is SSLv3. In this version, the contents of the padding
334// are random and cannot be checked.
335func removePaddingSSL30(payload []byte) ([]byte, byte) {
336 if len(payload) < 1 {
337 return payload, 0
338 }
339
340 paddingLen := int(payload[len(payload)-1]) + 1
341 if paddingLen > len(payload) {
342 return payload, 0
343 }
344
345 return payload[:len(payload)-paddingLen], 255
346}
347
348func roundUp(a, b int) int {
349 return a + (b-a%b)%b
350}
351
352// cbcMode is an interface for block ciphers using cipher block chaining.
353type cbcMode interface {
354 cipher.BlockMode
355 SetIV([]byte)
356}
357
358// decrypt checks and strips the mac and decrypts the data in b. Returns a
359// success boolean, the number of bytes to skip from the start of the record in
Nick Harper1fd39d82016-06-14 18:14:35 -0700360// order to get the application payload, the encrypted record type (or 0
361// if there is none), and an optional alert value.
362func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, contentType recordType, alertValue alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400363 recordHeaderLen := hc.recordHeaderLen()
364
Adam Langley95c29f32014-06-20 12:00:00 -0700365 // pull out payload
366 payload := b.data[recordHeaderLen:]
367
368 macSize := 0
369 if hc.mac != nil {
370 macSize = hc.mac.Size()
371 }
372
373 paddingGood := byte(255)
374 explicitIVLen := 0
375
David Benjamin83c0bc92014-08-04 01:23:53 -0400376 seq := hc.seq[:]
377 if hc.isDTLS {
378 // DTLS sequence numbers are explicit.
379 seq = b.data[3:11]
380 }
381
Adam Langley95c29f32014-06-20 12:00:00 -0700382 // decrypt
383 if hc.cipher != nil {
384 switch c := hc.cipher.(type) {
385 case cipher.Stream:
386 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400387 case *tlsAead:
388 nonce := seq
389 if c.explicitNonce {
390 explicitIVLen = 8
391 if len(payload) < explicitIVLen {
Nick Harper1fd39d82016-06-14 18:14:35 -0700392 return false, 0, 0, alertBadRecordMAC
David Benjamine9a80ff2015-04-07 00:46:46 -0400393 }
394 nonce = payload[:8]
395 payload = payload[8:]
Adam Langley95c29f32014-06-20 12:00:00 -0700396 }
Adam Langley95c29f32014-06-20 12:00:00 -0700397
Nick Harper1fd39d82016-06-14 18:14:35 -0700398 var additionalData []byte
399 if hc.version < VersionTLS13 {
400 additionalData = make([]byte, 13)
401 copy(additionalData, seq)
402 copy(additionalData[8:], b.data[:3])
403 n := len(payload) - c.Overhead()
404 additionalData[11] = byte(n >> 8)
405 additionalData[12] = byte(n)
406 }
Adam Langley95c29f32014-06-20 12:00:00 -0700407 var err error
Nick Harper1fd39d82016-06-14 18:14:35 -0700408 payload, err = c.Open(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700409 if err != nil {
Nick Harper1fd39d82016-06-14 18:14:35 -0700410 return false, 0, 0, alertBadRecordMAC
411 }
412 if hc.version >= VersionTLS13 {
413 i := len(payload)
414 for i > 0 && payload[i-1] == 0 {
415 i--
416 }
417 payload = payload[:i]
418 if len(payload) == 0 {
419 return false, 0, 0, alertUnexpectedMessage
420 }
421 contentType = recordType(payload[len(payload)-1])
422 payload = payload[:len(payload)-1]
Adam Langley95c29f32014-06-20 12:00:00 -0700423 }
424 b.resize(recordHeaderLen + explicitIVLen + len(payload))
425 case cbcMode:
426 blockSize := c.BlockSize()
David Benjamin83c0bc92014-08-04 01:23:53 -0400427 if hc.version >= VersionTLS11 || hc.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700428 explicitIVLen = blockSize
429 }
430
431 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
Nick Harper1fd39d82016-06-14 18:14:35 -0700432 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700433 }
434
435 if explicitIVLen > 0 {
436 c.SetIV(payload[:explicitIVLen])
437 payload = payload[explicitIVLen:]
438 }
439 c.CryptBlocks(payload, payload)
440 if hc.version == VersionSSL30 {
441 payload, paddingGood = removePaddingSSL30(payload)
442 } else {
443 payload, paddingGood = removePadding(payload)
444 }
445 b.resize(recordHeaderLen + explicitIVLen + len(payload))
446
447 // note that we still have a timing side-channel in the
448 // MAC check, below. An attacker can align the record
449 // so that a correct padding will cause one less hash
450 // block to be calculated. Then they can iteratively
451 // decrypt a record by breaking each byte. See
452 // "Password Interception in a SSL/TLS Channel", Brice
453 // Canvel et al.
454 //
455 // However, our behavior matches OpenSSL, so we leak
456 // only as much as they do.
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700457 case nullCipher:
458 break
Adam Langley95c29f32014-06-20 12:00:00 -0700459 default:
460 panic("unknown cipher type")
461 }
462 }
463
464 // check, strip mac
465 if hc.mac != nil {
466 if len(payload) < macSize {
Nick Harper1fd39d82016-06-14 18:14:35 -0700467 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700468 }
469
470 // strip mac off payload, b.data
471 n := len(payload) - macSize
David Benjamin83c0bc92014-08-04 01:23:53 -0400472 b.data[recordHeaderLen-2] = byte(n >> 8)
473 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700474 b.resize(recordHeaderLen + explicitIVLen + n)
475 remoteMAC := payload[n:]
David Benjamin83c0bc92014-08-04 01:23:53 -0400476 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
Adam Langley95c29f32014-06-20 12:00:00 -0700477
478 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
Nick Harper1fd39d82016-06-14 18:14:35 -0700479 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700480 }
481 hc.inDigestBuf = localMAC
482 }
David Benjamin5e961c12014-11-07 01:48:35 -0500483 hc.incSeq(false)
Adam Langley95c29f32014-06-20 12:00:00 -0700484
Nick Harper1fd39d82016-06-14 18:14:35 -0700485 return true, recordHeaderLen + explicitIVLen, contentType, 0
Adam Langley95c29f32014-06-20 12:00:00 -0700486}
487
488// padToBlockSize calculates the needed padding block, if any, for a payload.
489// On exit, prefix aliases payload and extends to the end of the last full
490// block of payload. finalBlock is a fresh slice which contains the contents of
491// any suffix of payload as well as the needed padding to make finalBlock a
492// full block.
Adam Langley80842bd2014-06-20 12:00:00 -0700493func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
Adam Langley95c29f32014-06-20 12:00:00 -0700494 overrun := len(payload) % blockSize
Adam Langley95c29f32014-06-20 12:00:00 -0700495 prefix = payload[:len(payload)-overrun]
Adam Langley80842bd2014-06-20 12:00:00 -0700496
497 paddingLen := blockSize - overrun
498 finalSize := blockSize
499 if config.Bugs.MaxPadding {
500 for paddingLen+blockSize <= 256 {
501 paddingLen += blockSize
502 }
503 finalSize = 256
504 }
505 finalBlock = make([]byte, finalSize)
506 for i := range finalBlock {
Adam Langley95c29f32014-06-20 12:00:00 -0700507 finalBlock[i] = byte(paddingLen - 1)
508 }
Adam Langley80842bd2014-06-20 12:00:00 -0700509 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
510 finalBlock[overrun] ^= 0xff
511 }
512 copy(finalBlock, payload[len(payload)-overrun:])
Adam Langley95c29f32014-06-20 12:00:00 -0700513 return
514}
515
516// encrypt encrypts and macs the data in b.
Nick Harper1fd39d82016-06-14 18:14:35 -0700517func (hc *halfConn) encrypt(b *block, explicitIVLen int, typ recordType) (bool, alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400518 recordHeaderLen := hc.recordHeaderLen()
519
Adam Langley95c29f32014-06-20 12:00:00 -0700520 // mac
521 if hc.mac != nil {
David Benjamin8e6db492015-07-25 18:29:23 -0400522 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 -0700523
524 n := len(b.data)
525 b.resize(n + len(mac))
526 copy(b.data[n:], mac)
527 hc.outDigestBuf = mac
528 }
529
530 payload := b.data[recordHeaderLen:]
531
532 // encrypt
533 if hc.cipher != nil {
534 switch c := hc.cipher.(type) {
535 case cipher.Stream:
536 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400537 case *tlsAead:
Adam Langley95c29f32014-06-20 12:00:00 -0700538 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
David Benjaminc9ae27c2016-06-24 22:56:37 -0400539 paddingLen := 0
Nick Harper1fd39d82016-06-14 18:14:35 -0700540 if hc.version >= VersionTLS13 {
David Benjaminc9ae27c2016-06-24 22:56:37 -0400541 payloadLen++
542 paddingLen = hc.config.Bugs.RecordPadding
543 }
544 if hc.config.Bugs.OmitRecordContents {
545 payloadLen = 0
546 }
547 b.resize(recordHeaderLen + explicitIVLen + payloadLen + paddingLen + c.Overhead())
548 if hc.version >= VersionTLS13 {
549 if !hc.config.Bugs.OmitRecordContents {
550 b.data[payloadLen+recordHeaderLen-1] = byte(typ)
551 }
552 for i := 0; i < hc.config.Bugs.RecordPadding; i++ {
553 b.data[payloadLen+recordHeaderLen+i] = 0
554 }
555 payloadLen += paddingLen
Nick Harper1fd39d82016-06-14 18:14:35 -0700556 }
David Benjamin8e6db492015-07-25 18:29:23 -0400557 nonce := hc.outSeq[:]
David Benjamine9a80ff2015-04-07 00:46:46 -0400558 if c.explicitNonce {
559 nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
560 }
Adam Langley95c29f32014-06-20 12:00:00 -0700561 payload := b.data[recordHeaderLen+explicitIVLen:]
562 payload = payload[:payloadLen]
563
Nick Harper1fd39d82016-06-14 18:14:35 -0700564 var additionalData []byte
565 if hc.version < VersionTLS13 {
566 additionalData = make([]byte, 13)
567 copy(additionalData, hc.outSeq[:])
568 copy(additionalData[8:], b.data[:3])
569 additionalData[11] = byte(payloadLen >> 8)
570 additionalData[12] = byte(payloadLen)
571 }
Adam Langley95c29f32014-06-20 12:00:00 -0700572
Nick Harper1fd39d82016-06-14 18:14:35 -0700573 c.Seal(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700574 case cbcMode:
575 blockSize := c.BlockSize()
576 if explicitIVLen > 0 {
577 c.SetIV(payload[:explicitIVLen])
578 payload = payload[explicitIVLen:]
579 }
Adam Langley80842bd2014-06-20 12:00:00 -0700580 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700581 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
582 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
583 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700584 case nullCipher:
585 break
Adam Langley95c29f32014-06-20 12:00:00 -0700586 default:
587 panic("unknown cipher type")
588 }
589 }
590
591 // update length to include MAC and any block padding needed.
592 n := len(b.data) - recordHeaderLen
David Benjamin83c0bc92014-08-04 01:23:53 -0400593 b.data[recordHeaderLen-2] = byte(n >> 8)
594 b.data[recordHeaderLen-1] = byte(n)
David Benjamin5e961c12014-11-07 01:48:35 -0500595 hc.incSeq(true)
Adam Langley95c29f32014-06-20 12:00:00 -0700596
597 return true, 0
598}
599
600// A block is a simple data buffer.
601type block struct {
602 data []byte
603 off int // index for Read
604 link *block
605}
606
607// resize resizes block to be n bytes, growing if necessary.
608func (b *block) resize(n int) {
609 if n > cap(b.data) {
610 b.reserve(n)
611 }
612 b.data = b.data[0:n]
613}
614
615// reserve makes sure that block contains a capacity of at least n bytes.
616func (b *block) reserve(n int) {
617 if cap(b.data) >= n {
618 return
619 }
620 m := cap(b.data)
621 if m == 0 {
622 m = 1024
623 }
624 for m < n {
625 m *= 2
626 }
627 data := make([]byte, len(b.data), m)
628 copy(data, b.data)
629 b.data = data
630}
631
632// readFromUntil reads from r into b until b contains at least n bytes
633// or else returns an error.
634func (b *block) readFromUntil(r io.Reader, n int) error {
635 // quick case
636 if len(b.data) >= n {
637 return nil
638 }
639
640 // read until have enough.
641 b.reserve(n)
642 for {
643 m, err := r.Read(b.data[len(b.data):cap(b.data)])
644 b.data = b.data[0 : len(b.data)+m]
645 if len(b.data) >= n {
646 // TODO(bradfitz,agl): slightly suspicious
647 // that we're throwing away r.Read's err here.
648 break
649 }
650 if err != nil {
651 return err
652 }
653 }
654 return nil
655}
656
657func (b *block) Read(p []byte) (n int, err error) {
658 n = copy(p, b.data[b.off:])
659 b.off += n
660 return
661}
662
663// newBlock allocates a new block, from hc's free list if possible.
664func (hc *halfConn) newBlock() *block {
665 b := hc.bfree
666 if b == nil {
667 return new(block)
668 }
669 hc.bfree = b.link
670 b.link = nil
671 b.resize(0)
672 return b
673}
674
675// freeBlock returns a block to hc's free list.
676// The protocol is such that each side only has a block or two on
677// its free list at a time, so there's no need to worry about
678// trimming the list, etc.
679func (hc *halfConn) freeBlock(b *block) {
680 b.link = hc.bfree
681 hc.bfree = b
682}
683
684// splitBlock splits a block after the first n bytes,
685// returning a block with those n bytes and a
686// block with the remainder. the latter may be nil.
687func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
688 if len(b.data) <= n {
689 return b, nil
690 }
691 bb := hc.newBlock()
692 bb.resize(len(b.data) - n)
693 copy(bb.data, b.data[n:])
694 b.data = b.data[0:n]
695 return b, bb
696}
697
David Benjamin83c0bc92014-08-04 01:23:53 -0400698func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
699 if c.isDTLS {
700 return c.dtlsDoReadRecord(want)
701 }
702
703 recordHeaderLen := tlsRecordHeaderLen
704
705 if c.rawInput == nil {
706 c.rawInput = c.in.newBlock()
707 }
708 b := c.rawInput
709
710 // Read header, payload.
711 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
712 // RFC suggests that EOF without an alertCloseNotify is
713 // an error, but popular web sites seem to do this,
David Benjamin30789da2015-08-29 22:56:45 -0400714 // so we can't make it an error, outside of tests.
715 if err == io.EOF && c.config.Bugs.ExpectCloseNotify {
716 err = io.ErrUnexpectedEOF
717 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400718 if e, ok := err.(net.Error); !ok || !e.Temporary() {
719 c.in.setErrorLocked(err)
720 }
721 return 0, nil, err
722 }
723 typ := recordType(b.data[0])
724
725 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
726 // start with a uint16 length where the MSB is set and the first record
727 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
728 // an SSLv2 client.
729 if want == recordTypeHandshake && typ == 0x80 {
730 c.sendAlert(alertProtocolVersion)
731 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
732 }
733
734 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
735 n := int(b.data[3])<<8 | int(b.data[4])
David Benjaminbde00392016-06-21 12:19:28 -0400736 // Alerts sent near version negotiation do not have a well-defined
737 // record-layer version prior to TLS 1.3. (In TLS 1.3, the record-layer
738 // version is irrelevant.)
739 if typ != recordTypeAlert {
740 if c.haveVers {
741 if vers != c.vers && c.vers < VersionTLS13 {
742 c.sendAlert(alertProtocolVersion)
743 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers))
744 }
745 } else {
746 if expect := c.config.Bugs.ExpectInitialRecordVersion; expect != 0 && vers != expect {
747 c.sendAlert(alertProtocolVersion)
748 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
749 }
David Benjamin1e29a6b2014-12-10 02:27:24 -0500750 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400751 }
752 if n > maxCiphertext {
753 c.sendAlert(alertRecordOverflow)
754 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
755 }
756 if !c.haveVers {
757 // First message, be extra suspicious:
758 // this might not be a TLS client.
759 // Bail out before reading a full 'body', if possible.
760 // The current max version is 3.1.
761 // If the version is >= 16.0, it's probably not real.
762 // Similarly, a clientHello message encodes in
763 // well under a kilobyte. If the length is >= 12 kB,
764 // it's probably not real.
765 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
766 c.sendAlert(alertUnexpectedMessage)
767 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
768 }
769 }
770 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
771 if err == io.EOF {
772 err = io.ErrUnexpectedEOF
773 }
774 if e, ok := err.(net.Error); !ok || !e.Temporary() {
775 c.in.setErrorLocked(err)
776 }
777 return 0, nil, err
778 }
779
780 // Process message.
781 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
David Benjaminff26f092016-07-01 16:13:42 -0400782 ok, off, encTyp, alertValue := c.in.decrypt(b)
783 if !ok {
784 return 0, nil, c.in.setErrorLocked(c.sendAlert(alertValue))
785 }
786 b.off = off
787
Nick Harper1fd39d82016-06-14 18:14:35 -0700788 if c.vers >= VersionTLS13 && c.in.cipher != nil {
David Benjaminc9ae27c2016-06-24 22:56:37 -0400789 if typ != recordTypeApplicationData {
790 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: outer record type is not application data"))
791 }
Nick Harper1fd39d82016-06-14 18:14:35 -0700792 typ = encTyp
793 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400794 return typ, b, nil
795}
796
Adam Langley95c29f32014-06-20 12:00:00 -0700797// readRecord reads the next TLS record from the connection
798// and updates the record layer state.
799// c.in.Mutex <= L; c.input == nil.
800func (c *Conn) readRecord(want recordType) error {
801 // Caller must be in sync with connection:
802 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700803 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700804 switch want {
805 default:
806 c.sendAlert(alertInternalError)
807 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
808 case recordTypeHandshake, recordTypeChangeCipherSpec:
809 if c.handshakeComplete {
810 c.sendAlert(alertInternalError)
811 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
812 }
813 case recordTypeApplicationData:
David Benjamine58c4f52014-08-24 03:47:07 -0400814 if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart {
Adam Langley95c29f32014-06-20 12:00:00 -0700815 c.sendAlert(alertInternalError)
816 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
817 }
David Benjamin30789da2015-08-29 22:56:45 -0400818 case recordTypeAlert:
819 // Looking for a close_notify. Note: unlike a real
820 // implementation, this is not tolerant of additional records.
821 // See the documentation for ExpectCloseNotify.
Adam Langley95c29f32014-06-20 12:00:00 -0700822 }
823
824Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400825 typ, b, err := c.doReadRecord(want)
826 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700827 return err
828 }
Adam Langley95c29f32014-06-20 12:00:00 -0700829 data := b.data[b.off:]
830 if len(data) > maxPlaintext {
831 err := c.sendAlert(alertRecordOverflow)
832 c.in.freeBlock(b)
833 return c.in.setErrorLocked(err)
834 }
835
836 switch typ {
837 default:
838 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
839
840 case recordTypeAlert:
841 if len(data) != 2 {
842 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
843 break
844 }
845 if alert(data[1]) == alertCloseNotify {
846 c.in.setErrorLocked(io.EOF)
847 break
848 }
849 switch data[0] {
850 case alertLevelWarning:
851 // drop on the floor
852 c.in.freeBlock(b)
853 goto Again
854 case alertLevelError:
855 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
856 default:
857 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
858 }
859
860 case recordTypeChangeCipherSpec:
861 if typ != want || len(data) != 1 || data[0] != 1 {
862 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
863 break
864 }
Adam Langley80842bd2014-06-20 12:00:00 -0700865 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700866 if err != nil {
867 c.in.setErrorLocked(c.sendAlert(err.(alert)))
868 }
869
870 case recordTypeApplicationData:
871 if typ != want {
872 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
873 break
874 }
875 c.input = b
876 b = nil
877
878 case recordTypeHandshake:
879 // TODO(rsc): Should at least pick off connection close.
880 if typ != want {
Adam Langley2ae77d22014-10-28 17:29:33 -0700881 // A client might need to process a HelloRequest from
882 // the server, thus receiving a handshake message when
David Benjamind9b091b2015-01-27 01:10:54 -0500883 // application data is expected is ok.
David Benjamin30789da2015-08-29 22:56:45 -0400884 if !c.isClient || want != recordTypeApplicationData {
Adam Langley2ae77d22014-10-28 17:29:33 -0700885 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
886 }
Adam Langley95c29f32014-06-20 12:00:00 -0700887 }
888 c.hand.Write(data)
889 }
890
891 if b != nil {
892 c.in.freeBlock(b)
893 }
894 return c.in.err
895}
896
897// sendAlert sends a TLS alert message.
898// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400899func (c *Conn) sendAlertLocked(level byte, err alert) error {
900 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700901 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400902 if c.config.Bugs.FragmentAlert {
903 c.writeRecord(recordTypeAlert, c.tmp[0:1])
904 c.writeRecord(recordTypeAlert, c.tmp[1:2])
David Benjamin0d3a8c62016-03-11 22:25:18 -0500905 } else if c.config.Bugs.DoubleAlert {
906 copy(c.tmp[2:4], c.tmp[0:2])
907 c.writeRecord(recordTypeAlert, c.tmp[0:4])
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400908 } else {
909 c.writeRecord(recordTypeAlert, c.tmp[0:2])
910 }
David Benjamin24f346d2015-06-06 03:28:08 -0400911 // Error alerts are fatal to the connection.
912 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700913 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
914 }
915 return nil
916}
917
918// sendAlert sends a TLS alert message.
919// L < c.out.Mutex.
920func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400921 level := byte(alertLevelError)
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500922 if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertficate {
David Benjamin24f346d2015-06-06 03:28:08 -0400923 level = alertLevelWarning
924 }
925 return c.SendAlert(level, err)
926}
927
928func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700929 c.out.Lock()
930 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -0400931 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -0700932}
933
David Benjamind86c7672014-08-02 04:07:12 -0400934// writeV2Record writes a record for a V2ClientHello.
935func (c *Conn) writeV2Record(data []byte) (n int, err error) {
936 record := make([]byte, 2+len(data))
937 record[0] = uint8(len(data)>>8) | 0x80
938 record[1] = uint8(len(data))
939 copy(record[2:], data)
940 return c.conn.Write(record)
941}
942
Adam Langley95c29f32014-06-20 12:00:00 -0700943// writeRecord writes a TLS record with the given type and payload
944// to the connection and updates the record layer state.
945// c.out.Mutex <= L.
946func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin0b8d5da2016-07-15 00:39:56 -0400947 if wrongType := c.config.Bugs.SendWrongMessageType; wrongType != 0 {
948 if typ == recordTypeHandshake && data[0] == wrongType {
949 newData := make([]byte, len(data))
950 copy(newData, data)
951 newData[0] += 42
952 data = newData
953 }
954 }
955
David Benjamin83c0bc92014-08-04 01:23:53 -0400956 if c.isDTLS {
957 return c.dtlsWriteRecord(typ, data)
958 }
959
David Benjamin71dd6662016-07-08 14:10:48 -0700960 if typ == recordTypeHandshake {
961 if c.config.Bugs.SendHelloRequestBeforeEveryHandshakeMessage {
962 newData := make([]byte, 0, 4+len(data))
963 newData = append(newData, typeHelloRequest, 0, 0, 0)
964 newData = append(newData, data...)
965 data = newData
966 }
967
968 if c.config.Bugs.PackHandshakeFlight {
969 c.pendingFlight.Write(data)
970 return len(data), nil
971 }
David Benjamin582ba042016-07-07 12:33:25 -0700972 }
973
974 return c.doWriteRecord(typ, data)
975}
976
977func (c *Conn) doWriteRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400978 recordHeaderLen := tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700979 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -0400980 first := true
981 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -0400982 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -0700983 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -0400984 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -0700985 m = maxPlaintext
986 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400987 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
988 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -0400989 // By default, do not fragment the client_version or
990 // server_version, which are located in the first 6
991 // bytes.
992 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
993 m = 6
994 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400995 }
Adam Langley95c29f32014-06-20 12:00:00 -0700996 explicitIVLen := 0
997 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -0400998 first = false
Adam Langley95c29f32014-06-20 12:00:00 -0700999
1000 var cbc cbcMode
1001 if c.out.version >= VersionTLS11 {
1002 var ok bool
1003 if cbc, ok = c.out.cipher.(cbcMode); ok {
1004 explicitIVLen = cbc.BlockSize()
1005 }
1006 }
1007 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -04001008 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -07001009 explicitIVLen = 8
1010 // The AES-GCM construction in TLS has an
1011 // explicit nonce so that the nonce can be
1012 // random. However, the nonce is only 8 bytes
1013 // which is too small for a secure, random
1014 // nonce. Therefore we use the sequence number
1015 // as the nonce.
1016 explicitIVIsSeq = true
1017 }
1018 }
1019 b.resize(recordHeaderLen + explicitIVLen + m)
1020 b.data[0] = byte(typ)
Nick Harper1fd39d82016-06-14 18:14:35 -07001021 if c.vers >= VersionTLS13 && c.out.cipher != nil {
Nick Harper1fd39d82016-06-14 18:14:35 -07001022 b.data[0] = byte(recordTypeApplicationData)
David Benjaminc9ae27c2016-06-24 22:56:37 -04001023 if outerType := c.config.Bugs.OuterRecordType; outerType != 0 {
1024 b.data[0] = byte(outerType)
1025 }
Nick Harper1fd39d82016-06-14 18:14:35 -07001026 }
Adam Langley95c29f32014-06-20 12:00:00 -07001027 vers := c.vers
Nick Harper1fd39d82016-06-14 18:14:35 -07001028 if vers == 0 || vers >= VersionTLS13 {
Adam Langley95c29f32014-06-20 12:00:00 -07001029 // Some TLS servers fail if the record version is
1030 // greater than TLS 1.0 for the initial ClientHello.
Nick Harper1fd39d82016-06-14 18:14:35 -07001031 //
1032 // TLS 1.3 fixes the version number in the record
1033 // layer to {3, 1}.
Adam Langley95c29f32014-06-20 12:00:00 -07001034 vers = VersionTLS10
1035 }
1036 b.data[1] = byte(vers >> 8)
1037 b.data[2] = byte(vers)
1038 b.data[3] = byte(m >> 8)
1039 b.data[4] = byte(m)
1040 if explicitIVLen > 0 {
1041 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
1042 if explicitIVIsSeq {
1043 copy(explicitIV, c.out.seq[:])
1044 } else {
1045 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
1046 break
1047 }
1048 }
1049 }
1050 copy(b.data[recordHeaderLen+explicitIVLen:], data)
Nick Harper1fd39d82016-06-14 18:14:35 -07001051 c.out.encrypt(b, explicitIVLen, typ)
Adam Langley95c29f32014-06-20 12:00:00 -07001052 _, err = c.conn.Write(b.data)
1053 if err != nil {
1054 break
1055 }
1056 n += m
1057 data = data[m:]
1058 }
1059 c.out.freeBlock(b)
1060
1061 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -07001062 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -07001063 if err != nil {
1064 // Cannot call sendAlert directly,
1065 // because we already hold c.out.Mutex.
1066 c.tmp[0] = alertLevelError
1067 c.tmp[1] = byte(err.(alert))
1068 c.writeRecord(recordTypeAlert, c.tmp[0:2])
1069 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
1070 }
1071 }
1072 return
1073}
1074
David Benjamin582ba042016-07-07 12:33:25 -07001075func (c *Conn) flushHandshake() error {
1076 if c.isDTLS {
1077 return c.dtlsFlushHandshake()
1078 }
1079
1080 for c.pendingFlight.Len() > 0 {
1081 var buf [maxPlaintext]byte
1082 n, _ := c.pendingFlight.Read(buf[:])
1083 if _, err := c.doWriteRecord(recordTypeHandshake, buf[:n]); err != nil {
1084 return err
1085 }
1086 }
1087
1088 c.pendingFlight.Reset()
1089 return nil
1090}
1091
David Benjamin83c0bc92014-08-04 01:23:53 -04001092func (c *Conn) doReadHandshake() ([]byte, error) {
1093 if c.isDTLS {
1094 return c.dtlsDoReadHandshake()
1095 }
1096
Adam Langley95c29f32014-06-20 12:00:00 -07001097 for c.hand.Len() < 4 {
1098 if err := c.in.err; err != nil {
1099 return nil, err
1100 }
1101 if err := c.readRecord(recordTypeHandshake); err != nil {
1102 return nil, err
1103 }
1104 }
1105
1106 data := c.hand.Bytes()
1107 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1108 if n > maxHandshake {
1109 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
1110 }
1111 for c.hand.Len() < 4+n {
1112 if err := c.in.err; err != nil {
1113 return nil, err
1114 }
1115 if err := c.readRecord(recordTypeHandshake); err != nil {
1116 return nil, err
1117 }
1118 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001119 return c.hand.Next(4 + n), nil
1120}
1121
1122// readHandshake reads the next handshake message from
1123// the record layer.
1124// c.in.Mutex < L; c.out.Mutex < L.
1125func (c *Conn) readHandshake() (interface{}, error) {
1126 data, err := c.doReadHandshake()
1127 if err != nil {
1128 return nil, err
1129 }
1130
Adam Langley95c29f32014-06-20 12:00:00 -07001131 var m handshakeMessage
1132 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001133 case typeHelloRequest:
1134 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001135 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001136 m = &clientHelloMsg{
1137 isDTLS: c.isDTLS,
1138 }
Adam Langley95c29f32014-06-20 12:00:00 -07001139 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001140 m = &serverHelloMsg{
1141 isDTLS: c.isDTLS,
1142 }
Nick Harperdcfbc672016-07-16 17:47:31 +02001143 case typeHelloRetryRequest:
1144 m = new(helloRetryRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001145 case typeNewSessionTicket:
1146 m = new(newSessionTicketMsg)
Nick Harperb41d2e42016-07-01 17:50:32 -04001147 case typeEncryptedExtensions:
1148 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001149 case typeCertificate:
Nick Harperb41d2e42016-07-01 17:50:32 -04001150 m = &certificateMsg{
David Benjamin8d315d72016-07-18 01:03:18 +02001151 hasRequestContext: c.vers >= VersionTLS13,
Nick Harperb41d2e42016-07-01 17:50:32 -04001152 }
Adam Langley95c29f32014-06-20 12:00:00 -07001153 case typeCertificateRequest:
1154 m = &certificateRequestMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001155 hasSignatureAlgorithm: c.vers >= VersionTLS12,
David Benjamin8d315d72016-07-18 01:03:18 +02001156 hasRequestContext: c.vers >= VersionTLS13,
Adam Langley95c29f32014-06-20 12:00:00 -07001157 }
1158 case typeCertificateStatus:
1159 m = new(certificateStatusMsg)
1160 case typeServerKeyExchange:
1161 m = new(serverKeyExchangeMsg)
1162 case typeServerHelloDone:
1163 m = new(serverHelloDoneMsg)
1164 case typeClientKeyExchange:
1165 m = new(clientKeyExchangeMsg)
1166 case typeCertificateVerify:
1167 m = &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001168 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001169 }
1170 case typeNextProtocol:
1171 m = new(nextProtoMsg)
1172 case typeFinished:
1173 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001174 case typeHelloVerifyRequest:
1175 m = new(helloVerifyRequestMsg)
David Benjamin24599a82016-06-30 18:56:53 -04001176 case typeChannelID:
1177 m = new(channelIDMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001178 default:
1179 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1180 }
1181
1182 // The handshake message unmarshallers
1183 // expect to be able to keep references to data,
1184 // so pass in a fresh copy that won't be overwritten.
1185 data = append([]byte(nil), data...)
1186
1187 if !m.unmarshal(data) {
1188 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1189 }
1190 return m, nil
1191}
1192
David Benjamin83f90402015-01-27 01:09:43 -05001193// skipPacket processes all the DTLS records in packet. It updates
1194// sequence number expectations but otherwise ignores them.
1195func (c *Conn) skipPacket(packet []byte) error {
1196 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001197 if len(packet) < 13 {
1198 return errors.New("tls: bad packet")
1199 }
David Benjamin83f90402015-01-27 01:09:43 -05001200 // Dropped packets are completely ignored save to update
1201 // expected sequence numbers for this and the next epoch. (We
1202 // don't assert on the contents of the packets both for
1203 // simplicity and because a previous test with one shorter
1204 // timeout schedule would have done so.)
1205 epoch := packet[3:5]
1206 seq := packet[5:11]
1207 length := uint16(packet[11])<<8 | uint16(packet[12])
1208 if bytes.Equal(c.in.seq[:2], epoch) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001209 if bytes.Compare(seq, c.in.seq[2:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001210 return errors.New("tls: sequence mismatch")
1211 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001212 copy(c.in.seq[2:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001213 c.in.incSeq(false)
1214 } else {
David Benjamin13e81fc2015-11-02 17:16:13 -05001215 if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001216 return errors.New("tls: sequence mismatch")
1217 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001218 copy(c.in.nextSeq[:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001219 c.in.incNextSeq()
1220 }
David Benjamin6ca93552015-08-28 16:16:25 -04001221 if len(packet) < 13+int(length) {
1222 return errors.New("tls: bad packet")
1223 }
David Benjamin83f90402015-01-27 01:09:43 -05001224 packet = packet[13+length:]
1225 }
1226 return nil
1227}
1228
1229// simulatePacketLoss simulates the loss of a handshake leg from the
1230// peer based on the schedule in c.config.Bugs. If resendFunc is
1231// non-nil, it is called after each simulated timeout to retransmit
1232// handshake messages from the local end. This is used in cases where
1233// the peer retransmits on a stale Finished rather than a timeout.
1234func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1235 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1236 return nil
1237 }
1238 if !c.isDTLS {
1239 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1240 }
1241 if c.config.Bugs.PacketAdaptor == nil {
1242 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1243 }
1244 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1245 // Simulate a timeout.
1246 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1247 if err != nil {
1248 return err
1249 }
1250 for _, packet := range packets {
1251 if err := c.skipPacket(packet); err != nil {
1252 return err
1253 }
1254 }
1255 if resendFunc != nil {
1256 resendFunc()
1257 }
1258 }
1259 return nil
1260}
1261
Adam Langley95c29f32014-06-20 12:00:00 -07001262// Write writes data to the connection.
1263func (c *Conn) Write(b []byte) (int, error) {
1264 if err := c.Handshake(); err != nil {
1265 return 0, err
1266 }
1267
1268 c.out.Lock()
1269 defer c.out.Unlock()
1270
1271 if err := c.out.err; err != nil {
1272 return 0, err
1273 }
1274
1275 if !c.handshakeComplete {
1276 return 0, alertInternalError
1277 }
1278
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001279 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001280 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001281 }
1282
Adam Langley27a0d082015-11-03 13:34:10 -08001283 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1284 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
David Benjamin582ba042016-07-07 12:33:25 -07001285 c.flushHandshake()
Adam Langley27a0d082015-11-03 13:34:10 -08001286 }
1287
Adam Langley95c29f32014-06-20 12:00:00 -07001288 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1289 // attack when using block mode ciphers due to predictable IVs.
1290 // This can be prevented by splitting each Application Data
1291 // record into two records, effectively randomizing the IV.
1292 //
1293 // http://www.openssl.org/~bodo/tls-cbc.txt
1294 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1295 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1296
1297 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001298 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001299 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1300 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1301 if err != nil {
1302 return n, c.out.setErrorLocked(err)
1303 }
1304 m, b = 1, b[1:]
1305 }
1306 }
1307
1308 n, err := c.writeRecord(recordTypeApplicationData, b)
1309 return n + m, c.out.setErrorLocked(err)
1310}
1311
Adam Langley2ae77d22014-10-28 17:29:33 -07001312func (c *Conn) handleRenegotiation() error {
1313 c.handshakeComplete = false
1314 if !c.isClient {
1315 panic("renegotiation should only happen for a client")
1316 }
1317
1318 msg, err := c.readHandshake()
1319 if err != nil {
1320 return err
1321 }
1322 _, ok := msg.(*helloRequestMsg)
1323 if !ok {
1324 c.sendAlert(alertUnexpectedMessage)
1325 return alertUnexpectedMessage
1326 }
1327
1328 return c.Handshake()
1329}
1330
Adam Langleycf2d4f42014-10-28 19:06:14 -07001331func (c *Conn) Renegotiate() error {
1332 if !c.isClient {
David Benjaminef5dfd22015-12-06 13:17:07 -05001333 helloReq := new(helloRequestMsg).marshal()
1334 if c.config.Bugs.BadHelloRequest != nil {
1335 helloReq = c.config.Bugs.BadHelloRequest
1336 }
1337 c.writeRecord(recordTypeHandshake, helloReq)
David Benjamin582ba042016-07-07 12:33:25 -07001338 c.flushHandshake()
Adam Langleycf2d4f42014-10-28 19:06:14 -07001339 }
1340
1341 c.handshakeComplete = false
1342 return c.Handshake()
1343}
1344
Adam Langley95c29f32014-06-20 12:00:00 -07001345// Read can be made to time out and return a net.Error with Timeout() == true
1346// after a fixed time limit; see SetDeadline and SetReadDeadline.
1347func (c *Conn) Read(b []byte) (n int, err error) {
1348 if err = c.Handshake(); err != nil {
1349 return
1350 }
1351
1352 c.in.Lock()
1353 defer c.in.Unlock()
1354
1355 // Some OpenSSL servers send empty records in order to randomize the
1356 // CBC IV. So this loop ignores a limited number of empty records.
1357 const maxConsecutiveEmptyRecords = 100
1358 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1359 for c.input == nil && c.in.err == nil {
1360 if err := c.readRecord(recordTypeApplicationData); err != nil {
1361 // Soft error, like EAGAIN
1362 return 0, err
1363 }
David Benjamind9b091b2015-01-27 01:10:54 -05001364 if c.hand.Len() > 0 {
Adam Langley2ae77d22014-10-28 17:29:33 -07001365 // We received handshake bytes, indicating the
David Benjamind9b091b2015-01-27 01:10:54 -05001366 // start of a renegotiation.
Adam Langley2ae77d22014-10-28 17:29:33 -07001367 if err := c.handleRenegotiation(); err != nil {
1368 return 0, err
1369 }
1370 continue
1371 }
Adam Langley95c29f32014-06-20 12:00:00 -07001372 }
1373 if err := c.in.err; err != nil {
1374 return 0, err
1375 }
1376
1377 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001378 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001379 c.in.freeBlock(c.input)
1380 c.input = nil
1381 }
1382
1383 // If a close-notify alert is waiting, read it so that
1384 // we can return (n, EOF) instead of (n, nil), to signal
1385 // to the HTTP response reading goroutine that the
1386 // connection is now closed. This eliminates a race
1387 // where the HTTP response reading goroutine would
1388 // otherwise not observe the EOF until its next read,
1389 // by which time a client goroutine might have already
1390 // tried to reuse the HTTP connection for a new
1391 // request.
1392 // See https://codereview.appspot.com/76400046
1393 // and http://golang.org/issue/3514
1394 if ri := c.rawInput; ri != nil &&
1395 n != 0 && err == nil &&
1396 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1397 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1398 err = recErr // will be io.EOF on closeNotify
1399 }
1400 }
1401
1402 if n != 0 || err != nil {
1403 return n, err
1404 }
1405 }
1406
1407 return 0, io.ErrNoProgress
1408}
1409
1410// Close closes the connection.
1411func (c *Conn) Close() error {
1412 var alertErr error
1413
1414 c.handshakeMutex.Lock()
1415 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001416 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
David Benjaminfa214e42016-05-10 17:03:10 -04001417 alert := alertCloseNotify
1418 if c.config.Bugs.SendAlertOnShutdown != 0 {
1419 alert = c.config.Bugs.SendAlertOnShutdown
1420 }
1421 alertErr = c.sendAlert(alert)
David Benjamin4d559612016-05-18 14:31:51 -04001422 // Clear local alerts when sending alerts so we continue to wait
1423 // for the peer rather than closing the socket early.
1424 if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1425 alertErr = nil
1426 }
Adam Langley95c29f32014-06-20 12:00:00 -07001427 }
1428
David Benjamin30789da2015-08-29 22:56:45 -04001429 // Consume a close_notify from the peer if one hasn't been received
1430 // already. This avoids the peer from failing |SSL_shutdown| due to a
1431 // write failing.
1432 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1433 for c.in.error() == nil {
1434 c.readRecord(recordTypeAlert)
1435 }
1436 if c.in.error() != io.EOF {
1437 alertErr = c.in.error()
1438 }
1439 }
1440
Adam Langley95c29f32014-06-20 12:00:00 -07001441 if err := c.conn.Close(); err != nil {
1442 return err
1443 }
1444 return alertErr
1445}
1446
1447// Handshake runs the client or server handshake
1448// protocol if it has not yet been run.
1449// Most uses of this package need not call Handshake
1450// explicitly: the first Read or Write will call it automatically.
1451func (c *Conn) Handshake() error {
1452 c.handshakeMutex.Lock()
1453 defer c.handshakeMutex.Unlock()
1454 if err := c.handshakeErr; err != nil {
1455 return err
1456 }
1457 if c.handshakeComplete {
1458 return nil
1459 }
1460
David Benjamin9a41d1b2015-05-16 01:30:09 -04001461 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1462 c.conn.Write([]byte{
1463 byte(recordTypeAlert), // type
1464 0xfe, 0xff, // version
1465 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1466 0x0, 0x2, // length
1467 })
1468 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1469 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001470 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1471 c.writeRecord(recordTypeApplicationData, data)
1472 }
Adam Langley95c29f32014-06-20 12:00:00 -07001473 if c.isClient {
1474 c.handshakeErr = c.clientHandshake()
1475 } else {
1476 c.handshakeErr = c.serverHandshake()
1477 }
David Benjaminddb9f152015-02-03 15:44:39 -05001478 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1479 c.writeRecord(recordType(42), []byte("invalid record"))
1480 }
Adam Langley95c29f32014-06-20 12:00:00 -07001481 return c.handshakeErr
1482}
1483
1484// ConnectionState returns basic TLS details about the connection.
1485func (c *Conn) ConnectionState() ConnectionState {
1486 c.handshakeMutex.Lock()
1487 defer c.handshakeMutex.Unlock()
1488
1489 var state ConnectionState
1490 state.HandshakeComplete = c.handshakeComplete
1491 if c.handshakeComplete {
1492 state.Version = c.vers
1493 state.NegotiatedProtocol = c.clientProtocol
1494 state.DidResume = c.didResume
1495 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001496 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001497 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001498 state.PeerCertificates = c.peerCertificates
1499 state.VerifiedChains = c.verifiedChains
1500 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001501 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001502 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001503 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001504 state.SCTList = c.sctList
Nick Harper60edffd2016-06-21 15:19:24 -07001505 state.PeerSignatureAlgorithm = c.peerSignatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -04001506 state.CurveID = c.curveID
Adam Langley95c29f32014-06-20 12:00:00 -07001507 }
1508
1509 return state
1510}
1511
1512// OCSPResponse returns the stapled OCSP response from the TLS server, if
1513// any. (Only valid for client connections.)
1514func (c *Conn) OCSPResponse() []byte {
1515 c.handshakeMutex.Lock()
1516 defer c.handshakeMutex.Unlock()
1517
1518 return c.ocspResponse
1519}
1520
1521// VerifyHostname checks that the peer certificate chain is valid for
1522// connecting to host. If so, it returns nil; if not, it returns an error
1523// describing the problem.
1524func (c *Conn) VerifyHostname(host string) error {
1525 c.handshakeMutex.Lock()
1526 defer c.handshakeMutex.Unlock()
1527 if !c.isClient {
1528 return errors.New("tls: VerifyHostname called on TLS server connection")
1529 }
1530 if !c.handshakeComplete {
1531 return errors.New("tls: handshake has not yet been performed")
1532 }
1533 return c.peerCertificates[0].VerifyHostname(host)
1534}
David Benjaminc565ebb2015-04-03 04:06:36 -04001535
1536// ExportKeyingMaterial exports keying material from the current connection
1537// state, as per RFC 5705.
1538func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1539 c.handshakeMutex.Lock()
1540 defer c.handshakeMutex.Unlock()
1541 if !c.handshakeComplete {
1542 return nil, errors.New("tls: handshake has not yet been performed")
1543 }
1544
David Benjamin8d315d72016-07-18 01:03:18 +02001545 if c.vers >= VersionTLS13 {
David Benjamin97a0a082016-07-13 17:57:35 -04001546 // TODO(davidben): What should we do with useContext? See
1547 // https://github.com/tlswg/tls13-spec/issues/546
1548 return hkdfExpandLabel(c.cipherSuite.hash(), c.exporterSecret, label, context, length), nil
1549 }
1550
David Benjaminc565ebb2015-04-03 04:06:36 -04001551 seedLen := len(c.clientRandom) + len(c.serverRandom)
1552 if useContext {
1553 seedLen += 2 + len(context)
1554 }
1555 seed := make([]byte, 0, seedLen)
1556 seed = append(seed, c.clientRandom[:]...)
1557 seed = append(seed, c.serverRandom[:]...)
1558 if useContext {
1559 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1560 seed = append(seed, context...)
1561 }
1562 result := make([]byte, length)
David Benjamin97a0a082016-07-13 17:57:35 -04001563 prfForVersion(c.vers, c.cipherSuite)(result, c.exporterSecret, label, seed)
David Benjaminc565ebb2015-04-03 04:06:36 -04001564 return result, nil
1565}
David Benjamin3e052de2015-11-25 20:10:31 -05001566
1567// noRenegotiationInfo returns true if the renegotiation info extension
1568// should be supported in the current handshake.
1569func (c *Conn) noRenegotiationInfo() bool {
1570 if c.config.Bugs.NoRenegotiationInfo {
1571 return true
1572 }
1573 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1574 return true
1575 }
1576 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1577 return true
1578 }
1579 return false
1580}