blob: 3e22465c2880640fda8db4d0f98cc3683a786231 [file] [log] [blame]
Adam Langley95c29f32014-06-20 12:00:00 -07001// Copyright 2010 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5// TLS low level connection and record layer
6
Adam Langleydc7e9c42015-09-29 15:21:04 -07007package runner
Adam Langley95c29f32014-06-20 12:00:00 -07008
9import (
10 "bytes"
11 "crypto/cipher"
David Benjamind30a9902014-08-24 01:44:23 -040012 "crypto/ecdsa"
Adam Langley95c29f32014-06-20 12:00:00 -070013 "crypto/subtle"
14 "crypto/x509"
David Benjamin8e6db492015-07-25 18:29:23 -040015 "encoding/binary"
Adam Langley95c29f32014-06-20 12:00:00 -070016 "errors"
17 "fmt"
18 "io"
19 "net"
20 "sync"
21 "time"
22)
23
David Benjamin053fee92017-01-02 08:30:36 -050024var errNoCertificateAlert = errors.New("tls: no certificate alert")
25
Adam Langley95c29f32014-06-20 12:00:00 -070026// A Conn represents a secured connection.
27// It implements the net.Conn interface.
28type Conn struct {
29 // constant
30 conn net.Conn
David Benjamin83c0bc92014-08-04 01:23:53 -040031 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -070032 isClient bool
33
34 // constant after handshake; protected by handshakeMutex
Adam Langley75712922014-10-10 16:23:43 -070035 handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
36 handshakeErr error // error resulting from handshake
37 vers uint16 // TLS version
38 haveVers bool // version has been negotiated
39 config *Config // configuration passed to constructor
40 handshakeComplete bool
41 didResume bool // whether this connection was a session resumption
42 extendedMasterSecret bool // whether this session used an extended master secret
David Benjaminc565ebb2015-04-03 04:06:36 -040043 cipherSuite *cipherSuite
Adam Langley75712922014-10-10 16:23:43 -070044 ocspResponse []byte // stapled OCSP response
Paul Lietar4fac72e2015-09-09 13:44:55 +010045 sctList []byte // signed certificate timestamp list
Adam Langley75712922014-10-10 16:23:43 -070046 peerCertificates []*x509.Certificate
Adam Langley95c29f32014-06-20 12:00:00 -070047 // verifiedChains contains the certificate chains that we built, as
48 // opposed to the ones presented by the server.
49 verifiedChains [][]*x509.Certificate
50 // serverName contains the server name indicated by the client, if any.
Adam Langleyaf0e32c2015-06-03 09:57:23 -070051 serverName string
52 // firstFinished contains the first Finished hash sent during the
53 // handshake. This is the "tls-unique" channel binding value.
54 firstFinished [12]byte
Nick Harper60edffd2016-06-21 15:19:24 -070055 // peerSignatureAlgorithm contains the signature algorithm that was used
56 // by the peer in the handshake, or zero if not applicable.
57 peerSignatureAlgorithm signatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -040058 // curveID contains the curve that was used in the handshake, or zero if
59 // not applicable.
60 curveID CurveID
Adam Langleyaf0e32c2015-06-03 09:57:23 -070061
David Benjaminc565ebb2015-04-03 04:06:36 -040062 clientRandom, serverRandom [32]byte
David Benjamin97a0a082016-07-13 17:57:35 -040063 exporterSecret []byte
David Benjamin58104882016-07-18 01:25:41 +020064 resumptionSecret []byte
Adam Langley95c29f32014-06-20 12:00:00 -070065
66 clientProtocol string
67 clientProtocolFallback bool
David Benjaminfc7b0862014-09-06 13:21:53 -040068 usedALPN bool
Adam Langley95c29f32014-06-20 12:00:00 -070069
Adam Langley2ae77d22014-10-28 17:29:33 -070070 // verify_data values for the renegotiation extension.
71 clientVerify []byte
72 serverVerify []byte
73
David Benjamind30a9902014-08-24 01:44:23 -040074 channelID *ecdsa.PublicKey
75
David Benjaminca6c8262014-11-15 19:06:08 -050076 srtpProtectionProfile uint16
77
David Benjaminc44b1df2014-11-23 12:11:01 -050078 clientVersion uint16
79
Adam Langley95c29f32014-06-20 12:00:00 -070080 // input/output
81 in, out halfConn // in.Mutex < out.Mutex
82 rawInput *block // raw input, right off the wire
David Benjamin83c0bc92014-08-04 01:23:53 -040083 input *block // application record waiting to be read
84 hand bytes.Buffer // handshake record waiting to be read
85
David Benjamin582ba042016-07-07 12:33:25 -070086 // pendingFlight, if PackHandshakeFlight is enabled, is the buffer of
87 // handshake data to be split into records at the end of the flight.
88 pendingFlight bytes.Buffer
89
David Benjamin83c0bc92014-08-04 01:23:53 -040090 // DTLS state
91 sendHandshakeSeq uint16
92 recvHandshakeSeq uint16
David Benjaminb3774b92015-01-31 17:16:01 -050093 handMsg []byte // pending assembled handshake message
94 handMsgLen int // handshake message length, not including the header
95 pendingFragments [][]byte // pending outgoing handshake fragments.
Adam Langley95c29f32014-06-20 12:00:00 -070096
Steven Valdezc4aa7272016-10-03 12:25:56 -040097 keyUpdateRequested bool
98
Adam Langley95c29f32014-06-20 12:00:00 -070099 tmp [16]byte
100}
101
David Benjamin5e961c12014-11-07 01:48:35 -0500102func (c *Conn) init() {
103 c.in.isDTLS = c.isDTLS
104 c.out.isDTLS = c.isDTLS
105 c.in.config = c.config
106 c.out.config = c.config
David Benjamin8e6db492015-07-25 18:29:23 -0400107
108 c.out.updateOutSeq()
David Benjamin5e961c12014-11-07 01:48:35 -0500109}
110
Adam Langley95c29f32014-06-20 12:00:00 -0700111// Access to net.Conn methods.
112// Cannot just embed net.Conn because that would
113// export the struct field too.
114
115// LocalAddr returns the local network address.
116func (c *Conn) LocalAddr() net.Addr {
117 return c.conn.LocalAddr()
118}
119
120// RemoteAddr returns the remote network address.
121func (c *Conn) RemoteAddr() net.Addr {
122 return c.conn.RemoteAddr()
123}
124
125// SetDeadline sets the read and write deadlines associated with the connection.
126// A zero value for t means Read and Write will not time out.
127// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
128func (c *Conn) SetDeadline(t time.Time) error {
129 return c.conn.SetDeadline(t)
130}
131
132// SetReadDeadline sets the read deadline on the underlying connection.
133// A zero value for t means Read will not time out.
134func (c *Conn) SetReadDeadline(t time.Time) error {
135 return c.conn.SetReadDeadline(t)
136}
137
138// SetWriteDeadline sets the write deadline on the underlying conneciton.
139// A zero value for t means Write will not time out.
140// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
141func (c *Conn) SetWriteDeadline(t time.Time) error {
142 return c.conn.SetWriteDeadline(t)
143}
144
145// A halfConn represents one direction of the record layer
146// connection, either sending or receiving.
147type halfConn struct {
148 sync.Mutex
149
David Benjamin83c0bc92014-08-04 01:23:53 -0400150 err error // first permanent error
151 version uint16 // protocol version
152 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -0700153 cipher interface{} // cipher algorithm
154 mac macFunction
155 seq [8]byte // 64-bit sequence number
David Benjamin8e6db492015-07-25 18:29:23 -0400156 outSeq [8]byte // Mapped sequence number
Adam Langley95c29f32014-06-20 12:00:00 -0700157 bfree *block // list of free blocks
158
159 nextCipher interface{} // next encryption state
160 nextMac macFunction // next MAC algorithm
David Benjamin83f90402015-01-27 01:09:43 -0500161 nextSeq [6]byte // next epoch's starting sequence number in DTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700162
163 // used to save allocating a new buffer for each MAC.
164 inDigestBuf, outDigestBuf []byte
Adam Langley80842bd2014-06-20 12:00:00 -0700165
Steven Valdezc4aa7272016-10-03 12:25:56 -0400166 trafficSecret []byte
David Benjamin21c00282016-07-18 21:56:23 +0200167
David Benjamin6f600d62016-12-21 16:06:54 -0500168 shortHeader bool
169
Adam Langley80842bd2014-06-20 12:00:00 -0700170 config *Config
Adam Langley95c29f32014-06-20 12:00:00 -0700171}
172
173func (hc *halfConn) setErrorLocked(err error) error {
174 hc.err = err
175 return err
176}
177
178func (hc *halfConn) error() error {
Adam Langley2ae77d22014-10-28 17:29:33 -0700179 // This should be locked, but I've removed it for the renegotiation
180 // tests since we don't concurrently read and write the same tls.Conn
181 // in any case during testing.
Adam Langley95c29f32014-06-20 12:00:00 -0700182 err := hc.err
Adam Langley95c29f32014-06-20 12:00:00 -0700183 return err
184}
185
186// prepareCipherSpec sets the encryption and MAC states
187// that a subsequent changeCipherSpec will use.
188func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
189 hc.version = version
190 hc.nextCipher = cipher
191 hc.nextMac = mac
192}
193
194// changeCipherSpec changes the encryption and MAC states
195// to the ones previously passed to prepareCipherSpec.
Adam Langley80842bd2014-06-20 12:00:00 -0700196func (hc *halfConn) changeCipherSpec(config *Config) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700197 if hc.nextCipher == nil {
198 return alertInternalError
199 }
200 hc.cipher = hc.nextCipher
201 hc.mac = hc.nextMac
202 hc.nextCipher = nil
203 hc.nextMac = nil
Adam Langley80842bd2014-06-20 12:00:00 -0700204 hc.config = config
David Benjamin83c0bc92014-08-04 01:23:53 -0400205 hc.incEpoch()
David Benjaminf2b83632016-03-01 22:57:46 -0500206
207 if config.Bugs.NullAllCiphers {
David Benjamin7a4aaa42016-09-20 17:58:14 -0400208 hc.cipher = nullCipher{}
David Benjaminf2b83632016-03-01 22:57:46 -0500209 hc.mac = nil
210 }
Adam Langley95c29f32014-06-20 12:00:00 -0700211 return nil
212}
213
David Benjamin21c00282016-07-18 21:56:23 +0200214// useTrafficSecret sets the current cipher state for TLS 1.3.
Steven Valdeza833c352016-11-01 13:39:36 -0400215func (hc *halfConn) useTrafficSecret(version uint16, suite *cipherSuite, secret []byte, side trafficDirection) {
Nick Harperb41d2e42016-07-01 17:50:32 -0400216 hc.version = version
Steven Valdeza833c352016-11-01 13:39:36 -0400217 hc.cipher = deriveTrafficAEAD(version, suite, secret, side)
David Benjamin7a4aaa42016-09-20 17:58:14 -0400218 if hc.config.Bugs.NullAllCiphers {
219 hc.cipher = nullCipher{}
220 }
David Benjamin21c00282016-07-18 21:56:23 +0200221 hc.trafficSecret = secret
Nick Harperb41d2e42016-07-01 17:50:32 -0400222 hc.incEpoch()
223}
224
David Benjamin21c00282016-07-18 21:56:23 +0200225func (hc *halfConn) doKeyUpdate(c *Conn, isOutgoing bool) {
226 side := serverWrite
227 if c.isClient == isOutgoing {
228 side = clientWrite
229 }
Steven Valdeza833c352016-11-01 13:39:36 -0400230 hc.useTrafficSecret(hc.version, c.cipherSuite, updateTrafficSecret(c.cipherSuite.hash(), hc.trafficSecret), side)
David Benjamin21c00282016-07-18 21:56:23 +0200231}
232
Adam Langley95c29f32014-06-20 12:00:00 -0700233// incSeq increments the sequence number.
David Benjamin5e961c12014-11-07 01:48:35 -0500234func (hc *halfConn) incSeq(isOutgoing bool) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400235 limit := 0
David Benjamin5e961c12014-11-07 01:48:35 -0500236 increment := uint64(1)
David Benjamin83c0bc92014-08-04 01:23:53 -0400237 if hc.isDTLS {
238 // Increment up to the epoch in DTLS.
239 limit = 2
240 }
241 for i := 7; i >= limit; i-- {
David Benjamin5e961c12014-11-07 01:48:35 -0500242 increment += uint64(hc.seq[i])
243 hc.seq[i] = byte(increment)
244 increment >>= 8
Adam Langley95c29f32014-06-20 12:00:00 -0700245 }
246
247 // Not allowed to let sequence number wrap.
248 // Instead, must renegotiate before it does.
249 // Not likely enough to bother.
David Benjamin5e961c12014-11-07 01:48:35 -0500250 if increment != 0 {
251 panic("TLS: sequence number wraparound")
252 }
David Benjamin8e6db492015-07-25 18:29:23 -0400253
254 hc.updateOutSeq()
Adam Langley95c29f32014-06-20 12:00:00 -0700255}
256
David Benjamin83f90402015-01-27 01:09:43 -0500257// incNextSeq increments the starting sequence number for the next epoch.
258func (hc *halfConn) incNextSeq() {
259 for i := len(hc.nextSeq) - 1; i >= 0; i-- {
260 hc.nextSeq[i]++
261 if hc.nextSeq[i] != 0 {
262 return
263 }
264 }
265 panic("TLS: sequence number wraparound")
266}
267
268// incEpoch resets the sequence number. In DTLS, it also increments the epoch
269// half of the sequence number.
David Benjamin83c0bc92014-08-04 01:23:53 -0400270func (hc *halfConn) incEpoch() {
David Benjamin83c0bc92014-08-04 01:23:53 -0400271 if hc.isDTLS {
272 for i := 1; i >= 0; i-- {
273 hc.seq[i]++
274 if hc.seq[i] != 0 {
275 break
276 }
277 if i == 0 {
278 panic("TLS: epoch number wraparound")
279 }
280 }
David Benjamin83f90402015-01-27 01:09:43 -0500281 copy(hc.seq[2:], hc.nextSeq[:])
282 for i := range hc.nextSeq {
283 hc.nextSeq[i] = 0
284 }
285 } else {
286 for i := range hc.seq {
287 hc.seq[i] = 0
288 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400289 }
David Benjamin8e6db492015-07-25 18:29:23 -0400290
291 hc.updateOutSeq()
292}
293
294func (hc *halfConn) updateOutSeq() {
295 if hc.config.Bugs.SequenceNumberMapping != nil {
296 seqU64 := binary.BigEndian.Uint64(hc.seq[:])
297 seqU64 = hc.config.Bugs.SequenceNumberMapping(seqU64)
298 binary.BigEndian.PutUint64(hc.outSeq[:], seqU64)
299
300 // The DTLS epoch cannot be changed.
301 copy(hc.outSeq[:2], hc.seq[:2])
302 return
303 }
304
305 copy(hc.outSeq[:], hc.seq[:])
David Benjamin83c0bc92014-08-04 01:23:53 -0400306}
307
David Benjamin6f600d62016-12-21 16:06:54 -0500308func (hc *halfConn) isShortHeader() bool {
309 return hc.shortHeader && hc.cipher != nil
310}
311
David Benjamin83c0bc92014-08-04 01:23:53 -0400312func (hc *halfConn) recordHeaderLen() int {
313 if hc.isDTLS {
314 return dtlsRecordHeaderLen
315 }
David Benjamin6f600d62016-12-21 16:06:54 -0500316 if hc.isShortHeader() {
317 return 2
318 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400319 return tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700320}
321
322// removePadding returns an unpadded slice, in constant time, which is a prefix
323// of the input. It also returns a byte which is equal to 255 if the padding
324// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
325func removePadding(payload []byte) ([]byte, byte) {
326 if len(payload) < 1 {
327 return payload, 0
328 }
329
330 paddingLen := payload[len(payload)-1]
331 t := uint(len(payload)-1) - uint(paddingLen)
332 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
333 good := byte(int32(^t) >> 31)
334
335 toCheck := 255 // the maximum possible padding length
336 // The length of the padded data is public, so we can use an if here
337 if toCheck+1 > len(payload) {
338 toCheck = len(payload) - 1
339 }
340
341 for i := 0; i < toCheck; i++ {
342 t := uint(paddingLen) - uint(i)
343 // if i <= paddingLen then the MSB of t is zero
344 mask := byte(int32(^t) >> 31)
345 b := payload[len(payload)-1-i]
346 good &^= mask&paddingLen ^ mask&b
347 }
348
349 // We AND together the bits of good and replicate the result across
350 // all the bits.
351 good &= good << 4
352 good &= good << 2
353 good &= good << 1
354 good = uint8(int8(good) >> 7)
355
356 toRemove := good&paddingLen + 1
357 return payload[:len(payload)-int(toRemove)], good
358}
359
360// removePaddingSSL30 is a replacement for removePadding in the case that the
361// protocol version is SSLv3. In this version, the contents of the padding
362// are random and cannot be checked.
363func removePaddingSSL30(payload []byte) ([]byte, byte) {
364 if len(payload) < 1 {
365 return payload, 0
366 }
367
368 paddingLen := int(payload[len(payload)-1]) + 1
369 if paddingLen > len(payload) {
370 return payload, 0
371 }
372
373 return payload[:len(payload)-paddingLen], 255
374}
375
376func roundUp(a, b int) int {
377 return a + (b-a%b)%b
378}
379
380// cbcMode is an interface for block ciphers using cipher block chaining.
381type cbcMode interface {
382 cipher.BlockMode
383 SetIV([]byte)
384}
385
386// decrypt checks and strips the mac and decrypts the data in b. Returns a
387// success boolean, the number of bytes to skip from the start of the record in
Nick Harper1fd39d82016-06-14 18:14:35 -0700388// order to get the application payload, the encrypted record type (or 0
389// if there is none), and an optional alert value.
390func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, contentType recordType, alertValue alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400391 recordHeaderLen := hc.recordHeaderLen()
392
Adam Langley95c29f32014-06-20 12:00:00 -0700393 // pull out payload
394 payload := b.data[recordHeaderLen:]
395
396 macSize := 0
397 if hc.mac != nil {
398 macSize = hc.mac.Size()
399 }
400
401 paddingGood := byte(255)
402 explicitIVLen := 0
403
David Benjamin83c0bc92014-08-04 01:23:53 -0400404 seq := hc.seq[:]
405 if hc.isDTLS {
406 // DTLS sequence numbers are explicit.
407 seq = b.data[3:11]
408 }
409
Adam Langley95c29f32014-06-20 12:00:00 -0700410 // decrypt
411 if hc.cipher != nil {
412 switch c := hc.cipher.(type) {
413 case cipher.Stream:
414 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400415 case *tlsAead:
416 nonce := seq
417 if c.explicitNonce {
418 explicitIVLen = 8
419 if len(payload) < explicitIVLen {
Nick Harper1fd39d82016-06-14 18:14:35 -0700420 return false, 0, 0, alertBadRecordMAC
David Benjamine9a80ff2015-04-07 00:46:46 -0400421 }
422 nonce = payload[:8]
423 payload = payload[8:]
Adam Langley95c29f32014-06-20 12:00:00 -0700424 }
Adam Langley95c29f32014-06-20 12:00:00 -0700425
Nick Harper1fd39d82016-06-14 18:14:35 -0700426 var additionalData []byte
427 if hc.version < VersionTLS13 {
428 additionalData = make([]byte, 13)
429 copy(additionalData, seq)
430 copy(additionalData[8:], b.data[:3])
431 n := len(payload) - c.Overhead()
432 additionalData[11] = byte(n >> 8)
433 additionalData[12] = byte(n)
434 }
Adam Langley95c29f32014-06-20 12:00:00 -0700435 var err error
Nick Harper1fd39d82016-06-14 18:14:35 -0700436 payload, err = c.Open(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700437 if err != nil {
Nick Harper1fd39d82016-06-14 18:14:35 -0700438 return false, 0, 0, alertBadRecordMAC
439 }
Adam Langley95c29f32014-06-20 12:00:00 -0700440 b.resize(recordHeaderLen + explicitIVLen + len(payload))
441 case cbcMode:
442 blockSize := c.BlockSize()
David Benjamin83c0bc92014-08-04 01:23:53 -0400443 if hc.version >= VersionTLS11 || hc.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700444 explicitIVLen = blockSize
445 }
446
447 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
Nick Harper1fd39d82016-06-14 18:14:35 -0700448 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700449 }
450
451 if explicitIVLen > 0 {
452 c.SetIV(payload[:explicitIVLen])
453 payload = payload[explicitIVLen:]
454 }
455 c.CryptBlocks(payload, payload)
456 if hc.version == VersionSSL30 {
457 payload, paddingGood = removePaddingSSL30(payload)
458 } else {
459 payload, paddingGood = removePadding(payload)
460 }
461 b.resize(recordHeaderLen + explicitIVLen + len(payload))
462
463 // note that we still have a timing side-channel in the
464 // MAC check, below. An attacker can align the record
465 // so that a correct padding will cause one less hash
466 // block to be calculated. Then they can iteratively
467 // decrypt a record by breaking each byte. See
468 // "Password Interception in a SSL/TLS Channel", Brice
469 // Canvel et al.
470 //
471 // However, our behavior matches OpenSSL, so we leak
472 // only as much as they do.
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700473 case nullCipher:
474 break
Adam Langley95c29f32014-06-20 12:00:00 -0700475 default:
476 panic("unknown cipher type")
477 }
David Benjamin7a4aaa42016-09-20 17:58:14 -0400478
479 if hc.version >= VersionTLS13 {
480 i := len(payload)
481 for i > 0 && payload[i-1] == 0 {
482 i--
483 }
484 payload = payload[:i]
485 if len(payload) == 0 {
486 return false, 0, 0, alertUnexpectedMessage
487 }
488 contentType = recordType(payload[len(payload)-1])
489 payload = payload[:len(payload)-1]
490 b.resize(recordHeaderLen + len(payload))
491 }
Adam Langley95c29f32014-06-20 12:00:00 -0700492 }
493
494 // check, strip mac
495 if hc.mac != nil {
496 if len(payload) < macSize {
Nick Harper1fd39d82016-06-14 18:14:35 -0700497 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700498 }
499
500 // strip mac off payload, b.data
501 n := len(payload) - macSize
David Benjamin83c0bc92014-08-04 01:23:53 -0400502 b.data[recordHeaderLen-2] = byte(n >> 8)
503 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700504 b.resize(recordHeaderLen + explicitIVLen + n)
505 remoteMAC := payload[n:]
David Benjamin83c0bc92014-08-04 01:23:53 -0400506 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
Adam Langley95c29f32014-06-20 12:00:00 -0700507
508 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
Nick Harper1fd39d82016-06-14 18:14:35 -0700509 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700510 }
511 hc.inDigestBuf = localMAC
512 }
David Benjamin5e961c12014-11-07 01:48:35 -0500513 hc.incSeq(false)
Adam Langley95c29f32014-06-20 12:00:00 -0700514
Nick Harper1fd39d82016-06-14 18:14:35 -0700515 return true, recordHeaderLen + explicitIVLen, contentType, 0
Adam Langley95c29f32014-06-20 12:00:00 -0700516}
517
518// padToBlockSize calculates the needed padding block, if any, for a payload.
519// On exit, prefix aliases payload and extends to the end of the last full
520// block of payload. finalBlock is a fresh slice which contains the contents of
521// any suffix of payload as well as the needed padding to make finalBlock a
522// full block.
Adam Langley80842bd2014-06-20 12:00:00 -0700523func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
Adam Langley95c29f32014-06-20 12:00:00 -0700524 overrun := len(payload) % blockSize
Adam Langley95c29f32014-06-20 12:00:00 -0700525 prefix = payload[:len(payload)-overrun]
Adam Langley80842bd2014-06-20 12:00:00 -0700526
527 paddingLen := blockSize - overrun
528 finalSize := blockSize
529 if config.Bugs.MaxPadding {
530 for paddingLen+blockSize <= 256 {
531 paddingLen += blockSize
532 }
533 finalSize = 256
534 }
535 finalBlock = make([]byte, finalSize)
536 for i := range finalBlock {
Adam Langley95c29f32014-06-20 12:00:00 -0700537 finalBlock[i] = byte(paddingLen - 1)
538 }
Adam Langley80842bd2014-06-20 12:00:00 -0700539 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
540 finalBlock[overrun] ^= 0xff
541 }
542 copy(finalBlock, payload[len(payload)-overrun:])
Adam Langley95c29f32014-06-20 12:00:00 -0700543 return
544}
545
546// encrypt encrypts and macs the data in b.
Nick Harper1fd39d82016-06-14 18:14:35 -0700547func (hc *halfConn) encrypt(b *block, explicitIVLen int, typ recordType) (bool, alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400548 recordHeaderLen := hc.recordHeaderLen()
549
Adam Langley95c29f32014-06-20 12:00:00 -0700550 // mac
551 if hc.mac != nil {
David Benjamin8e6db492015-07-25 18:29:23 -0400552 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 -0700553
554 n := len(b.data)
555 b.resize(n + len(mac))
556 copy(b.data[n:], mac)
557 hc.outDigestBuf = mac
558 }
559
560 payload := b.data[recordHeaderLen:]
561
562 // encrypt
563 if hc.cipher != nil {
David Benjamin7a4aaa42016-09-20 17:58:14 -0400564 // Add TLS 1.3 padding.
565 if hc.version >= VersionTLS13 {
566 paddingLen := hc.config.Bugs.RecordPadding
567 if hc.config.Bugs.OmitRecordContents {
568 b.resize(recordHeaderLen + paddingLen)
569 } else {
570 b.resize(len(b.data) + 1 + paddingLen)
571 b.data[len(b.data)-paddingLen-1] = byte(typ)
572 }
573 for i := 0; i < paddingLen; i++ {
574 b.data[len(b.data)-paddingLen+i] = 0
575 }
576 }
577
Adam Langley95c29f32014-06-20 12:00:00 -0700578 switch c := hc.cipher.(type) {
579 case cipher.Stream:
580 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400581 case *tlsAead:
Adam Langley95c29f32014-06-20 12:00:00 -0700582 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
David Benjamin7a4aaa42016-09-20 17:58:14 -0400583 b.resize(len(b.data) + c.Overhead())
David Benjamin8e6db492015-07-25 18:29:23 -0400584 nonce := hc.outSeq[:]
David Benjamine9a80ff2015-04-07 00:46:46 -0400585 if c.explicitNonce {
586 nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
587 }
Adam Langley95c29f32014-06-20 12:00:00 -0700588 payload := b.data[recordHeaderLen+explicitIVLen:]
589 payload = payload[:payloadLen]
590
Nick Harper1fd39d82016-06-14 18:14:35 -0700591 var additionalData []byte
592 if hc.version < VersionTLS13 {
593 additionalData = make([]byte, 13)
594 copy(additionalData, hc.outSeq[:])
595 copy(additionalData[8:], b.data[:3])
596 additionalData[11] = byte(payloadLen >> 8)
597 additionalData[12] = byte(payloadLen)
598 }
Adam Langley95c29f32014-06-20 12:00:00 -0700599
Nick Harper1fd39d82016-06-14 18:14:35 -0700600 c.Seal(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700601 case cbcMode:
602 blockSize := c.BlockSize()
603 if explicitIVLen > 0 {
604 c.SetIV(payload[:explicitIVLen])
605 payload = payload[explicitIVLen:]
606 }
Adam Langley80842bd2014-06-20 12:00:00 -0700607 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700608 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
609 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
610 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700611 case nullCipher:
612 break
Adam Langley95c29f32014-06-20 12:00:00 -0700613 default:
614 panic("unknown cipher type")
615 }
616 }
617
618 // update length to include MAC and any block padding needed.
619 n := len(b.data) - recordHeaderLen
David Benjamin83c0bc92014-08-04 01:23:53 -0400620 b.data[recordHeaderLen-2] = byte(n >> 8)
621 b.data[recordHeaderLen-1] = byte(n)
David Benjamin6f600d62016-12-21 16:06:54 -0500622 if hc.isShortHeader() && !hc.config.Bugs.ClearShortHeaderBit {
623 b.data[0] |= 0x80
624 }
David Benjamin5e961c12014-11-07 01:48:35 -0500625 hc.incSeq(true)
Adam Langley95c29f32014-06-20 12:00:00 -0700626
627 return true, 0
628}
629
630// A block is a simple data buffer.
631type block struct {
632 data []byte
633 off int // index for Read
634 link *block
635}
636
637// resize resizes block to be n bytes, growing if necessary.
638func (b *block) resize(n int) {
639 if n > cap(b.data) {
640 b.reserve(n)
641 }
642 b.data = b.data[0:n]
643}
644
645// reserve makes sure that block contains a capacity of at least n bytes.
646func (b *block) reserve(n int) {
647 if cap(b.data) >= n {
648 return
649 }
650 m := cap(b.data)
651 if m == 0 {
652 m = 1024
653 }
654 for m < n {
655 m *= 2
656 }
657 data := make([]byte, len(b.data), m)
658 copy(data, b.data)
659 b.data = data
660}
661
662// readFromUntil reads from r into b until b contains at least n bytes
663// or else returns an error.
664func (b *block) readFromUntil(r io.Reader, n int) error {
665 // quick case
666 if len(b.data) >= n {
667 return nil
668 }
669
670 // read until have enough.
671 b.reserve(n)
672 for {
673 m, err := r.Read(b.data[len(b.data):cap(b.data)])
674 b.data = b.data[0 : len(b.data)+m]
675 if len(b.data) >= n {
676 // TODO(bradfitz,agl): slightly suspicious
677 // that we're throwing away r.Read's err here.
678 break
679 }
680 if err != nil {
681 return err
682 }
683 }
684 return nil
685}
686
687func (b *block) Read(p []byte) (n int, err error) {
688 n = copy(p, b.data[b.off:])
689 b.off += n
690 return
691}
692
693// newBlock allocates a new block, from hc's free list if possible.
694func (hc *halfConn) newBlock() *block {
695 b := hc.bfree
696 if b == nil {
697 return new(block)
698 }
699 hc.bfree = b.link
700 b.link = nil
701 b.resize(0)
702 return b
703}
704
705// freeBlock returns a block to hc's free list.
706// The protocol is such that each side only has a block or two on
707// its free list at a time, so there's no need to worry about
708// trimming the list, etc.
709func (hc *halfConn) freeBlock(b *block) {
710 b.link = hc.bfree
711 hc.bfree = b
712}
713
714// splitBlock splits a block after the first n bytes,
715// returning a block with those n bytes and a
716// block with the remainder. the latter may be nil.
717func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
718 if len(b.data) <= n {
719 return b, nil
720 }
721 bb := hc.newBlock()
722 bb.resize(len(b.data) - n)
723 copy(bb.data, b.data[n:])
724 b.data = b.data[0:n]
725 return b, bb
726}
727
David Benjamin83c0bc92014-08-04 01:23:53 -0400728func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
729 if c.isDTLS {
730 return c.dtlsDoReadRecord(want)
731 }
732
David Benjamin6f600d62016-12-21 16:06:54 -0500733 recordHeaderLen := c.in.recordHeaderLen()
David Benjamin83c0bc92014-08-04 01:23:53 -0400734
735 if c.rawInput == nil {
736 c.rawInput = c.in.newBlock()
737 }
738 b := c.rawInput
739
740 // Read header, payload.
741 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
742 // RFC suggests that EOF without an alertCloseNotify is
743 // an error, but popular web sites seem to do this,
David Benjamin30789da2015-08-29 22:56:45 -0400744 // so we can't make it an error, outside of tests.
745 if err == io.EOF && c.config.Bugs.ExpectCloseNotify {
746 err = io.ErrUnexpectedEOF
747 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400748 if e, ok := err.(net.Error); !ok || !e.Temporary() {
749 c.in.setErrorLocked(err)
750 }
751 return 0, nil, err
752 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400753
David Benjamin6f600d62016-12-21 16:06:54 -0500754 var typ recordType
755 var vers uint16
756 var n int
757 if c.in.isShortHeader() {
758 typ = recordTypeApplicationData
759 vers = VersionTLS10
760 n = int(b.data[0])<<8 | int(b.data[1])
761 if n&0x8000 == 0 {
762 c.sendAlert(alertDecodeError)
763 return 0, nil, c.in.setErrorLocked(errors.New("tls: length did not have high bit set"))
764 }
765
766 n = n & 0x7fff
767 } else {
768 typ = recordType(b.data[0])
769
770 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
771 // start with a uint16 length where the MSB is set and the first record
772 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
773 // an SSLv2 client.
774 if want == recordTypeHandshake && typ == 0x80 {
775 c.sendAlert(alertProtocolVersion)
776 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
777 }
778
779 vers = uint16(b.data[1])<<8 | uint16(b.data[2])
780 n = int(b.data[3])<<8 | int(b.data[4])
David Benjamin83c0bc92014-08-04 01:23:53 -0400781 }
782
David Benjaminbde00392016-06-21 12:19:28 -0400783 // Alerts sent near version negotiation do not have a well-defined
784 // record-layer version prior to TLS 1.3. (In TLS 1.3, the record-layer
785 // version is irrelevant.)
786 if typ != recordTypeAlert {
David Benjamine6f22212016-11-08 14:28:24 -0500787 var expect uint16
David Benjaminbde00392016-06-21 12:19:28 -0400788 if c.haveVers {
David Benjamine6f22212016-11-08 14:28:24 -0500789 expect = c.vers
790 if c.vers >= VersionTLS13 {
791 expect = VersionTLS10
David Benjaminbde00392016-06-21 12:19:28 -0400792 }
793 } else {
David Benjamine6f22212016-11-08 14:28:24 -0500794 expect = c.config.Bugs.ExpectInitialRecordVersion
795 }
796 if expect != 0 && vers != expect {
797 c.sendAlert(alertProtocolVersion)
798 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
David Benjamin1e29a6b2014-12-10 02:27:24 -0500799 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400800 }
801 if n > maxCiphertext {
802 c.sendAlert(alertRecordOverflow)
803 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
804 }
805 if !c.haveVers {
806 // First message, be extra suspicious:
807 // this might not be a TLS client.
808 // Bail out before reading a full 'body', if possible.
809 // The current max version is 3.1.
810 // If the version is >= 16.0, it's probably not real.
811 // Similarly, a clientHello message encodes in
812 // well under a kilobyte. If the length is >= 12 kB,
813 // it's probably not real.
814 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
815 c.sendAlert(alertUnexpectedMessage)
816 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
817 }
818 }
819 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
820 if err == io.EOF {
821 err = io.ErrUnexpectedEOF
822 }
823 if e, ok := err.(net.Error); !ok || !e.Temporary() {
824 c.in.setErrorLocked(err)
825 }
826 return 0, nil, err
827 }
828
829 // Process message.
830 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
David Benjaminff26f092016-07-01 16:13:42 -0400831 ok, off, encTyp, alertValue := c.in.decrypt(b)
832 if !ok {
833 return 0, nil, c.in.setErrorLocked(c.sendAlert(alertValue))
834 }
835 b.off = off
836
Nick Harper1fd39d82016-06-14 18:14:35 -0700837 if c.vers >= VersionTLS13 && c.in.cipher != nil {
David Benjaminc9ae27c2016-06-24 22:56:37 -0400838 if typ != recordTypeApplicationData {
839 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: outer record type is not application data"))
840 }
Nick Harper1fd39d82016-06-14 18:14:35 -0700841 typ = encTyp
842 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400843 return typ, b, nil
844}
845
Adam Langley95c29f32014-06-20 12:00:00 -0700846// readRecord reads the next TLS record from the connection
847// and updates the record layer state.
848// c.in.Mutex <= L; c.input == nil.
849func (c *Conn) readRecord(want recordType) error {
850 // Caller must be in sync with connection:
851 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700852 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700853 switch want {
854 default:
855 c.sendAlert(alertInternalError)
856 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
857 case recordTypeHandshake, recordTypeChangeCipherSpec:
858 if c.handshakeComplete {
859 c.sendAlert(alertInternalError)
860 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
861 }
862 case recordTypeApplicationData:
David Benjamine58c4f52014-08-24 03:47:07 -0400863 if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart {
Adam Langley95c29f32014-06-20 12:00:00 -0700864 c.sendAlert(alertInternalError)
865 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
866 }
David Benjamin30789da2015-08-29 22:56:45 -0400867 case recordTypeAlert:
868 // Looking for a close_notify. Note: unlike a real
869 // implementation, this is not tolerant of additional records.
870 // See the documentation for ExpectCloseNotify.
Adam Langley95c29f32014-06-20 12:00:00 -0700871 }
872
873Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400874 typ, b, err := c.doReadRecord(want)
875 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700876 return err
877 }
Adam Langley95c29f32014-06-20 12:00:00 -0700878 data := b.data[b.off:]
879 if len(data) > maxPlaintext {
880 err := c.sendAlert(alertRecordOverflow)
881 c.in.freeBlock(b)
882 return c.in.setErrorLocked(err)
883 }
884
885 switch typ {
886 default:
887 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
888
889 case recordTypeAlert:
890 if len(data) != 2 {
891 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
892 break
893 }
894 if alert(data[1]) == alertCloseNotify {
895 c.in.setErrorLocked(io.EOF)
896 break
897 }
898 switch data[0] {
899 case alertLevelWarning:
David Benjamin053fee92017-01-02 08:30:36 -0500900 if alert(data[1]) == alertNoCertificate {
901 c.in.freeBlock(b)
902 return errNoCertificateAlert
903 }
904
Adam Langley95c29f32014-06-20 12:00:00 -0700905 // drop on the floor
906 c.in.freeBlock(b)
907 goto Again
908 case alertLevelError:
909 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
910 default:
911 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
912 }
913
914 case recordTypeChangeCipherSpec:
915 if typ != want || len(data) != 1 || data[0] != 1 {
916 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
917 break
918 }
Adam Langley80842bd2014-06-20 12:00:00 -0700919 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700920 if err != nil {
921 c.in.setErrorLocked(c.sendAlert(err.(alert)))
922 }
923
924 case recordTypeApplicationData:
925 if typ != want {
926 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
927 break
928 }
929 c.input = b
930 b = nil
931
932 case recordTypeHandshake:
David Benjamind5a4ecb2016-07-18 01:17:13 +0200933 // Allow handshake data while reading application data to
934 // trigger post-handshake messages.
Adam Langley95c29f32014-06-20 12:00:00 -0700935 // TODO(rsc): Should at least pick off connection close.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200936 if typ != want && want != recordTypeApplicationData {
937 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
Adam Langley95c29f32014-06-20 12:00:00 -0700938 }
939 c.hand.Write(data)
940 }
941
942 if b != nil {
943 c.in.freeBlock(b)
944 }
945 return c.in.err
946}
947
948// sendAlert sends a TLS alert message.
949// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400950func (c *Conn) sendAlertLocked(level byte, err alert) error {
951 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700952 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400953 if c.config.Bugs.FragmentAlert {
954 c.writeRecord(recordTypeAlert, c.tmp[0:1])
955 c.writeRecord(recordTypeAlert, c.tmp[1:2])
David Benjamin0d3a8c62016-03-11 22:25:18 -0500956 } else if c.config.Bugs.DoubleAlert {
957 copy(c.tmp[2:4], c.tmp[0:2])
958 c.writeRecord(recordTypeAlert, c.tmp[0:4])
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400959 } else {
960 c.writeRecord(recordTypeAlert, c.tmp[0:2])
961 }
David Benjamin24f346d2015-06-06 03:28:08 -0400962 // Error alerts are fatal to the connection.
963 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700964 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
965 }
966 return nil
967}
968
969// sendAlert sends a TLS alert message.
970// L < c.out.Mutex.
971func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400972 level := byte(alertLevelError)
David Benjamin053fee92017-01-02 08:30:36 -0500973 if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertificate {
David Benjamin24f346d2015-06-06 03:28:08 -0400974 level = alertLevelWarning
975 }
976 return c.SendAlert(level, err)
977}
978
979func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700980 c.out.Lock()
981 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -0400982 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -0700983}
984
David Benjamind86c7672014-08-02 04:07:12 -0400985// writeV2Record writes a record for a V2ClientHello.
986func (c *Conn) writeV2Record(data []byte) (n int, err error) {
987 record := make([]byte, 2+len(data))
988 record[0] = uint8(len(data)>>8) | 0x80
989 record[1] = uint8(len(data))
990 copy(record[2:], data)
991 return c.conn.Write(record)
992}
993
Adam Langley95c29f32014-06-20 12:00:00 -0700994// writeRecord writes a TLS record with the given type and payload
995// to the connection and updates the record layer state.
996// c.out.Mutex <= L.
997func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin639846e2016-09-09 11:41:18 -0400998 if msgType := c.config.Bugs.SendWrongMessageType; msgType != 0 {
999 if typ == recordTypeHandshake && data[0] == msgType {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001000 newData := make([]byte, len(data))
1001 copy(newData, data)
1002 newData[0] += 42
1003 data = newData
1004 }
1005 }
1006
David Benjamin639846e2016-09-09 11:41:18 -04001007 if msgType := c.config.Bugs.SendTrailingMessageData; msgType != 0 {
1008 if typ == recordTypeHandshake && data[0] == msgType {
1009 newData := make([]byte, len(data))
1010 copy(newData, data)
1011
1012 // Add a 0 to the body.
1013 newData = append(newData, 0)
1014 // Fix the header.
1015 newLen := len(newData) - 4
1016 newData[1] = byte(newLen >> 16)
1017 newData[2] = byte(newLen >> 8)
1018 newData[3] = byte(newLen)
1019
1020 data = newData
1021 }
1022 }
1023
David Benjamin83c0bc92014-08-04 01:23:53 -04001024 if c.isDTLS {
1025 return c.dtlsWriteRecord(typ, data)
1026 }
1027
David Benjamin71dd6662016-07-08 14:10:48 -07001028 if typ == recordTypeHandshake {
1029 if c.config.Bugs.SendHelloRequestBeforeEveryHandshakeMessage {
1030 newData := make([]byte, 0, 4+len(data))
1031 newData = append(newData, typeHelloRequest, 0, 0, 0)
1032 newData = append(newData, data...)
1033 data = newData
1034 }
1035
1036 if c.config.Bugs.PackHandshakeFlight {
1037 c.pendingFlight.Write(data)
1038 return len(data), nil
1039 }
David Benjamin582ba042016-07-07 12:33:25 -07001040 }
1041
1042 return c.doWriteRecord(typ, data)
1043}
1044
1045func (c *Conn) doWriteRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin6f600d62016-12-21 16:06:54 -05001046 recordHeaderLen := c.out.recordHeaderLen()
Adam Langley95c29f32014-06-20 12:00:00 -07001047 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -04001048 first := true
1049 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -04001050 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -07001051 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -04001052 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -07001053 m = maxPlaintext
1054 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001055 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
1056 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -04001057 // By default, do not fragment the client_version or
1058 // server_version, which are located in the first 6
1059 // bytes.
1060 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
1061 m = 6
1062 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001063 }
Adam Langley95c29f32014-06-20 12:00:00 -07001064 explicitIVLen := 0
1065 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -04001066 first = false
Adam Langley95c29f32014-06-20 12:00:00 -07001067
1068 var cbc cbcMode
1069 if c.out.version >= VersionTLS11 {
1070 var ok bool
1071 if cbc, ok = c.out.cipher.(cbcMode); ok {
1072 explicitIVLen = cbc.BlockSize()
1073 }
1074 }
1075 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -04001076 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -07001077 explicitIVLen = 8
1078 // The AES-GCM construction in TLS has an
1079 // explicit nonce so that the nonce can be
1080 // random. However, the nonce is only 8 bytes
1081 // which is too small for a secure, random
1082 // nonce. Therefore we use the sequence number
1083 // as the nonce.
1084 explicitIVIsSeq = true
1085 }
1086 }
1087 b.resize(recordHeaderLen + explicitIVLen + m)
David Benjamin6f600d62016-12-21 16:06:54 -05001088 // If using a short record header, the length will be filled in
1089 // by encrypt.
1090 if !c.out.isShortHeader() {
1091 b.data[0] = byte(typ)
1092 if c.vers >= VersionTLS13 && c.out.cipher != nil {
1093 b.data[0] = byte(recordTypeApplicationData)
1094 if outerType := c.config.Bugs.OuterRecordType; outerType != 0 {
1095 b.data[0] = byte(outerType)
1096 }
David Benjaminc9ae27c2016-06-24 22:56:37 -04001097 }
David Benjamin6f600d62016-12-21 16:06:54 -05001098 vers := c.vers
1099 if vers == 0 || vers >= VersionTLS13 {
1100 // Some TLS servers fail if the record version is
1101 // greater than TLS 1.0 for the initial ClientHello.
1102 //
1103 // TLS 1.3 fixes the version number in the record
1104 // layer to {3, 1}.
1105 vers = VersionTLS10
1106 }
1107 if c.config.Bugs.SendRecordVersion != 0 {
1108 vers = c.config.Bugs.SendRecordVersion
1109 }
1110 if c.vers == 0 && c.config.Bugs.SendInitialRecordVersion != 0 {
1111 vers = c.config.Bugs.SendInitialRecordVersion
1112 }
1113 b.data[1] = byte(vers >> 8)
1114 b.data[2] = byte(vers)
1115 b.data[3] = byte(m >> 8)
1116 b.data[4] = byte(m)
Nick Harper1fd39d82016-06-14 18:14:35 -07001117 }
Adam Langley95c29f32014-06-20 12:00:00 -07001118 if explicitIVLen > 0 {
1119 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
1120 if explicitIVIsSeq {
1121 copy(explicitIV, c.out.seq[:])
1122 } else {
1123 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
1124 break
1125 }
1126 }
1127 }
1128 copy(b.data[recordHeaderLen+explicitIVLen:], data)
Nick Harper1fd39d82016-06-14 18:14:35 -07001129 c.out.encrypt(b, explicitIVLen, typ)
Adam Langley95c29f32014-06-20 12:00:00 -07001130 _, err = c.conn.Write(b.data)
1131 if err != nil {
1132 break
1133 }
1134 n += m
1135 data = data[m:]
1136 }
1137 c.out.freeBlock(b)
1138
1139 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -07001140 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -07001141 if err != nil {
1142 // Cannot call sendAlert directly,
1143 // because we already hold c.out.Mutex.
1144 c.tmp[0] = alertLevelError
1145 c.tmp[1] = byte(err.(alert))
1146 c.writeRecord(recordTypeAlert, c.tmp[0:2])
1147 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
1148 }
1149 }
1150 return
1151}
1152
David Benjamin582ba042016-07-07 12:33:25 -07001153func (c *Conn) flushHandshake() error {
1154 if c.isDTLS {
1155 return c.dtlsFlushHandshake()
1156 }
1157
1158 for c.pendingFlight.Len() > 0 {
1159 var buf [maxPlaintext]byte
1160 n, _ := c.pendingFlight.Read(buf[:])
1161 if _, err := c.doWriteRecord(recordTypeHandshake, buf[:n]); err != nil {
1162 return err
1163 }
1164 }
1165
1166 c.pendingFlight.Reset()
1167 return nil
1168}
1169
David Benjamin83c0bc92014-08-04 01:23:53 -04001170func (c *Conn) doReadHandshake() ([]byte, error) {
1171 if c.isDTLS {
1172 return c.dtlsDoReadHandshake()
1173 }
1174
Adam Langley95c29f32014-06-20 12:00:00 -07001175 for c.hand.Len() < 4 {
1176 if err := c.in.err; err != nil {
1177 return nil, err
1178 }
1179 if err := c.readRecord(recordTypeHandshake); err != nil {
1180 return nil, err
1181 }
1182 }
1183
1184 data := c.hand.Bytes()
1185 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1186 if n > maxHandshake {
1187 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
1188 }
1189 for c.hand.Len() < 4+n {
1190 if err := c.in.err; err != nil {
1191 return nil, err
1192 }
1193 if err := c.readRecord(recordTypeHandshake); err != nil {
1194 return nil, err
1195 }
1196 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001197 return c.hand.Next(4 + n), nil
1198}
1199
1200// readHandshake reads the next handshake message from
1201// the record layer.
1202// c.in.Mutex < L; c.out.Mutex < L.
1203func (c *Conn) readHandshake() (interface{}, error) {
1204 data, err := c.doReadHandshake()
David Benjamin053fee92017-01-02 08:30:36 -05001205 if err == errNoCertificateAlert {
1206 if c.hand.Len() != 0 {
1207 // The warning alert may not interleave with a handshake message.
1208 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1209 }
1210 return new(ssl3NoCertificateMsg), nil
1211 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001212 if err != nil {
1213 return nil, err
1214 }
1215
Adam Langley95c29f32014-06-20 12:00:00 -07001216 var m handshakeMessage
1217 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001218 case typeHelloRequest:
1219 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001220 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001221 m = &clientHelloMsg{
1222 isDTLS: c.isDTLS,
1223 }
Adam Langley95c29f32014-06-20 12:00:00 -07001224 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001225 m = &serverHelloMsg{
1226 isDTLS: c.isDTLS,
1227 }
Nick Harperdcfbc672016-07-16 17:47:31 +02001228 case typeHelloRetryRequest:
1229 m = new(helloRetryRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001230 case typeNewSessionTicket:
David Benjamin58104882016-07-18 01:25:41 +02001231 m = &newSessionTicketMsg{
1232 version: c.vers,
1233 }
Nick Harperb41d2e42016-07-01 17:50:32 -04001234 case typeEncryptedExtensions:
1235 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001236 case typeCertificate:
Nick Harperb41d2e42016-07-01 17:50:32 -04001237 m = &certificateMsg{
David Benjamin8d315d72016-07-18 01:03:18 +02001238 hasRequestContext: c.vers >= VersionTLS13,
Nick Harperb41d2e42016-07-01 17:50:32 -04001239 }
Adam Langley95c29f32014-06-20 12:00:00 -07001240 case typeCertificateRequest:
1241 m = &certificateRequestMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001242 hasSignatureAlgorithm: c.vers >= VersionTLS12,
David Benjamin8d315d72016-07-18 01:03:18 +02001243 hasRequestContext: c.vers >= VersionTLS13,
Adam Langley95c29f32014-06-20 12:00:00 -07001244 }
1245 case typeCertificateStatus:
1246 m = new(certificateStatusMsg)
1247 case typeServerKeyExchange:
1248 m = new(serverKeyExchangeMsg)
1249 case typeServerHelloDone:
1250 m = new(serverHelloDoneMsg)
1251 case typeClientKeyExchange:
1252 m = new(clientKeyExchangeMsg)
1253 case typeCertificateVerify:
1254 m = &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001255 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001256 }
1257 case typeNextProtocol:
1258 m = new(nextProtoMsg)
1259 case typeFinished:
1260 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001261 case typeHelloVerifyRequest:
1262 m = new(helloVerifyRequestMsg)
David Benjamin24599a82016-06-30 18:56:53 -04001263 case typeChannelID:
1264 m = new(channelIDMsg)
David Benjamin21c00282016-07-18 21:56:23 +02001265 case typeKeyUpdate:
1266 m = new(keyUpdateMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001267 default:
1268 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1269 }
1270
1271 // The handshake message unmarshallers
1272 // expect to be able to keep references to data,
1273 // so pass in a fresh copy that won't be overwritten.
1274 data = append([]byte(nil), data...)
1275
1276 if !m.unmarshal(data) {
1277 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1278 }
1279 return m, nil
1280}
1281
David Benjamin83f90402015-01-27 01:09:43 -05001282// skipPacket processes all the DTLS records in packet. It updates
1283// sequence number expectations but otherwise ignores them.
1284func (c *Conn) skipPacket(packet []byte) error {
1285 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001286 if len(packet) < 13 {
1287 return errors.New("tls: bad packet")
1288 }
David Benjamin83f90402015-01-27 01:09:43 -05001289 // Dropped packets are completely ignored save to update
1290 // expected sequence numbers for this and the next epoch. (We
1291 // don't assert on the contents of the packets both for
1292 // simplicity and because a previous test with one shorter
1293 // timeout schedule would have done so.)
1294 epoch := packet[3:5]
1295 seq := packet[5:11]
1296 length := uint16(packet[11])<<8 | uint16(packet[12])
1297 if bytes.Equal(c.in.seq[:2], epoch) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001298 if bytes.Compare(seq, c.in.seq[2:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001299 return errors.New("tls: sequence mismatch")
1300 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001301 copy(c.in.seq[2:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001302 c.in.incSeq(false)
1303 } else {
David Benjamin13e81fc2015-11-02 17:16:13 -05001304 if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001305 return errors.New("tls: sequence mismatch")
1306 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001307 copy(c.in.nextSeq[:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001308 c.in.incNextSeq()
1309 }
David Benjamin6ca93552015-08-28 16:16:25 -04001310 if len(packet) < 13+int(length) {
1311 return errors.New("tls: bad packet")
1312 }
David Benjamin83f90402015-01-27 01:09:43 -05001313 packet = packet[13+length:]
1314 }
1315 return nil
1316}
1317
1318// simulatePacketLoss simulates the loss of a handshake leg from the
1319// peer based on the schedule in c.config.Bugs. If resendFunc is
1320// non-nil, it is called after each simulated timeout to retransmit
1321// handshake messages from the local end. This is used in cases where
1322// the peer retransmits on a stale Finished rather than a timeout.
1323func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1324 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1325 return nil
1326 }
1327 if !c.isDTLS {
1328 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1329 }
1330 if c.config.Bugs.PacketAdaptor == nil {
1331 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1332 }
1333 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1334 // Simulate a timeout.
1335 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1336 if err != nil {
1337 return err
1338 }
1339 for _, packet := range packets {
1340 if err := c.skipPacket(packet); err != nil {
1341 return err
1342 }
1343 }
1344 if resendFunc != nil {
1345 resendFunc()
1346 }
1347 }
1348 return nil
1349}
1350
David Benjamin47921102016-07-28 11:29:18 -04001351func (c *Conn) SendHalfHelloRequest() error {
1352 if err := c.Handshake(); err != nil {
1353 return err
1354 }
1355
1356 c.out.Lock()
1357 defer c.out.Unlock()
1358
1359 if _, err := c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0}); err != nil {
1360 return err
1361 }
1362 return c.flushHandshake()
1363}
1364
Adam Langley95c29f32014-06-20 12:00:00 -07001365// Write writes data to the connection.
1366func (c *Conn) Write(b []byte) (int, error) {
1367 if err := c.Handshake(); err != nil {
1368 return 0, err
1369 }
1370
1371 c.out.Lock()
1372 defer c.out.Unlock()
1373
David Benjamin12d2c482016-07-24 10:56:51 -04001374 // Flush any pending handshake data. PackHelloRequestWithFinished may
1375 // have been set and the handshake not followed by Renegotiate.
1376 c.flushHandshake()
1377
Adam Langley95c29f32014-06-20 12:00:00 -07001378 if err := c.out.err; err != nil {
1379 return 0, err
1380 }
1381
1382 if !c.handshakeComplete {
1383 return 0, alertInternalError
1384 }
1385
Steven Valdezc4aa7272016-10-03 12:25:56 -04001386 if c.keyUpdateRequested {
1387 if err := c.sendKeyUpdateLocked(keyUpdateNotRequested); err != nil {
David Benjamin21c00282016-07-18 21:56:23 +02001388 return 0, err
1389 }
Steven Valdezc4aa7272016-10-03 12:25:56 -04001390 c.keyUpdateRequested = false
David Benjamin21c00282016-07-18 21:56:23 +02001391 }
1392
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001393 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001394 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001395 }
1396
Adam Langley27a0d082015-11-03 13:34:10 -08001397 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1398 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
David Benjamin582ba042016-07-07 12:33:25 -07001399 c.flushHandshake()
Adam Langley27a0d082015-11-03 13:34:10 -08001400 }
1401
Adam Langley95c29f32014-06-20 12:00:00 -07001402 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1403 // attack when using block mode ciphers due to predictable IVs.
1404 // This can be prevented by splitting each Application Data
1405 // record into two records, effectively randomizing the IV.
1406 //
1407 // http://www.openssl.org/~bodo/tls-cbc.txt
1408 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1409 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1410
1411 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001412 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001413 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1414 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1415 if err != nil {
1416 return n, c.out.setErrorLocked(err)
1417 }
1418 m, b = 1, b[1:]
1419 }
1420 }
1421
1422 n, err := c.writeRecord(recordTypeApplicationData, b)
1423 return n + m, c.out.setErrorLocked(err)
1424}
1425
David Benjamind5a4ecb2016-07-18 01:17:13 +02001426func (c *Conn) handlePostHandshakeMessage() error {
Adam Langley2ae77d22014-10-28 17:29:33 -07001427 msg, err := c.readHandshake()
1428 if err != nil {
1429 return err
1430 }
David Benjamind5a4ecb2016-07-18 01:17:13 +02001431
1432 if c.vers < VersionTLS13 {
1433 if !c.isClient {
1434 c.sendAlert(alertUnexpectedMessage)
1435 return errors.New("tls: unexpected post-handshake message")
1436 }
1437
1438 _, ok := msg.(*helloRequestMsg)
1439 if !ok {
1440 c.sendAlert(alertUnexpectedMessage)
1441 return alertUnexpectedMessage
1442 }
1443
1444 c.handshakeComplete = false
1445 return c.Handshake()
Adam Langley2ae77d22014-10-28 17:29:33 -07001446 }
1447
David Benjamind5a4ecb2016-07-18 01:17:13 +02001448 if c.isClient {
1449 if newSessionTicket, ok := msg.(*newSessionTicketMsg); ok {
David Benjamin1a5e8ec2016-10-07 15:19:18 -04001450 if c.config.Bugs.ExpectGREASE && !newSessionTicket.hasGREASEExtension {
1451 return errors.New("tls: no GREASE ticket extension found")
1452 }
1453
Steven Valdeza833c352016-11-01 13:39:36 -04001454 if c.config.Bugs.ExpectNoNewSessionTicket {
1455 return errors.New("tls: received unexpected NewSessionTicket")
1456 }
1457
David Benjamind5a4ecb2016-07-18 01:17:13 +02001458 if c.config.ClientSessionCache == nil || newSessionTicket.ticketLifetime == 0 {
1459 return nil
1460 }
1461
1462 session := &ClientSessionState{
1463 sessionTicket: newSessionTicket.ticket,
1464 vers: c.vers,
1465 cipherSuite: c.cipherSuite.id,
1466 masterSecret: c.resumptionSecret,
1467 serverCertificates: c.peerCertificates,
1468 sctList: c.sctList,
1469 ocspResponse: c.ocspResponse,
Nick Harper0b3625b2016-07-25 16:16:28 -07001470 ticketCreationTime: c.config.time(),
1471 ticketExpiration: c.config.time().Add(time.Duration(newSessionTicket.ticketLifetime) * time.Second),
Steven Valdeza833c352016-11-01 13:39:36 -04001472 ticketAgeAdd: newSessionTicket.ticketAgeAdd,
David Benjamind5a4ecb2016-07-18 01:17:13 +02001473 }
1474
1475 cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
1476 c.config.ClientSessionCache.Put(cacheKey, session)
1477 return nil
1478 }
1479 }
1480
Steven Valdezc4aa7272016-10-03 12:25:56 -04001481 if keyUpdate, ok := msg.(*keyUpdateMsg); ok {
Steven Valdez1dc53d22016-07-26 12:27:38 -04001482 c.in.doKeyUpdate(c, false)
Steven Valdezc4aa7272016-10-03 12:25:56 -04001483 if keyUpdate.keyUpdateRequest == keyUpdateRequested {
1484 c.keyUpdateRequested = true
1485 }
David Benjamin21c00282016-07-18 21:56:23 +02001486 return nil
1487 }
1488
David Benjamind5a4ecb2016-07-18 01:17:13 +02001489 // TODO(davidben): Add support for KeyUpdate.
1490 c.sendAlert(alertUnexpectedMessage)
1491 return alertUnexpectedMessage
Adam Langley2ae77d22014-10-28 17:29:33 -07001492}
1493
Adam Langleycf2d4f42014-10-28 19:06:14 -07001494func (c *Conn) Renegotiate() error {
1495 if !c.isClient {
David Benjaminef5dfd22015-12-06 13:17:07 -05001496 helloReq := new(helloRequestMsg).marshal()
1497 if c.config.Bugs.BadHelloRequest != nil {
1498 helloReq = c.config.Bugs.BadHelloRequest
1499 }
1500 c.writeRecord(recordTypeHandshake, helloReq)
David Benjamin582ba042016-07-07 12:33:25 -07001501 c.flushHandshake()
Adam Langleycf2d4f42014-10-28 19:06:14 -07001502 }
1503
1504 c.handshakeComplete = false
1505 return c.Handshake()
1506}
1507
Adam Langley95c29f32014-06-20 12:00:00 -07001508// Read can be made to time out and return a net.Error with Timeout() == true
1509// after a fixed time limit; see SetDeadline and SetReadDeadline.
1510func (c *Conn) Read(b []byte) (n int, err error) {
1511 if err = c.Handshake(); err != nil {
1512 return
1513 }
1514
1515 c.in.Lock()
1516 defer c.in.Unlock()
1517
1518 // Some OpenSSL servers send empty records in order to randomize the
1519 // CBC IV. So this loop ignores a limited number of empty records.
1520 const maxConsecutiveEmptyRecords = 100
1521 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1522 for c.input == nil && c.in.err == nil {
1523 if err := c.readRecord(recordTypeApplicationData); err != nil {
1524 // Soft error, like EAGAIN
1525 return 0, err
1526 }
David Benjamind9b091b2015-01-27 01:10:54 -05001527 if c.hand.Len() > 0 {
David Benjamind5a4ecb2016-07-18 01:17:13 +02001528 // We received handshake bytes, indicating a
1529 // post-handshake message.
1530 if err := c.handlePostHandshakeMessage(); err != nil {
Adam Langley2ae77d22014-10-28 17:29:33 -07001531 return 0, err
1532 }
1533 continue
1534 }
Adam Langley95c29f32014-06-20 12:00:00 -07001535 }
1536 if err := c.in.err; err != nil {
1537 return 0, err
1538 }
1539
1540 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001541 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001542 c.in.freeBlock(c.input)
1543 c.input = nil
1544 }
1545
1546 // If a close-notify alert is waiting, read it so that
1547 // we can return (n, EOF) instead of (n, nil), to signal
1548 // to the HTTP response reading goroutine that the
1549 // connection is now closed. This eliminates a race
1550 // where the HTTP response reading goroutine would
1551 // otherwise not observe the EOF until its next read,
1552 // by which time a client goroutine might have already
1553 // tried to reuse the HTTP connection for a new
1554 // request.
1555 // See https://codereview.appspot.com/76400046
1556 // and http://golang.org/issue/3514
1557 if ri := c.rawInput; ri != nil &&
1558 n != 0 && err == nil &&
1559 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1560 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1561 err = recErr // will be io.EOF on closeNotify
1562 }
1563 }
1564
1565 if n != 0 || err != nil {
1566 return n, err
1567 }
1568 }
1569
1570 return 0, io.ErrNoProgress
1571}
1572
1573// Close closes the connection.
1574func (c *Conn) Close() error {
1575 var alertErr error
1576
1577 c.handshakeMutex.Lock()
1578 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001579 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
David Benjaminfa214e42016-05-10 17:03:10 -04001580 alert := alertCloseNotify
1581 if c.config.Bugs.SendAlertOnShutdown != 0 {
1582 alert = c.config.Bugs.SendAlertOnShutdown
1583 }
1584 alertErr = c.sendAlert(alert)
David Benjamin4d559612016-05-18 14:31:51 -04001585 // Clear local alerts when sending alerts so we continue to wait
1586 // for the peer rather than closing the socket early.
1587 if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1588 alertErr = nil
1589 }
Adam Langley95c29f32014-06-20 12:00:00 -07001590 }
1591
David Benjamin30789da2015-08-29 22:56:45 -04001592 // Consume a close_notify from the peer if one hasn't been received
1593 // already. This avoids the peer from failing |SSL_shutdown| due to a
1594 // write failing.
1595 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1596 for c.in.error() == nil {
1597 c.readRecord(recordTypeAlert)
1598 }
1599 if c.in.error() != io.EOF {
1600 alertErr = c.in.error()
1601 }
1602 }
1603
Adam Langley95c29f32014-06-20 12:00:00 -07001604 if err := c.conn.Close(); err != nil {
1605 return err
1606 }
1607 return alertErr
1608}
1609
1610// Handshake runs the client or server handshake
1611// protocol if it has not yet been run.
1612// Most uses of this package need not call Handshake
1613// explicitly: the first Read or Write will call it automatically.
1614func (c *Conn) Handshake() error {
1615 c.handshakeMutex.Lock()
1616 defer c.handshakeMutex.Unlock()
1617 if err := c.handshakeErr; err != nil {
1618 return err
1619 }
1620 if c.handshakeComplete {
1621 return nil
1622 }
1623
David Benjamin9a41d1b2015-05-16 01:30:09 -04001624 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1625 c.conn.Write([]byte{
1626 byte(recordTypeAlert), // type
1627 0xfe, 0xff, // version
1628 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1629 0x0, 0x2, // length
1630 })
1631 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1632 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001633 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1634 c.writeRecord(recordTypeApplicationData, data)
1635 }
Adam Langley95c29f32014-06-20 12:00:00 -07001636 if c.isClient {
1637 c.handshakeErr = c.clientHandshake()
1638 } else {
1639 c.handshakeErr = c.serverHandshake()
1640 }
David Benjaminddb9f152015-02-03 15:44:39 -05001641 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1642 c.writeRecord(recordType(42), []byte("invalid record"))
1643 }
Adam Langley95c29f32014-06-20 12:00:00 -07001644 return c.handshakeErr
1645}
1646
1647// ConnectionState returns basic TLS details about the connection.
1648func (c *Conn) ConnectionState() ConnectionState {
1649 c.handshakeMutex.Lock()
1650 defer c.handshakeMutex.Unlock()
1651
1652 var state ConnectionState
1653 state.HandshakeComplete = c.handshakeComplete
1654 if c.handshakeComplete {
1655 state.Version = c.vers
1656 state.NegotiatedProtocol = c.clientProtocol
1657 state.DidResume = c.didResume
1658 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001659 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001660 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001661 state.PeerCertificates = c.peerCertificates
1662 state.VerifiedChains = c.verifiedChains
1663 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001664 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001665 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001666 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001667 state.SCTList = c.sctList
Nick Harper60edffd2016-06-21 15:19:24 -07001668 state.PeerSignatureAlgorithm = c.peerSignatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -04001669 state.CurveID = c.curveID
David Benjamin6f600d62016-12-21 16:06:54 -05001670 state.ShortHeader = c.in.shortHeader
Adam Langley95c29f32014-06-20 12:00:00 -07001671 }
1672
1673 return state
1674}
1675
1676// OCSPResponse returns the stapled OCSP response from the TLS server, if
1677// any. (Only valid for client connections.)
1678func (c *Conn) OCSPResponse() []byte {
1679 c.handshakeMutex.Lock()
1680 defer c.handshakeMutex.Unlock()
1681
1682 return c.ocspResponse
1683}
1684
1685// VerifyHostname checks that the peer certificate chain is valid for
1686// connecting to host. If so, it returns nil; if not, it returns an error
1687// describing the problem.
1688func (c *Conn) VerifyHostname(host string) error {
1689 c.handshakeMutex.Lock()
1690 defer c.handshakeMutex.Unlock()
1691 if !c.isClient {
1692 return errors.New("tls: VerifyHostname called on TLS server connection")
1693 }
1694 if !c.handshakeComplete {
1695 return errors.New("tls: handshake has not yet been performed")
1696 }
1697 return c.peerCertificates[0].VerifyHostname(host)
1698}
David Benjaminc565ebb2015-04-03 04:06:36 -04001699
1700// ExportKeyingMaterial exports keying material from the current connection
1701// state, as per RFC 5705.
1702func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1703 c.handshakeMutex.Lock()
1704 defer c.handshakeMutex.Unlock()
1705 if !c.handshakeComplete {
1706 return nil, errors.New("tls: handshake has not yet been performed")
1707 }
1708
David Benjamin8d315d72016-07-18 01:03:18 +02001709 if c.vers >= VersionTLS13 {
David Benjamin97a0a082016-07-13 17:57:35 -04001710 // TODO(davidben): What should we do with useContext? See
1711 // https://github.com/tlswg/tls13-spec/issues/546
1712 return hkdfExpandLabel(c.cipherSuite.hash(), c.exporterSecret, label, context, length), nil
1713 }
1714
David Benjaminc565ebb2015-04-03 04:06:36 -04001715 seedLen := len(c.clientRandom) + len(c.serverRandom)
1716 if useContext {
1717 seedLen += 2 + len(context)
1718 }
1719 seed := make([]byte, 0, seedLen)
1720 seed = append(seed, c.clientRandom[:]...)
1721 seed = append(seed, c.serverRandom[:]...)
1722 if useContext {
1723 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1724 seed = append(seed, context...)
1725 }
1726 result := make([]byte, length)
David Benjamin97a0a082016-07-13 17:57:35 -04001727 prfForVersion(c.vers, c.cipherSuite)(result, c.exporterSecret, label, seed)
David Benjaminc565ebb2015-04-03 04:06:36 -04001728 return result, nil
1729}
David Benjamin3e052de2015-11-25 20:10:31 -05001730
1731// noRenegotiationInfo returns true if the renegotiation info extension
1732// should be supported in the current handshake.
1733func (c *Conn) noRenegotiationInfo() bool {
1734 if c.config.Bugs.NoRenegotiationInfo {
1735 return true
1736 }
1737 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1738 return true
1739 }
1740 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1741 return true
1742 }
1743 return false
1744}
David Benjamin58104882016-07-18 01:25:41 +02001745
1746func (c *Conn) SendNewSessionTicket() error {
1747 if c.isClient || c.vers < VersionTLS13 {
1748 return errors.New("tls: cannot send post-handshake NewSessionTicket")
1749 }
1750
1751 var peerCertificatesRaw [][]byte
1752 for _, cert := range c.peerCertificates {
1753 peerCertificatesRaw = append(peerCertificatesRaw, cert.Raw)
1754 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001755
Steven Valdeza833c352016-11-01 13:39:36 -04001756 addBuffer := make([]byte, 4)
1757 _, err := io.ReadFull(c.config.rand(), addBuffer)
1758 if err != nil {
1759 c.sendAlert(alertInternalError)
1760 return errors.New("tls: short read from Rand: " + err.Error())
1761 }
1762 ticketAgeAdd := uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0])
1763
David Benjamin58104882016-07-18 01:25:41 +02001764 // TODO(davidben): Allow configuring these values.
1765 m := &newSessionTicketMsg{
David Benjamin1286bee2016-10-07 15:25:06 -04001766 version: c.vers,
1767 ticketLifetime: uint32(24 * time.Hour / time.Second),
David Benjamin1286bee2016-10-07 15:25:06 -04001768 customExtension: c.config.Bugs.CustomTicketExtension,
Steven Valdeza833c352016-11-01 13:39:36 -04001769 ticketAgeAdd: ticketAgeAdd,
David Benjamin58104882016-07-18 01:25:41 +02001770 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001771
1772 state := sessionState{
1773 vers: c.vers,
1774 cipherSuite: c.cipherSuite.id,
1775 masterSecret: c.resumptionSecret,
1776 certificates: peerCertificatesRaw,
1777 ticketCreationTime: c.config.time(),
1778 ticketExpiration: c.config.time().Add(time.Duration(m.ticketLifetime) * time.Second),
Steven Valdeza833c352016-11-01 13:39:36 -04001779 ticketAgeAdd: uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0]),
Nick Harper0b3625b2016-07-25 16:16:28 -07001780 }
1781
David Benjamin58104882016-07-18 01:25:41 +02001782 if !c.config.Bugs.SendEmptySessionTicket {
1783 var err error
1784 m.ticket, err = c.encryptTicket(&state)
1785 if err != nil {
1786 return err
1787 }
1788 }
1789
1790 c.out.Lock()
1791 defer c.out.Unlock()
Steven Valdeza833c352016-11-01 13:39:36 -04001792 _, err = c.writeRecord(recordTypeHandshake, m.marshal())
David Benjamin58104882016-07-18 01:25:41 +02001793 return err
1794}
David Benjamin21c00282016-07-18 21:56:23 +02001795
Steven Valdezc4aa7272016-10-03 12:25:56 -04001796func (c *Conn) SendKeyUpdate(keyUpdateRequest byte) error {
David Benjamin21c00282016-07-18 21:56:23 +02001797 c.out.Lock()
1798 defer c.out.Unlock()
Steven Valdezc4aa7272016-10-03 12:25:56 -04001799 return c.sendKeyUpdateLocked(keyUpdateRequest)
David Benjamin21c00282016-07-18 21:56:23 +02001800}
1801
Steven Valdezc4aa7272016-10-03 12:25:56 -04001802func (c *Conn) sendKeyUpdateLocked(keyUpdateRequest byte) error {
David Benjamin7f0965a2016-09-30 15:14:01 -04001803 if c.vers < VersionTLS13 {
1804 return errors.New("tls: attempted to send KeyUpdate before TLS 1.3")
1805 }
1806
Steven Valdezc4aa7272016-10-03 12:25:56 -04001807 m := keyUpdateMsg{
1808 keyUpdateRequest: keyUpdateRequest,
1809 }
David Benjamin21c00282016-07-18 21:56:23 +02001810 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
1811 return err
1812 }
1813 if err := c.flushHandshake(); err != nil {
1814 return err
1815 }
Steven Valdez1dc53d22016-07-26 12:27:38 -04001816 c.out.doKeyUpdate(c, true)
David Benjamin21c00282016-07-18 21:56:23 +02001817 return nil
1818}
Steven Valdeza4ee74d2016-11-29 13:36:45 -05001819
1820func (c *Conn) sendFakeEarlyData(len int) error {
1821 // Assemble a fake early data record. This does not use writeRecord
1822 // because the record layer may be using different keys at this point.
1823 payload := make([]byte, 5+len)
1824 payload[0] = byte(recordTypeApplicationData)
1825 payload[1] = 3
1826 payload[2] = 1
1827 payload[3] = byte(len >> 8)
1828 payload[4] = byte(len)
1829 _, err := c.conn.Write(payload)
1830 return err
1831}
David Benjamin6f600d62016-12-21 16:06:54 -05001832
1833func (c *Conn) setShortHeader() {
1834 c.in.shortHeader = true
1835 c.out.shortHeader = true
1836}