blob: a4cb573de04ade6cff61925e15bbd30ae0208715 [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")
Nick Harperab20cec2016-12-19 17:38:41 -080025var errEndOfEarlyDataAlert = errors.New("tls: end of early data alert")
David Benjamin053fee92017-01-02 08:30:36 -050026
Adam Langley95c29f32014-06-20 12:00:00 -070027// A Conn represents a secured connection.
28// It implements the net.Conn interface.
29type Conn struct {
30 // constant
31 conn net.Conn
David Benjamin83c0bc92014-08-04 01:23:53 -040032 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -070033 isClient bool
34
35 // constant after handshake; protected by handshakeMutex
Adam Langley75712922014-10-10 16:23:43 -070036 handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
37 handshakeErr error // error resulting from handshake
38 vers uint16 // TLS version
39 haveVers bool // version has been negotiated
40 config *Config // configuration passed to constructor
41 handshakeComplete bool
Nick Harperab20cec2016-12-19 17:38:41 -080042 skipEarlyData bool // On a server, indicates that the client is sending early data that must be skipped over.
Adam Langley75712922014-10-10 16:23:43 -070043 didResume bool // whether this connection was a session resumption
44 extendedMasterSecret bool // whether this session used an extended master secret
David Benjaminc565ebb2015-04-03 04:06:36 -040045 cipherSuite *cipherSuite
Adam Langley75712922014-10-10 16:23:43 -070046 ocspResponse []byte // stapled OCSP response
Paul Lietar4fac72e2015-09-09 13:44:55 +010047 sctList []byte // signed certificate timestamp list
Adam Langley75712922014-10-10 16:23:43 -070048 peerCertificates []*x509.Certificate
Adam Langley95c29f32014-06-20 12:00:00 -070049 // verifiedChains contains the certificate chains that we built, as
50 // opposed to the ones presented by the server.
51 verifiedChains [][]*x509.Certificate
52 // serverName contains the server name indicated by the client, if any.
Adam Langleyaf0e32c2015-06-03 09:57:23 -070053 serverName string
54 // firstFinished contains the first Finished hash sent during the
55 // handshake. This is the "tls-unique" channel binding value.
56 firstFinished [12]byte
Nick Harper60edffd2016-06-21 15:19:24 -070057 // peerSignatureAlgorithm contains the signature algorithm that was used
58 // by the peer in the handshake, or zero if not applicable.
59 peerSignatureAlgorithm signatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -040060 // curveID contains the curve that was used in the handshake, or zero if
61 // not applicable.
62 curveID CurveID
Adam Langleyaf0e32c2015-06-03 09:57:23 -070063
David Benjaminc565ebb2015-04-03 04:06:36 -040064 clientRandom, serverRandom [32]byte
David Benjamin97a0a082016-07-13 17:57:35 -040065 exporterSecret []byte
David Benjamin58104882016-07-18 01:25:41 +020066 resumptionSecret []byte
Adam Langley95c29f32014-06-20 12:00:00 -070067
68 clientProtocol string
69 clientProtocolFallback bool
David Benjaminfc7b0862014-09-06 13:21:53 -040070 usedALPN bool
Adam Langley95c29f32014-06-20 12:00:00 -070071
Adam Langley2ae77d22014-10-28 17:29:33 -070072 // verify_data values for the renegotiation extension.
73 clientVerify []byte
74 serverVerify []byte
75
David Benjamind30a9902014-08-24 01:44:23 -040076 channelID *ecdsa.PublicKey
77
David Benjaminca6c8262014-11-15 19:06:08 -050078 srtpProtectionProfile uint16
79
David Benjaminc44b1df2014-11-23 12:11:01 -050080 clientVersion uint16
81
Adam Langley95c29f32014-06-20 12:00:00 -070082 // input/output
83 in, out halfConn // in.Mutex < out.Mutex
84 rawInput *block // raw input, right off the wire
David Benjamin83c0bc92014-08-04 01:23:53 -040085 input *block // application record waiting to be read
86 hand bytes.Buffer // handshake record waiting to be read
87
David Benjamin582ba042016-07-07 12:33:25 -070088 // pendingFlight, if PackHandshakeFlight is enabled, is the buffer of
89 // handshake data to be split into records at the end of the flight.
90 pendingFlight bytes.Buffer
91
David Benjamin83c0bc92014-08-04 01:23:53 -040092 // DTLS state
93 sendHandshakeSeq uint16
94 recvHandshakeSeq uint16
David Benjaminb3774b92015-01-31 17:16:01 -050095 handMsg []byte // pending assembled handshake message
96 handMsgLen int // handshake message length, not including the header
97 pendingFragments [][]byte // pending outgoing handshake fragments.
Adam Langley95c29f32014-06-20 12:00:00 -070098
Steven Valdezc4aa7272016-10-03 12:25:56 -040099 keyUpdateRequested bool
100
Adam Langley95c29f32014-06-20 12:00:00 -0700101 tmp [16]byte
102}
103
David Benjamin5e961c12014-11-07 01:48:35 -0500104func (c *Conn) init() {
105 c.in.isDTLS = c.isDTLS
106 c.out.isDTLS = c.isDTLS
107 c.in.config = c.config
108 c.out.config = c.config
David Benjamin8e6db492015-07-25 18:29:23 -0400109
110 c.out.updateOutSeq()
David Benjamin5e961c12014-11-07 01:48:35 -0500111}
112
Adam Langley95c29f32014-06-20 12:00:00 -0700113// Access to net.Conn methods.
114// Cannot just embed net.Conn because that would
115// export the struct field too.
116
117// LocalAddr returns the local network address.
118func (c *Conn) LocalAddr() net.Addr {
119 return c.conn.LocalAddr()
120}
121
122// RemoteAddr returns the remote network address.
123func (c *Conn) RemoteAddr() net.Addr {
124 return c.conn.RemoteAddr()
125}
126
127// SetDeadline sets the read and write deadlines associated with the connection.
128// A zero value for t means Read and Write will not time out.
129// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
130func (c *Conn) SetDeadline(t time.Time) error {
131 return c.conn.SetDeadline(t)
132}
133
134// SetReadDeadline sets the read deadline on the underlying connection.
135// A zero value for t means Read will not time out.
136func (c *Conn) SetReadDeadline(t time.Time) error {
137 return c.conn.SetReadDeadline(t)
138}
139
140// SetWriteDeadline sets the write deadline on the underlying conneciton.
141// A zero value for t means Write will not time out.
142// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
143func (c *Conn) SetWriteDeadline(t time.Time) error {
144 return c.conn.SetWriteDeadline(t)
145}
146
147// A halfConn represents one direction of the record layer
148// connection, either sending or receiving.
149type halfConn struct {
150 sync.Mutex
151
David Benjamin83c0bc92014-08-04 01:23:53 -0400152 err error // first permanent error
153 version uint16 // protocol version
154 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -0700155 cipher interface{} // cipher algorithm
156 mac macFunction
157 seq [8]byte // 64-bit sequence number
David Benjamin8e6db492015-07-25 18:29:23 -0400158 outSeq [8]byte // Mapped sequence number
Adam Langley95c29f32014-06-20 12:00:00 -0700159 bfree *block // list of free blocks
160
161 nextCipher interface{} // next encryption state
162 nextMac macFunction // next MAC algorithm
David Benjamin83f90402015-01-27 01:09:43 -0500163 nextSeq [6]byte // next epoch's starting sequence number in DTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700164
165 // used to save allocating a new buffer for each MAC.
166 inDigestBuf, outDigestBuf []byte
Adam Langley80842bd2014-06-20 12:00:00 -0700167
Steven Valdezc4aa7272016-10-03 12:25:56 -0400168 trafficSecret []byte
David Benjamin21c00282016-07-18 21:56:23 +0200169
David Benjamin6f600d62016-12-21 16:06:54 -0500170 shortHeader bool
171
Adam Langley80842bd2014-06-20 12:00:00 -0700172 config *Config
Adam Langley95c29f32014-06-20 12:00:00 -0700173}
174
175func (hc *halfConn) setErrorLocked(err error) error {
176 hc.err = err
177 return err
178}
179
180func (hc *halfConn) error() error {
Adam Langley2ae77d22014-10-28 17:29:33 -0700181 // This should be locked, but I've removed it for the renegotiation
182 // tests since we don't concurrently read and write the same tls.Conn
183 // in any case during testing.
Adam Langley95c29f32014-06-20 12:00:00 -0700184 err := hc.err
Adam Langley95c29f32014-06-20 12:00:00 -0700185 return err
186}
187
188// prepareCipherSpec sets the encryption and MAC states
189// that a subsequent changeCipherSpec will use.
190func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
191 hc.version = version
192 hc.nextCipher = cipher
193 hc.nextMac = mac
194}
195
196// changeCipherSpec changes the encryption and MAC states
197// to the ones previously passed to prepareCipherSpec.
Adam Langley80842bd2014-06-20 12:00:00 -0700198func (hc *halfConn) changeCipherSpec(config *Config) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700199 if hc.nextCipher == nil {
200 return alertInternalError
201 }
202 hc.cipher = hc.nextCipher
203 hc.mac = hc.nextMac
204 hc.nextCipher = nil
205 hc.nextMac = nil
Adam Langley80842bd2014-06-20 12:00:00 -0700206 hc.config = config
David Benjamin83c0bc92014-08-04 01:23:53 -0400207 hc.incEpoch()
David Benjaminf2b83632016-03-01 22:57:46 -0500208
209 if config.Bugs.NullAllCiphers {
David Benjamin7a4aaa42016-09-20 17:58:14 -0400210 hc.cipher = nullCipher{}
David Benjaminf2b83632016-03-01 22:57:46 -0500211 hc.mac = nil
212 }
Adam Langley95c29f32014-06-20 12:00:00 -0700213 return nil
214}
215
David Benjamin21c00282016-07-18 21:56:23 +0200216// useTrafficSecret sets the current cipher state for TLS 1.3.
Steven Valdeza833c352016-11-01 13:39:36 -0400217func (hc *halfConn) useTrafficSecret(version uint16, suite *cipherSuite, secret []byte, side trafficDirection) {
Nick Harperb41d2e42016-07-01 17:50:32 -0400218 hc.version = version
Steven Valdeza833c352016-11-01 13:39:36 -0400219 hc.cipher = deriveTrafficAEAD(version, suite, secret, side)
David Benjamin7a4aaa42016-09-20 17:58:14 -0400220 if hc.config.Bugs.NullAllCiphers {
221 hc.cipher = nullCipher{}
222 }
David Benjamin21c00282016-07-18 21:56:23 +0200223 hc.trafficSecret = secret
Nick Harperb41d2e42016-07-01 17:50:32 -0400224 hc.incEpoch()
225}
226
Nick Harperf2511f12016-12-06 16:02:31 -0800227// resetCipher changes the cipher state back to no encryption to be able
228// to send an unencrypted ClientHello in response to HelloRetryRequest
229// after 0-RTT data was rejected.
230func (hc *halfConn) resetCipher() {
231 hc.cipher = nil
232 hc.incEpoch()
233}
234
David Benjamin21c00282016-07-18 21:56:23 +0200235func (hc *halfConn) doKeyUpdate(c *Conn, isOutgoing bool) {
236 side := serverWrite
237 if c.isClient == isOutgoing {
238 side = clientWrite
239 }
Steven Valdeza833c352016-11-01 13:39:36 -0400240 hc.useTrafficSecret(hc.version, c.cipherSuite, updateTrafficSecret(c.cipherSuite.hash(), hc.trafficSecret), side)
David Benjamin21c00282016-07-18 21:56:23 +0200241}
242
Adam Langley95c29f32014-06-20 12:00:00 -0700243// incSeq increments the sequence number.
David Benjamin5e961c12014-11-07 01:48:35 -0500244func (hc *halfConn) incSeq(isOutgoing bool) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400245 limit := 0
David Benjamin5e961c12014-11-07 01:48:35 -0500246 increment := uint64(1)
David Benjamin83c0bc92014-08-04 01:23:53 -0400247 if hc.isDTLS {
248 // Increment up to the epoch in DTLS.
249 limit = 2
250 }
251 for i := 7; i >= limit; i-- {
David Benjamin5e961c12014-11-07 01:48:35 -0500252 increment += uint64(hc.seq[i])
253 hc.seq[i] = byte(increment)
254 increment >>= 8
Adam Langley95c29f32014-06-20 12:00:00 -0700255 }
256
257 // Not allowed to let sequence number wrap.
258 // Instead, must renegotiate before it does.
259 // Not likely enough to bother.
David Benjamin5e961c12014-11-07 01:48:35 -0500260 if increment != 0 {
261 panic("TLS: sequence number wraparound")
262 }
David Benjamin8e6db492015-07-25 18:29:23 -0400263
264 hc.updateOutSeq()
Adam Langley95c29f32014-06-20 12:00:00 -0700265}
266
David Benjamin83f90402015-01-27 01:09:43 -0500267// incNextSeq increments the starting sequence number for the next epoch.
268func (hc *halfConn) incNextSeq() {
269 for i := len(hc.nextSeq) - 1; i >= 0; i-- {
270 hc.nextSeq[i]++
271 if hc.nextSeq[i] != 0 {
272 return
273 }
274 }
275 panic("TLS: sequence number wraparound")
276}
277
278// incEpoch resets the sequence number. In DTLS, it also increments the epoch
279// half of the sequence number.
David Benjamin83c0bc92014-08-04 01:23:53 -0400280func (hc *halfConn) incEpoch() {
David Benjamin83c0bc92014-08-04 01:23:53 -0400281 if hc.isDTLS {
282 for i := 1; i >= 0; i-- {
283 hc.seq[i]++
284 if hc.seq[i] != 0 {
285 break
286 }
287 if i == 0 {
288 panic("TLS: epoch number wraparound")
289 }
290 }
David Benjamin83f90402015-01-27 01:09:43 -0500291 copy(hc.seq[2:], hc.nextSeq[:])
292 for i := range hc.nextSeq {
293 hc.nextSeq[i] = 0
294 }
295 } else {
296 for i := range hc.seq {
297 hc.seq[i] = 0
298 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400299 }
David Benjamin8e6db492015-07-25 18:29:23 -0400300
301 hc.updateOutSeq()
302}
303
304func (hc *halfConn) updateOutSeq() {
305 if hc.config.Bugs.SequenceNumberMapping != nil {
306 seqU64 := binary.BigEndian.Uint64(hc.seq[:])
307 seqU64 = hc.config.Bugs.SequenceNumberMapping(seqU64)
308 binary.BigEndian.PutUint64(hc.outSeq[:], seqU64)
309
310 // The DTLS epoch cannot be changed.
311 copy(hc.outSeq[:2], hc.seq[:2])
312 return
313 }
314
315 copy(hc.outSeq[:], hc.seq[:])
David Benjamin83c0bc92014-08-04 01:23:53 -0400316}
317
David Benjamin6f600d62016-12-21 16:06:54 -0500318func (hc *halfConn) isShortHeader() bool {
319 return hc.shortHeader && hc.cipher != nil
320}
321
David Benjamin83c0bc92014-08-04 01:23:53 -0400322func (hc *halfConn) recordHeaderLen() int {
323 if hc.isDTLS {
324 return dtlsRecordHeaderLen
325 }
David Benjamin6f600d62016-12-21 16:06:54 -0500326 if hc.isShortHeader() {
327 return 2
328 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400329 return tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700330}
331
332// removePadding returns an unpadded slice, in constant time, which is a prefix
333// of the input. It also returns a byte which is equal to 255 if the padding
334// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
335func removePadding(payload []byte) ([]byte, byte) {
336 if len(payload) < 1 {
337 return payload, 0
338 }
339
340 paddingLen := payload[len(payload)-1]
341 t := uint(len(payload)-1) - uint(paddingLen)
342 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
343 good := byte(int32(^t) >> 31)
344
345 toCheck := 255 // the maximum possible padding length
346 // The length of the padded data is public, so we can use an if here
347 if toCheck+1 > len(payload) {
348 toCheck = len(payload) - 1
349 }
350
351 for i := 0; i < toCheck; i++ {
352 t := uint(paddingLen) - uint(i)
353 // if i <= paddingLen then the MSB of t is zero
354 mask := byte(int32(^t) >> 31)
355 b := payload[len(payload)-1-i]
356 good &^= mask&paddingLen ^ mask&b
357 }
358
359 // We AND together the bits of good and replicate the result across
360 // all the bits.
361 good &= good << 4
362 good &= good << 2
363 good &= good << 1
364 good = uint8(int8(good) >> 7)
365
366 toRemove := good&paddingLen + 1
367 return payload[:len(payload)-int(toRemove)], good
368}
369
370// removePaddingSSL30 is a replacement for removePadding in the case that the
371// protocol version is SSLv3. In this version, the contents of the padding
372// are random and cannot be checked.
373func removePaddingSSL30(payload []byte) ([]byte, byte) {
374 if len(payload) < 1 {
375 return payload, 0
376 }
377
378 paddingLen := int(payload[len(payload)-1]) + 1
379 if paddingLen > len(payload) {
380 return payload, 0
381 }
382
383 return payload[:len(payload)-paddingLen], 255
384}
385
386func roundUp(a, b int) int {
387 return a + (b-a%b)%b
388}
389
390// cbcMode is an interface for block ciphers using cipher block chaining.
391type cbcMode interface {
392 cipher.BlockMode
393 SetIV([]byte)
394}
395
396// decrypt checks and strips the mac and decrypts the data in b. Returns a
397// success boolean, the number of bytes to skip from the start of the record in
Nick Harper1fd39d82016-06-14 18:14:35 -0700398// order to get the application payload, the encrypted record type (or 0
399// if there is none), and an optional alert value.
400func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, contentType recordType, alertValue alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400401 recordHeaderLen := hc.recordHeaderLen()
402
Adam Langley95c29f32014-06-20 12:00:00 -0700403 // pull out payload
404 payload := b.data[recordHeaderLen:]
405
406 macSize := 0
407 if hc.mac != nil {
408 macSize = hc.mac.Size()
409 }
410
411 paddingGood := byte(255)
412 explicitIVLen := 0
413
David Benjamin83c0bc92014-08-04 01:23:53 -0400414 seq := hc.seq[:]
415 if hc.isDTLS {
416 // DTLS sequence numbers are explicit.
417 seq = b.data[3:11]
418 }
419
Adam Langley95c29f32014-06-20 12:00:00 -0700420 // decrypt
421 if hc.cipher != nil {
422 switch c := hc.cipher.(type) {
423 case cipher.Stream:
424 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400425 case *tlsAead:
426 nonce := seq
427 if c.explicitNonce {
428 explicitIVLen = 8
429 if len(payload) < explicitIVLen {
Nick Harper1fd39d82016-06-14 18:14:35 -0700430 return false, 0, 0, alertBadRecordMAC
David Benjamine9a80ff2015-04-07 00:46:46 -0400431 }
432 nonce = payload[:8]
433 payload = payload[8:]
Adam Langley95c29f32014-06-20 12:00:00 -0700434 }
Adam Langley95c29f32014-06-20 12:00:00 -0700435
Nick Harper1fd39d82016-06-14 18:14:35 -0700436 var additionalData []byte
437 if hc.version < VersionTLS13 {
438 additionalData = make([]byte, 13)
439 copy(additionalData, seq)
440 copy(additionalData[8:], b.data[:3])
441 n := len(payload) - c.Overhead()
442 additionalData[11] = byte(n >> 8)
443 additionalData[12] = byte(n)
444 }
Adam Langley95c29f32014-06-20 12:00:00 -0700445 var err error
Nick Harper1fd39d82016-06-14 18:14:35 -0700446 payload, err = c.Open(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700447 if err != nil {
Nick Harper1fd39d82016-06-14 18:14:35 -0700448 return false, 0, 0, alertBadRecordMAC
449 }
Adam Langley95c29f32014-06-20 12:00:00 -0700450 b.resize(recordHeaderLen + explicitIVLen + len(payload))
451 case cbcMode:
452 blockSize := c.BlockSize()
David Benjamin83c0bc92014-08-04 01:23:53 -0400453 if hc.version >= VersionTLS11 || hc.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700454 explicitIVLen = blockSize
455 }
456
457 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
Nick Harper1fd39d82016-06-14 18:14:35 -0700458 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700459 }
460
461 if explicitIVLen > 0 {
462 c.SetIV(payload[:explicitIVLen])
463 payload = payload[explicitIVLen:]
464 }
465 c.CryptBlocks(payload, payload)
466 if hc.version == VersionSSL30 {
467 payload, paddingGood = removePaddingSSL30(payload)
468 } else {
469 payload, paddingGood = removePadding(payload)
470 }
471 b.resize(recordHeaderLen + explicitIVLen + len(payload))
472
473 // note that we still have a timing side-channel in the
474 // MAC check, below. An attacker can align the record
475 // so that a correct padding will cause one less hash
476 // block to be calculated. Then they can iteratively
477 // decrypt a record by breaking each byte. See
478 // "Password Interception in a SSL/TLS Channel", Brice
479 // Canvel et al.
480 //
481 // However, our behavior matches OpenSSL, so we leak
482 // only as much as they do.
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700483 case nullCipher:
484 break
Adam Langley95c29f32014-06-20 12:00:00 -0700485 default:
486 panic("unknown cipher type")
487 }
David Benjamin7a4aaa42016-09-20 17:58:14 -0400488
489 if hc.version >= VersionTLS13 {
490 i := len(payload)
491 for i > 0 && payload[i-1] == 0 {
492 i--
493 }
494 payload = payload[:i]
495 if len(payload) == 0 {
496 return false, 0, 0, alertUnexpectedMessage
497 }
498 contentType = recordType(payload[len(payload)-1])
499 payload = payload[:len(payload)-1]
500 b.resize(recordHeaderLen + len(payload))
501 }
Adam Langley95c29f32014-06-20 12:00:00 -0700502 }
503
504 // check, strip mac
505 if hc.mac != nil {
506 if len(payload) < macSize {
Nick Harper1fd39d82016-06-14 18:14:35 -0700507 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700508 }
509
510 // strip mac off payload, b.data
511 n := len(payload) - macSize
David Benjamin83c0bc92014-08-04 01:23:53 -0400512 b.data[recordHeaderLen-2] = byte(n >> 8)
513 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700514 b.resize(recordHeaderLen + explicitIVLen + n)
515 remoteMAC := payload[n:]
David Benjamin83c0bc92014-08-04 01:23:53 -0400516 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
Adam Langley95c29f32014-06-20 12:00:00 -0700517
518 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
Nick Harper1fd39d82016-06-14 18:14:35 -0700519 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700520 }
521 hc.inDigestBuf = localMAC
522 }
David Benjamin5e961c12014-11-07 01:48:35 -0500523 hc.incSeq(false)
Adam Langley95c29f32014-06-20 12:00:00 -0700524
Nick Harper1fd39d82016-06-14 18:14:35 -0700525 return true, recordHeaderLen + explicitIVLen, contentType, 0
Adam Langley95c29f32014-06-20 12:00:00 -0700526}
527
528// padToBlockSize calculates the needed padding block, if any, for a payload.
529// On exit, prefix aliases payload and extends to the end of the last full
530// block of payload. finalBlock is a fresh slice which contains the contents of
531// any suffix of payload as well as the needed padding to make finalBlock a
532// full block.
Adam Langley80842bd2014-06-20 12:00:00 -0700533func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
Adam Langley95c29f32014-06-20 12:00:00 -0700534 overrun := len(payload) % blockSize
Adam Langley95c29f32014-06-20 12:00:00 -0700535 prefix = payload[:len(payload)-overrun]
Adam Langley80842bd2014-06-20 12:00:00 -0700536
537 paddingLen := blockSize - overrun
538 finalSize := blockSize
539 if config.Bugs.MaxPadding {
540 for paddingLen+blockSize <= 256 {
541 paddingLen += blockSize
542 }
543 finalSize = 256
544 }
545 finalBlock = make([]byte, finalSize)
546 for i := range finalBlock {
Adam Langley95c29f32014-06-20 12:00:00 -0700547 finalBlock[i] = byte(paddingLen - 1)
548 }
Adam Langley80842bd2014-06-20 12:00:00 -0700549 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
550 finalBlock[overrun] ^= 0xff
551 }
552 copy(finalBlock, payload[len(payload)-overrun:])
Adam Langley95c29f32014-06-20 12:00:00 -0700553 return
554}
555
556// encrypt encrypts and macs the data in b.
Nick Harper1fd39d82016-06-14 18:14:35 -0700557func (hc *halfConn) encrypt(b *block, explicitIVLen int, typ recordType) (bool, alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400558 recordHeaderLen := hc.recordHeaderLen()
559
Adam Langley95c29f32014-06-20 12:00:00 -0700560 // mac
561 if hc.mac != nil {
David Benjamin8e6db492015-07-25 18:29:23 -0400562 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 -0700563
564 n := len(b.data)
565 b.resize(n + len(mac))
566 copy(b.data[n:], mac)
567 hc.outDigestBuf = mac
568 }
569
570 payload := b.data[recordHeaderLen:]
571
572 // encrypt
573 if hc.cipher != nil {
David Benjamin7a4aaa42016-09-20 17:58:14 -0400574 // Add TLS 1.3 padding.
575 if hc.version >= VersionTLS13 {
576 paddingLen := hc.config.Bugs.RecordPadding
577 if hc.config.Bugs.OmitRecordContents {
578 b.resize(recordHeaderLen + paddingLen)
579 } else {
580 b.resize(len(b.data) + 1 + paddingLen)
581 b.data[len(b.data)-paddingLen-1] = byte(typ)
582 }
583 for i := 0; i < paddingLen; i++ {
584 b.data[len(b.data)-paddingLen+i] = 0
585 }
586 }
587
Adam Langley95c29f32014-06-20 12:00:00 -0700588 switch c := hc.cipher.(type) {
589 case cipher.Stream:
590 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400591 case *tlsAead:
Adam Langley95c29f32014-06-20 12:00:00 -0700592 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
David Benjamin7a4aaa42016-09-20 17:58:14 -0400593 b.resize(len(b.data) + c.Overhead())
David Benjamin8e6db492015-07-25 18:29:23 -0400594 nonce := hc.outSeq[:]
David Benjamine9a80ff2015-04-07 00:46:46 -0400595 if c.explicitNonce {
596 nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
597 }
Adam Langley95c29f32014-06-20 12:00:00 -0700598 payload := b.data[recordHeaderLen+explicitIVLen:]
599 payload = payload[:payloadLen]
600
Nick Harper1fd39d82016-06-14 18:14:35 -0700601 var additionalData []byte
602 if hc.version < VersionTLS13 {
603 additionalData = make([]byte, 13)
604 copy(additionalData, hc.outSeq[:])
605 copy(additionalData[8:], b.data[:3])
606 additionalData[11] = byte(payloadLen >> 8)
607 additionalData[12] = byte(payloadLen)
608 }
Adam Langley95c29f32014-06-20 12:00:00 -0700609
Nick Harper1fd39d82016-06-14 18:14:35 -0700610 c.Seal(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700611 case cbcMode:
612 blockSize := c.BlockSize()
613 if explicitIVLen > 0 {
614 c.SetIV(payload[:explicitIVLen])
615 payload = payload[explicitIVLen:]
616 }
Adam Langley80842bd2014-06-20 12:00:00 -0700617 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700618 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
619 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
620 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700621 case nullCipher:
622 break
Adam Langley95c29f32014-06-20 12:00:00 -0700623 default:
624 panic("unknown cipher type")
625 }
626 }
627
628 // update length to include MAC and any block padding needed.
629 n := len(b.data) - recordHeaderLen
David Benjamin83c0bc92014-08-04 01:23:53 -0400630 b.data[recordHeaderLen-2] = byte(n >> 8)
631 b.data[recordHeaderLen-1] = byte(n)
David Benjamin6f600d62016-12-21 16:06:54 -0500632 if hc.isShortHeader() && !hc.config.Bugs.ClearShortHeaderBit {
633 b.data[0] |= 0x80
634 }
David Benjamin5e961c12014-11-07 01:48:35 -0500635 hc.incSeq(true)
Adam Langley95c29f32014-06-20 12:00:00 -0700636
637 return true, 0
638}
639
640// A block is a simple data buffer.
641type block struct {
642 data []byte
643 off int // index for Read
644 link *block
645}
646
647// resize resizes block to be n bytes, growing if necessary.
648func (b *block) resize(n int) {
649 if n > cap(b.data) {
650 b.reserve(n)
651 }
652 b.data = b.data[0:n]
653}
654
655// reserve makes sure that block contains a capacity of at least n bytes.
656func (b *block) reserve(n int) {
657 if cap(b.data) >= n {
658 return
659 }
660 m := cap(b.data)
661 if m == 0 {
662 m = 1024
663 }
664 for m < n {
665 m *= 2
666 }
667 data := make([]byte, len(b.data), m)
668 copy(data, b.data)
669 b.data = data
670}
671
672// readFromUntil reads from r into b until b contains at least n bytes
673// or else returns an error.
674func (b *block) readFromUntil(r io.Reader, n int) error {
675 // quick case
676 if len(b.data) >= n {
677 return nil
678 }
679
680 // read until have enough.
681 b.reserve(n)
682 for {
683 m, err := r.Read(b.data[len(b.data):cap(b.data)])
684 b.data = b.data[0 : len(b.data)+m]
685 if len(b.data) >= n {
686 // TODO(bradfitz,agl): slightly suspicious
687 // that we're throwing away r.Read's err here.
688 break
689 }
690 if err != nil {
691 return err
692 }
693 }
694 return nil
695}
696
697func (b *block) Read(p []byte) (n int, err error) {
698 n = copy(p, b.data[b.off:])
699 b.off += n
700 return
701}
702
703// newBlock allocates a new block, from hc's free list if possible.
704func (hc *halfConn) newBlock() *block {
705 b := hc.bfree
706 if b == nil {
707 return new(block)
708 }
709 hc.bfree = b.link
710 b.link = nil
711 b.resize(0)
712 return b
713}
714
715// freeBlock returns a block to hc's free list.
716// The protocol is such that each side only has a block or two on
717// its free list at a time, so there's no need to worry about
718// trimming the list, etc.
719func (hc *halfConn) freeBlock(b *block) {
720 b.link = hc.bfree
721 hc.bfree = b
722}
723
724// splitBlock splits a block after the first n bytes,
725// returning a block with those n bytes and a
726// block with the remainder. the latter may be nil.
727func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
728 if len(b.data) <= n {
729 return b, nil
730 }
731 bb := hc.newBlock()
732 bb.resize(len(b.data) - n)
733 copy(bb.data, b.data[n:])
734 b.data = b.data[0:n]
735 return b, bb
736}
737
David Benjamin83c0bc92014-08-04 01:23:53 -0400738func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
Nick Harper47383aa2016-11-30 12:50:43 -0800739RestartReadRecord:
David Benjamin83c0bc92014-08-04 01:23:53 -0400740 if c.isDTLS {
741 return c.dtlsDoReadRecord(want)
742 }
743
David Benjamin6f600d62016-12-21 16:06:54 -0500744 recordHeaderLen := c.in.recordHeaderLen()
David Benjamin83c0bc92014-08-04 01:23:53 -0400745
746 if c.rawInput == nil {
747 c.rawInput = c.in.newBlock()
748 }
749 b := c.rawInput
750
751 // Read header, payload.
752 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
753 // RFC suggests that EOF without an alertCloseNotify is
754 // an error, but popular web sites seem to do this,
David Benjamin30789da2015-08-29 22:56:45 -0400755 // so we can't make it an error, outside of tests.
756 if err == io.EOF && c.config.Bugs.ExpectCloseNotify {
757 err = io.ErrUnexpectedEOF
758 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400759 if e, ok := err.(net.Error); !ok || !e.Temporary() {
760 c.in.setErrorLocked(err)
761 }
762 return 0, nil, err
763 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400764
David Benjamin6f600d62016-12-21 16:06:54 -0500765 var typ recordType
766 var vers uint16
767 var n int
768 if c.in.isShortHeader() {
769 typ = recordTypeApplicationData
770 vers = VersionTLS10
771 n = int(b.data[0])<<8 | int(b.data[1])
772 if n&0x8000 == 0 {
773 c.sendAlert(alertDecodeError)
774 return 0, nil, c.in.setErrorLocked(errors.New("tls: length did not have high bit set"))
775 }
776
777 n = n & 0x7fff
778 } else {
779 typ = recordType(b.data[0])
780
781 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
782 // start with a uint16 length where the MSB is set and the first record
783 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
784 // an SSLv2 client.
785 if want == recordTypeHandshake && typ == 0x80 {
786 c.sendAlert(alertProtocolVersion)
787 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
788 }
789
790 vers = uint16(b.data[1])<<8 | uint16(b.data[2])
791 n = int(b.data[3])<<8 | int(b.data[4])
David Benjamin83c0bc92014-08-04 01:23:53 -0400792 }
793
David Benjaminbde00392016-06-21 12:19:28 -0400794 // Alerts sent near version negotiation do not have a well-defined
795 // record-layer version prior to TLS 1.3. (In TLS 1.3, the record-layer
796 // version is irrelevant.)
797 if typ != recordTypeAlert {
David Benjamine6f22212016-11-08 14:28:24 -0500798 var expect uint16
David Benjaminbde00392016-06-21 12:19:28 -0400799 if c.haveVers {
David Benjamine6f22212016-11-08 14:28:24 -0500800 expect = c.vers
801 if c.vers >= VersionTLS13 {
802 expect = VersionTLS10
David Benjaminbde00392016-06-21 12:19:28 -0400803 }
804 } else {
David Benjamine6f22212016-11-08 14:28:24 -0500805 expect = c.config.Bugs.ExpectInitialRecordVersion
806 }
807 if expect != 0 && vers != expect {
808 c.sendAlert(alertProtocolVersion)
809 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 -0500810 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400811 }
812 if n > maxCiphertext {
813 c.sendAlert(alertRecordOverflow)
814 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
815 }
816 if !c.haveVers {
817 // First message, be extra suspicious:
818 // this might not be a TLS client.
819 // Bail out before reading a full 'body', if possible.
820 // The current max version is 3.1.
821 // If the version is >= 16.0, it's probably not real.
822 // Similarly, a clientHello message encodes in
823 // well under a kilobyte. If the length is >= 12 kB,
824 // it's probably not real.
825 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
826 c.sendAlert(alertUnexpectedMessage)
827 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
828 }
829 }
830 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
831 if err == io.EOF {
832 err = io.ErrUnexpectedEOF
833 }
834 if e, ok := err.(net.Error); !ok || !e.Temporary() {
835 c.in.setErrorLocked(err)
836 }
837 return 0, nil, err
838 }
839
840 // Process message.
841 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
David Benjaminff26f092016-07-01 16:13:42 -0400842 ok, off, encTyp, alertValue := c.in.decrypt(b)
Nick Harper47383aa2016-11-30 12:50:43 -0800843
844 // Handle skipping over early data.
845 if !ok && c.skipEarlyData {
846 goto RestartReadRecord
847 }
848
849 // If the server is expecting a second ClientHello (in response to
850 // a HelloRetryRequest) and the client sends early data, there
851 // won't be a decryption failure but it still needs to be skipped.
852 if c.in.cipher == nil && typ == recordTypeApplicationData && c.skipEarlyData {
853 goto RestartReadRecord
854 }
855
David Benjaminff26f092016-07-01 16:13:42 -0400856 if !ok {
857 return 0, nil, c.in.setErrorLocked(c.sendAlert(alertValue))
858 }
859 b.off = off
Nick Harper47383aa2016-11-30 12:50:43 -0800860 c.skipEarlyData = false
David Benjaminff26f092016-07-01 16:13:42 -0400861
Nick Harper1fd39d82016-06-14 18:14:35 -0700862 if c.vers >= VersionTLS13 && c.in.cipher != nil {
David Benjaminc9ae27c2016-06-24 22:56:37 -0400863 if typ != recordTypeApplicationData {
864 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: outer record type is not application data"))
865 }
Nick Harper1fd39d82016-06-14 18:14:35 -0700866 typ = encTyp
867 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400868 return typ, b, nil
869}
870
Adam Langley95c29f32014-06-20 12:00:00 -0700871// readRecord reads the next TLS record from the connection
872// and updates the record layer state.
873// c.in.Mutex <= L; c.input == nil.
874func (c *Conn) readRecord(want recordType) error {
875 // Caller must be in sync with connection:
876 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700877 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700878 switch want {
879 default:
880 c.sendAlert(alertInternalError)
881 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
882 case recordTypeHandshake, recordTypeChangeCipherSpec:
883 if c.handshakeComplete {
884 c.sendAlert(alertInternalError)
885 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
886 }
887 case recordTypeApplicationData:
Nick Harperab20cec2016-12-19 17:38:41 -0800888 if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart && len(c.config.Bugs.ExpectHalfRTTData) == 0 && len(c.config.Bugs.ExpectEarlyData) == 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700889 c.sendAlert(alertInternalError)
890 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
891 }
David Benjamin30789da2015-08-29 22:56:45 -0400892 case recordTypeAlert:
893 // Looking for a close_notify. Note: unlike a real
894 // implementation, this is not tolerant of additional records.
895 // See the documentation for ExpectCloseNotify.
Adam Langley95c29f32014-06-20 12:00:00 -0700896 }
897
898Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400899 typ, b, err := c.doReadRecord(want)
900 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700901 return err
902 }
Adam Langley95c29f32014-06-20 12:00:00 -0700903 data := b.data[b.off:]
David Benjamine3fbb362017-01-06 16:19:28 -0500904 max := maxPlaintext
905 if c.config.Bugs.MaxReceivePlaintext != 0 {
906 max = c.config.Bugs.MaxReceivePlaintext
907 }
908 if len(data) > max {
Adam Langley95c29f32014-06-20 12:00:00 -0700909 err := c.sendAlert(alertRecordOverflow)
910 c.in.freeBlock(b)
911 return c.in.setErrorLocked(err)
912 }
913
914 switch typ {
915 default:
916 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
917
918 case recordTypeAlert:
919 if len(data) != 2 {
920 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
921 break
922 }
923 if alert(data[1]) == alertCloseNotify {
924 c.in.setErrorLocked(io.EOF)
925 break
926 }
927 switch data[0] {
928 case alertLevelWarning:
David Benjamin053fee92017-01-02 08:30:36 -0500929 if alert(data[1]) == alertNoCertificate {
930 c.in.freeBlock(b)
931 return errNoCertificateAlert
932 }
Nick Harperab20cec2016-12-19 17:38:41 -0800933 if alert(data[1]) == alertEndOfEarlyData {
934 c.in.freeBlock(b)
935 return errEndOfEarlyDataAlert
936 }
David Benjamin053fee92017-01-02 08:30:36 -0500937
Adam Langley95c29f32014-06-20 12:00:00 -0700938 // drop on the floor
939 c.in.freeBlock(b)
940 goto Again
941 case alertLevelError:
942 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
943 default:
944 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
945 }
946
947 case recordTypeChangeCipherSpec:
948 if typ != want || len(data) != 1 || data[0] != 1 {
949 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
950 break
951 }
Adam Langley80842bd2014-06-20 12:00:00 -0700952 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700953 if err != nil {
954 c.in.setErrorLocked(c.sendAlert(err.(alert)))
955 }
956
957 case recordTypeApplicationData:
958 if typ != want {
959 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
960 break
961 }
962 c.input = b
963 b = nil
964
965 case recordTypeHandshake:
David Benjamind5a4ecb2016-07-18 01:17:13 +0200966 // Allow handshake data while reading application data to
967 // trigger post-handshake messages.
Adam Langley95c29f32014-06-20 12:00:00 -0700968 // TODO(rsc): Should at least pick off connection close.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200969 if typ != want && want != recordTypeApplicationData {
970 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
Adam Langley95c29f32014-06-20 12:00:00 -0700971 }
972 c.hand.Write(data)
973 }
974
975 if b != nil {
976 c.in.freeBlock(b)
977 }
978 return c.in.err
979}
980
981// sendAlert sends a TLS alert message.
982// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400983func (c *Conn) sendAlertLocked(level byte, err alert) error {
984 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700985 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400986 if c.config.Bugs.FragmentAlert {
987 c.writeRecord(recordTypeAlert, c.tmp[0:1])
988 c.writeRecord(recordTypeAlert, c.tmp[1:2])
David Benjamin0d3a8c62016-03-11 22:25:18 -0500989 } else if c.config.Bugs.DoubleAlert {
990 copy(c.tmp[2:4], c.tmp[0:2])
991 c.writeRecord(recordTypeAlert, c.tmp[0:4])
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400992 } else {
993 c.writeRecord(recordTypeAlert, c.tmp[0:2])
994 }
David Benjamin24f346d2015-06-06 03:28:08 -0400995 // Error alerts are fatal to the connection.
996 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700997 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
998 }
999 return nil
1000}
1001
1002// sendAlert sends a TLS alert message.
1003// L < c.out.Mutex.
1004func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -04001005 level := byte(alertLevelError)
Nick Harperf2511f12016-12-06 16:02:31 -08001006 if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertificate || err == alertEndOfEarlyData {
David Benjamin24f346d2015-06-06 03:28:08 -04001007 level = alertLevelWarning
1008 }
1009 return c.SendAlert(level, err)
1010}
1011
1012func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001013 c.out.Lock()
1014 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -04001015 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -07001016}
1017
David Benjamind86c7672014-08-02 04:07:12 -04001018// writeV2Record writes a record for a V2ClientHello.
1019func (c *Conn) writeV2Record(data []byte) (n int, err error) {
1020 record := make([]byte, 2+len(data))
1021 record[0] = uint8(len(data)>>8) | 0x80
1022 record[1] = uint8(len(data))
1023 copy(record[2:], data)
1024 return c.conn.Write(record)
1025}
1026
Adam Langley95c29f32014-06-20 12:00:00 -07001027// writeRecord writes a TLS record with the given type and payload
1028// to the connection and updates the record layer state.
1029// c.out.Mutex <= L.
1030func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin639846e2016-09-09 11:41:18 -04001031 if msgType := c.config.Bugs.SendWrongMessageType; msgType != 0 {
1032 if typ == recordTypeHandshake && data[0] == msgType {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001033 newData := make([]byte, len(data))
1034 copy(newData, data)
1035 newData[0] += 42
1036 data = newData
1037 }
1038 }
1039
David Benjamin639846e2016-09-09 11:41:18 -04001040 if msgType := c.config.Bugs.SendTrailingMessageData; msgType != 0 {
1041 if typ == recordTypeHandshake && data[0] == msgType {
1042 newData := make([]byte, len(data))
1043 copy(newData, data)
1044
1045 // Add a 0 to the body.
1046 newData = append(newData, 0)
1047 // Fix the header.
1048 newLen := len(newData) - 4
1049 newData[1] = byte(newLen >> 16)
1050 newData[2] = byte(newLen >> 8)
1051 newData[3] = byte(newLen)
1052
1053 data = newData
1054 }
1055 }
1056
David Benjamin83c0bc92014-08-04 01:23:53 -04001057 if c.isDTLS {
1058 return c.dtlsWriteRecord(typ, data)
1059 }
1060
David Benjamin71dd6662016-07-08 14:10:48 -07001061 if typ == recordTypeHandshake {
1062 if c.config.Bugs.SendHelloRequestBeforeEveryHandshakeMessage {
1063 newData := make([]byte, 0, 4+len(data))
1064 newData = append(newData, typeHelloRequest, 0, 0, 0)
1065 newData = append(newData, data...)
1066 data = newData
1067 }
1068
1069 if c.config.Bugs.PackHandshakeFlight {
1070 c.pendingFlight.Write(data)
1071 return len(data), nil
1072 }
David Benjamin582ba042016-07-07 12:33:25 -07001073 }
1074
1075 return c.doWriteRecord(typ, data)
1076}
1077
1078func (c *Conn) doWriteRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin6f600d62016-12-21 16:06:54 -05001079 recordHeaderLen := c.out.recordHeaderLen()
Adam Langley95c29f32014-06-20 12:00:00 -07001080 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -04001081 first := true
1082 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -04001083 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -07001084 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -04001085 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -07001086 m = maxPlaintext
1087 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001088 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
1089 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -04001090 // By default, do not fragment the client_version or
1091 // server_version, which are located in the first 6
1092 // bytes.
1093 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
1094 m = 6
1095 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001096 }
Adam Langley95c29f32014-06-20 12:00:00 -07001097 explicitIVLen := 0
1098 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -04001099 first = false
Adam Langley95c29f32014-06-20 12:00:00 -07001100
1101 var cbc cbcMode
1102 if c.out.version >= VersionTLS11 {
1103 var ok bool
1104 if cbc, ok = c.out.cipher.(cbcMode); ok {
1105 explicitIVLen = cbc.BlockSize()
1106 }
1107 }
1108 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -04001109 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -07001110 explicitIVLen = 8
1111 // The AES-GCM construction in TLS has an
1112 // explicit nonce so that the nonce can be
1113 // random. However, the nonce is only 8 bytes
1114 // which is too small for a secure, random
1115 // nonce. Therefore we use the sequence number
1116 // as the nonce.
1117 explicitIVIsSeq = true
1118 }
1119 }
1120 b.resize(recordHeaderLen + explicitIVLen + m)
David Benjamin6f600d62016-12-21 16:06:54 -05001121 // If using a short record header, the length will be filled in
1122 // by encrypt.
1123 if !c.out.isShortHeader() {
1124 b.data[0] = byte(typ)
1125 if c.vers >= VersionTLS13 && c.out.cipher != nil {
1126 b.data[0] = byte(recordTypeApplicationData)
1127 if outerType := c.config.Bugs.OuterRecordType; outerType != 0 {
1128 b.data[0] = byte(outerType)
1129 }
David Benjaminc9ae27c2016-06-24 22:56:37 -04001130 }
David Benjamin6f600d62016-12-21 16:06:54 -05001131 vers := c.vers
1132 if vers == 0 || vers >= VersionTLS13 {
1133 // Some TLS servers fail if the record version is
1134 // greater than TLS 1.0 for the initial ClientHello.
1135 //
1136 // TLS 1.3 fixes the version number in the record
1137 // layer to {3, 1}.
1138 vers = VersionTLS10
1139 }
1140 if c.config.Bugs.SendRecordVersion != 0 {
1141 vers = c.config.Bugs.SendRecordVersion
1142 }
1143 if c.vers == 0 && c.config.Bugs.SendInitialRecordVersion != 0 {
1144 vers = c.config.Bugs.SendInitialRecordVersion
1145 }
1146 b.data[1] = byte(vers >> 8)
1147 b.data[2] = byte(vers)
1148 b.data[3] = byte(m >> 8)
1149 b.data[4] = byte(m)
Nick Harper1fd39d82016-06-14 18:14:35 -07001150 }
Adam Langley95c29f32014-06-20 12:00:00 -07001151 if explicitIVLen > 0 {
1152 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
1153 if explicitIVIsSeq {
1154 copy(explicitIV, c.out.seq[:])
1155 } else {
1156 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
1157 break
1158 }
1159 }
1160 }
1161 copy(b.data[recordHeaderLen+explicitIVLen:], data)
Nick Harper1fd39d82016-06-14 18:14:35 -07001162 c.out.encrypt(b, explicitIVLen, typ)
Adam Langley95c29f32014-06-20 12:00:00 -07001163 _, err = c.conn.Write(b.data)
1164 if err != nil {
1165 break
1166 }
1167 n += m
1168 data = data[m:]
1169 }
1170 c.out.freeBlock(b)
1171
1172 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -07001173 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -07001174 if err != nil {
1175 // Cannot call sendAlert directly,
1176 // because we already hold c.out.Mutex.
1177 c.tmp[0] = alertLevelError
1178 c.tmp[1] = byte(err.(alert))
1179 c.writeRecord(recordTypeAlert, c.tmp[0:2])
1180 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
1181 }
1182 }
1183 return
1184}
1185
David Benjamin582ba042016-07-07 12:33:25 -07001186func (c *Conn) flushHandshake() error {
1187 if c.isDTLS {
1188 return c.dtlsFlushHandshake()
1189 }
1190
1191 for c.pendingFlight.Len() > 0 {
1192 var buf [maxPlaintext]byte
1193 n, _ := c.pendingFlight.Read(buf[:])
1194 if _, err := c.doWriteRecord(recordTypeHandshake, buf[:n]); err != nil {
1195 return err
1196 }
1197 }
1198
1199 c.pendingFlight.Reset()
1200 return nil
1201}
1202
David Benjamin83c0bc92014-08-04 01:23:53 -04001203func (c *Conn) doReadHandshake() ([]byte, error) {
1204 if c.isDTLS {
1205 return c.dtlsDoReadHandshake()
1206 }
1207
Adam Langley95c29f32014-06-20 12:00:00 -07001208 for c.hand.Len() < 4 {
1209 if err := c.in.err; err != nil {
1210 return nil, err
1211 }
1212 if err := c.readRecord(recordTypeHandshake); err != nil {
1213 return nil, err
1214 }
1215 }
1216
1217 data := c.hand.Bytes()
1218 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1219 if n > maxHandshake {
1220 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
1221 }
1222 for c.hand.Len() < 4+n {
1223 if err := c.in.err; err != nil {
1224 return nil, err
1225 }
1226 if err := c.readRecord(recordTypeHandshake); err != nil {
1227 return nil, err
1228 }
1229 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001230 return c.hand.Next(4 + n), nil
1231}
1232
1233// readHandshake reads the next handshake message from
1234// the record layer.
1235// c.in.Mutex < L; c.out.Mutex < L.
1236func (c *Conn) readHandshake() (interface{}, error) {
1237 data, err := c.doReadHandshake()
David Benjamin053fee92017-01-02 08:30:36 -05001238 if err == errNoCertificateAlert {
1239 if c.hand.Len() != 0 {
1240 // The warning alert may not interleave with a handshake message.
1241 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1242 }
1243 return new(ssl3NoCertificateMsg), nil
1244 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001245 if err != nil {
1246 return nil, err
1247 }
1248
Adam Langley95c29f32014-06-20 12:00:00 -07001249 var m handshakeMessage
1250 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001251 case typeHelloRequest:
1252 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001253 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001254 m = &clientHelloMsg{
1255 isDTLS: c.isDTLS,
1256 }
Adam Langley95c29f32014-06-20 12:00:00 -07001257 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001258 m = &serverHelloMsg{
1259 isDTLS: c.isDTLS,
1260 }
Nick Harperdcfbc672016-07-16 17:47:31 +02001261 case typeHelloRetryRequest:
1262 m = new(helloRetryRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001263 case typeNewSessionTicket:
David Benjamin58104882016-07-18 01:25:41 +02001264 m = &newSessionTicketMsg{
1265 version: c.vers,
1266 }
Nick Harperb41d2e42016-07-01 17:50:32 -04001267 case typeEncryptedExtensions:
1268 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001269 case typeCertificate:
Nick Harperb41d2e42016-07-01 17:50:32 -04001270 m = &certificateMsg{
David Benjamin8d315d72016-07-18 01:03:18 +02001271 hasRequestContext: c.vers >= VersionTLS13,
Nick Harperb41d2e42016-07-01 17:50:32 -04001272 }
Adam Langley95c29f32014-06-20 12:00:00 -07001273 case typeCertificateRequest:
1274 m = &certificateRequestMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001275 hasSignatureAlgorithm: c.vers >= VersionTLS12,
David Benjamin8d315d72016-07-18 01:03:18 +02001276 hasRequestContext: c.vers >= VersionTLS13,
Adam Langley95c29f32014-06-20 12:00:00 -07001277 }
1278 case typeCertificateStatus:
1279 m = new(certificateStatusMsg)
1280 case typeServerKeyExchange:
1281 m = new(serverKeyExchangeMsg)
1282 case typeServerHelloDone:
1283 m = new(serverHelloDoneMsg)
1284 case typeClientKeyExchange:
1285 m = new(clientKeyExchangeMsg)
1286 case typeCertificateVerify:
1287 m = &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001288 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001289 }
1290 case typeNextProtocol:
1291 m = new(nextProtoMsg)
1292 case typeFinished:
1293 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001294 case typeHelloVerifyRequest:
1295 m = new(helloVerifyRequestMsg)
David Benjamin24599a82016-06-30 18:56:53 -04001296 case typeChannelID:
1297 m = new(channelIDMsg)
David Benjamin21c00282016-07-18 21:56:23 +02001298 case typeKeyUpdate:
1299 m = new(keyUpdateMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001300 default:
1301 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1302 }
1303
1304 // The handshake message unmarshallers
1305 // expect to be able to keep references to data,
1306 // so pass in a fresh copy that won't be overwritten.
1307 data = append([]byte(nil), data...)
1308
1309 if !m.unmarshal(data) {
1310 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1311 }
1312 return m, nil
1313}
1314
David Benjamin83f90402015-01-27 01:09:43 -05001315// skipPacket processes all the DTLS records in packet. It updates
1316// sequence number expectations but otherwise ignores them.
1317func (c *Conn) skipPacket(packet []byte) error {
1318 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001319 if len(packet) < 13 {
1320 return errors.New("tls: bad packet")
1321 }
David Benjamin83f90402015-01-27 01:09:43 -05001322 // Dropped packets are completely ignored save to update
1323 // expected sequence numbers for this and the next epoch. (We
1324 // don't assert on the contents of the packets both for
1325 // simplicity and because a previous test with one shorter
1326 // timeout schedule would have done so.)
1327 epoch := packet[3:5]
1328 seq := packet[5:11]
1329 length := uint16(packet[11])<<8 | uint16(packet[12])
1330 if bytes.Equal(c.in.seq[:2], epoch) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001331 if bytes.Compare(seq, c.in.seq[2:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001332 return errors.New("tls: sequence mismatch")
1333 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001334 copy(c.in.seq[2:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001335 c.in.incSeq(false)
1336 } else {
David Benjamin13e81fc2015-11-02 17:16:13 -05001337 if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001338 return errors.New("tls: sequence mismatch")
1339 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001340 copy(c.in.nextSeq[:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001341 c.in.incNextSeq()
1342 }
David Benjamin6ca93552015-08-28 16:16:25 -04001343 if len(packet) < 13+int(length) {
1344 return errors.New("tls: bad packet")
1345 }
David Benjamin83f90402015-01-27 01:09:43 -05001346 packet = packet[13+length:]
1347 }
1348 return nil
1349}
1350
1351// simulatePacketLoss simulates the loss of a handshake leg from the
1352// peer based on the schedule in c.config.Bugs. If resendFunc is
1353// non-nil, it is called after each simulated timeout to retransmit
1354// handshake messages from the local end. This is used in cases where
1355// the peer retransmits on a stale Finished rather than a timeout.
1356func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1357 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1358 return nil
1359 }
1360 if !c.isDTLS {
1361 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1362 }
1363 if c.config.Bugs.PacketAdaptor == nil {
1364 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1365 }
1366 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1367 // Simulate a timeout.
1368 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1369 if err != nil {
1370 return err
1371 }
1372 for _, packet := range packets {
1373 if err := c.skipPacket(packet); err != nil {
1374 return err
1375 }
1376 }
1377 if resendFunc != nil {
1378 resendFunc()
1379 }
1380 }
1381 return nil
1382}
1383
David Benjamin47921102016-07-28 11:29:18 -04001384func (c *Conn) SendHalfHelloRequest() error {
1385 if err := c.Handshake(); err != nil {
1386 return err
1387 }
1388
1389 c.out.Lock()
1390 defer c.out.Unlock()
1391
1392 if _, err := c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0}); err != nil {
1393 return err
1394 }
1395 return c.flushHandshake()
1396}
1397
Adam Langley95c29f32014-06-20 12:00:00 -07001398// Write writes data to the connection.
1399func (c *Conn) Write(b []byte) (int, error) {
1400 if err := c.Handshake(); err != nil {
1401 return 0, err
1402 }
1403
1404 c.out.Lock()
1405 defer c.out.Unlock()
1406
David Benjamin12d2c482016-07-24 10:56:51 -04001407 // Flush any pending handshake data. PackHelloRequestWithFinished may
1408 // have been set and the handshake not followed by Renegotiate.
1409 c.flushHandshake()
1410
Adam Langley95c29f32014-06-20 12:00:00 -07001411 if err := c.out.err; err != nil {
1412 return 0, err
1413 }
1414
1415 if !c.handshakeComplete {
1416 return 0, alertInternalError
1417 }
1418
Steven Valdezc4aa7272016-10-03 12:25:56 -04001419 if c.keyUpdateRequested {
1420 if err := c.sendKeyUpdateLocked(keyUpdateNotRequested); err != nil {
David Benjamin21c00282016-07-18 21:56:23 +02001421 return 0, err
1422 }
Steven Valdezc4aa7272016-10-03 12:25:56 -04001423 c.keyUpdateRequested = false
David Benjamin21c00282016-07-18 21:56:23 +02001424 }
1425
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001426 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001427 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001428 }
1429
Adam Langley27a0d082015-11-03 13:34:10 -08001430 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1431 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
David Benjamin582ba042016-07-07 12:33:25 -07001432 c.flushHandshake()
Adam Langley27a0d082015-11-03 13:34:10 -08001433 }
1434
Adam Langley95c29f32014-06-20 12:00:00 -07001435 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1436 // attack when using block mode ciphers due to predictable IVs.
1437 // This can be prevented by splitting each Application Data
1438 // record into two records, effectively randomizing the IV.
1439 //
1440 // http://www.openssl.org/~bodo/tls-cbc.txt
1441 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1442 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1443
1444 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001445 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001446 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1447 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1448 if err != nil {
1449 return n, c.out.setErrorLocked(err)
1450 }
1451 m, b = 1, b[1:]
1452 }
1453 }
1454
1455 n, err := c.writeRecord(recordTypeApplicationData, b)
1456 return n + m, c.out.setErrorLocked(err)
1457}
1458
David Benjamind5a4ecb2016-07-18 01:17:13 +02001459func (c *Conn) handlePostHandshakeMessage() error {
Adam Langley2ae77d22014-10-28 17:29:33 -07001460 msg, err := c.readHandshake()
1461 if err != nil {
1462 return err
1463 }
David Benjamind5a4ecb2016-07-18 01:17:13 +02001464
1465 if c.vers < VersionTLS13 {
1466 if !c.isClient {
1467 c.sendAlert(alertUnexpectedMessage)
1468 return errors.New("tls: unexpected post-handshake message")
1469 }
1470
1471 _, ok := msg.(*helloRequestMsg)
1472 if !ok {
1473 c.sendAlert(alertUnexpectedMessage)
1474 return alertUnexpectedMessage
1475 }
1476
1477 c.handshakeComplete = false
1478 return c.Handshake()
Adam Langley2ae77d22014-10-28 17:29:33 -07001479 }
1480
David Benjamind5a4ecb2016-07-18 01:17:13 +02001481 if c.isClient {
1482 if newSessionTicket, ok := msg.(*newSessionTicketMsg); ok {
David Benjamin1a5e8ec2016-10-07 15:19:18 -04001483 if c.config.Bugs.ExpectGREASE && !newSessionTicket.hasGREASEExtension {
1484 return errors.New("tls: no GREASE ticket extension found")
1485 }
1486
Nick Harperf2511f12016-12-06 16:02:31 -08001487 if c.config.Bugs.ExpectTicketEarlyDataInfo && newSessionTicket.maxEarlyDataSize == 0 {
Steven Valdez08b65f42016-12-07 15:29:45 -05001488 return errors.New("tls: no ticket_early_data_info extension found")
1489 }
1490
Steven Valdeza833c352016-11-01 13:39:36 -04001491 if c.config.Bugs.ExpectNoNewSessionTicket {
1492 return errors.New("tls: received unexpected NewSessionTicket")
1493 }
1494
David Benjamind5a4ecb2016-07-18 01:17:13 +02001495 if c.config.ClientSessionCache == nil || newSessionTicket.ticketLifetime == 0 {
1496 return nil
1497 }
1498
1499 session := &ClientSessionState{
1500 sessionTicket: newSessionTicket.ticket,
1501 vers: c.vers,
1502 cipherSuite: c.cipherSuite.id,
1503 masterSecret: c.resumptionSecret,
1504 serverCertificates: c.peerCertificates,
1505 sctList: c.sctList,
1506 ocspResponse: c.ocspResponse,
Nick Harper0b3625b2016-07-25 16:16:28 -07001507 ticketCreationTime: c.config.time(),
1508 ticketExpiration: c.config.time().Add(time.Duration(newSessionTicket.ticketLifetime) * time.Second),
Steven Valdeza833c352016-11-01 13:39:36 -04001509 ticketAgeAdd: newSessionTicket.ticketAgeAdd,
Nick Harperf2511f12016-12-06 16:02:31 -08001510 maxEarlyDataSize: newSessionTicket.maxEarlyDataSize,
David Benjamind5a4ecb2016-07-18 01:17:13 +02001511 }
1512
1513 cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
1514 c.config.ClientSessionCache.Put(cacheKey, session)
1515 return nil
1516 }
1517 }
1518
Steven Valdezc4aa7272016-10-03 12:25:56 -04001519 if keyUpdate, ok := msg.(*keyUpdateMsg); ok {
Steven Valdez1dc53d22016-07-26 12:27:38 -04001520 c.in.doKeyUpdate(c, false)
Steven Valdezc4aa7272016-10-03 12:25:56 -04001521 if keyUpdate.keyUpdateRequest == keyUpdateRequested {
1522 c.keyUpdateRequested = true
1523 }
David Benjamin21c00282016-07-18 21:56:23 +02001524 return nil
1525 }
1526
David Benjamind5a4ecb2016-07-18 01:17:13 +02001527 // TODO(davidben): Add support for KeyUpdate.
1528 c.sendAlert(alertUnexpectedMessage)
1529 return alertUnexpectedMessage
Adam Langley2ae77d22014-10-28 17:29:33 -07001530}
1531
Adam Langleycf2d4f42014-10-28 19:06:14 -07001532func (c *Conn) Renegotiate() error {
1533 if !c.isClient {
David Benjaminef5dfd22015-12-06 13:17:07 -05001534 helloReq := new(helloRequestMsg).marshal()
1535 if c.config.Bugs.BadHelloRequest != nil {
1536 helloReq = c.config.Bugs.BadHelloRequest
1537 }
1538 c.writeRecord(recordTypeHandshake, helloReq)
David Benjamin582ba042016-07-07 12:33:25 -07001539 c.flushHandshake()
Adam Langleycf2d4f42014-10-28 19:06:14 -07001540 }
1541
1542 c.handshakeComplete = false
1543 return c.Handshake()
1544}
1545
Adam Langley95c29f32014-06-20 12:00:00 -07001546// Read can be made to time out and return a net.Error with Timeout() == true
1547// after a fixed time limit; see SetDeadline and SetReadDeadline.
1548func (c *Conn) Read(b []byte) (n int, err error) {
1549 if err = c.Handshake(); err != nil {
1550 return
1551 }
1552
1553 c.in.Lock()
1554 defer c.in.Unlock()
1555
1556 // Some OpenSSL servers send empty records in order to randomize the
1557 // CBC IV. So this loop ignores a limited number of empty records.
1558 const maxConsecutiveEmptyRecords = 100
1559 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1560 for c.input == nil && c.in.err == nil {
1561 if err := c.readRecord(recordTypeApplicationData); err != nil {
1562 // Soft error, like EAGAIN
1563 return 0, err
1564 }
David Benjamind9b091b2015-01-27 01:10:54 -05001565 if c.hand.Len() > 0 {
David Benjamind5a4ecb2016-07-18 01:17:13 +02001566 // We received handshake bytes, indicating a
1567 // post-handshake message.
1568 if err := c.handlePostHandshakeMessage(); err != nil {
Adam Langley2ae77d22014-10-28 17:29:33 -07001569 return 0, err
1570 }
1571 continue
1572 }
Adam Langley95c29f32014-06-20 12:00:00 -07001573 }
1574 if err := c.in.err; err != nil {
1575 return 0, err
1576 }
1577
1578 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001579 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001580 c.in.freeBlock(c.input)
1581 c.input = nil
1582 }
1583
1584 // If a close-notify alert is waiting, read it so that
1585 // we can return (n, EOF) instead of (n, nil), to signal
1586 // to the HTTP response reading goroutine that the
1587 // connection is now closed. This eliminates a race
1588 // where the HTTP response reading goroutine would
1589 // otherwise not observe the EOF until its next read,
1590 // by which time a client goroutine might have already
1591 // tried to reuse the HTTP connection for a new
1592 // request.
1593 // See https://codereview.appspot.com/76400046
1594 // and http://golang.org/issue/3514
1595 if ri := c.rawInput; ri != nil &&
1596 n != 0 && err == nil &&
1597 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1598 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1599 err = recErr // will be io.EOF on closeNotify
1600 }
1601 }
1602
1603 if n != 0 || err != nil {
1604 return n, err
1605 }
1606 }
1607
1608 return 0, io.ErrNoProgress
1609}
1610
1611// Close closes the connection.
1612func (c *Conn) Close() error {
1613 var alertErr error
1614
1615 c.handshakeMutex.Lock()
1616 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001617 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
David Benjaminfa214e42016-05-10 17:03:10 -04001618 alert := alertCloseNotify
1619 if c.config.Bugs.SendAlertOnShutdown != 0 {
1620 alert = c.config.Bugs.SendAlertOnShutdown
1621 }
1622 alertErr = c.sendAlert(alert)
David Benjamin4d559612016-05-18 14:31:51 -04001623 // Clear local alerts when sending alerts so we continue to wait
1624 // for the peer rather than closing the socket early.
1625 if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1626 alertErr = nil
1627 }
Adam Langley95c29f32014-06-20 12:00:00 -07001628 }
1629
David Benjamin30789da2015-08-29 22:56:45 -04001630 // Consume a close_notify from the peer if one hasn't been received
1631 // already. This avoids the peer from failing |SSL_shutdown| due to a
1632 // write failing.
1633 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1634 for c.in.error() == nil {
1635 c.readRecord(recordTypeAlert)
1636 }
1637 if c.in.error() != io.EOF {
1638 alertErr = c.in.error()
1639 }
1640 }
1641
Adam Langley95c29f32014-06-20 12:00:00 -07001642 if err := c.conn.Close(); err != nil {
1643 return err
1644 }
1645 return alertErr
1646}
1647
1648// Handshake runs the client or server handshake
1649// protocol if it has not yet been run.
1650// Most uses of this package need not call Handshake
1651// explicitly: the first Read or Write will call it automatically.
1652func (c *Conn) Handshake() error {
1653 c.handshakeMutex.Lock()
1654 defer c.handshakeMutex.Unlock()
1655 if err := c.handshakeErr; err != nil {
1656 return err
1657 }
1658 if c.handshakeComplete {
1659 return nil
1660 }
1661
David Benjamin9a41d1b2015-05-16 01:30:09 -04001662 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1663 c.conn.Write([]byte{
1664 byte(recordTypeAlert), // type
1665 0xfe, 0xff, // version
1666 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1667 0x0, 0x2, // length
1668 })
1669 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1670 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001671 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1672 c.writeRecord(recordTypeApplicationData, data)
1673 }
Adam Langley95c29f32014-06-20 12:00:00 -07001674 if c.isClient {
1675 c.handshakeErr = c.clientHandshake()
1676 } else {
1677 c.handshakeErr = c.serverHandshake()
1678 }
David Benjaminddb9f152015-02-03 15:44:39 -05001679 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1680 c.writeRecord(recordType(42), []byte("invalid record"))
1681 }
Adam Langley95c29f32014-06-20 12:00:00 -07001682 return c.handshakeErr
1683}
1684
1685// ConnectionState returns basic TLS details about the connection.
1686func (c *Conn) ConnectionState() ConnectionState {
1687 c.handshakeMutex.Lock()
1688 defer c.handshakeMutex.Unlock()
1689
1690 var state ConnectionState
1691 state.HandshakeComplete = c.handshakeComplete
1692 if c.handshakeComplete {
1693 state.Version = c.vers
1694 state.NegotiatedProtocol = c.clientProtocol
1695 state.DidResume = c.didResume
1696 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001697 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001698 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001699 state.PeerCertificates = c.peerCertificates
1700 state.VerifiedChains = c.verifiedChains
1701 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001702 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001703 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001704 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001705 state.SCTList = c.sctList
Nick Harper60edffd2016-06-21 15:19:24 -07001706 state.PeerSignatureAlgorithm = c.peerSignatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -04001707 state.CurveID = c.curveID
David Benjamin6f600d62016-12-21 16:06:54 -05001708 state.ShortHeader = c.in.shortHeader
Adam Langley95c29f32014-06-20 12:00:00 -07001709 }
1710
1711 return state
1712}
1713
1714// OCSPResponse returns the stapled OCSP response from the TLS server, if
1715// any. (Only valid for client connections.)
1716func (c *Conn) OCSPResponse() []byte {
1717 c.handshakeMutex.Lock()
1718 defer c.handshakeMutex.Unlock()
1719
1720 return c.ocspResponse
1721}
1722
1723// VerifyHostname checks that the peer certificate chain is valid for
1724// connecting to host. If so, it returns nil; if not, it returns an error
1725// describing the problem.
1726func (c *Conn) VerifyHostname(host string) error {
1727 c.handshakeMutex.Lock()
1728 defer c.handshakeMutex.Unlock()
1729 if !c.isClient {
1730 return errors.New("tls: VerifyHostname called on TLS server connection")
1731 }
1732 if !c.handshakeComplete {
1733 return errors.New("tls: handshake has not yet been performed")
1734 }
1735 return c.peerCertificates[0].VerifyHostname(host)
1736}
David Benjaminc565ebb2015-04-03 04:06:36 -04001737
1738// ExportKeyingMaterial exports keying material from the current connection
1739// state, as per RFC 5705.
1740func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1741 c.handshakeMutex.Lock()
1742 defer c.handshakeMutex.Unlock()
1743 if !c.handshakeComplete {
1744 return nil, errors.New("tls: handshake has not yet been performed")
1745 }
1746
David Benjamin8d315d72016-07-18 01:03:18 +02001747 if c.vers >= VersionTLS13 {
David Benjamin97a0a082016-07-13 17:57:35 -04001748 // TODO(davidben): What should we do with useContext? See
1749 // https://github.com/tlswg/tls13-spec/issues/546
1750 return hkdfExpandLabel(c.cipherSuite.hash(), c.exporterSecret, label, context, length), nil
1751 }
1752
David Benjaminc565ebb2015-04-03 04:06:36 -04001753 seedLen := len(c.clientRandom) + len(c.serverRandom)
1754 if useContext {
1755 seedLen += 2 + len(context)
1756 }
1757 seed := make([]byte, 0, seedLen)
1758 seed = append(seed, c.clientRandom[:]...)
1759 seed = append(seed, c.serverRandom[:]...)
1760 if useContext {
1761 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1762 seed = append(seed, context...)
1763 }
1764 result := make([]byte, length)
David Benjamin97a0a082016-07-13 17:57:35 -04001765 prfForVersion(c.vers, c.cipherSuite)(result, c.exporterSecret, label, seed)
David Benjaminc565ebb2015-04-03 04:06:36 -04001766 return result, nil
1767}
David Benjamin3e052de2015-11-25 20:10:31 -05001768
1769// noRenegotiationInfo returns true if the renegotiation info extension
1770// should be supported in the current handshake.
1771func (c *Conn) noRenegotiationInfo() bool {
1772 if c.config.Bugs.NoRenegotiationInfo {
1773 return true
1774 }
1775 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1776 return true
1777 }
1778 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1779 return true
1780 }
1781 return false
1782}
David Benjamin58104882016-07-18 01:25:41 +02001783
1784func (c *Conn) SendNewSessionTicket() error {
1785 if c.isClient || c.vers < VersionTLS13 {
1786 return errors.New("tls: cannot send post-handshake NewSessionTicket")
1787 }
1788
1789 var peerCertificatesRaw [][]byte
1790 for _, cert := range c.peerCertificates {
1791 peerCertificatesRaw = append(peerCertificatesRaw, cert.Raw)
1792 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001793
Steven Valdeza833c352016-11-01 13:39:36 -04001794 addBuffer := make([]byte, 4)
1795 _, err := io.ReadFull(c.config.rand(), addBuffer)
1796 if err != nil {
1797 c.sendAlert(alertInternalError)
1798 return errors.New("tls: short read from Rand: " + err.Error())
1799 }
1800 ticketAgeAdd := uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0])
1801
David Benjamin58104882016-07-18 01:25:41 +02001802 // TODO(davidben): Allow configuring these values.
1803 m := &newSessionTicketMsg{
David Benjamin9c33ae82017-01-08 06:04:43 -05001804 version: c.vers,
1805 ticketLifetime: uint32(24 * time.Hour / time.Second),
David Benjamin9c33ae82017-01-08 06:04:43 -05001806 duplicateEarlyDataInfo: c.config.Bugs.DuplicateTicketEarlyDataInfo,
1807 customExtension: c.config.Bugs.CustomTicketExtension,
1808 ticketAgeAdd: ticketAgeAdd,
Nick Harperab20cec2016-12-19 17:38:41 -08001809 maxEarlyDataSize: c.config.MaxEarlyDataSize,
David Benjamin58104882016-07-18 01:25:41 +02001810 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001811
David Benjamin17b30832017-01-28 14:00:32 -05001812 if c.config.Bugs.SendTicketLifetime != 0 {
1813 m.ticketLifetime = uint32(c.config.Bugs.SendTicketLifetime / time.Second)
1814 }
1815
Nick Harper0b3625b2016-07-25 16:16:28 -07001816 state := sessionState{
1817 vers: c.vers,
1818 cipherSuite: c.cipherSuite.id,
1819 masterSecret: c.resumptionSecret,
1820 certificates: peerCertificatesRaw,
1821 ticketCreationTime: c.config.time(),
1822 ticketExpiration: c.config.time().Add(time.Duration(m.ticketLifetime) * time.Second),
Steven Valdeza833c352016-11-01 13:39:36 -04001823 ticketAgeAdd: uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0]),
Nick Harper0b3625b2016-07-25 16:16:28 -07001824 }
1825
David Benjamin58104882016-07-18 01:25:41 +02001826 if !c.config.Bugs.SendEmptySessionTicket {
1827 var err error
1828 m.ticket, err = c.encryptTicket(&state)
1829 if err != nil {
1830 return err
1831 }
1832 }
1833
1834 c.out.Lock()
1835 defer c.out.Unlock()
Steven Valdeza833c352016-11-01 13:39:36 -04001836 _, err = c.writeRecord(recordTypeHandshake, m.marshal())
David Benjamin58104882016-07-18 01:25:41 +02001837 return err
1838}
David Benjamin21c00282016-07-18 21:56:23 +02001839
Steven Valdezc4aa7272016-10-03 12:25:56 -04001840func (c *Conn) SendKeyUpdate(keyUpdateRequest byte) error {
David Benjamin21c00282016-07-18 21:56:23 +02001841 c.out.Lock()
1842 defer c.out.Unlock()
Steven Valdezc4aa7272016-10-03 12:25:56 -04001843 return c.sendKeyUpdateLocked(keyUpdateRequest)
David Benjamin21c00282016-07-18 21:56:23 +02001844}
1845
Steven Valdezc4aa7272016-10-03 12:25:56 -04001846func (c *Conn) sendKeyUpdateLocked(keyUpdateRequest byte) error {
David Benjamin7f0965a2016-09-30 15:14:01 -04001847 if c.vers < VersionTLS13 {
1848 return errors.New("tls: attempted to send KeyUpdate before TLS 1.3")
1849 }
1850
Steven Valdezc4aa7272016-10-03 12:25:56 -04001851 m := keyUpdateMsg{
1852 keyUpdateRequest: keyUpdateRequest,
1853 }
David Benjamin21c00282016-07-18 21:56:23 +02001854 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
1855 return err
1856 }
1857 if err := c.flushHandshake(); err != nil {
1858 return err
1859 }
Steven Valdez1dc53d22016-07-26 12:27:38 -04001860 c.out.doKeyUpdate(c, true)
David Benjamin21c00282016-07-18 21:56:23 +02001861 return nil
1862}
Steven Valdeza4ee74d2016-11-29 13:36:45 -05001863
1864func (c *Conn) sendFakeEarlyData(len int) error {
1865 // Assemble a fake early data record. This does not use writeRecord
1866 // because the record layer may be using different keys at this point.
1867 payload := make([]byte, 5+len)
1868 payload[0] = byte(recordTypeApplicationData)
1869 payload[1] = 3
1870 payload[2] = 1
1871 payload[3] = byte(len >> 8)
1872 payload[4] = byte(len)
1873 _, err := c.conn.Write(payload)
1874 return err
1875}
David Benjamin6f600d62016-12-21 16:06:54 -05001876
1877func (c *Conn) setShortHeader() {
1878 c.in.shortHeader = true
1879 c.out.shortHeader = true
1880}