blob: 3cbd496a30596ea5cb18ef37822d4877ac9296d0 [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:]
David Benjamine3fbb362017-01-06 16:19:28 -0500879 max := maxPlaintext
880 if c.config.Bugs.MaxReceivePlaintext != 0 {
881 max = c.config.Bugs.MaxReceivePlaintext
882 }
883 if len(data) > max {
Adam Langley95c29f32014-06-20 12:00:00 -0700884 err := c.sendAlert(alertRecordOverflow)
885 c.in.freeBlock(b)
886 return c.in.setErrorLocked(err)
887 }
888
889 switch typ {
890 default:
891 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
892
893 case recordTypeAlert:
894 if len(data) != 2 {
895 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
896 break
897 }
898 if alert(data[1]) == alertCloseNotify {
899 c.in.setErrorLocked(io.EOF)
900 break
901 }
902 switch data[0] {
903 case alertLevelWarning:
David Benjamin053fee92017-01-02 08:30:36 -0500904 if alert(data[1]) == alertNoCertificate {
905 c.in.freeBlock(b)
906 return errNoCertificateAlert
907 }
908
Adam Langley95c29f32014-06-20 12:00:00 -0700909 // drop on the floor
910 c.in.freeBlock(b)
911 goto Again
912 case alertLevelError:
913 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
914 default:
915 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
916 }
917
918 case recordTypeChangeCipherSpec:
919 if typ != want || len(data) != 1 || data[0] != 1 {
920 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
921 break
922 }
Adam Langley80842bd2014-06-20 12:00:00 -0700923 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700924 if err != nil {
925 c.in.setErrorLocked(c.sendAlert(err.(alert)))
926 }
927
928 case recordTypeApplicationData:
929 if typ != want {
930 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
931 break
932 }
933 c.input = b
934 b = nil
935
936 case recordTypeHandshake:
David Benjamind5a4ecb2016-07-18 01:17:13 +0200937 // Allow handshake data while reading application data to
938 // trigger post-handshake messages.
Adam Langley95c29f32014-06-20 12:00:00 -0700939 // TODO(rsc): Should at least pick off connection close.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200940 if typ != want && want != recordTypeApplicationData {
941 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
Adam Langley95c29f32014-06-20 12:00:00 -0700942 }
943 c.hand.Write(data)
944 }
945
946 if b != nil {
947 c.in.freeBlock(b)
948 }
949 return c.in.err
950}
951
952// sendAlert sends a TLS alert message.
953// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400954func (c *Conn) sendAlertLocked(level byte, err alert) error {
955 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700956 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400957 if c.config.Bugs.FragmentAlert {
958 c.writeRecord(recordTypeAlert, c.tmp[0:1])
959 c.writeRecord(recordTypeAlert, c.tmp[1:2])
David Benjamin0d3a8c62016-03-11 22:25:18 -0500960 } else if c.config.Bugs.DoubleAlert {
961 copy(c.tmp[2:4], c.tmp[0:2])
962 c.writeRecord(recordTypeAlert, c.tmp[0:4])
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400963 } else {
964 c.writeRecord(recordTypeAlert, c.tmp[0:2])
965 }
David Benjamin24f346d2015-06-06 03:28:08 -0400966 // Error alerts are fatal to the connection.
967 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700968 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
969 }
970 return nil
971}
972
973// sendAlert sends a TLS alert message.
974// L < c.out.Mutex.
975func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400976 level := byte(alertLevelError)
David Benjamin053fee92017-01-02 08:30:36 -0500977 if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertificate {
David Benjamin24f346d2015-06-06 03:28:08 -0400978 level = alertLevelWarning
979 }
980 return c.SendAlert(level, err)
981}
982
983func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700984 c.out.Lock()
985 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -0400986 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -0700987}
988
David Benjamind86c7672014-08-02 04:07:12 -0400989// writeV2Record writes a record for a V2ClientHello.
990func (c *Conn) writeV2Record(data []byte) (n int, err error) {
991 record := make([]byte, 2+len(data))
992 record[0] = uint8(len(data)>>8) | 0x80
993 record[1] = uint8(len(data))
994 copy(record[2:], data)
995 return c.conn.Write(record)
996}
997
Adam Langley95c29f32014-06-20 12:00:00 -0700998// writeRecord writes a TLS record with the given type and payload
999// to the connection and updates the record layer state.
1000// c.out.Mutex <= L.
1001func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin639846e2016-09-09 11:41:18 -04001002 if msgType := c.config.Bugs.SendWrongMessageType; msgType != 0 {
1003 if typ == recordTypeHandshake && data[0] == msgType {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001004 newData := make([]byte, len(data))
1005 copy(newData, data)
1006 newData[0] += 42
1007 data = newData
1008 }
1009 }
1010
David Benjamin639846e2016-09-09 11:41:18 -04001011 if msgType := c.config.Bugs.SendTrailingMessageData; msgType != 0 {
1012 if typ == recordTypeHandshake && data[0] == msgType {
1013 newData := make([]byte, len(data))
1014 copy(newData, data)
1015
1016 // Add a 0 to the body.
1017 newData = append(newData, 0)
1018 // Fix the header.
1019 newLen := len(newData) - 4
1020 newData[1] = byte(newLen >> 16)
1021 newData[2] = byte(newLen >> 8)
1022 newData[3] = byte(newLen)
1023
1024 data = newData
1025 }
1026 }
1027
David Benjamin83c0bc92014-08-04 01:23:53 -04001028 if c.isDTLS {
1029 return c.dtlsWriteRecord(typ, data)
1030 }
1031
David Benjamin71dd6662016-07-08 14:10:48 -07001032 if typ == recordTypeHandshake {
1033 if c.config.Bugs.SendHelloRequestBeforeEveryHandshakeMessage {
1034 newData := make([]byte, 0, 4+len(data))
1035 newData = append(newData, typeHelloRequest, 0, 0, 0)
1036 newData = append(newData, data...)
1037 data = newData
1038 }
1039
1040 if c.config.Bugs.PackHandshakeFlight {
1041 c.pendingFlight.Write(data)
1042 return len(data), nil
1043 }
David Benjamin582ba042016-07-07 12:33:25 -07001044 }
1045
1046 return c.doWriteRecord(typ, data)
1047}
1048
1049func (c *Conn) doWriteRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin6f600d62016-12-21 16:06:54 -05001050 recordHeaderLen := c.out.recordHeaderLen()
Adam Langley95c29f32014-06-20 12:00:00 -07001051 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -04001052 first := true
1053 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -04001054 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -07001055 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -04001056 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -07001057 m = maxPlaintext
1058 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001059 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
1060 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -04001061 // By default, do not fragment the client_version or
1062 // server_version, which are located in the first 6
1063 // bytes.
1064 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
1065 m = 6
1066 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001067 }
Adam Langley95c29f32014-06-20 12:00:00 -07001068 explicitIVLen := 0
1069 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -04001070 first = false
Adam Langley95c29f32014-06-20 12:00:00 -07001071
1072 var cbc cbcMode
1073 if c.out.version >= VersionTLS11 {
1074 var ok bool
1075 if cbc, ok = c.out.cipher.(cbcMode); ok {
1076 explicitIVLen = cbc.BlockSize()
1077 }
1078 }
1079 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -04001080 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -07001081 explicitIVLen = 8
1082 // The AES-GCM construction in TLS has an
1083 // explicit nonce so that the nonce can be
1084 // random. However, the nonce is only 8 bytes
1085 // which is too small for a secure, random
1086 // nonce. Therefore we use the sequence number
1087 // as the nonce.
1088 explicitIVIsSeq = true
1089 }
1090 }
1091 b.resize(recordHeaderLen + explicitIVLen + m)
David Benjamin6f600d62016-12-21 16:06:54 -05001092 // If using a short record header, the length will be filled in
1093 // by encrypt.
1094 if !c.out.isShortHeader() {
1095 b.data[0] = byte(typ)
1096 if c.vers >= VersionTLS13 && c.out.cipher != nil {
1097 b.data[0] = byte(recordTypeApplicationData)
1098 if outerType := c.config.Bugs.OuterRecordType; outerType != 0 {
1099 b.data[0] = byte(outerType)
1100 }
David Benjaminc9ae27c2016-06-24 22:56:37 -04001101 }
David Benjamin6f600d62016-12-21 16:06:54 -05001102 vers := c.vers
1103 if vers == 0 || vers >= VersionTLS13 {
1104 // Some TLS servers fail if the record version is
1105 // greater than TLS 1.0 for the initial ClientHello.
1106 //
1107 // TLS 1.3 fixes the version number in the record
1108 // layer to {3, 1}.
1109 vers = VersionTLS10
1110 }
1111 if c.config.Bugs.SendRecordVersion != 0 {
1112 vers = c.config.Bugs.SendRecordVersion
1113 }
1114 if c.vers == 0 && c.config.Bugs.SendInitialRecordVersion != 0 {
1115 vers = c.config.Bugs.SendInitialRecordVersion
1116 }
1117 b.data[1] = byte(vers >> 8)
1118 b.data[2] = byte(vers)
1119 b.data[3] = byte(m >> 8)
1120 b.data[4] = byte(m)
Nick Harper1fd39d82016-06-14 18:14:35 -07001121 }
Adam Langley95c29f32014-06-20 12:00:00 -07001122 if explicitIVLen > 0 {
1123 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
1124 if explicitIVIsSeq {
1125 copy(explicitIV, c.out.seq[:])
1126 } else {
1127 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
1128 break
1129 }
1130 }
1131 }
1132 copy(b.data[recordHeaderLen+explicitIVLen:], data)
Nick Harper1fd39d82016-06-14 18:14:35 -07001133 c.out.encrypt(b, explicitIVLen, typ)
Adam Langley95c29f32014-06-20 12:00:00 -07001134 _, err = c.conn.Write(b.data)
1135 if err != nil {
1136 break
1137 }
1138 n += m
1139 data = data[m:]
1140 }
1141 c.out.freeBlock(b)
1142
1143 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -07001144 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -07001145 if err != nil {
1146 // Cannot call sendAlert directly,
1147 // because we already hold c.out.Mutex.
1148 c.tmp[0] = alertLevelError
1149 c.tmp[1] = byte(err.(alert))
1150 c.writeRecord(recordTypeAlert, c.tmp[0:2])
1151 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
1152 }
1153 }
1154 return
1155}
1156
David Benjamin582ba042016-07-07 12:33:25 -07001157func (c *Conn) flushHandshake() error {
1158 if c.isDTLS {
1159 return c.dtlsFlushHandshake()
1160 }
1161
1162 for c.pendingFlight.Len() > 0 {
1163 var buf [maxPlaintext]byte
1164 n, _ := c.pendingFlight.Read(buf[:])
1165 if _, err := c.doWriteRecord(recordTypeHandshake, buf[:n]); err != nil {
1166 return err
1167 }
1168 }
1169
1170 c.pendingFlight.Reset()
1171 return nil
1172}
1173
David Benjamin83c0bc92014-08-04 01:23:53 -04001174func (c *Conn) doReadHandshake() ([]byte, error) {
1175 if c.isDTLS {
1176 return c.dtlsDoReadHandshake()
1177 }
1178
Adam Langley95c29f32014-06-20 12:00:00 -07001179 for c.hand.Len() < 4 {
1180 if err := c.in.err; err != nil {
1181 return nil, err
1182 }
1183 if err := c.readRecord(recordTypeHandshake); err != nil {
1184 return nil, err
1185 }
1186 }
1187
1188 data := c.hand.Bytes()
1189 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1190 if n > maxHandshake {
1191 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
1192 }
1193 for c.hand.Len() < 4+n {
1194 if err := c.in.err; err != nil {
1195 return nil, err
1196 }
1197 if err := c.readRecord(recordTypeHandshake); err != nil {
1198 return nil, err
1199 }
1200 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001201 return c.hand.Next(4 + n), nil
1202}
1203
1204// readHandshake reads the next handshake message from
1205// the record layer.
1206// c.in.Mutex < L; c.out.Mutex < L.
1207func (c *Conn) readHandshake() (interface{}, error) {
1208 data, err := c.doReadHandshake()
David Benjamin053fee92017-01-02 08:30:36 -05001209 if err == errNoCertificateAlert {
1210 if c.hand.Len() != 0 {
1211 // The warning alert may not interleave with a handshake message.
1212 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1213 }
1214 return new(ssl3NoCertificateMsg), nil
1215 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001216 if err != nil {
1217 return nil, err
1218 }
1219
Adam Langley95c29f32014-06-20 12:00:00 -07001220 var m handshakeMessage
1221 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001222 case typeHelloRequest:
1223 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001224 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001225 m = &clientHelloMsg{
1226 isDTLS: c.isDTLS,
1227 }
Adam Langley95c29f32014-06-20 12:00:00 -07001228 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001229 m = &serverHelloMsg{
1230 isDTLS: c.isDTLS,
1231 }
Nick Harperdcfbc672016-07-16 17:47:31 +02001232 case typeHelloRetryRequest:
1233 m = new(helloRetryRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001234 case typeNewSessionTicket:
David Benjamin58104882016-07-18 01:25:41 +02001235 m = &newSessionTicketMsg{
1236 version: c.vers,
1237 }
Nick Harperb41d2e42016-07-01 17:50:32 -04001238 case typeEncryptedExtensions:
1239 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001240 case typeCertificate:
Nick Harperb41d2e42016-07-01 17:50:32 -04001241 m = &certificateMsg{
David Benjamin8d315d72016-07-18 01:03:18 +02001242 hasRequestContext: c.vers >= VersionTLS13,
Nick Harperb41d2e42016-07-01 17:50:32 -04001243 }
Adam Langley95c29f32014-06-20 12:00:00 -07001244 case typeCertificateRequest:
1245 m = &certificateRequestMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001246 hasSignatureAlgorithm: c.vers >= VersionTLS12,
David Benjamin8d315d72016-07-18 01:03:18 +02001247 hasRequestContext: c.vers >= VersionTLS13,
Adam Langley95c29f32014-06-20 12:00:00 -07001248 }
1249 case typeCertificateStatus:
1250 m = new(certificateStatusMsg)
1251 case typeServerKeyExchange:
1252 m = new(serverKeyExchangeMsg)
1253 case typeServerHelloDone:
1254 m = new(serverHelloDoneMsg)
1255 case typeClientKeyExchange:
1256 m = new(clientKeyExchangeMsg)
1257 case typeCertificateVerify:
1258 m = &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001259 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001260 }
1261 case typeNextProtocol:
1262 m = new(nextProtoMsg)
1263 case typeFinished:
1264 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001265 case typeHelloVerifyRequest:
1266 m = new(helloVerifyRequestMsg)
David Benjamin24599a82016-06-30 18:56:53 -04001267 case typeChannelID:
1268 m = new(channelIDMsg)
David Benjamin21c00282016-07-18 21:56:23 +02001269 case typeKeyUpdate:
1270 m = new(keyUpdateMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001271 default:
1272 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1273 }
1274
1275 // The handshake message unmarshallers
1276 // expect to be able to keep references to data,
1277 // so pass in a fresh copy that won't be overwritten.
1278 data = append([]byte(nil), data...)
1279
1280 if !m.unmarshal(data) {
1281 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1282 }
1283 return m, nil
1284}
1285
David Benjamin83f90402015-01-27 01:09:43 -05001286// skipPacket processes all the DTLS records in packet. It updates
1287// sequence number expectations but otherwise ignores them.
1288func (c *Conn) skipPacket(packet []byte) error {
1289 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001290 if len(packet) < 13 {
1291 return errors.New("tls: bad packet")
1292 }
David Benjamin83f90402015-01-27 01:09:43 -05001293 // Dropped packets are completely ignored save to update
1294 // expected sequence numbers for this and the next epoch. (We
1295 // don't assert on the contents of the packets both for
1296 // simplicity and because a previous test with one shorter
1297 // timeout schedule would have done so.)
1298 epoch := packet[3:5]
1299 seq := packet[5:11]
1300 length := uint16(packet[11])<<8 | uint16(packet[12])
1301 if bytes.Equal(c.in.seq[:2], epoch) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001302 if bytes.Compare(seq, c.in.seq[2:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001303 return errors.New("tls: sequence mismatch")
1304 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001305 copy(c.in.seq[2:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001306 c.in.incSeq(false)
1307 } else {
David Benjamin13e81fc2015-11-02 17:16:13 -05001308 if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001309 return errors.New("tls: sequence mismatch")
1310 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001311 copy(c.in.nextSeq[:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001312 c.in.incNextSeq()
1313 }
David Benjamin6ca93552015-08-28 16:16:25 -04001314 if len(packet) < 13+int(length) {
1315 return errors.New("tls: bad packet")
1316 }
David Benjamin83f90402015-01-27 01:09:43 -05001317 packet = packet[13+length:]
1318 }
1319 return nil
1320}
1321
1322// simulatePacketLoss simulates the loss of a handshake leg from the
1323// peer based on the schedule in c.config.Bugs. If resendFunc is
1324// non-nil, it is called after each simulated timeout to retransmit
1325// handshake messages from the local end. This is used in cases where
1326// the peer retransmits on a stale Finished rather than a timeout.
1327func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1328 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1329 return nil
1330 }
1331 if !c.isDTLS {
1332 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1333 }
1334 if c.config.Bugs.PacketAdaptor == nil {
1335 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1336 }
1337 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1338 // Simulate a timeout.
1339 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1340 if err != nil {
1341 return err
1342 }
1343 for _, packet := range packets {
1344 if err := c.skipPacket(packet); err != nil {
1345 return err
1346 }
1347 }
1348 if resendFunc != nil {
1349 resendFunc()
1350 }
1351 }
1352 return nil
1353}
1354
David Benjamin47921102016-07-28 11:29:18 -04001355func (c *Conn) SendHalfHelloRequest() error {
1356 if err := c.Handshake(); err != nil {
1357 return err
1358 }
1359
1360 c.out.Lock()
1361 defer c.out.Unlock()
1362
1363 if _, err := c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0}); err != nil {
1364 return err
1365 }
1366 return c.flushHandshake()
1367}
1368
Adam Langley95c29f32014-06-20 12:00:00 -07001369// Write writes data to the connection.
1370func (c *Conn) Write(b []byte) (int, error) {
1371 if err := c.Handshake(); err != nil {
1372 return 0, err
1373 }
1374
1375 c.out.Lock()
1376 defer c.out.Unlock()
1377
David Benjamin12d2c482016-07-24 10:56:51 -04001378 // Flush any pending handshake data. PackHelloRequestWithFinished may
1379 // have been set and the handshake not followed by Renegotiate.
1380 c.flushHandshake()
1381
Adam Langley95c29f32014-06-20 12:00:00 -07001382 if err := c.out.err; err != nil {
1383 return 0, err
1384 }
1385
1386 if !c.handshakeComplete {
1387 return 0, alertInternalError
1388 }
1389
Steven Valdezc4aa7272016-10-03 12:25:56 -04001390 if c.keyUpdateRequested {
1391 if err := c.sendKeyUpdateLocked(keyUpdateNotRequested); err != nil {
David Benjamin21c00282016-07-18 21:56:23 +02001392 return 0, err
1393 }
Steven Valdezc4aa7272016-10-03 12:25:56 -04001394 c.keyUpdateRequested = false
David Benjamin21c00282016-07-18 21:56:23 +02001395 }
1396
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001397 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001398 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001399 }
1400
Adam Langley27a0d082015-11-03 13:34:10 -08001401 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1402 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
David Benjamin582ba042016-07-07 12:33:25 -07001403 c.flushHandshake()
Adam Langley27a0d082015-11-03 13:34:10 -08001404 }
1405
Adam Langley95c29f32014-06-20 12:00:00 -07001406 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1407 // attack when using block mode ciphers due to predictable IVs.
1408 // This can be prevented by splitting each Application Data
1409 // record into two records, effectively randomizing the IV.
1410 //
1411 // http://www.openssl.org/~bodo/tls-cbc.txt
1412 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1413 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1414
1415 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001416 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001417 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1418 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1419 if err != nil {
1420 return n, c.out.setErrorLocked(err)
1421 }
1422 m, b = 1, b[1:]
1423 }
1424 }
1425
1426 n, err := c.writeRecord(recordTypeApplicationData, b)
1427 return n + m, c.out.setErrorLocked(err)
1428}
1429
David Benjamind5a4ecb2016-07-18 01:17:13 +02001430func (c *Conn) handlePostHandshakeMessage() error {
Adam Langley2ae77d22014-10-28 17:29:33 -07001431 msg, err := c.readHandshake()
1432 if err != nil {
1433 return err
1434 }
David Benjamind5a4ecb2016-07-18 01:17:13 +02001435
1436 if c.vers < VersionTLS13 {
1437 if !c.isClient {
1438 c.sendAlert(alertUnexpectedMessage)
1439 return errors.New("tls: unexpected post-handshake message")
1440 }
1441
1442 _, ok := msg.(*helloRequestMsg)
1443 if !ok {
1444 c.sendAlert(alertUnexpectedMessage)
1445 return alertUnexpectedMessage
1446 }
1447
1448 c.handshakeComplete = false
1449 return c.Handshake()
Adam Langley2ae77d22014-10-28 17:29:33 -07001450 }
1451
David Benjamind5a4ecb2016-07-18 01:17:13 +02001452 if c.isClient {
1453 if newSessionTicket, ok := msg.(*newSessionTicketMsg); ok {
David Benjamin1a5e8ec2016-10-07 15:19:18 -04001454 if c.config.Bugs.ExpectGREASE && !newSessionTicket.hasGREASEExtension {
1455 return errors.New("tls: no GREASE ticket extension found")
1456 }
1457
Steven Valdez08b65f42016-12-07 15:29:45 -05001458 if c.config.Bugs.ExpectTicketEarlyDataInfo && newSessionTicket.earlyDataInfo == 0 {
1459 return errors.New("tls: no ticket_early_data_info extension found")
1460 }
1461
Steven Valdeza833c352016-11-01 13:39:36 -04001462 if c.config.Bugs.ExpectNoNewSessionTicket {
1463 return errors.New("tls: received unexpected NewSessionTicket")
1464 }
1465
David Benjamind5a4ecb2016-07-18 01:17:13 +02001466 if c.config.ClientSessionCache == nil || newSessionTicket.ticketLifetime == 0 {
1467 return nil
1468 }
1469
1470 session := &ClientSessionState{
1471 sessionTicket: newSessionTicket.ticket,
1472 vers: c.vers,
1473 cipherSuite: c.cipherSuite.id,
1474 masterSecret: c.resumptionSecret,
1475 serverCertificates: c.peerCertificates,
1476 sctList: c.sctList,
1477 ocspResponse: c.ocspResponse,
Nick Harper0b3625b2016-07-25 16:16:28 -07001478 ticketCreationTime: c.config.time(),
1479 ticketExpiration: c.config.time().Add(time.Duration(newSessionTicket.ticketLifetime) * time.Second),
Steven Valdeza833c352016-11-01 13:39:36 -04001480 ticketAgeAdd: newSessionTicket.ticketAgeAdd,
David Benjamind5a4ecb2016-07-18 01:17:13 +02001481 }
1482
1483 cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
1484 c.config.ClientSessionCache.Put(cacheKey, session)
1485 return nil
1486 }
1487 }
1488
Steven Valdezc4aa7272016-10-03 12:25:56 -04001489 if keyUpdate, ok := msg.(*keyUpdateMsg); ok {
Steven Valdez1dc53d22016-07-26 12:27:38 -04001490 c.in.doKeyUpdate(c, false)
Steven Valdezc4aa7272016-10-03 12:25:56 -04001491 if keyUpdate.keyUpdateRequest == keyUpdateRequested {
1492 c.keyUpdateRequested = true
1493 }
David Benjamin21c00282016-07-18 21:56:23 +02001494 return nil
1495 }
1496
David Benjamind5a4ecb2016-07-18 01:17:13 +02001497 // TODO(davidben): Add support for KeyUpdate.
1498 c.sendAlert(alertUnexpectedMessage)
1499 return alertUnexpectedMessage
Adam Langley2ae77d22014-10-28 17:29:33 -07001500}
1501
Adam Langleycf2d4f42014-10-28 19:06:14 -07001502func (c *Conn) Renegotiate() error {
1503 if !c.isClient {
David Benjaminef5dfd22015-12-06 13:17:07 -05001504 helloReq := new(helloRequestMsg).marshal()
1505 if c.config.Bugs.BadHelloRequest != nil {
1506 helloReq = c.config.Bugs.BadHelloRequest
1507 }
1508 c.writeRecord(recordTypeHandshake, helloReq)
David Benjamin582ba042016-07-07 12:33:25 -07001509 c.flushHandshake()
Adam Langleycf2d4f42014-10-28 19:06:14 -07001510 }
1511
1512 c.handshakeComplete = false
1513 return c.Handshake()
1514}
1515
Adam Langley95c29f32014-06-20 12:00:00 -07001516// Read can be made to time out and return a net.Error with Timeout() == true
1517// after a fixed time limit; see SetDeadline and SetReadDeadline.
1518func (c *Conn) Read(b []byte) (n int, err error) {
1519 if err = c.Handshake(); err != nil {
1520 return
1521 }
1522
1523 c.in.Lock()
1524 defer c.in.Unlock()
1525
1526 // Some OpenSSL servers send empty records in order to randomize the
1527 // CBC IV. So this loop ignores a limited number of empty records.
1528 const maxConsecutiveEmptyRecords = 100
1529 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1530 for c.input == nil && c.in.err == nil {
1531 if err := c.readRecord(recordTypeApplicationData); err != nil {
1532 // Soft error, like EAGAIN
1533 return 0, err
1534 }
David Benjamind9b091b2015-01-27 01:10:54 -05001535 if c.hand.Len() > 0 {
David Benjamind5a4ecb2016-07-18 01:17:13 +02001536 // We received handshake bytes, indicating a
1537 // post-handshake message.
1538 if err := c.handlePostHandshakeMessage(); err != nil {
Adam Langley2ae77d22014-10-28 17:29:33 -07001539 return 0, err
1540 }
1541 continue
1542 }
Adam Langley95c29f32014-06-20 12:00:00 -07001543 }
1544 if err := c.in.err; err != nil {
1545 return 0, err
1546 }
1547
1548 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001549 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001550 c.in.freeBlock(c.input)
1551 c.input = nil
1552 }
1553
1554 // If a close-notify alert is waiting, read it so that
1555 // we can return (n, EOF) instead of (n, nil), to signal
1556 // to the HTTP response reading goroutine that the
1557 // connection is now closed. This eliminates a race
1558 // where the HTTP response reading goroutine would
1559 // otherwise not observe the EOF until its next read,
1560 // by which time a client goroutine might have already
1561 // tried to reuse the HTTP connection for a new
1562 // request.
1563 // See https://codereview.appspot.com/76400046
1564 // and http://golang.org/issue/3514
1565 if ri := c.rawInput; ri != nil &&
1566 n != 0 && err == nil &&
1567 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1568 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1569 err = recErr // will be io.EOF on closeNotify
1570 }
1571 }
1572
1573 if n != 0 || err != nil {
1574 return n, err
1575 }
1576 }
1577
1578 return 0, io.ErrNoProgress
1579}
1580
1581// Close closes the connection.
1582func (c *Conn) Close() error {
1583 var alertErr error
1584
1585 c.handshakeMutex.Lock()
1586 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001587 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
David Benjaminfa214e42016-05-10 17:03:10 -04001588 alert := alertCloseNotify
1589 if c.config.Bugs.SendAlertOnShutdown != 0 {
1590 alert = c.config.Bugs.SendAlertOnShutdown
1591 }
1592 alertErr = c.sendAlert(alert)
David Benjamin4d559612016-05-18 14:31:51 -04001593 // Clear local alerts when sending alerts so we continue to wait
1594 // for the peer rather than closing the socket early.
1595 if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1596 alertErr = nil
1597 }
Adam Langley95c29f32014-06-20 12:00:00 -07001598 }
1599
David Benjamin30789da2015-08-29 22:56:45 -04001600 // Consume a close_notify from the peer if one hasn't been received
1601 // already. This avoids the peer from failing |SSL_shutdown| due to a
1602 // write failing.
1603 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1604 for c.in.error() == nil {
1605 c.readRecord(recordTypeAlert)
1606 }
1607 if c.in.error() != io.EOF {
1608 alertErr = c.in.error()
1609 }
1610 }
1611
Adam Langley95c29f32014-06-20 12:00:00 -07001612 if err := c.conn.Close(); err != nil {
1613 return err
1614 }
1615 return alertErr
1616}
1617
1618// Handshake runs the client or server handshake
1619// protocol if it has not yet been run.
1620// Most uses of this package need not call Handshake
1621// explicitly: the first Read or Write will call it automatically.
1622func (c *Conn) Handshake() error {
1623 c.handshakeMutex.Lock()
1624 defer c.handshakeMutex.Unlock()
1625 if err := c.handshakeErr; err != nil {
1626 return err
1627 }
1628 if c.handshakeComplete {
1629 return nil
1630 }
1631
David Benjamin9a41d1b2015-05-16 01:30:09 -04001632 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1633 c.conn.Write([]byte{
1634 byte(recordTypeAlert), // type
1635 0xfe, 0xff, // version
1636 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1637 0x0, 0x2, // length
1638 })
1639 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1640 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001641 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1642 c.writeRecord(recordTypeApplicationData, data)
1643 }
Adam Langley95c29f32014-06-20 12:00:00 -07001644 if c.isClient {
1645 c.handshakeErr = c.clientHandshake()
1646 } else {
1647 c.handshakeErr = c.serverHandshake()
1648 }
David Benjaminddb9f152015-02-03 15:44:39 -05001649 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1650 c.writeRecord(recordType(42), []byte("invalid record"))
1651 }
Adam Langley95c29f32014-06-20 12:00:00 -07001652 return c.handshakeErr
1653}
1654
1655// ConnectionState returns basic TLS details about the connection.
1656func (c *Conn) ConnectionState() ConnectionState {
1657 c.handshakeMutex.Lock()
1658 defer c.handshakeMutex.Unlock()
1659
1660 var state ConnectionState
1661 state.HandshakeComplete = c.handshakeComplete
1662 if c.handshakeComplete {
1663 state.Version = c.vers
1664 state.NegotiatedProtocol = c.clientProtocol
1665 state.DidResume = c.didResume
1666 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001667 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001668 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001669 state.PeerCertificates = c.peerCertificates
1670 state.VerifiedChains = c.verifiedChains
1671 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001672 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001673 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001674 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001675 state.SCTList = c.sctList
Nick Harper60edffd2016-06-21 15:19:24 -07001676 state.PeerSignatureAlgorithm = c.peerSignatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -04001677 state.CurveID = c.curveID
David Benjamin6f600d62016-12-21 16:06:54 -05001678 state.ShortHeader = c.in.shortHeader
Adam Langley95c29f32014-06-20 12:00:00 -07001679 }
1680
1681 return state
1682}
1683
1684// OCSPResponse returns the stapled OCSP response from the TLS server, if
1685// any. (Only valid for client connections.)
1686func (c *Conn) OCSPResponse() []byte {
1687 c.handshakeMutex.Lock()
1688 defer c.handshakeMutex.Unlock()
1689
1690 return c.ocspResponse
1691}
1692
1693// VerifyHostname checks that the peer certificate chain is valid for
1694// connecting to host. If so, it returns nil; if not, it returns an error
1695// describing the problem.
1696func (c *Conn) VerifyHostname(host string) error {
1697 c.handshakeMutex.Lock()
1698 defer c.handshakeMutex.Unlock()
1699 if !c.isClient {
1700 return errors.New("tls: VerifyHostname called on TLS server connection")
1701 }
1702 if !c.handshakeComplete {
1703 return errors.New("tls: handshake has not yet been performed")
1704 }
1705 return c.peerCertificates[0].VerifyHostname(host)
1706}
David Benjaminc565ebb2015-04-03 04:06:36 -04001707
1708// ExportKeyingMaterial exports keying material from the current connection
1709// state, as per RFC 5705.
1710func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1711 c.handshakeMutex.Lock()
1712 defer c.handshakeMutex.Unlock()
1713 if !c.handshakeComplete {
1714 return nil, errors.New("tls: handshake has not yet been performed")
1715 }
1716
David Benjamin8d315d72016-07-18 01:03:18 +02001717 if c.vers >= VersionTLS13 {
David Benjamin97a0a082016-07-13 17:57:35 -04001718 // TODO(davidben): What should we do with useContext? See
1719 // https://github.com/tlswg/tls13-spec/issues/546
1720 return hkdfExpandLabel(c.cipherSuite.hash(), c.exporterSecret, label, context, length), nil
1721 }
1722
David Benjaminc565ebb2015-04-03 04:06:36 -04001723 seedLen := len(c.clientRandom) + len(c.serverRandom)
1724 if useContext {
1725 seedLen += 2 + len(context)
1726 }
1727 seed := make([]byte, 0, seedLen)
1728 seed = append(seed, c.clientRandom[:]...)
1729 seed = append(seed, c.serverRandom[:]...)
1730 if useContext {
1731 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1732 seed = append(seed, context...)
1733 }
1734 result := make([]byte, length)
David Benjamin97a0a082016-07-13 17:57:35 -04001735 prfForVersion(c.vers, c.cipherSuite)(result, c.exporterSecret, label, seed)
David Benjaminc565ebb2015-04-03 04:06:36 -04001736 return result, nil
1737}
David Benjamin3e052de2015-11-25 20:10:31 -05001738
1739// noRenegotiationInfo returns true if the renegotiation info extension
1740// should be supported in the current handshake.
1741func (c *Conn) noRenegotiationInfo() bool {
1742 if c.config.Bugs.NoRenegotiationInfo {
1743 return true
1744 }
1745 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1746 return true
1747 }
1748 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1749 return true
1750 }
1751 return false
1752}
David Benjamin58104882016-07-18 01:25:41 +02001753
1754func (c *Conn) SendNewSessionTicket() error {
1755 if c.isClient || c.vers < VersionTLS13 {
1756 return errors.New("tls: cannot send post-handshake NewSessionTicket")
1757 }
1758
1759 var peerCertificatesRaw [][]byte
1760 for _, cert := range c.peerCertificates {
1761 peerCertificatesRaw = append(peerCertificatesRaw, cert.Raw)
1762 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001763
Steven Valdeza833c352016-11-01 13:39:36 -04001764 addBuffer := make([]byte, 4)
1765 _, err := io.ReadFull(c.config.rand(), addBuffer)
1766 if err != nil {
1767 c.sendAlert(alertInternalError)
1768 return errors.New("tls: short read from Rand: " + err.Error())
1769 }
1770 ticketAgeAdd := uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0])
1771
David Benjamin58104882016-07-18 01:25:41 +02001772 // TODO(davidben): Allow configuring these values.
1773 m := &newSessionTicketMsg{
David Benjamin9c33ae82017-01-08 06:04:43 -05001774 version: c.vers,
1775 ticketLifetime: uint32(24 * time.Hour / time.Second),
1776 earlyDataInfo: c.config.Bugs.SendTicketEarlyDataInfo,
1777 duplicateEarlyDataInfo: c.config.Bugs.DuplicateTicketEarlyDataInfo,
1778 customExtension: c.config.Bugs.CustomTicketExtension,
1779 ticketAgeAdd: ticketAgeAdd,
David Benjamin58104882016-07-18 01:25:41 +02001780 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001781
1782 state := sessionState{
1783 vers: c.vers,
1784 cipherSuite: c.cipherSuite.id,
1785 masterSecret: c.resumptionSecret,
1786 certificates: peerCertificatesRaw,
1787 ticketCreationTime: c.config.time(),
1788 ticketExpiration: c.config.time().Add(time.Duration(m.ticketLifetime) * time.Second),
Steven Valdeza833c352016-11-01 13:39:36 -04001789 ticketAgeAdd: uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0]),
Nick Harper0b3625b2016-07-25 16:16:28 -07001790 }
1791
David Benjamin58104882016-07-18 01:25:41 +02001792 if !c.config.Bugs.SendEmptySessionTicket {
1793 var err error
1794 m.ticket, err = c.encryptTicket(&state)
1795 if err != nil {
1796 return err
1797 }
1798 }
1799
1800 c.out.Lock()
1801 defer c.out.Unlock()
Steven Valdeza833c352016-11-01 13:39:36 -04001802 _, err = c.writeRecord(recordTypeHandshake, m.marshal())
David Benjamin58104882016-07-18 01:25:41 +02001803 return err
1804}
David Benjamin21c00282016-07-18 21:56:23 +02001805
Steven Valdezc4aa7272016-10-03 12:25:56 -04001806func (c *Conn) SendKeyUpdate(keyUpdateRequest byte) error {
David Benjamin21c00282016-07-18 21:56:23 +02001807 c.out.Lock()
1808 defer c.out.Unlock()
Steven Valdezc4aa7272016-10-03 12:25:56 -04001809 return c.sendKeyUpdateLocked(keyUpdateRequest)
David Benjamin21c00282016-07-18 21:56:23 +02001810}
1811
Steven Valdezc4aa7272016-10-03 12:25:56 -04001812func (c *Conn) sendKeyUpdateLocked(keyUpdateRequest byte) error {
David Benjamin7f0965a2016-09-30 15:14:01 -04001813 if c.vers < VersionTLS13 {
1814 return errors.New("tls: attempted to send KeyUpdate before TLS 1.3")
1815 }
1816
Steven Valdezc4aa7272016-10-03 12:25:56 -04001817 m := keyUpdateMsg{
1818 keyUpdateRequest: keyUpdateRequest,
1819 }
David Benjamin21c00282016-07-18 21:56:23 +02001820 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
1821 return err
1822 }
1823 if err := c.flushHandshake(); err != nil {
1824 return err
1825 }
Steven Valdez1dc53d22016-07-26 12:27:38 -04001826 c.out.doKeyUpdate(c, true)
David Benjamin21c00282016-07-18 21:56:23 +02001827 return nil
1828}
Steven Valdeza4ee74d2016-11-29 13:36:45 -05001829
1830func (c *Conn) sendFakeEarlyData(len int) error {
1831 // Assemble a fake early data record. This does not use writeRecord
1832 // because the record layer may be using different keys at this point.
1833 payload := make([]byte, 5+len)
1834 payload[0] = byte(recordTypeApplicationData)
1835 payload[1] = 3
1836 payload[2] = 1
1837 payload[3] = byte(len >> 8)
1838 payload[4] = byte(len)
1839 _, err := c.conn.Write(payload)
1840 return err
1841}
David Benjamin6f600d62016-12-21 16:06:54 -05001842
1843func (c *Conn) setShortHeader() {
1844 c.in.shortHeader = true
1845 c.out.shortHeader = true
1846}