blob: f10a49515bca9f51cd98c605206d12551868e0f1 [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
Adam Langleyaf0e32c2015-06-03 09:57:23 -070056
David Benjaminc565ebb2015-04-03 04:06:36 -040057 clientRandom, serverRandom [32]byte
David Benjamin97a0a082016-07-13 17:57:35 -040058 exporterSecret []byte
Adam Langley95c29f32014-06-20 12:00:00 -070059
60 clientProtocol string
61 clientProtocolFallback bool
David Benjaminfc7b0862014-09-06 13:21:53 -040062 usedALPN bool
Adam Langley95c29f32014-06-20 12:00:00 -070063
Adam Langley2ae77d22014-10-28 17:29:33 -070064 // verify_data values for the renegotiation extension.
65 clientVerify []byte
66 serverVerify []byte
67
David Benjamind30a9902014-08-24 01:44:23 -040068 channelID *ecdsa.PublicKey
69
David Benjaminca6c8262014-11-15 19:06:08 -050070 srtpProtectionProfile uint16
71
David Benjaminc44b1df2014-11-23 12:11:01 -050072 clientVersion uint16
73
Adam Langley95c29f32014-06-20 12:00:00 -070074 // input/output
75 in, out halfConn // in.Mutex < out.Mutex
76 rawInput *block // raw input, right off the wire
David Benjamin83c0bc92014-08-04 01:23:53 -040077 input *block // application record waiting to be read
78 hand bytes.Buffer // handshake record waiting to be read
79
David Benjamin582ba042016-07-07 12:33:25 -070080 // pendingFlight, if PackHandshakeFlight is enabled, is the buffer of
81 // handshake data to be split into records at the end of the flight.
82 pendingFlight bytes.Buffer
83
David Benjamin83c0bc92014-08-04 01:23:53 -040084 // DTLS state
85 sendHandshakeSeq uint16
86 recvHandshakeSeq uint16
David Benjaminb3774b92015-01-31 17:16:01 -050087 handMsg []byte // pending assembled handshake message
88 handMsgLen int // handshake message length, not including the header
89 pendingFragments [][]byte // pending outgoing handshake fragments.
Adam Langley95c29f32014-06-20 12:00:00 -070090
91 tmp [16]byte
92}
93
David Benjamin5e961c12014-11-07 01:48:35 -050094func (c *Conn) init() {
95 c.in.isDTLS = c.isDTLS
96 c.out.isDTLS = c.isDTLS
97 c.in.config = c.config
98 c.out.config = c.config
David Benjamin8e6db492015-07-25 18:29:23 -040099
100 c.out.updateOutSeq()
David Benjamin5e961c12014-11-07 01:48:35 -0500101}
102
Adam Langley95c29f32014-06-20 12:00:00 -0700103// Access to net.Conn methods.
104// Cannot just embed net.Conn because that would
105// export the struct field too.
106
107// LocalAddr returns the local network address.
108func (c *Conn) LocalAddr() net.Addr {
109 return c.conn.LocalAddr()
110}
111
112// RemoteAddr returns the remote network address.
113func (c *Conn) RemoteAddr() net.Addr {
114 return c.conn.RemoteAddr()
115}
116
117// SetDeadline sets the read and write deadlines associated with the connection.
118// A zero value for t means Read and Write will not time out.
119// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
120func (c *Conn) SetDeadline(t time.Time) error {
121 return c.conn.SetDeadline(t)
122}
123
124// SetReadDeadline sets the read deadline on the underlying connection.
125// A zero value for t means Read will not time out.
126func (c *Conn) SetReadDeadline(t time.Time) error {
127 return c.conn.SetReadDeadline(t)
128}
129
130// SetWriteDeadline sets the write deadline on the underlying conneciton.
131// A zero value for t means Write will not time out.
132// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
133func (c *Conn) SetWriteDeadline(t time.Time) error {
134 return c.conn.SetWriteDeadline(t)
135}
136
137// A halfConn represents one direction of the record layer
138// connection, either sending or receiving.
139type halfConn struct {
140 sync.Mutex
141
David Benjamin83c0bc92014-08-04 01:23:53 -0400142 err error // first permanent error
143 version uint16 // protocol version
144 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -0700145 cipher interface{} // cipher algorithm
146 mac macFunction
147 seq [8]byte // 64-bit sequence number
David Benjamin8e6db492015-07-25 18:29:23 -0400148 outSeq [8]byte // Mapped sequence number
Adam Langley95c29f32014-06-20 12:00:00 -0700149 bfree *block // list of free blocks
150
151 nextCipher interface{} // next encryption state
152 nextMac macFunction // next MAC algorithm
David Benjamin83f90402015-01-27 01:09:43 -0500153 nextSeq [6]byte // next epoch's starting sequence number in DTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700154
155 // used to save allocating a new buffer for each MAC.
156 inDigestBuf, outDigestBuf []byte
Adam Langley80842bd2014-06-20 12:00:00 -0700157
158 config *Config
Adam Langley95c29f32014-06-20 12:00:00 -0700159}
160
161func (hc *halfConn) setErrorLocked(err error) error {
162 hc.err = err
163 return err
164}
165
166func (hc *halfConn) error() error {
Adam Langley2ae77d22014-10-28 17:29:33 -0700167 // This should be locked, but I've removed it for the renegotiation
168 // tests since we don't concurrently read and write the same tls.Conn
169 // in any case during testing.
Adam Langley95c29f32014-06-20 12:00:00 -0700170 err := hc.err
Adam Langley95c29f32014-06-20 12:00:00 -0700171 return err
172}
173
174// prepareCipherSpec sets the encryption and MAC states
175// that a subsequent changeCipherSpec will use.
176func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
177 hc.version = version
178 hc.nextCipher = cipher
179 hc.nextMac = mac
180}
181
182// changeCipherSpec changes the encryption and MAC states
183// to the ones previously passed to prepareCipherSpec.
Adam Langley80842bd2014-06-20 12:00:00 -0700184func (hc *halfConn) changeCipherSpec(config *Config) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700185 if hc.nextCipher == nil {
186 return alertInternalError
187 }
188 hc.cipher = hc.nextCipher
189 hc.mac = hc.nextMac
190 hc.nextCipher = nil
191 hc.nextMac = nil
Adam Langley80842bd2014-06-20 12:00:00 -0700192 hc.config = config
David Benjamin83c0bc92014-08-04 01:23:53 -0400193 hc.incEpoch()
David Benjaminf2b83632016-03-01 22:57:46 -0500194
195 if config.Bugs.NullAllCiphers {
196 hc.cipher = nil
197 hc.mac = nil
198 }
Adam Langley95c29f32014-06-20 12:00:00 -0700199 return nil
200}
201
Nick Harperb41d2e42016-07-01 17:50:32 -0400202// updateKeys sets the current cipher state.
203func (hc *halfConn) updateKeys(cipher interface{}, version uint16) {
204 hc.version = version
205 hc.cipher = cipher
206 hc.incEpoch()
207}
208
Adam Langley95c29f32014-06-20 12:00:00 -0700209// incSeq increments the sequence number.
David Benjamin5e961c12014-11-07 01:48:35 -0500210func (hc *halfConn) incSeq(isOutgoing bool) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400211 limit := 0
David Benjamin5e961c12014-11-07 01:48:35 -0500212 increment := uint64(1)
David Benjamin83c0bc92014-08-04 01:23:53 -0400213 if hc.isDTLS {
214 // Increment up to the epoch in DTLS.
215 limit = 2
216 }
217 for i := 7; i >= limit; i-- {
David Benjamin5e961c12014-11-07 01:48:35 -0500218 increment += uint64(hc.seq[i])
219 hc.seq[i] = byte(increment)
220 increment >>= 8
Adam Langley95c29f32014-06-20 12:00:00 -0700221 }
222
223 // Not allowed to let sequence number wrap.
224 // Instead, must renegotiate before it does.
225 // Not likely enough to bother.
David Benjamin5e961c12014-11-07 01:48:35 -0500226 if increment != 0 {
227 panic("TLS: sequence number wraparound")
228 }
David Benjamin8e6db492015-07-25 18:29:23 -0400229
230 hc.updateOutSeq()
Adam Langley95c29f32014-06-20 12:00:00 -0700231}
232
David Benjamin83f90402015-01-27 01:09:43 -0500233// incNextSeq increments the starting sequence number for the next epoch.
234func (hc *halfConn) incNextSeq() {
235 for i := len(hc.nextSeq) - 1; i >= 0; i-- {
236 hc.nextSeq[i]++
237 if hc.nextSeq[i] != 0 {
238 return
239 }
240 }
241 panic("TLS: sequence number wraparound")
242}
243
244// incEpoch resets the sequence number. In DTLS, it also increments the epoch
245// half of the sequence number.
David Benjamin83c0bc92014-08-04 01:23:53 -0400246func (hc *halfConn) incEpoch() {
David Benjamin83c0bc92014-08-04 01:23:53 -0400247 if hc.isDTLS {
248 for i := 1; i >= 0; i-- {
249 hc.seq[i]++
250 if hc.seq[i] != 0 {
251 break
252 }
253 if i == 0 {
254 panic("TLS: epoch number wraparound")
255 }
256 }
David Benjamin83f90402015-01-27 01:09:43 -0500257 copy(hc.seq[2:], hc.nextSeq[:])
258 for i := range hc.nextSeq {
259 hc.nextSeq[i] = 0
260 }
261 } else {
262 for i := range hc.seq {
263 hc.seq[i] = 0
264 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400265 }
David Benjamin8e6db492015-07-25 18:29:23 -0400266
267 hc.updateOutSeq()
268}
269
270func (hc *halfConn) updateOutSeq() {
271 if hc.config.Bugs.SequenceNumberMapping != nil {
272 seqU64 := binary.BigEndian.Uint64(hc.seq[:])
273 seqU64 = hc.config.Bugs.SequenceNumberMapping(seqU64)
274 binary.BigEndian.PutUint64(hc.outSeq[:], seqU64)
275
276 // The DTLS epoch cannot be changed.
277 copy(hc.outSeq[:2], hc.seq[:2])
278 return
279 }
280
281 copy(hc.outSeq[:], hc.seq[:])
David Benjamin83c0bc92014-08-04 01:23:53 -0400282}
283
284func (hc *halfConn) recordHeaderLen() int {
285 if hc.isDTLS {
286 return dtlsRecordHeaderLen
287 }
288 return tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700289}
290
291// removePadding returns an unpadded slice, in constant time, which is a prefix
292// of the input. It also returns a byte which is equal to 255 if the padding
293// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
294func removePadding(payload []byte) ([]byte, byte) {
295 if len(payload) < 1 {
296 return payload, 0
297 }
298
299 paddingLen := payload[len(payload)-1]
300 t := uint(len(payload)-1) - uint(paddingLen)
301 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
302 good := byte(int32(^t) >> 31)
303
304 toCheck := 255 // the maximum possible padding length
305 // The length of the padded data is public, so we can use an if here
306 if toCheck+1 > len(payload) {
307 toCheck = len(payload) - 1
308 }
309
310 for i := 0; i < toCheck; i++ {
311 t := uint(paddingLen) - uint(i)
312 // if i <= paddingLen then the MSB of t is zero
313 mask := byte(int32(^t) >> 31)
314 b := payload[len(payload)-1-i]
315 good &^= mask&paddingLen ^ mask&b
316 }
317
318 // We AND together the bits of good and replicate the result across
319 // all the bits.
320 good &= good << 4
321 good &= good << 2
322 good &= good << 1
323 good = uint8(int8(good) >> 7)
324
325 toRemove := good&paddingLen + 1
326 return payload[:len(payload)-int(toRemove)], good
327}
328
329// removePaddingSSL30 is a replacement for removePadding in the case that the
330// protocol version is SSLv3. In this version, the contents of the padding
331// are random and cannot be checked.
332func removePaddingSSL30(payload []byte) ([]byte, byte) {
333 if len(payload) < 1 {
334 return payload, 0
335 }
336
337 paddingLen := int(payload[len(payload)-1]) + 1
338 if paddingLen > len(payload) {
339 return payload, 0
340 }
341
342 return payload[:len(payload)-paddingLen], 255
343}
344
345func roundUp(a, b int) int {
346 return a + (b-a%b)%b
347}
348
349// cbcMode is an interface for block ciphers using cipher block chaining.
350type cbcMode interface {
351 cipher.BlockMode
352 SetIV([]byte)
353}
354
355// decrypt checks and strips the mac and decrypts the data in b. Returns a
356// success boolean, the number of bytes to skip from the start of the record in
Nick Harper1fd39d82016-06-14 18:14:35 -0700357// order to get the application payload, the encrypted record type (or 0
358// if there is none), and an optional alert value.
359func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, contentType recordType, alertValue alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400360 recordHeaderLen := hc.recordHeaderLen()
361
Adam Langley95c29f32014-06-20 12:00:00 -0700362 // pull out payload
363 payload := b.data[recordHeaderLen:]
364
365 macSize := 0
366 if hc.mac != nil {
367 macSize = hc.mac.Size()
368 }
369
370 paddingGood := byte(255)
371 explicitIVLen := 0
372
David Benjamin83c0bc92014-08-04 01:23:53 -0400373 seq := hc.seq[:]
374 if hc.isDTLS {
375 // DTLS sequence numbers are explicit.
376 seq = b.data[3:11]
377 }
378
Adam Langley95c29f32014-06-20 12:00:00 -0700379 // decrypt
380 if hc.cipher != nil {
381 switch c := hc.cipher.(type) {
382 case cipher.Stream:
383 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400384 case *tlsAead:
385 nonce := seq
386 if c.explicitNonce {
387 explicitIVLen = 8
388 if len(payload) < explicitIVLen {
Nick Harper1fd39d82016-06-14 18:14:35 -0700389 return false, 0, 0, alertBadRecordMAC
David Benjamine9a80ff2015-04-07 00:46:46 -0400390 }
391 nonce = payload[:8]
392 payload = payload[8:]
Adam Langley95c29f32014-06-20 12:00:00 -0700393 }
Adam Langley95c29f32014-06-20 12:00:00 -0700394
Nick Harper1fd39d82016-06-14 18:14:35 -0700395 var additionalData []byte
396 if hc.version < VersionTLS13 {
397 additionalData = make([]byte, 13)
398 copy(additionalData, seq)
399 copy(additionalData[8:], b.data[:3])
400 n := len(payload) - c.Overhead()
401 additionalData[11] = byte(n >> 8)
402 additionalData[12] = byte(n)
403 }
Adam Langley95c29f32014-06-20 12:00:00 -0700404 var err error
Nick Harper1fd39d82016-06-14 18:14:35 -0700405 payload, err = c.Open(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700406 if err != nil {
Nick Harper1fd39d82016-06-14 18:14:35 -0700407 return false, 0, 0, alertBadRecordMAC
408 }
409 if hc.version >= VersionTLS13 {
410 i := len(payload)
411 for i > 0 && payload[i-1] == 0 {
412 i--
413 }
414 payload = payload[:i]
415 if len(payload) == 0 {
416 return false, 0, 0, alertUnexpectedMessage
417 }
418 contentType = recordType(payload[len(payload)-1])
419 payload = payload[:len(payload)-1]
Adam Langley95c29f32014-06-20 12:00:00 -0700420 }
421 b.resize(recordHeaderLen + explicitIVLen + len(payload))
422 case cbcMode:
423 blockSize := c.BlockSize()
David Benjamin83c0bc92014-08-04 01:23:53 -0400424 if hc.version >= VersionTLS11 || hc.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700425 explicitIVLen = blockSize
426 }
427
428 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
Nick Harper1fd39d82016-06-14 18:14:35 -0700429 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700430 }
431
432 if explicitIVLen > 0 {
433 c.SetIV(payload[:explicitIVLen])
434 payload = payload[explicitIVLen:]
435 }
436 c.CryptBlocks(payload, payload)
437 if hc.version == VersionSSL30 {
438 payload, paddingGood = removePaddingSSL30(payload)
439 } else {
440 payload, paddingGood = removePadding(payload)
441 }
442 b.resize(recordHeaderLen + explicitIVLen + len(payload))
443
444 // note that we still have a timing side-channel in the
445 // MAC check, below. An attacker can align the record
446 // so that a correct padding will cause one less hash
447 // block to be calculated. Then they can iteratively
448 // decrypt a record by breaking each byte. See
449 // "Password Interception in a SSL/TLS Channel", Brice
450 // Canvel et al.
451 //
452 // However, our behavior matches OpenSSL, so we leak
453 // only as much as they do.
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700454 case nullCipher:
455 break
Adam Langley95c29f32014-06-20 12:00:00 -0700456 default:
457 panic("unknown cipher type")
458 }
459 }
460
461 // check, strip mac
462 if hc.mac != nil {
463 if len(payload) < macSize {
Nick Harper1fd39d82016-06-14 18:14:35 -0700464 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700465 }
466
467 // strip mac off payload, b.data
468 n := len(payload) - macSize
David Benjamin83c0bc92014-08-04 01:23:53 -0400469 b.data[recordHeaderLen-2] = byte(n >> 8)
470 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700471 b.resize(recordHeaderLen + explicitIVLen + n)
472 remoteMAC := payload[n:]
David Benjamin83c0bc92014-08-04 01:23:53 -0400473 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
Adam Langley95c29f32014-06-20 12:00:00 -0700474
475 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
Nick Harper1fd39d82016-06-14 18:14:35 -0700476 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700477 }
478 hc.inDigestBuf = localMAC
479 }
David Benjamin5e961c12014-11-07 01:48:35 -0500480 hc.incSeq(false)
Adam Langley95c29f32014-06-20 12:00:00 -0700481
Nick Harper1fd39d82016-06-14 18:14:35 -0700482 return true, recordHeaderLen + explicitIVLen, contentType, 0
Adam Langley95c29f32014-06-20 12:00:00 -0700483}
484
485// padToBlockSize calculates the needed padding block, if any, for a payload.
486// On exit, prefix aliases payload and extends to the end of the last full
487// block of payload. finalBlock is a fresh slice which contains the contents of
488// any suffix of payload as well as the needed padding to make finalBlock a
489// full block.
Adam Langley80842bd2014-06-20 12:00:00 -0700490func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
Adam Langley95c29f32014-06-20 12:00:00 -0700491 overrun := len(payload) % blockSize
Adam Langley95c29f32014-06-20 12:00:00 -0700492 prefix = payload[:len(payload)-overrun]
Adam Langley80842bd2014-06-20 12:00:00 -0700493
494 paddingLen := blockSize - overrun
495 finalSize := blockSize
496 if config.Bugs.MaxPadding {
497 for paddingLen+blockSize <= 256 {
498 paddingLen += blockSize
499 }
500 finalSize = 256
501 }
502 finalBlock = make([]byte, finalSize)
503 for i := range finalBlock {
Adam Langley95c29f32014-06-20 12:00:00 -0700504 finalBlock[i] = byte(paddingLen - 1)
505 }
Adam Langley80842bd2014-06-20 12:00:00 -0700506 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
507 finalBlock[overrun] ^= 0xff
508 }
509 copy(finalBlock, payload[len(payload)-overrun:])
Adam Langley95c29f32014-06-20 12:00:00 -0700510 return
511}
512
513// encrypt encrypts and macs the data in b.
Nick Harper1fd39d82016-06-14 18:14:35 -0700514func (hc *halfConn) encrypt(b *block, explicitIVLen int, typ recordType) (bool, alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400515 recordHeaderLen := hc.recordHeaderLen()
516
Adam Langley95c29f32014-06-20 12:00:00 -0700517 // mac
518 if hc.mac != nil {
David Benjamin8e6db492015-07-25 18:29:23 -0400519 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 -0700520
521 n := len(b.data)
522 b.resize(n + len(mac))
523 copy(b.data[n:], mac)
524 hc.outDigestBuf = mac
525 }
526
527 payload := b.data[recordHeaderLen:]
528
529 // encrypt
530 if hc.cipher != nil {
531 switch c := hc.cipher.(type) {
532 case cipher.Stream:
533 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400534 case *tlsAead:
Adam Langley95c29f32014-06-20 12:00:00 -0700535 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
David Benjaminc9ae27c2016-06-24 22:56:37 -0400536 paddingLen := 0
Nick Harper1fd39d82016-06-14 18:14:35 -0700537 if hc.version >= VersionTLS13 {
David Benjaminc9ae27c2016-06-24 22:56:37 -0400538 payloadLen++
539 paddingLen = hc.config.Bugs.RecordPadding
540 }
541 if hc.config.Bugs.OmitRecordContents {
542 payloadLen = 0
543 }
544 b.resize(recordHeaderLen + explicitIVLen + payloadLen + paddingLen + c.Overhead())
545 if hc.version >= VersionTLS13 {
546 if !hc.config.Bugs.OmitRecordContents {
547 b.data[payloadLen+recordHeaderLen-1] = byte(typ)
548 }
549 for i := 0; i < hc.config.Bugs.RecordPadding; i++ {
550 b.data[payloadLen+recordHeaderLen+i] = 0
551 }
552 payloadLen += paddingLen
Nick Harper1fd39d82016-06-14 18:14:35 -0700553 }
David Benjamin8e6db492015-07-25 18:29:23 -0400554 nonce := hc.outSeq[:]
David Benjamine9a80ff2015-04-07 00:46:46 -0400555 if c.explicitNonce {
556 nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
557 }
Adam Langley95c29f32014-06-20 12:00:00 -0700558 payload := b.data[recordHeaderLen+explicitIVLen:]
559 payload = payload[:payloadLen]
560
Nick Harper1fd39d82016-06-14 18:14:35 -0700561 var additionalData []byte
562 if hc.version < VersionTLS13 {
563 additionalData = make([]byte, 13)
564 copy(additionalData, hc.outSeq[:])
565 copy(additionalData[8:], b.data[:3])
566 additionalData[11] = byte(payloadLen >> 8)
567 additionalData[12] = byte(payloadLen)
568 }
Adam Langley95c29f32014-06-20 12:00:00 -0700569
Nick Harper1fd39d82016-06-14 18:14:35 -0700570 c.Seal(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700571 case cbcMode:
572 blockSize := c.BlockSize()
573 if explicitIVLen > 0 {
574 c.SetIV(payload[:explicitIVLen])
575 payload = payload[explicitIVLen:]
576 }
Adam Langley80842bd2014-06-20 12:00:00 -0700577 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700578 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
579 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
580 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700581 case nullCipher:
582 break
Adam Langley95c29f32014-06-20 12:00:00 -0700583 default:
584 panic("unknown cipher type")
585 }
586 }
587
588 // update length to include MAC and any block padding needed.
589 n := len(b.data) - recordHeaderLen
David Benjamin83c0bc92014-08-04 01:23:53 -0400590 b.data[recordHeaderLen-2] = byte(n >> 8)
591 b.data[recordHeaderLen-1] = byte(n)
David Benjamin5e961c12014-11-07 01:48:35 -0500592 hc.incSeq(true)
Adam Langley95c29f32014-06-20 12:00:00 -0700593
594 return true, 0
595}
596
597// A block is a simple data buffer.
598type block struct {
599 data []byte
600 off int // index for Read
601 link *block
602}
603
604// resize resizes block to be n bytes, growing if necessary.
605func (b *block) resize(n int) {
606 if n > cap(b.data) {
607 b.reserve(n)
608 }
609 b.data = b.data[0:n]
610}
611
612// reserve makes sure that block contains a capacity of at least n bytes.
613func (b *block) reserve(n int) {
614 if cap(b.data) >= n {
615 return
616 }
617 m := cap(b.data)
618 if m == 0 {
619 m = 1024
620 }
621 for m < n {
622 m *= 2
623 }
624 data := make([]byte, len(b.data), m)
625 copy(data, b.data)
626 b.data = data
627}
628
629// readFromUntil reads from r into b until b contains at least n bytes
630// or else returns an error.
631func (b *block) readFromUntil(r io.Reader, n int) error {
632 // quick case
633 if len(b.data) >= n {
634 return nil
635 }
636
637 // read until have enough.
638 b.reserve(n)
639 for {
640 m, err := r.Read(b.data[len(b.data):cap(b.data)])
641 b.data = b.data[0 : len(b.data)+m]
642 if len(b.data) >= n {
643 // TODO(bradfitz,agl): slightly suspicious
644 // that we're throwing away r.Read's err here.
645 break
646 }
647 if err != nil {
648 return err
649 }
650 }
651 return nil
652}
653
654func (b *block) Read(p []byte) (n int, err error) {
655 n = copy(p, b.data[b.off:])
656 b.off += n
657 return
658}
659
660// newBlock allocates a new block, from hc's free list if possible.
661func (hc *halfConn) newBlock() *block {
662 b := hc.bfree
663 if b == nil {
664 return new(block)
665 }
666 hc.bfree = b.link
667 b.link = nil
668 b.resize(0)
669 return b
670}
671
672// freeBlock returns a block to hc's free list.
673// The protocol is such that each side only has a block or two on
674// its free list at a time, so there's no need to worry about
675// trimming the list, etc.
676func (hc *halfConn) freeBlock(b *block) {
677 b.link = hc.bfree
678 hc.bfree = b
679}
680
681// splitBlock splits a block after the first n bytes,
682// returning a block with those n bytes and a
683// block with the remainder. the latter may be nil.
684func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
685 if len(b.data) <= n {
686 return b, nil
687 }
688 bb := hc.newBlock()
689 bb.resize(len(b.data) - n)
690 copy(bb.data, b.data[n:])
691 b.data = b.data[0:n]
692 return b, bb
693}
694
David Benjamin83c0bc92014-08-04 01:23:53 -0400695func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
696 if c.isDTLS {
697 return c.dtlsDoReadRecord(want)
698 }
699
700 recordHeaderLen := tlsRecordHeaderLen
701
702 if c.rawInput == nil {
703 c.rawInput = c.in.newBlock()
704 }
705 b := c.rawInput
706
707 // Read header, payload.
708 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
709 // RFC suggests that EOF without an alertCloseNotify is
710 // an error, but popular web sites seem to do this,
David Benjamin30789da2015-08-29 22:56:45 -0400711 // so we can't make it an error, outside of tests.
712 if err == io.EOF && c.config.Bugs.ExpectCloseNotify {
713 err = io.ErrUnexpectedEOF
714 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400715 if e, ok := err.(net.Error); !ok || !e.Temporary() {
716 c.in.setErrorLocked(err)
717 }
718 return 0, nil, err
719 }
720 typ := recordType(b.data[0])
721
722 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
723 // start with a uint16 length where the MSB is set and the first record
724 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
725 // an SSLv2 client.
726 if want == recordTypeHandshake && typ == 0x80 {
727 c.sendAlert(alertProtocolVersion)
728 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
729 }
730
731 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
732 n := int(b.data[3])<<8 | int(b.data[4])
David Benjaminbde00392016-06-21 12:19:28 -0400733 // Alerts sent near version negotiation do not have a well-defined
734 // record-layer version prior to TLS 1.3. (In TLS 1.3, the record-layer
735 // version is irrelevant.)
736 if typ != recordTypeAlert {
737 if c.haveVers {
738 if vers != c.vers && c.vers < VersionTLS13 {
739 c.sendAlert(alertProtocolVersion)
740 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers))
741 }
742 } else {
743 if expect := c.config.Bugs.ExpectInitialRecordVersion; expect != 0 && vers != expect {
744 c.sendAlert(alertProtocolVersion)
745 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
746 }
David Benjamin1e29a6b2014-12-10 02:27:24 -0500747 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400748 }
749 if n > maxCiphertext {
750 c.sendAlert(alertRecordOverflow)
751 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
752 }
753 if !c.haveVers {
754 // First message, be extra suspicious:
755 // this might not be a TLS client.
756 // Bail out before reading a full 'body', if possible.
757 // The current max version is 3.1.
758 // If the version is >= 16.0, it's probably not real.
759 // Similarly, a clientHello message encodes in
760 // well under a kilobyte. If the length is >= 12 kB,
761 // it's probably not real.
762 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
763 c.sendAlert(alertUnexpectedMessage)
764 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
765 }
766 }
767 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
768 if err == io.EOF {
769 err = io.ErrUnexpectedEOF
770 }
771 if e, ok := err.(net.Error); !ok || !e.Temporary() {
772 c.in.setErrorLocked(err)
773 }
774 return 0, nil, err
775 }
776
777 // Process message.
778 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
David Benjaminff26f092016-07-01 16:13:42 -0400779 ok, off, encTyp, alertValue := c.in.decrypt(b)
780 if !ok {
781 return 0, nil, c.in.setErrorLocked(c.sendAlert(alertValue))
782 }
783 b.off = off
784
Nick Harper1fd39d82016-06-14 18:14:35 -0700785 if c.vers >= VersionTLS13 && c.in.cipher != nil {
David Benjaminc9ae27c2016-06-24 22:56:37 -0400786 if typ != recordTypeApplicationData {
787 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: outer record type is not application data"))
788 }
Nick Harper1fd39d82016-06-14 18:14:35 -0700789 typ = encTyp
790 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400791 return typ, b, nil
792}
793
Adam Langley95c29f32014-06-20 12:00:00 -0700794// readRecord reads the next TLS record from the connection
795// and updates the record layer state.
796// c.in.Mutex <= L; c.input == nil.
797func (c *Conn) readRecord(want recordType) error {
798 // Caller must be in sync with connection:
799 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700800 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700801 switch want {
802 default:
803 c.sendAlert(alertInternalError)
804 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
805 case recordTypeHandshake, recordTypeChangeCipherSpec:
806 if c.handshakeComplete {
807 c.sendAlert(alertInternalError)
808 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
809 }
810 case recordTypeApplicationData:
David Benjamine58c4f52014-08-24 03:47:07 -0400811 if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart {
Adam Langley95c29f32014-06-20 12:00:00 -0700812 c.sendAlert(alertInternalError)
813 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
814 }
David Benjamin30789da2015-08-29 22:56:45 -0400815 case recordTypeAlert:
816 // Looking for a close_notify. Note: unlike a real
817 // implementation, this is not tolerant of additional records.
818 // See the documentation for ExpectCloseNotify.
Adam Langley95c29f32014-06-20 12:00:00 -0700819 }
820
821Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400822 typ, b, err := c.doReadRecord(want)
823 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700824 return err
825 }
Adam Langley95c29f32014-06-20 12:00:00 -0700826 data := b.data[b.off:]
827 if len(data) > maxPlaintext {
828 err := c.sendAlert(alertRecordOverflow)
829 c.in.freeBlock(b)
830 return c.in.setErrorLocked(err)
831 }
832
833 switch typ {
834 default:
835 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
836
837 case recordTypeAlert:
838 if len(data) != 2 {
839 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
840 break
841 }
842 if alert(data[1]) == alertCloseNotify {
843 c.in.setErrorLocked(io.EOF)
844 break
845 }
846 switch data[0] {
847 case alertLevelWarning:
848 // drop on the floor
849 c.in.freeBlock(b)
850 goto Again
851 case alertLevelError:
852 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
853 default:
854 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
855 }
856
857 case recordTypeChangeCipherSpec:
858 if typ != want || len(data) != 1 || data[0] != 1 {
859 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
860 break
861 }
Adam Langley80842bd2014-06-20 12:00:00 -0700862 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700863 if err != nil {
864 c.in.setErrorLocked(c.sendAlert(err.(alert)))
865 }
866
867 case recordTypeApplicationData:
868 if typ != want {
869 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
870 break
871 }
872 c.input = b
873 b = nil
874
875 case recordTypeHandshake:
876 // TODO(rsc): Should at least pick off connection close.
877 if typ != want {
Adam Langley2ae77d22014-10-28 17:29:33 -0700878 // A client might need to process a HelloRequest from
879 // the server, thus receiving a handshake message when
David Benjamind9b091b2015-01-27 01:10:54 -0500880 // application data is expected is ok.
David Benjamin30789da2015-08-29 22:56:45 -0400881 if !c.isClient || want != recordTypeApplicationData {
Adam Langley2ae77d22014-10-28 17:29:33 -0700882 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
883 }
Adam Langley95c29f32014-06-20 12:00:00 -0700884 }
885 c.hand.Write(data)
886 }
887
888 if b != nil {
889 c.in.freeBlock(b)
890 }
891 return c.in.err
892}
893
894// sendAlert sends a TLS alert message.
895// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400896func (c *Conn) sendAlertLocked(level byte, err alert) error {
897 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700898 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400899 if c.config.Bugs.FragmentAlert {
900 c.writeRecord(recordTypeAlert, c.tmp[0:1])
901 c.writeRecord(recordTypeAlert, c.tmp[1:2])
David Benjamin0d3a8c62016-03-11 22:25:18 -0500902 } else if c.config.Bugs.DoubleAlert {
903 copy(c.tmp[2:4], c.tmp[0:2])
904 c.writeRecord(recordTypeAlert, c.tmp[0:4])
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400905 } else {
906 c.writeRecord(recordTypeAlert, c.tmp[0:2])
907 }
David Benjamin24f346d2015-06-06 03:28:08 -0400908 // Error alerts are fatal to the connection.
909 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700910 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
911 }
912 return nil
913}
914
915// sendAlert sends a TLS alert message.
916// L < c.out.Mutex.
917func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400918 level := byte(alertLevelError)
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500919 if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertficate {
David Benjamin24f346d2015-06-06 03:28:08 -0400920 level = alertLevelWarning
921 }
922 return c.SendAlert(level, err)
923}
924
925func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700926 c.out.Lock()
927 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -0400928 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -0700929}
930
David Benjamind86c7672014-08-02 04:07:12 -0400931// writeV2Record writes a record for a V2ClientHello.
932func (c *Conn) writeV2Record(data []byte) (n int, err error) {
933 record := make([]byte, 2+len(data))
934 record[0] = uint8(len(data)>>8) | 0x80
935 record[1] = uint8(len(data))
936 copy(record[2:], data)
937 return c.conn.Write(record)
938}
939
Adam Langley95c29f32014-06-20 12:00:00 -0700940// writeRecord writes a TLS record with the given type and payload
941// to the connection and updates the record layer state.
942// c.out.Mutex <= L.
943func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400944 if c.isDTLS {
945 return c.dtlsWriteRecord(typ, data)
946 }
947
David Benjamin71dd6662016-07-08 14:10:48 -0700948 if typ == recordTypeHandshake {
949 if c.config.Bugs.SendHelloRequestBeforeEveryHandshakeMessage {
950 newData := make([]byte, 0, 4+len(data))
951 newData = append(newData, typeHelloRequest, 0, 0, 0)
952 newData = append(newData, data...)
953 data = newData
954 }
955
956 if c.config.Bugs.PackHandshakeFlight {
957 c.pendingFlight.Write(data)
958 return len(data), nil
959 }
David Benjamin582ba042016-07-07 12:33:25 -0700960 }
961
962 return c.doWriteRecord(typ, data)
963}
964
965func (c *Conn) doWriteRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400966 recordHeaderLen := tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700967 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -0400968 first := true
969 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -0400970 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -0700971 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -0400972 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -0700973 m = maxPlaintext
974 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400975 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
976 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -0400977 // By default, do not fragment the client_version or
978 // server_version, which are located in the first 6
979 // bytes.
980 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
981 m = 6
982 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400983 }
Adam Langley95c29f32014-06-20 12:00:00 -0700984 explicitIVLen := 0
985 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -0400986 first = false
Adam Langley95c29f32014-06-20 12:00:00 -0700987
988 var cbc cbcMode
989 if c.out.version >= VersionTLS11 {
990 var ok bool
991 if cbc, ok = c.out.cipher.(cbcMode); ok {
992 explicitIVLen = cbc.BlockSize()
993 }
994 }
995 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -0400996 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -0700997 explicitIVLen = 8
998 // The AES-GCM construction in TLS has an
999 // explicit nonce so that the nonce can be
1000 // random. However, the nonce is only 8 bytes
1001 // which is too small for a secure, random
1002 // nonce. Therefore we use the sequence number
1003 // as the nonce.
1004 explicitIVIsSeq = true
1005 }
1006 }
1007 b.resize(recordHeaderLen + explicitIVLen + m)
1008 b.data[0] = byte(typ)
Nick Harper1fd39d82016-06-14 18:14:35 -07001009 if c.vers >= VersionTLS13 && c.out.cipher != nil {
Nick Harper1fd39d82016-06-14 18:14:35 -07001010 b.data[0] = byte(recordTypeApplicationData)
David Benjaminc9ae27c2016-06-24 22:56:37 -04001011 if outerType := c.config.Bugs.OuterRecordType; outerType != 0 {
1012 b.data[0] = byte(outerType)
1013 }
Nick Harper1fd39d82016-06-14 18:14:35 -07001014 }
Adam Langley95c29f32014-06-20 12:00:00 -07001015 vers := c.vers
Nick Harper1fd39d82016-06-14 18:14:35 -07001016 if vers == 0 || vers >= VersionTLS13 {
Adam Langley95c29f32014-06-20 12:00:00 -07001017 // Some TLS servers fail if the record version is
1018 // greater than TLS 1.0 for the initial ClientHello.
Nick Harper1fd39d82016-06-14 18:14:35 -07001019 //
1020 // TLS 1.3 fixes the version number in the record
1021 // layer to {3, 1}.
Adam Langley95c29f32014-06-20 12:00:00 -07001022 vers = VersionTLS10
1023 }
1024 b.data[1] = byte(vers >> 8)
1025 b.data[2] = byte(vers)
1026 b.data[3] = byte(m >> 8)
1027 b.data[4] = byte(m)
1028 if explicitIVLen > 0 {
1029 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
1030 if explicitIVIsSeq {
1031 copy(explicitIV, c.out.seq[:])
1032 } else {
1033 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
1034 break
1035 }
1036 }
1037 }
1038 copy(b.data[recordHeaderLen+explicitIVLen:], data)
Nick Harper1fd39d82016-06-14 18:14:35 -07001039 c.out.encrypt(b, explicitIVLen, typ)
Adam Langley95c29f32014-06-20 12:00:00 -07001040 _, err = c.conn.Write(b.data)
1041 if err != nil {
1042 break
1043 }
1044 n += m
1045 data = data[m:]
1046 }
1047 c.out.freeBlock(b)
1048
1049 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -07001050 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -07001051 if err != nil {
1052 // Cannot call sendAlert directly,
1053 // because we already hold c.out.Mutex.
1054 c.tmp[0] = alertLevelError
1055 c.tmp[1] = byte(err.(alert))
1056 c.writeRecord(recordTypeAlert, c.tmp[0:2])
1057 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
1058 }
1059 }
1060 return
1061}
1062
David Benjamin582ba042016-07-07 12:33:25 -07001063func (c *Conn) flushHandshake() error {
1064 if c.isDTLS {
1065 return c.dtlsFlushHandshake()
1066 }
1067
1068 for c.pendingFlight.Len() > 0 {
1069 var buf [maxPlaintext]byte
1070 n, _ := c.pendingFlight.Read(buf[:])
1071 if _, err := c.doWriteRecord(recordTypeHandshake, buf[:n]); err != nil {
1072 return err
1073 }
1074 }
1075
1076 c.pendingFlight.Reset()
1077 return nil
1078}
1079
David Benjamin83c0bc92014-08-04 01:23:53 -04001080func (c *Conn) doReadHandshake() ([]byte, error) {
1081 if c.isDTLS {
1082 return c.dtlsDoReadHandshake()
1083 }
1084
Adam Langley95c29f32014-06-20 12:00:00 -07001085 for c.hand.Len() < 4 {
1086 if err := c.in.err; err != nil {
1087 return nil, err
1088 }
1089 if err := c.readRecord(recordTypeHandshake); err != nil {
1090 return nil, err
1091 }
1092 }
1093
1094 data := c.hand.Bytes()
1095 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1096 if n > maxHandshake {
1097 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
1098 }
1099 for c.hand.Len() < 4+n {
1100 if err := c.in.err; err != nil {
1101 return nil, err
1102 }
1103 if err := c.readRecord(recordTypeHandshake); err != nil {
1104 return nil, err
1105 }
1106 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001107 return c.hand.Next(4 + n), nil
1108}
1109
1110// readHandshake reads the next handshake message from
1111// the record layer.
1112// c.in.Mutex < L; c.out.Mutex < L.
1113func (c *Conn) readHandshake() (interface{}, error) {
1114 data, err := c.doReadHandshake()
1115 if err != nil {
1116 return nil, err
1117 }
1118
Adam Langley95c29f32014-06-20 12:00:00 -07001119 var m handshakeMessage
1120 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001121 case typeHelloRequest:
1122 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001123 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001124 m = &clientHelloMsg{
1125 isDTLS: c.isDTLS,
1126 }
Adam Langley95c29f32014-06-20 12:00:00 -07001127 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001128 m = &serverHelloMsg{
1129 isDTLS: c.isDTLS,
1130 }
Adam Langley95c29f32014-06-20 12:00:00 -07001131 case typeNewSessionTicket:
1132 m = new(newSessionTicketMsg)
Nick Harperb41d2e42016-07-01 17:50:32 -04001133 case typeEncryptedExtensions:
1134 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001135 case typeCertificate:
Nick Harperb41d2e42016-07-01 17:50:32 -04001136 m = &certificateMsg{
1137 hasRequestContext: c.vers >= VersionTLS13 && enableTLS13Handshake,
1138 }
Adam Langley95c29f32014-06-20 12:00:00 -07001139 case typeCertificateRequest:
1140 m = &certificateRequestMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001141 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Nick Harperb41d2e42016-07-01 17:50:32 -04001142 hasRequestContext: c.vers >= VersionTLS13 && enableTLS13Handshake,
Adam Langley95c29f32014-06-20 12:00:00 -07001143 }
1144 case typeCertificateStatus:
1145 m = new(certificateStatusMsg)
1146 case typeServerKeyExchange:
1147 m = new(serverKeyExchangeMsg)
1148 case typeServerHelloDone:
1149 m = new(serverHelloDoneMsg)
1150 case typeClientKeyExchange:
1151 m = new(clientKeyExchangeMsg)
1152 case typeCertificateVerify:
1153 m = &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001154 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001155 }
1156 case typeNextProtocol:
1157 m = new(nextProtoMsg)
1158 case typeFinished:
1159 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001160 case typeHelloVerifyRequest:
1161 m = new(helloVerifyRequestMsg)
David Benjamin24599a82016-06-30 18:56:53 -04001162 case typeChannelID:
1163 m = new(channelIDMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001164 default:
1165 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1166 }
1167
1168 // The handshake message unmarshallers
1169 // expect to be able to keep references to data,
1170 // so pass in a fresh copy that won't be overwritten.
1171 data = append([]byte(nil), data...)
1172
1173 if !m.unmarshal(data) {
1174 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1175 }
1176 return m, nil
1177}
1178
David Benjamin83f90402015-01-27 01:09:43 -05001179// skipPacket processes all the DTLS records in packet. It updates
1180// sequence number expectations but otherwise ignores them.
1181func (c *Conn) skipPacket(packet []byte) error {
1182 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001183 if len(packet) < 13 {
1184 return errors.New("tls: bad packet")
1185 }
David Benjamin83f90402015-01-27 01:09:43 -05001186 // Dropped packets are completely ignored save to update
1187 // expected sequence numbers for this and the next epoch. (We
1188 // don't assert on the contents of the packets both for
1189 // simplicity and because a previous test with one shorter
1190 // timeout schedule would have done so.)
1191 epoch := packet[3:5]
1192 seq := packet[5:11]
1193 length := uint16(packet[11])<<8 | uint16(packet[12])
1194 if bytes.Equal(c.in.seq[:2], epoch) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001195 if bytes.Compare(seq, c.in.seq[2:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001196 return errors.New("tls: sequence mismatch")
1197 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001198 copy(c.in.seq[2:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001199 c.in.incSeq(false)
1200 } else {
David Benjamin13e81fc2015-11-02 17:16:13 -05001201 if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001202 return errors.New("tls: sequence mismatch")
1203 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001204 copy(c.in.nextSeq[:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001205 c.in.incNextSeq()
1206 }
David Benjamin6ca93552015-08-28 16:16:25 -04001207 if len(packet) < 13+int(length) {
1208 return errors.New("tls: bad packet")
1209 }
David Benjamin83f90402015-01-27 01:09:43 -05001210 packet = packet[13+length:]
1211 }
1212 return nil
1213}
1214
1215// simulatePacketLoss simulates the loss of a handshake leg from the
1216// peer based on the schedule in c.config.Bugs. If resendFunc is
1217// non-nil, it is called after each simulated timeout to retransmit
1218// handshake messages from the local end. This is used in cases where
1219// the peer retransmits on a stale Finished rather than a timeout.
1220func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1221 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1222 return nil
1223 }
1224 if !c.isDTLS {
1225 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1226 }
1227 if c.config.Bugs.PacketAdaptor == nil {
1228 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1229 }
1230 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1231 // Simulate a timeout.
1232 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1233 if err != nil {
1234 return err
1235 }
1236 for _, packet := range packets {
1237 if err := c.skipPacket(packet); err != nil {
1238 return err
1239 }
1240 }
1241 if resendFunc != nil {
1242 resendFunc()
1243 }
1244 }
1245 return nil
1246}
1247
Adam Langley95c29f32014-06-20 12:00:00 -07001248// Write writes data to the connection.
1249func (c *Conn) Write(b []byte) (int, error) {
1250 if err := c.Handshake(); err != nil {
1251 return 0, err
1252 }
1253
1254 c.out.Lock()
1255 defer c.out.Unlock()
1256
1257 if err := c.out.err; err != nil {
1258 return 0, err
1259 }
1260
1261 if !c.handshakeComplete {
1262 return 0, alertInternalError
1263 }
1264
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001265 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001266 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001267 }
1268
Adam Langley27a0d082015-11-03 13:34:10 -08001269 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1270 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
David Benjamin582ba042016-07-07 12:33:25 -07001271 c.flushHandshake()
Adam Langley27a0d082015-11-03 13:34:10 -08001272 }
1273
Adam Langley95c29f32014-06-20 12:00:00 -07001274 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1275 // attack when using block mode ciphers due to predictable IVs.
1276 // This can be prevented by splitting each Application Data
1277 // record into two records, effectively randomizing the IV.
1278 //
1279 // http://www.openssl.org/~bodo/tls-cbc.txt
1280 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1281 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1282
1283 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001284 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001285 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1286 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1287 if err != nil {
1288 return n, c.out.setErrorLocked(err)
1289 }
1290 m, b = 1, b[1:]
1291 }
1292 }
1293
1294 n, err := c.writeRecord(recordTypeApplicationData, b)
1295 return n + m, c.out.setErrorLocked(err)
1296}
1297
Adam Langley2ae77d22014-10-28 17:29:33 -07001298func (c *Conn) handleRenegotiation() error {
1299 c.handshakeComplete = false
1300 if !c.isClient {
1301 panic("renegotiation should only happen for a client")
1302 }
1303
1304 msg, err := c.readHandshake()
1305 if err != nil {
1306 return err
1307 }
1308 _, ok := msg.(*helloRequestMsg)
1309 if !ok {
1310 c.sendAlert(alertUnexpectedMessage)
1311 return alertUnexpectedMessage
1312 }
1313
1314 return c.Handshake()
1315}
1316
Adam Langleycf2d4f42014-10-28 19:06:14 -07001317func (c *Conn) Renegotiate() error {
1318 if !c.isClient {
David Benjaminef5dfd22015-12-06 13:17:07 -05001319 helloReq := new(helloRequestMsg).marshal()
1320 if c.config.Bugs.BadHelloRequest != nil {
1321 helloReq = c.config.Bugs.BadHelloRequest
1322 }
1323 c.writeRecord(recordTypeHandshake, helloReq)
David Benjamin582ba042016-07-07 12:33:25 -07001324 c.flushHandshake()
Adam Langleycf2d4f42014-10-28 19:06:14 -07001325 }
1326
1327 c.handshakeComplete = false
1328 return c.Handshake()
1329}
1330
Adam Langley95c29f32014-06-20 12:00:00 -07001331// Read can be made to time out and return a net.Error with Timeout() == true
1332// after a fixed time limit; see SetDeadline and SetReadDeadline.
1333func (c *Conn) Read(b []byte) (n int, err error) {
1334 if err = c.Handshake(); err != nil {
1335 return
1336 }
1337
1338 c.in.Lock()
1339 defer c.in.Unlock()
1340
1341 // Some OpenSSL servers send empty records in order to randomize the
1342 // CBC IV. So this loop ignores a limited number of empty records.
1343 const maxConsecutiveEmptyRecords = 100
1344 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1345 for c.input == nil && c.in.err == nil {
1346 if err := c.readRecord(recordTypeApplicationData); err != nil {
1347 // Soft error, like EAGAIN
1348 return 0, err
1349 }
David Benjamind9b091b2015-01-27 01:10:54 -05001350 if c.hand.Len() > 0 {
Adam Langley2ae77d22014-10-28 17:29:33 -07001351 // We received handshake bytes, indicating the
David Benjamind9b091b2015-01-27 01:10:54 -05001352 // start of a renegotiation.
Adam Langley2ae77d22014-10-28 17:29:33 -07001353 if err := c.handleRenegotiation(); err != nil {
1354 return 0, err
1355 }
1356 continue
1357 }
Adam Langley95c29f32014-06-20 12:00:00 -07001358 }
1359 if err := c.in.err; err != nil {
1360 return 0, err
1361 }
1362
1363 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001364 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001365 c.in.freeBlock(c.input)
1366 c.input = nil
1367 }
1368
1369 // If a close-notify alert is waiting, read it so that
1370 // we can return (n, EOF) instead of (n, nil), to signal
1371 // to the HTTP response reading goroutine that the
1372 // connection is now closed. This eliminates a race
1373 // where the HTTP response reading goroutine would
1374 // otherwise not observe the EOF until its next read,
1375 // by which time a client goroutine might have already
1376 // tried to reuse the HTTP connection for a new
1377 // request.
1378 // See https://codereview.appspot.com/76400046
1379 // and http://golang.org/issue/3514
1380 if ri := c.rawInput; ri != nil &&
1381 n != 0 && err == nil &&
1382 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1383 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1384 err = recErr // will be io.EOF on closeNotify
1385 }
1386 }
1387
1388 if n != 0 || err != nil {
1389 return n, err
1390 }
1391 }
1392
1393 return 0, io.ErrNoProgress
1394}
1395
1396// Close closes the connection.
1397func (c *Conn) Close() error {
1398 var alertErr error
1399
1400 c.handshakeMutex.Lock()
1401 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001402 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
David Benjaminfa214e42016-05-10 17:03:10 -04001403 alert := alertCloseNotify
1404 if c.config.Bugs.SendAlertOnShutdown != 0 {
1405 alert = c.config.Bugs.SendAlertOnShutdown
1406 }
1407 alertErr = c.sendAlert(alert)
David Benjamin4d559612016-05-18 14:31:51 -04001408 // Clear local alerts when sending alerts so we continue to wait
1409 // for the peer rather than closing the socket early.
1410 if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1411 alertErr = nil
1412 }
Adam Langley95c29f32014-06-20 12:00:00 -07001413 }
1414
David Benjamin30789da2015-08-29 22:56:45 -04001415 // Consume a close_notify from the peer if one hasn't been received
1416 // already. This avoids the peer from failing |SSL_shutdown| due to a
1417 // write failing.
1418 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1419 for c.in.error() == nil {
1420 c.readRecord(recordTypeAlert)
1421 }
1422 if c.in.error() != io.EOF {
1423 alertErr = c.in.error()
1424 }
1425 }
1426
Adam Langley95c29f32014-06-20 12:00:00 -07001427 if err := c.conn.Close(); err != nil {
1428 return err
1429 }
1430 return alertErr
1431}
1432
1433// Handshake runs the client or server handshake
1434// protocol if it has not yet been run.
1435// Most uses of this package need not call Handshake
1436// explicitly: the first Read or Write will call it automatically.
1437func (c *Conn) Handshake() error {
1438 c.handshakeMutex.Lock()
1439 defer c.handshakeMutex.Unlock()
1440 if err := c.handshakeErr; err != nil {
1441 return err
1442 }
1443 if c.handshakeComplete {
1444 return nil
1445 }
1446
David Benjamin9a41d1b2015-05-16 01:30:09 -04001447 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1448 c.conn.Write([]byte{
1449 byte(recordTypeAlert), // type
1450 0xfe, 0xff, // version
1451 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1452 0x0, 0x2, // length
1453 })
1454 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1455 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001456 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1457 c.writeRecord(recordTypeApplicationData, data)
1458 }
Adam Langley95c29f32014-06-20 12:00:00 -07001459 if c.isClient {
1460 c.handshakeErr = c.clientHandshake()
1461 } else {
1462 c.handshakeErr = c.serverHandshake()
1463 }
David Benjaminddb9f152015-02-03 15:44:39 -05001464 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1465 c.writeRecord(recordType(42), []byte("invalid record"))
1466 }
Adam Langley95c29f32014-06-20 12:00:00 -07001467 return c.handshakeErr
1468}
1469
1470// ConnectionState returns basic TLS details about the connection.
1471func (c *Conn) ConnectionState() ConnectionState {
1472 c.handshakeMutex.Lock()
1473 defer c.handshakeMutex.Unlock()
1474
1475 var state ConnectionState
1476 state.HandshakeComplete = c.handshakeComplete
1477 if c.handshakeComplete {
1478 state.Version = c.vers
1479 state.NegotiatedProtocol = c.clientProtocol
1480 state.DidResume = c.didResume
1481 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001482 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001483 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001484 state.PeerCertificates = c.peerCertificates
1485 state.VerifiedChains = c.verifiedChains
1486 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001487 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001488 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001489 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001490 state.SCTList = c.sctList
Nick Harper60edffd2016-06-21 15:19:24 -07001491 state.PeerSignatureAlgorithm = c.peerSignatureAlgorithm
Adam Langley95c29f32014-06-20 12:00:00 -07001492 }
1493
1494 return state
1495}
1496
1497// OCSPResponse returns the stapled OCSP response from the TLS server, if
1498// any. (Only valid for client connections.)
1499func (c *Conn) OCSPResponse() []byte {
1500 c.handshakeMutex.Lock()
1501 defer c.handshakeMutex.Unlock()
1502
1503 return c.ocspResponse
1504}
1505
1506// VerifyHostname checks that the peer certificate chain is valid for
1507// connecting to host. If so, it returns nil; if not, it returns an error
1508// describing the problem.
1509func (c *Conn) VerifyHostname(host string) error {
1510 c.handshakeMutex.Lock()
1511 defer c.handshakeMutex.Unlock()
1512 if !c.isClient {
1513 return errors.New("tls: VerifyHostname called on TLS server connection")
1514 }
1515 if !c.handshakeComplete {
1516 return errors.New("tls: handshake has not yet been performed")
1517 }
1518 return c.peerCertificates[0].VerifyHostname(host)
1519}
David Benjaminc565ebb2015-04-03 04:06:36 -04001520
1521// ExportKeyingMaterial exports keying material from the current connection
1522// state, as per RFC 5705.
1523func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1524 c.handshakeMutex.Lock()
1525 defer c.handshakeMutex.Unlock()
1526 if !c.handshakeComplete {
1527 return nil, errors.New("tls: handshake has not yet been performed")
1528 }
1529
David Benjamin97a0a082016-07-13 17:57:35 -04001530 if enableTLS13Handshake && c.vers >= VersionTLS13 {
1531 // TODO(davidben): What should we do with useContext? See
1532 // https://github.com/tlswg/tls13-spec/issues/546
1533 return hkdfExpandLabel(c.cipherSuite.hash(), c.exporterSecret, label, context, length), nil
1534 }
1535
David Benjaminc565ebb2015-04-03 04:06:36 -04001536 seedLen := len(c.clientRandom) + len(c.serverRandom)
1537 if useContext {
1538 seedLen += 2 + len(context)
1539 }
1540 seed := make([]byte, 0, seedLen)
1541 seed = append(seed, c.clientRandom[:]...)
1542 seed = append(seed, c.serverRandom[:]...)
1543 if useContext {
1544 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1545 seed = append(seed, context...)
1546 }
1547 result := make([]byte, length)
David Benjamin97a0a082016-07-13 17:57:35 -04001548 prfForVersion(c.vers, c.cipherSuite)(result, c.exporterSecret, label, seed)
David Benjaminc565ebb2015-04-03 04:06:36 -04001549 return result, nil
1550}
David Benjamin3e052de2015-11-25 20:10:31 -05001551
1552// noRenegotiationInfo returns true if the renegotiation info extension
1553// should be supported in the current handshake.
1554func (c *Conn) noRenegotiationInfo() bool {
1555 if c.config.Bugs.NoRenegotiationInfo {
1556 return true
1557 }
1558 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1559 return true
1560 }
1561 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1562 return true
1563 }
1564 return false
1565}