blob: 39c27850093797d4e9250215749e061d729cd44a [file] [log] [blame]
Adam Langley95c29f32014-06-20 12:00:00 -07001// Copyright 2010 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5// TLS low level connection and record layer
6
Adam Langleydc7e9c42015-09-29 15:21:04 -07007package runner
Adam Langley95c29f32014-06-20 12:00:00 -07008
9import (
10 "bytes"
11 "crypto/cipher"
David Benjamind30a9902014-08-24 01:44:23 -040012 "crypto/ecdsa"
Adam Langley95c29f32014-06-20 12:00:00 -070013 "crypto/subtle"
14 "crypto/x509"
David Benjamin8e6db492015-07-25 18:29:23 -040015 "encoding/binary"
Adam Langley95c29f32014-06-20 12:00:00 -070016 "errors"
17 "fmt"
18 "io"
19 "net"
20 "sync"
21 "time"
22)
23
24// A Conn represents a secured connection.
25// It implements the net.Conn interface.
26type Conn struct {
27 // constant
28 conn net.Conn
David Benjamin83c0bc92014-08-04 01:23:53 -040029 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -070030 isClient bool
31
32 // constant after handshake; protected by handshakeMutex
Adam Langley75712922014-10-10 16:23:43 -070033 handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
34 handshakeErr error // error resulting from handshake
35 vers uint16 // TLS version
36 haveVers bool // version has been negotiated
37 config *Config // configuration passed to constructor
38 handshakeComplete bool
39 didResume bool // whether this connection was a session resumption
40 extendedMasterSecret bool // whether this session used an extended master secret
David Benjaminc565ebb2015-04-03 04:06:36 -040041 cipherSuite *cipherSuite
Adam Langley75712922014-10-10 16:23:43 -070042 ocspResponse []byte // stapled OCSP response
Paul Lietar4fac72e2015-09-09 13:44:55 +010043 sctList []byte // signed certificate timestamp list
Adam Langley75712922014-10-10 16:23:43 -070044 peerCertificates []*x509.Certificate
Adam Langley95c29f32014-06-20 12:00:00 -070045 // verifiedChains contains the certificate chains that we built, as
46 // opposed to the ones presented by the server.
47 verifiedChains [][]*x509.Certificate
48 // serverName contains the server name indicated by the client, if any.
Adam Langleyaf0e32c2015-06-03 09:57:23 -070049 serverName string
50 // firstFinished contains the first Finished hash sent during the
51 // handshake. This is the "tls-unique" channel binding value.
52 firstFinished [12]byte
Nick Harper60edffd2016-06-21 15:19:24 -070053 // peerSignatureAlgorithm contains the signature algorithm that was used
54 // by the peer in the handshake, or zero if not applicable.
55 peerSignatureAlgorithm signatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -040056 // curveID contains the curve that was used in the handshake, or zero if
57 // not applicable.
58 curveID CurveID
Adam Langleyaf0e32c2015-06-03 09:57:23 -070059
David Benjaminc565ebb2015-04-03 04:06:36 -040060 clientRandom, serverRandom [32]byte
David Benjamin97a0a082016-07-13 17:57:35 -040061 exporterSecret []byte
David Benjamin58104882016-07-18 01:25:41 +020062 resumptionSecret []byte
Adam Langley95c29f32014-06-20 12:00:00 -070063
64 clientProtocol string
65 clientProtocolFallback bool
David Benjaminfc7b0862014-09-06 13:21:53 -040066 usedALPN bool
Adam Langley95c29f32014-06-20 12:00:00 -070067
Adam Langley2ae77d22014-10-28 17:29:33 -070068 // verify_data values for the renegotiation extension.
69 clientVerify []byte
70 serverVerify []byte
71
David Benjamind30a9902014-08-24 01:44:23 -040072 channelID *ecdsa.PublicKey
73
David Benjaminca6c8262014-11-15 19:06:08 -050074 srtpProtectionProfile uint16
75
David Benjaminc44b1df2014-11-23 12:11:01 -050076 clientVersion uint16
77
Adam Langley95c29f32014-06-20 12:00:00 -070078 // input/output
79 in, out halfConn // in.Mutex < out.Mutex
80 rawInput *block // raw input, right off the wire
David Benjamin83c0bc92014-08-04 01:23:53 -040081 input *block // application record waiting to be read
82 hand bytes.Buffer // handshake record waiting to be read
83
David Benjamin582ba042016-07-07 12:33:25 -070084 // pendingFlight, if PackHandshakeFlight is enabled, is the buffer of
85 // handshake data to be split into records at the end of the flight.
86 pendingFlight bytes.Buffer
87
David Benjamin83c0bc92014-08-04 01:23:53 -040088 // DTLS state
89 sendHandshakeSeq uint16
90 recvHandshakeSeq uint16
David Benjaminb3774b92015-01-31 17:16:01 -050091 handMsg []byte // pending assembled handshake message
92 handMsgLen int // handshake message length, not including the header
93 pendingFragments [][]byte // pending outgoing handshake fragments.
Adam Langley95c29f32014-06-20 12:00:00 -070094
Steven Valdezc4aa7272016-10-03 12:25:56 -040095 keyUpdateRequested bool
96
Adam Langley95c29f32014-06-20 12:00:00 -070097 tmp [16]byte
98}
99
David Benjamin5e961c12014-11-07 01:48:35 -0500100func (c *Conn) init() {
101 c.in.isDTLS = c.isDTLS
102 c.out.isDTLS = c.isDTLS
103 c.in.config = c.config
104 c.out.config = c.config
David Benjamin8e6db492015-07-25 18:29:23 -0400105
106 c.out.updateOutSeq()
David Benjamin5e961c12014-11-07 01:48:35 -0500107}
108
Adam Langley95c29f32014-06-20 12:00:00 -0700109// Access to net.Conn methods.
110// Cannot just embed net.Conn because that would
111// export the struct field too.
112
113// LocalAddr returns the local network address.
114func (c *Conn) LocalAddr() net.Addr {
115 return c.conn.LocalAddr()
116}
117
118// RemoteAddr returns the remote network address.
119func (c *Conn) RemoteAddr() net.Addr {
120 return c.conn.RemoteAddr()
121}
122
123// SetDeadline sets the read and write deadlines associated with the connection.
124// A zero value for t means Read and Write will not time out.
125// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
126func (c *Conn) SetDeadline(t time.Time) error {
127 return c.conn.SetDeadline(t)
128}
129
130// SetReadDeadline sets the read deadline on the underlying connection.
131// A zero value for t means Read will not time out.
132func (c *Conn) SetReadDeadline(t time.Time) error {
133 return c.conn.SetReadDeadline(t)
134}
135
136// SetWriteDeadline sets the write deadline on the underlying conneciton.
137// A zero value for t means Write will not time out.
138// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
139func (c *Conn) SetWriteDeadline(t time.Time) error {
140 return c.conn.SetWriteDeadline(t)
141}
142
143// A halfConn represents one direction of the record layer
144// connection, either sending or receiving.
145type halfConn struct {
146 sync.Mutex
147
David Benjamin83c0bc92014-08-04 01:23:53 -0400148 err error // first permanent error
149 version uint16 // protocol version
150 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -0700151 cipher interface{} // cipher algorithm
152 mac macFunction
153 seq [8]byte // 64-bit sequence number
David Benjamin8e6db492015-07-25 18:29:23 -0400154 outSeq [8]byte // Mapped sequence number
Adam Langley95c29f32014-06-20 12:00:00 -0700155 bfree *block // list of free blocks
156
157 nextCipher interface{} // next encryption state
158 nextMac macFunction // next MAC algorithm
David Benjamin83f90402015-01-27 01:09:43 -0500159 nextSeq [6]byte // next epoch's starting sequence number in DTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700160
161 // used to save allocating a new buffer for each MAC.
162 inDigestBuf, outDigestBuf []byte
Adam Langley80842bd2014-06-20 12:00:00 -0700163
Steven Valdezc4aa7272016-10-03 12:25:56 -0400164 trafficSecret []byte
David Benjamin21c00282016-07-18 21:56:23 +0200165
Adam Langley80842bd2014-06-20 12:00:00 -0700166 config *Config
Adam Langley95c29f32014-06-20 12:00:00 -0700167}
168
169func (hc *halfConn) setErrorLocked(err error) error {
170 hc.err = err
171 return err
172}
173
174func (hc *halfConn) error() error {
Adam Langley2ae77d22014-10-28 17:29:33 -0700175 // This should be locked, but I've removed it for the renegotiation
176 // tests since we don't concurrently read and write the same tls.Conn
177 // in any case during testing.
Adam Langley95c29f32014-06-20 12:00:00 -0700178 err := hc.err
Adam Langley95c29f32014-06-20 12:00:00 -0700179 return err
180}
181
182// prepareCipherSpec sets the encryption and MAC states
183// that a subsequent changeCipherSpec will use.
184func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
185 hc.version = version
186 hc.nextCipher = cipher
187 hc.nextMac = mac
188}
189
190// changeCipherSpec changes the encryption and MAC states
191// to the ones previously passed to prepareCipherSpec.
Adam Langley80842bd2014-06-20 12:00:00 -0700192func (hc *halfConn) changeCipherSpec(config *Config) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700193 if hc.nextCipher == nil {
194 return alertInternalError
195 }
196 hc.cipher = hc.nextCipher
197 hc.mac = hc.nextMac
198 hc.nextCipher = nil
199 hc.nextMac = nil
Adam Langley80842bd2014-06-20 12:00:00 -0700200 hc.config = config
David Benjamin83c0bc92014-08-04 01:23:53 -0400201 hc.incEpoch()
David Benjaminf2b83632016-03-01 22:57:46 -0500202
203 if config.Bugs.NullAllCiphers {
David Benjamin7a4aaa42016-09-20 17:58:14 -0400204 hc.cipher = nullCipher{}
David Benjaminf2b83632016-03-01 22:57:46 -0500205 hc.mac = nil
206 }
Adam Langley95c29f32014-06-20 12:00:00 -0700207 return nil
208}
209
David Benjamin21c00282016-07-18 21:56:23 +0200210// useTrafficSecret sets the current cipher state for TLS 1.3.
Steven Valdeza833c352016-11-01 13:39:36 -0400211func (hc *halfConn) useTrafficSecret(version uint16, suite *cipherSuite, secret []byte, side trafficDirection) {
Nick Harperb41d2e42016-07-01 17:50:32 -0400212 hc.version = version
Steven Valdeza833c352016-11-01 13:39:36 -0400213 hc.cipher = deriveTrafficAEAD(version, suite, secret, side)
David Benjamin7a4aaa42016-09-20 17:58:14 -0400214 if hc.config.Bugs.NullAllCiphers {
215 hc.cipher = nullCipher{}
216 }
David Benjamin21c00282016-07-18 21:56:23 +0200217 hc.trafficSecret = secret
Nick Harperb41d2e42016-07-01 17:50:32 -0400218 hc.incEpoch()
219}
220
David Benjamin21c00282016-07-18 21:56:23 +0200221func (hc *halfConn) doKeyUpdate(c *Conn, isOutgoing bool) {
222 side := serverWrite
223 if c.isClient == isOutgoing {
224 side = clientWrite
225 }
Steven Valdeza833c352016-11-01 13:39:36 -0400226 hc.useTrafficSecret(hc.version, c.cipherSuite, updateTrafficSecret(c.cipherSuite.hash(), hc.trafficSecret), side)
David Benjamin21c00282016-07-18 21:56:23 +0200227}
228
Adam Langley95c29f32014-06-20 12:00:00 -0700229// incSeq increments the sequence number.
David Benjamin5e961c12014-11-07 01:48:35 -0500230func (hc *halfConn) incSeq(isOutgoing bool) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400231 limit := 0
David Benjamin5e961c12014-11-07 01:48:35 -0500232 increment := uint64(1)
David Benjamin83c0bc92014-08-04 01:23:53 -0400233 if hc.isDTLS {
234 // Increment up to the epoch in DTLS.
235 limit = 2
236 }
237 for i := 7; i >= limit; i-- {
David Benjamin5e961c12014-11-07 01:48:35 -0500238 increment += uint64(hc.seq[i])
239 hc.seq[i] = byte(increment)
240 increment >>= 8
Adam Langley95c29f32014-06-20 12:00:00 -0700241 }
242
243 // Not allowed to let sequence number wrap.
244 // Instead, must renegotiate before it does.
245 // Not likely enough to bother.
David Benjamin5e961c12014-11-07 01:48:35 -0500246 if increment != 0 {
247 panic("TLS: sequence number wraparound")
248 }
David Benjamin8e6db492015-07-25 18:29:23 -0400249
250 hc.updateOutSeq()
Adam Langley95c29f32014-06-20 12:00:00 -0700251}
252
David Benjamin83f90402015-01-27 01:09:43 -0500253// incNextSeq increments the starting sequence number for the next epoch.
254func (hc *halfConn) incNextSeq() {
255 for i := len(hc.nextSeq) - 1; i >= 0; i-- {
256 hc.nextSeq[i]++
257 if hc.nextSeq[i] != 0 {
258 return
259 }
260 }
261 panic("TLS: sequence number wraparound")
262}
263
264// incEpoch resets the sequence number. In DTLS, it also increments the epoch
265// half of the sequence number.
David Benjamin83c0bc92014-08-04 01:23:53 -0400266func (hc *halfConn) incEpoch() {
David Benjamin83c0bc92014-08-04 01:23:53 -0400267 if hc.isDTLS {
268 for i := 1; i >= 0; i-- {
269 hc.seq[i]++
270 if hc.seq[i] != 0 {
271 break
272 }
273 if i == 0 {
274 panic("TLS: epoch number wraparound")
275 }
276 }
David Benjamin83f90402015-01-27 01:09:43 -0500277 copy(hc.seq[2:], hc.nextSeq[:])
278 for i := range hc.nextSeq {
279 hc.nextSeq[i] = 0
280 }
281 } else {
282 for i := range hc.seq {
283 hc.seq[i] = 0
284 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400285 }
David Benjamin8e6db492015-07-25 18:29:23 -0400286
287 hc.updateOutSeq()
288}
289
290func (hc *halfConn) updateOutSeq() {
291 if hc.config.Bugs.SequenceNumberMapping != nil {
292 seqU64 := binary.BigEndian.Uint64(hc.seq[:])
293 seqU64 = hc.config.Bugs.SequenceNumberMapping(seqU64)
294 binary.BigEndian.PutUint64(hc.outSeq[:], seqU64)
295
296 // The DTLS epoch cannot be changed.
297 copy(hc.outSeq[:2], hc.seq[:2])
298 return
299 }
300
301 copy(hc.outSeq[:], hc.seq[:])
David Benjamin83c0bc92014-08-04 01:23:53 -0400302}
303
304func (hc *halfConn) recordHeaderLen() int {
305 if hc.isDTLS {
306 return dtlsRecordHeaderLen
307 }
308 return tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700309}
310
311// removePadding returns an unpadded slice, in constant time, which is a prefix
312// of the input. It also returns a byte which is equal to 255 if the padding
313// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
314func removePadding(payload []byte) ([]byte, byte) {
315 if len(payload) < 1 {
316 return payload, 0
317 }
318
319 paddingLen := payload[len(payload)-1]
320 t := uint(len(payload)-1) - uint(paddingLen)
321 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
322 good := byte(int32(^t) >> 31)
323
324 toCheck := 255 // the maximum possible padding length
325 // The length of the padded data is public, so we can use an if here
326 if toCheck+1 > len(payload) {
327 toCheck = len(payload) - 1
328 }
329
330 for i := 0; i < toCheck; i++ {
331 t := uint(paddingLen) - uint(i)
332 // if i <= paddingLen then the MSB of t is zero
333 mask := byte(int32(^t) >> 31)
334 b := payload[len(payload)-1-i]
335 good &^= mask&paddingLen ^ mask&b
336 }
337
338 // We AND together the bits of good and replicate the result across
339 // all the bits.
340 good &= good << 4
341 good &= good << 2
342 good &= good << 1
343 good = uint8(int8(good) >> 7)
344
345 toRemove := good&paddingLen + 1
346 return payload[:len(payload)-int(toRemove)], good
347}
348
349// removePaddingSSL30 is a replacement for removePadding in the case that the
350// protocol version is SSLv3. In this version, the contents of the padding
351// are random and cannot be checked.
352func removePaddingSSL30(payload []byte) ([]byte, byte) {
353 if len(payload) < 1 {
354 return payload, 0
355 }
356
357 paddingLen := int(payload[len(payload)-1]) + 1
358 if paddingLen > len(payload) {
359 return payload, 0
360 }
361
362 return payload[:len(payload)-paddingLen], 255
363}
364
365func roundUp(a, b int) int {
366 return a + (b-a%b)%b
367}
368
369// cbcMode is an interface for block ciphers using cipher block chaining.
370type cbcMode interface {
371 cipher.BlockMode
372 SetIV([]byte)
373}
374
375// decrypt checks and strips the mac and decrypts the data in b. Returns a
376// success boolean, the number of bytes to skip from the start of the record in
Nick Harper1fd39d82016-06-14 18:14:35 -0700377// order to get the application payload, the encrypted record type (or 0
378// if there is none), and an optional alert value.
379func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, contentType recordType, alertValue alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400380 recordHeaderLen := hc.recordHeaderLen()
381
Adam Langley95c29f32014-06-20 12:00:00 -0700382 // pull out payload
383 payload := b.data[recordHeaderLen:]
384
385 macSize := 0
386 if hc.mac != nil {
387 macSize = hc.mac.Size()
388 }
389
390 paddingGood := byte(255)
391 explicitIVLen := 0
392
David Benjamin83c0bc92014-08-04 01:23:53 -0400393 seq := hc.seq[:]
394 if hc.isDTLS {
395 // DTLS sequence numbers are explicit.
396 seq = b.data[3:11]
397 }
398
Adam Langley95c29f32014-06-20 12:00:00 -0700399 // decrypt
400 if hc.cipher != nil {
401 switch c := hc.cipher.(type) {
402 case cipher.Stream:
403 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400404 case *tlsAead:
405 nonce := seq
406 if c.explicitNonce {
407 explicitIVLen = 8
408 if len(payload) < explicitIVLen {
Nick Harper1fd39d82016-06-14 18:14:35 -0700409 return false, 0, 0, alertBadRecordMAC
David Benjamine9a80ff2015-04-07 00:46:46 -0400410 }
411 nonce = payload[:8]
412 payload = payload[8:]
Adam Langley95c29f32014-06-20 12:00:00 -0700413 }
Adam Langley95c29f32014-06-20 12:00:00 -0700414
Nick Harper1fd39d82016-06-14 18:14:35 -0700415 var additionalData []byte
416 if hc.version < VersionTLS13 {
417 additionalData = make([]byte, 13)
418 copy(additionalData, seq)
419 copy(additionalData[8:], b.data[:3])
420 n := len(payload) - c.Overhead()
421 additionalData[11] = byte(n >> 8)
422 additionalData[12] = byte(n)
423 }
Adam Langley95c29f32014-06-20 12:00:00 -0700424 var err error
Nick Harper1fd39d82016-06-14 18:14:35 -0700425 payload, err = c.Open(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700426 if err != nil {
Nick Harper1fd39d82016-06-14 18:14:35 -0700427 return false, 0, 0, alertBadRecordMAC
428 }
Adam Langley95c29f32014-06-20 12:00:00 -0700429 b.resize(recordHeaderLen + explicitIVLen + len(payload))
430 case cbcMode:
431 blockSize := c.BlockSize()
David Benjamin83c0bc92014-08-04 01:23:53 -0400432 if hc.version >= VersionTLS11 || hc.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700433 explicitIVLen = blockSize
434 }
435
436 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
Nick Harper1fd39d82016-06-14 18:14:35 -0700437 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700438 }
439
440 if explicitIVLen > 0 {
441 c.SetIV(payload[:explicitIVLen])
442 payload = payload[explicitIVLen:]
443 }
444 c.CryptBlocks(payload, payload)
445 if hc.version == VersionSSL30 {
446 payload, paddingGood = removePaddingSSL30(payload)
447 } else {
448 payload, paddingGood = removePadding(payload)
449 }
450 b.resize(recordHeaderLen + explicitIVLen + len(payload))
451
452 // note that we still have a timing side-channel in the
453 // MAC check, below. An attacker can align the record
454 // so that a correct padding will cause one less hash
455 // block to be calculated. Then they can iteratively
456 // decrypt a record by breaking each byte. See
457 // "Password Interception in a SSL/TLS Channel", Brice
458 // Canvel et al.
459 //
460 // However, our behavior matches OpenSSL, so we leak
461 // only as much as they do.
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700462 case nullCipher:
463 break
Adam Langley95c29f32014-06-20 12:00:00 -0700464 default:
465 panic("unknown cipher type")
466 }
David Benjamin7a4aaa42016-09-20 17:58:14 -0400467
468 if hc.version >= VersionTLS13 {
469 i := len(payload)
470 for i > 0 && payload[i-1] == 0 {
471 i--
472 }
473 payload = payload[:i]
474 if len(payload) == 0 {
475 return false, 0, 0, alertUnexpectedMessage
476 }
477 contentType = recordType(payload[len(payload)-1])
478 payload = payload[:len(payload)-1]
479 b.resize(recordHeaderLen + len(payload))
480 }
Adam Langley95c29f32014-06-20 12:00:00 -0700481 }
482
483 // check, strip mac
484 if hc.mac != nil {
485 if len(payload) < macSize {
Nick Harper1fd39d82016-06-14 18:14:35 -0700486 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700487 }
488
489 // strip mac off payload, b.data
490 n := len(payload) - macSize
David Benjamin83c0bc92014-08-04 01:23:53 -0400491 b.data[recordHeaderLen-2] = byte(n >> 8)
492 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700493 b.resize(recordHeaderLen + explicitIVLen + n)
494 remoteMAC := payload[n:]
David Benjamin83c0bc92014-08-04 01:23:53 -0400495 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
Adam Langley95c29f32014-06-20 12:00:00 -0700496
497 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
Nick Harper1fd39d82016-06-14 18:14:35 -0700498 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700499 }
500 hc.inDigestBuf = localMAC
501 }
David Benjamin5e961c12014-11-07 01:48:35 -0500502 hc.incSeq(false)
Adam Langley95c29f32014-06-20 12:00:00 -0700503
Nick Harper1fd39d82016-06-14 18:14:35 -0700504 return true, recordHeaderLen + explicitIVLen, contentType, 0
Adam Langley95c29f32014-06-20 12:00:00 -0700505}
506
507// padToBlockSize calculates the needed padding block, if any, for a payload.
508// On exit, prefix aliases payload and extends to the end of the last full
509// block of payload. finalBlock is a fresh slice which contains the contents of
510// any suffix of payload as well as the needed padding to make finalBlock a
511// full block.
Adam Langley80842bd2014-06-20 12:00:00 -0700512func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
Adam Langley95c29f32014-06-20 12:00:00 -0700513 overrun := len(payload) % blockSize
Adam Langley95c29f32014-06-20 12:00:00 -0700514 prefix = payload[:len(payload)-overrun]
Adam Langley80842bd2014-06-20 12:00:00 -0700515
516 paddingLen := blockSize - overrun
517 finalSize := blockSize
518 if config.Bugs.MaxPadding {
519 for paddingLen+blockSize <= 256 {
520 paddingLen += blockSize
521 }
522 finalSize = 256
523 }
524 finalBlock = make([]byte, finalSize)
525 for i := range finalBlock {
Adam Langley95c29f32014-06-20 12:00:00 -0700526 finalBlock[i] = byte(paddingLen - 1)
527 }
Adam Langley80842bd2014-06-20 12:00:00 -0700528 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
529 finalBlock[overrun] ^= 0xff
530 }
531 copy(finalBlock, payload[len(payload)-overrun:])
Adam Langley95c29f32014-06-20 12:00:00 -0700532 return
533}
534
535// encrypt encrypts and macs the data in b.
Nick Harper1fd39d82016-06-14 18:14:35 -0700536func (hc *halfConn) encrypt(b *block, explicitIVLen int, typ recordType) (bool, alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400537 recordHeaderLen := hc.recordHeaderLen()
538
Adam Langley95c29f32014-06-20 12:00:00 -0700539 // mac
540 if hc.mac != nil {
David Benjamin8e6db492015-07-25 18:29:23 -0400541 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 -0700542
543 n := len(b.data)
544 b.resize(n + len(mac))
545 copy(b.data[n:], mac)
546 hc.outDigestBuf = mac
547 }
548
549 payload := b.data[recordHeaderLen:]
550
551 // encrypt
552 if hc.cipher != nil {
David Benjamin7a4aaa42016-09-20 17:58:14 -0400553 // Add TLS 1.3 padding.
554 if hc.version >= VersionTLS13 {
555 paddingLen := hc.config.Bugs.RecordPadding
556 if hc.config.Bugs.OmitRecordContents {
557 b.resize(recordHeaderLen + paddingLen)
558 } else {
559 b.resize(len(b.data) + 1 + paddingLen)
560 b.data[len(b.data)-paddingLen-1] = byte(typ)
561 }
562 for i := 0; i < paddingLen; i++ {
563 b.data[len(b.data)-paddingLen+i] = 0
564 }
565 }
566
Adam Langley95c29f32014-06-20 12:00:00 -0700567 switch c := hc.cipher.(type) {
568 case cipher.Stream:
569 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400570 case *tlsAead:
Adam Langley95c29f32014-06-20 12:00:00 -0700571 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
David Benjamin7a4aaa42016-09-20 17:58:14 -0400572 b.resize(len(b.data) + c.Overhead())
David Benjamin8e6db492015-07-25 18:29:23 -0400573 nonce := hc.outSeq[:]
David Benjamine9a80ff2015-04-07 00:46:46 -0400574 if c.explicitNonce {
575 nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
576 }
Adam Langley95c29f32014-06-20 12:00:00 -0700577 payload := b.data[recordHeaderLen+explicitIVLen:]
578 payload = payload[:payloadLen]
579
Nick Harper1fd39d82016-06-14 18:14:35 -0700580 var additionalData []byte
581 if hc.version < VersionTLS13 {
582 additionalData = make([]byte, 13)
583 copy(additionalData, hc.outSeq[:])
584 copy(additionalData[8:], b.data[:3])
585 additionalData[11] = byte(payloadLen >> 8)
586 additionalData[12] = byte(payloadLen)
587 }
Adam Langley95c29f32014-06-20 12:00:00 -0700588
Nick Harper1fd39d82016-06-14 18:14:35 -0700589 c.Seal(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700590 case cbcMode:
591 blockSize := c.BlockSize()
592 if explicitIVLen > 0 {
593 c.SetIV(payload[:explicitIVLen])
594 payload = payload[explicitIVLen:]
595 }
Adam Langley80842bd2014-06-20 12:00:00 -0700596 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700597 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
598 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
599 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700600 case nullCipher:
601 break
Adam Langley95c29f32014-06-20 12:00:00 -0700602 default:
603 panic("unknown cipher type")
604 }
605 }
606
607 // update length to include MAC and any block padding needed.
608 n := len(b.data) - recordHeaderLen
David Benjamin83c0bc92014-08-04 01:23:53 -0400609 b.data[recordHeaderLen-2] = byte(n >> 8)
610 b.data[recordHeaderLen-1] = byte(n)
David Benjamin5e961c12014-11-07 01:48:35 -0500611 hc.incSeq(true)
Adam Langley95c29f32014-06-20 12:00:00 -0700612
613 return true, 0
614}
615
616// A block is a simple data buffer.
617type block struct {
618 data []byte
619 off int // index for Read
620 link *block
621}
622
623// resize resizes block to be n bytes, growing if necessary.
624func (b *block) resize(n int) {
625 if n > cap(b.data) {
626 b.reserve(n)
627 }
628 b.data = b.data[0:n]
629}
630
631// reserve makes sure that block contains a capacity of at least n bytes.
632func (b *block) reserve(n int) {
633 if cap(b.data) >= n {
634 return
635 }
636 m := cap(b.data)
637 if m == 0 {
638 m = 1024
639 }
640 for m < n {
641 m *= 2
642 }
643 data := make([]byte, len(b.data), m)
644 copy(data, b.data)
645 b.data = data
646}
647
648// readFromUntil reads from r into b until b contains at least n bytes
649// or else returns an error.
650func (b *block) readFromUntil(r io.Reader, n int) error {
651 // quick case
652 if len(b.data) >= n {
653 return nil
654 }
655
656 // read until have enough.
657 b.reserve(n)
658 for {
659 m, err := r.Read(b.data[len(b.data):cap(b.data)])
660 b.data = b.data[0 : len(b.data)+m]
661 if len(b.data) >= n {
662 // TODO(bradfitz,agl): slightly suspicious
663 // that we're throwing away r.Read's err here.
664 break
665 }
666 if err != nil {
667 return err
668 }
669 }
670 return nil
671}
672
673func (b *block) Read(p []byte) (n int, err error) {
674 n = copy(p, b.data[b.off:])
675 b.off += n
676 return
677}
678
679// newBlock allocates a new block, from hc's free list if possible.
680func (hc *halfConn) newBlock() *block {
681 b := hc.bfree
682 if b == nil {
683 return new(block)
684 }
685 hc.bfree = b.link
686 b.link = nil
687 b.resize(0)
688 return b
689}
690
691// freeBlock returns a block to hc's free list.
692// The protocol is such that each side only has a block or two on
693// its free list at a time, so there's no need to worry about
694// trimming the list, etc.
695func (hc *halfConn) freeBlock(b *block) {
696 b.link = hc.bfree
697 hc.bfree = b
698}
699
700// splitBlock splits a block after the first n bytes,
701// returning a block with those n bytes and a
702// block with the remainder. the latter may be nil.
703func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
704 if len(b.data) <= n {
705 return b, nil
706 }
707 bb := hc.newBlock()
708 bb.resize(len(b.data) - n)
709 copy(bb.data, b.data[n:])
710 b.data = b.data[0:n]
711 return b, bb
712}
713
David Benjamin83c0bc92014-08-04 01:23:53 -0400714func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
715 if c.isDTLS {
716 return c.dtlsDoReadRecord(want)
717 }
718
719 recordHeaderLen := tlsRecordHeaderLen
720
721 if c.rawInput == nil {
722 c.rawInput = c.in.newBlock()
723 }
724 b := c.rawInput
725
726 // Read header, payload.
727 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
728 // RFC suggests that EOF without an alertCloseNotify is
729 // an error, but popular web sites seem to do this,
David Benjamin30789da2015-08-29 22:56:45 -0400730 // so we can't make it an error, outside of tests.
731 if err == io.EOF && c.config.Bugs.ExpectCloseNotify {
732 err = io.ErrUnexpectedEOF
733 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400734 if e, ok := err.(net.Error); !ok || !e.Temporary() {
735 c.in.setErrorLocked(err)
736 }
737 return 0, nil, err
738 }
739 typ := recordType(b.data[0])
740
741 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
742 // start with a uint16 length where the MSB is set and the first record
743 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
744 // an SSLv2 client.
745 if want == recordTypeHandshake && typ == 0x80 {
746 c.sendAlert(alertProtocolVersion)
747 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
748 }
749
750 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
751 n := int(b.data[3])<<8 | int(b.data[4])
David Benjaminbde00392016-06-21 12:19:28 -0400752 // Alerts sent near version negotiation do not have a well-defined
753 // record-layer version prior to TLS 1.3. (In TLS 1.3, the record-layer
754 // version is irrelevant.)
755 if typ != recordTypeAlert {
David Benjamine6f22212016-11-08 14:28:24 -0500756 var expect uint16
David Benjaminbde00392016-06-21 12:19:28 -0400757 if c.haveVers {
David Benjamine6f22212016-11-08 14:28:24 -0500758 expect = c.vers
759 if c.vers >= VersionTLS13 {
760 expect = VersionTLS10
David Benjaminbde00392016-06-21 12:19:28 -0400761 }
762 } else {
David Benjamine6f22212016-11-08 14:28:24 -0500763 expect = c.config.Bugs.ExpectInitialRecordVersion
764 }
765 if expect != 0 && vers != expect {
766 c.sendAlert(alertProtocolVersion)
767 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 -0500768 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400769 }
770 if n > maxCiphertext {
771 c.sendAlert(alertRecordOverflow)
772 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
773 }
774 if !c.haveVers {
775 // First message, be extra suspicious:
776 // this might not be a TLS client.
777 // Bail out before reading a full 'body', if possible.
778 // The current max version is 3.1.
779 // If the version is >= 16.0, it's probably not real.
780 // Similarly, a clientHello message encodes in
781 // well under a kilobyte. If the length is >= 12 kB,
782 // it's probably not real.
783 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
784 c.sendAlert(alertUnexpectedMessage)
785 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
786 }
787 }
788 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
789 if err == io.EOF {
790 err = io.ErrUnexpectedEOF
791 }
792 if e, ok := err.(net.Error); !ok || !e.Temporary() {
793 c.in.setErrorLocked(err)
794 }
795 return 0, nil, err
796 }
797
798 // Process message.
799 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
David Benjaminff26f092016-07-01 16:13:42 -0400800 ok, off, encTyp, alertValue := c.in.decrypt(b)
801 if !ok {
802 return 0, nil, c.in.setErrorLocked(c.sendAlert(alertValue))
803 }
804 b.off = off
805
Nick Harper1fd39d82016-06-14 18:14:35 -0700806 if c.vers >= VersionTLS13 && c.in.cipher != nil {
David Benjaminc9ae27c2016-06-24 22:56:37 -0400807 if typ != recordTypeApplicationData {
808 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: outer record type is not application data"))
809 }
Nick Harper1fd39d82016-06-14 18:14:35 -0700810 typ = encTyp
811 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400812 return typ, b, nil
813}
814
Adam Langley95c29f32014-06-20 12:00:00 -0700815// readRecord reads the next TLS record from the connection
816// and updates the record layer state.
817// c.in.Mutex <= L; c.input == nil.
818func (c *Conn) readRecord(want recordType) error {
819 // Caller must be in sync with connection:
820 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700821 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700822 switch want {
823 default:
824 c.sendAlert(alertInternalError)
825 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
826 case recordTypeHandshake, recordTypeChangeCipherSpec:
827 if c.handshakeComplete {
828 c.sendAlert(alertInternalError)
829 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
830 }
831 case recordTypeApplicationData:
David Benjamine58c4f52014-08-24 03:47:07 -0400832 if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart {
Adam Langley95c29f32014-06-20 12:00:00 -0700833 c.sendAlert(alertInternalError)
834 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
835 }
David Benjamin30789da2015-08-29 22:56:45 -0400836 case recordTypeAlert:
837 // Looking for a close_notify. Note: unlike a real
838 // implementation, this is not tolerant of additional records.
839 // See the documentation for ExpectCloseNotify.
Adam Langley95c29f32014-06-20 12:00:00 -0700840 }
841
842Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400843 typ, b, err := c.doReadRecord(want)
844 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700845 return err
846 }
Adam Langley95c29f32014-06-20 12:00:00 -0700847 data := b.data[b.off:]
848 if len(data) > maxPlaintext {
849 err := c.sendAlert(alertRecordOverflow)
850 c.in.freeBlock(b)
851 return c.in.setErrorLocked(err)
852 }
853
854 switch typ {
855 default:
856 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
857
858 case recordTypeAlert:
859 if len(data) != 2 {
860 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
861 break
862 }
863 if alert(data[1]) == alertCloseNotify {
864 c.in.setErrorLocked(io.EOF)
865 break
866 }
867 switch data[0] {
868 case alertLevelWarning:
869 // drop on the floor
870 c.in.freeBlock(b)
871 goto Again
872 case alertLevelError:
873 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
874 default:
875 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
876 }
877
878 case recordTypeChangeCipherSpec:
879 if typ != want || len(data) != 1 || data[0] != 1 {
880 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
881 break
882 }
Adam Langley80842bd2014-06-20 12:00:00 -0700883 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700884 if err != nil {
885 c.in.setErrorLocked(c.sendAlert(err.(alert)))
886 }
887
888 case recordTypeApplicationData:
889 if typ != want {
890 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
891 break
892 }
893 c.input = b
894 b = nil
895
896 case recordTypeHandshake:
David Benjamind5a4ecb2016-07-18 01:17:13 +0200897 // Allow handshake data while reading application data to
898 // trigger post-handshake messages.
Adam Langley95c29f32014-06-20 12:00:00 -0700899 // TODO(rsc): Should at least pick off connection close.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200900 if typ != want && want != recordTypeApplicationData {
901 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
Adam Langley95c29f32014-06-20 12:00:00 -0700902 }
903 c.hand.Write(data)
904 }
905
906 if b != nil {
907 c.in.freeBlock(b)
908 }
909 return c.in.err
910}
911
912// sendAlert sends a TLS alert message.
913// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400914func (c *Conn) sendAlertLocked(level byte, err alert) error {
915 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700916 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400917 if c.config.Bugs.FragmentAlert {
918 c.writeRecord(recordTypeAlert, c.tmp[0:1])
919 c.writeRecord(recordTypeAlert, c.tmp[1:2])
David Benjamin0d3a8c62016-03-11 22:25:18 -0500920 } else if c.config.Bugs.DoubleAlert {
921 copy(c.tmp[2:4], c.tmp[0:2])
922 c.writeRecord(recordTypeAlert, c.tmp[0:4])
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400923 } else {
924 c.writeRecord(recordTypeAlert, c.tmp[0:2])
925 }
David Benjamin24f346d2015-06-06 03:28:08 -0400926 // Error alerts are fatal to the connection.
927 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700928 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
929 }
930 return nil
931}
932
933// sendAlert sends a TLS alert message.
934// L < c.out.Mutex.
935func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400936 level := byte(alertLevelError)
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500937 if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertficate {
David Benjamin24f346d2015-06-06 03:28:08 -0400938 level = alertLevelWarning
939 }
940 return c.SendAlert(level, err)
941}
942
943func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700944 c.out.Lock()
945 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -0400946 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -0700947}
948
David Benjamind86c7672014-08-02 04:07:12 -0400949// writeV2Record writes a record for a V2ClientHello.
950func (c *Conn) writeV2Record(data []byte) (n int, err error) {
951 record := make([]byte, 2+len(data))
952 record[0] = uint8(len(data)>>8) | 0x80
953 record[1] = uint8(len(data))
954 copy(record[2:], data)
955 return c.conn.Write(record)
956}
957
Adam Langley95c29f32014-06-20 12:00:00 -0700958// writeRecord writes a TLS record with the given type and payload
959// to the connection and updates the record layer state.
960// c.out.Mutex <= L.
961func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin639846e2016-09-09 11:41:18 -0400962 if msgType := c.config.Bugs.SendWrongMessageType; msgType != 0 {
963 if typ == recordTypeHandshake && data[0] == msgType {
David Benjamin0b8d5da2016-07-15 00:39:56 -0400964 newData := make([]byte, len(data))
965 copy(newData, data)
966 newData[0] += 42
967 data = newData
968 }
969 }
970
David Benjamin639846e2016-09-09 11:41:18 -0400971 if msgType := c.config.Bugs.SendTrailingMessageData; msgType != 0 {
972 if typ == recordTypeHandshake && data[0] == msgType {
973 newData := make([]byte, len(data))
974 copy(newData, data)
975
976 // Add a 0 to the body.
977 newData = append(newData, 0)
978 // Fix the header.
979 newLen := len(newData) - 4
980 newData[1] = byte(newLen >> 16)
981 newData[2] = byte(newLen >> 8)
982 newData[3] = byte(newLen)
983
984 data = newData
985 }
986 }
987
David Benjamin83c0bc92014-08-04 01:23:53 -0400988 if c.isDTLS {
989 return c.dtlsWriteRecord(typ, data)
990 }
991
David Benjamin71dd6662016-07-08 14:10:48 -0700992 if typ == recordTypeHandshake {
993 if c.config.Bugs.SendHelloRequestBeforeEveryHandshakeMessage {
994 newData := make([]byte, 0, 4+len(data))
995 newData = append(newData, typeHelloRequest, 0, 0, 0)
996 newData = append(newData, data...)
997 data = newData
998 }
999
1000 if c.config.Bugs.PackHandshakeFlight {
1001 c.pendingFlight.Write(data)
1002 return len(data), nil
1003 }
David Benjamin582ba042016-07-07 12:33:25 -07001004 }
1005
1006 return c.doWriteRecord(typ, data)
1007}
1008
1009func (c *Conn) doWriteRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin83c0bc92014-08-04 01:23:53 -04001010 recordHeaderLen := tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -07001011 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -04001012 first := true
1013 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -04001014 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -07001015 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -04001016 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -07001017 m = maxPlaintext
1018 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001019 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
1020 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -04001021 // By default, do not fragment the client_version or
1022 // server_version, which are located in the first 6
1023 // bytes.
1024 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
1025 m = 6
1026 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001027 }
Adam Langley95c29f32014-06-20 12:00:00 -07001028 explicitIVLen := 0
1029 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -04001030 first = false
Adam Langley95c29f32014-06-20 12:00:00 -07001031
1032 var cbc cbcMode
1033 if c.out.version >= VersionTLS11 {
1034 var ok bool
1035 if cbc, ok = c.out.cipher.(cbcMode); ok {
1036 explicitIVLen = cbc.BlockSize()
1037 }
1038 }
1039 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -04001040 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -07001041 explicitIVLen = 8
1042 // The AES-GCM construction in TLS has an
1043 // explicit nonce so that the nonce can be
1044 // random. However, the nonce is only 8 bytes
1045 // which is too small for a secure, random
1046 // nonce. Therefore we use the sequence number
1047 // as the nonce.
1048 explicitIVIsSeq = true
1049 }
1050 }
1051 b.resize(recordHeaderLen + explicitIVLen + m)
1052 b.data[0] = byte(typ)
Nick Harper1fd39d82016-06-14 18:14:35 -07001053 if c.vers >= VersionTLS13 && c.out.cipher != nil {
Nick Harper1fd39d82016-06-14 18:14:35 -07001054 b.data[0] = byte(recordTypeApplicationData)
David Benjaminc9ae27c2016-06-24 22:56:37 -04001055 if outerType := c.config.Bugs.OuterRecordType; outerType != 0 {
1056 b.data[0] = byte(outerType)
1057 }
Nick Harper1fd39d82016-06-14 18:14:35 -07001058 }
Adam Langley95c29f32014-06-20 12:00:00 -07001059 vers := c.vers
Nick Harper1fd39d82016-06-14 18:14:35 -07001060 if vers == 0 || vers >= VersionTLS13 {
Adam Langley95c29f32014-06-20 12:00:00 -07001061 // Some TLS servers fail if the record version is
1062 // greater than TLS 1.0 for the initial ClientHello.
Nick Harper1fd39d82016-06-14 18:14:35 -07001063 //
1064 // TLS 1.3 fixes the version number in the record
1065 // layer to {3, 1}.
Adam Langley95c29f32014-06-20 12:00:00 -07001066 vers = VersionTLS10
1067 }
David Benjamine6f22212016-11-08 14:28:24 -05001068 if c.config.Bugs.SendRecordVersion != 0 {
1069 vers = c.config.Bugs.SendRecordVersion
1070 }
1071 if c.vers == 0 && c.config.Bugs.SendInitialRecordVersion != 0 {
1072 vers = c.config.Bugs.SendInitialRecordVersion
1073 }
Adam Langley95c29f32014-06-20 12:00:00 -07001074 b.data[1] = byte(vers >> 8)
1075 b.data[2] = byte(vers)
1076 b.data[3] = byte(m >> 8)
1077 b.data[4] = byte(m)
1078 if explicitIVLen > 0 {
1079 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
1080 if explicitIVIsSeq {
1081 copy(explicitIV, c.out.seq[:])
1082 } else {
1083 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
1084 break
1085 }
1086 }
1087 }
1088 copy(b.data[recordHeaderLen+explicitIVLen:], data)
Nick Harper1fd39d82016-06-14 18:14:35 -07001089 c.out.encrypt(b, explicitIVLen, typ)
Adam Langley95c29f32014-06-20 12:00:00 -07001090 _, err = c.conn.Write(b.data)
1091 if err != nil {
1092 break
1093 }
1094 n += m
1095 data = data[m:]
1096 }
1097 c.out.freeBlock(b)
1098
1099 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -07001100 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -07001101 if err != nil {
1102 // Cannot call sendAlert directly,
1103 // because we already hold c.out.Mutex.
1104 c.tmp[0] = alertLevelError
1105 c.tmp[1] = byte(err.(alert))
1106 c.writeRecord(recordTypeAlert, c.tmp[0:2])
1107 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
1108 }
1109 }
1110 return
1111}
1112
David Benjamin582ba042016-07-07 12:33:25 -07001113func (c *Conn) flushHandshake() error {
1114 if c.isDTLS {
1115 return c.dtlsFlushHandshake()
1116 }
1117
1118 for c.pendingFlight.Len() > 0 {
1119 var buf [maxPlaintext]byte
1120 n, _ := c.pendingFlight.Read(buf[:])
1121 if _, err := c.doWriteRecord(recordTypeHandshake, buf[:n]); err != nil {
1122 return err
1123 }
1124 }
1125
1126 c.pendingFlight.Reset()
1127 return nil
1128}
1129
David Benjamin83c0bc92014-08-04 01:23:53 -04001130func (c *Conn) doReadHandshake() ([]byte, error) {
1131 if c.isDTLS {
1132 return c.dtlsDoReadHandshake()
1133 }
1134
Adam Langley95c29f32014-06-20 12:00:00 -07001135 for c.hand.Len() < 4 {
1136 if err := c.in.err; err != nil {
1137 return nil, err
1138 }
1139 if err := c.readRecord(recordTypeHandshake); err != nil {
1140 return nil, err
1141 }
1142 }
1143
1144 data := c.hand.Bytes()
1145 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1146 if n > maxHandshake {
1147 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
1148 }
1149 for c.hand.Len() < 4+n {
1150 if err := c.in.err; err != nil {
1151 return nil, err
1152 }
1153 if err := c.readRecord(recordTypeHandshake); err != nil {
1154 return nil, err
1155 }
1156 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001157 return c.hand.Next(4 + n), nil
1158}
1159
1160// readHandshake reads the next handshake message from
1161// the record layer.
1162// c.in.Mutex < L; c.out.Mutex < L.
1163func (c *Conn) readHandshake() (interface{}, error) {
1164 data, err := c.doReadHandshake()
1165 if err != nil {
1166 return nil, err
1167 }
1168
Adam Langley95c29f32014-06-20 12:00:00 -07001169 var m handshakeMessage
1170 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001171 case typeHelloRequest:
1172 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001173 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001174 m = &clientHelloMsg{
1175 isDTLS: c.isDTLS,
1176 }
Adam Langley95c29f32014-06-20 12:00:00 -07001177 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001178 m = &serverHelloMsg{
1179 isDTLS: c.isDTLS,
1180 }
Nick Harperdcfbc672016-07-16 17:47:31 +02001181 case typeHelloRetryRequest:
1182 m = new(helloRetryRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001183 case typeNewSessionTicket:
David Benjamin58104882016-07-18 01:25:41 +02001184 m = &newSessionTicketMsg{
1185 version: c.vers,
1186 }
Nick Harperb41d2e42016-07-01 17:50:32 -04001187 case typeEncryptedExtensions:
1188 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001189 case typeCertificate:
Nick Harperb41d2e42016-07-01 17:50:32 -04001190 m = &certificateMsg{
David Benjamin8d315d72016-07-18 01:03:18 +02001191 hasRequestContext: c.vers >= VersionTLS13,
Nick Harperb41d2e42016-07-01 17:50:32 -04001192 }
Adam Langley95c29f32014-06-20 12:00:00 -07001193 case typeCertificateRequest:
1194 m = &certificateRequestMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001195 hasSignatureAlgorithm: c.vers >= VersionTLS12,
David Benjamin8d315d72016-07-18 01:03:18 +02001196 hasRequestContext: c.vers >= VersionTLS13,
Adam Langley95c29f32014-06-20 12:00:00 -07001197 }
1198 case typeCertificateStatus:
1199 m = new(certificateStatusMsg)
1200 case typeServerKeyExchange:
1201 m = new(serverKeyExchangeMsg)
1202 case typeServerHelloDone:
1203 m = new(serverHelloDoneMsg)
1204 case typeClientKeyExchange:
1205 m = new(clientKeyExchangeMsg)
1206 case typeCertificateVerify:
1207 m = &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001208 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001209 }
1210 case typeNextProtocol:
1211 m = new(nextProtoMsg)
1212 case typeFinished:
1213 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001214 case typeHelloVerifyRequest:
1215 m = new(helloVerifyRequestMsg)
David Benjamin24599a82016-06-30 18:56:53 -04001216 case typeChannelID:
1217 m = new(channelIDMsg)
David Benjamin21c00282016-07-18 21:56:23 +02001218 case typeKeyUpdate:
1219 m = new(keyUpdateMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001220 default:
1221 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1222 }
1223
1224 // The handshake message unmarshallers
1225 // expect to be able to keep references to data,
1226 // so pass in a fresh copy that won't be overwritten.
1227 data = append([]byte(nil), data...)
1228
1229 if !m.unmarshal(data) {
1230 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1231 }
1232 return m, nil
1233}
1234
David Benjamin83f90402015-01-27 01:09:43 -05001235// skipPacket processes all the DTLS records in packet. It updates
1236// sequence number expectations but otherwise ignores them.
1237func (c *Conn) skipPacket(packet []byte) error {
1238 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001239 if len(packet) < 13 {
1240 return errors.New("tls: bad packet")
1241 }
David Benjamin83f90402015-01-27 01:09:43 -05001242 // Dropped packets are completely ignored save to update
1243 // expected sequence numbers for this and the next epoch. (We
1244 // don't assert on the contents of the packets both for
1245 // simplicity and because a previous test with one shorter
1246 // timeout schedule would have done so.)
1247 epoch := packet[3:5]
1248 seq := packet[5:11]
1249 length := uint16(packet[11])<<8 | uint16(packet[12])
1250 if bytes.Equal(c.in.seq[:2], epoch) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001251 if bytes.Compare(seq, c.in.seq[2:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001252 return errors.New("tls: sequence mismatch")
1253 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001254 copy(c.in.seq[2:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001255 c.in.incSeq(false)
1256 } else {
David Benjamin13e81fc2015-11-02 17:16:13 -05001257 if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001258 return errors.New("tls: sequence mismatch")
1259 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001260 copy(c.in.nextSeq[:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001261 c.in.incNextSeq()
1262 }
David Benjamin6ca93552015-08-28 16:16:25 -04001263 if len(packet) < 13+int(length) {
1264 return errors.New("tls: bad packet")
1265 }
David Benjamin83f90402015-01-27 01:09:43 -05001266 packet = packet[13+length:]
1267 }
1268 return nil
1269}
1270
1271// simulatePacketLoss simulates the loss of a handshake leg from the
1272// peer based on the schedule in c.config.Bugs. If resendFunc is
1273// non-nil, it is called after each simulated timeout to retransmit
1274// handshake messages from the local end. This is used in cases where
1275// the peer retransmits on a stale Finished rather than a timeout.
1276func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1277 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1278 return nil
1279 }
1280 if !c.isDTLS {
1281 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1282 }
1283 if c.config.Bugs.PacketAdaptor == nil {
1284 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1285 }
1286 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1287 // Simulate a timeout.
1288 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1289 if err != nil {
1290 return err
1291 }
1292 for _, packet := range packets {
1293 if err := c.skipPacket(packet); err != nil {
1294 return err
1295 }
1296 }
1297 if resendFunc != nil {
1298 resendFunc()
1299 }
1300 }
1301 return nil
1302}
1303
David Benjamin47921102016-07-28 11:29:18 -04001304func (c *Conn) SendHalfHelloRequest() error {
1305 if err := c.Handshake(); err != nil {
1306 return err
1307 }
1308
1309 c.out.Lock()
1310 defer c.out.Unlock()
1311
1312 if _, err := c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0}); err != nil {
1313 return err
1314 }
1315 return c.flushHandshake()
1316}
1317
Adam Langley95c29f32014-06-20 12:00:00 -07001318// Write writes data to the connection.
1319func (c *Conn) Write(b []byte) (int, error) {
1320 if err := c.Handshake(); err != nil {
1321 return 0, err
1322 }
1323
1324 c.out.Lock()
1325 defer c.out.Unlock()
1326
David Benjamin12d2c482016-07-24 10:56:51 -04001327 // Flush any pending handshake data. PackHelloRequestWithFinished may
1328 // have been set and the handshake not followed by Renegotiate.
1329 c.flushHandshake()
1330
Adam Langley95c29f32014-06-20 12:00:00 -07001331 if err := c.out.err; err != nil {
1332 return 0, err
1333 }
1334
1335 if !c.handshakeComplete {
1336 return 0, alertInternalError
1337 }
1338
Steven Valdezc4aa7272016-10-03 12:25:56 -04001339 if c.keyUpdateRequested {
1340 if err := c.sendKeyUpdateLocked(keyUpdateNotRequested); err != nil {
David Benjamin21c00282016-07-18 21:56:23 +02001341 return 0, err
1342 }
Steven Valdezc4aa7272016-10-03 12:25:56 -04001343 c.keyUpdateRequested = false
David Benjamin21c00282016-07-18 21:56:23 +02001344 }
1345
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001346 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001347 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001348 }
1349
Adam Langley27a0d082015-11-03 13:34:10 -08001350 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1351 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
David Benjamin582ba042016-07-07 12:33:25 -07001352 c.flushHandshake()
Adam Langley27a0d082015-11-03 13:34:10 -08001353 }
1354
Adam Langley95c29f32014-06-20 12:00:00 -07001355 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1356 // attack when using block mode ciphers due to predictable IVs.
1357 // This can be prevented by splitting each Application Data
1358 // record into two records, effectively randomizing the IV.
1359 //
1360 // http://www.openssl.org/~bodo/tls-cbc.txt
1361 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1362 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1363
1364 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001365 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001366 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1367 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1368 if err != nil {
1369 return n, c.out.setErrorLocked(err)
1370 }
1371 m, b = 1, b[1:]
1372 }
1373 }
1374
1375 n, err := c.writeRecord(recordTypeApplicationData, b)
1376 return n + m, c.out.setErrorLocked(err)
1377}
1378
David Benjamind5a4ecb2016-07-18 01:17:13 +02001379func (c *Conn) handlePostHandshakeMessage() error {
Adam Langley2ae77d22014-10-28 17:29:33 -07001380 msg, err := c.readHandshake()
1381 if err != nil {
1382 return err
1383 }
David Benjamind5a4ecb2016-07-18 01:17:13 +02001384
1385 if c.vers < VersionTLS13 {
1386 if !c.isClient {
1387 c.sendAlert(alertUnexpectedMessage)
1388 return errors.New("tls: unexpected post-handshake message")
1389 }
1390
1391 _, ok := msg.(*helloRequestMsg)
1392 if !ok {
1393 c.sendAlert(alertUnexpectedMessage)
1394 return alertUnexpectedMessage
1395 }
1396
1397 c.handshakeComplete = false
1398 return c.Handshake()
Adam Langley2ae77d22014-10-28 17:29:33 -07001399 }
1400
David Benjamind5a4ecb2016-07-18 01:17:13 +02001401 if c.isClient {
1402 if newSessionTicket, ok := msg.(*newSessionTicketMsg); ok {
David Benjamin1a5e8ec2016-10-07 15:19:18 -04001403 if c.config.Bugs.ExpectGREASE && !newSessionTicket.hasGREASEExtension {
1404 return errors.New("tls: no GREASE ticket extension found")
1405 }
1406
Steven Valdeza833c352016-11-01 13:39:36 -04001407 if c.config.Bugs.ExpectNoNewSessionTicket {
1408 return errors.New("tls: received unexpected NewSessionTicket")
1409 }
1410
David Benjamind5a4ecb2016-07-18 01:17:13 +02001411 if c.config.ClientSessionCache == nil || newSessionTicket.ticketLifetime == 0 {
1412 return nil
1413 }
1414
1415 session := &ClientSessionState{
1416 sessionTicket: newSessionTicket.ticket,
1417 vers: c.vers,
1418 cipherSuite: c.cipherSuite.id,
1419 masterSecret: c.resumptionSecret,
1420 serverCertificates: c.peerCertificates,
1421 sctList: c.sctList,
1422 ocspResponse: c.ocspResponse,
Nick Harper0b3625b2016-07-25 16:16:28 -07001423 ticketCreationTime: c.config.time(),
1424 ticketExpiration: c.config.time().Add(time.Duration(newSessionTicket.ticketLifetime) * time.Second),
Steven Valdeza833c352016-11-01 13:39:36 -04001425 ticketAgeAdd: newSessionTicket.ticketAgeAdd,
David Benjamind5a4ecb2016-07-18 01:17:13 +02001426 }
1427
1428 cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
1429 c.config.ClientSessionCache.Put(cacheKey, session)
1430 return nil
1431 }
1432 }
1433
Steven Valdezc4aa7272016-10-03 12:25:56 -04001434 if keyUpdate, ok := msg.(*keyUpdateMsg); ok {
Steven Valdez1dc53d22016-07-26 12:27:38 -04001435 c.in.doKeyUpdate(c, false)
Steven Valdezc4aa7272016-10-03 12:25:56 -04001436 if keyUpdate.keyUpdateRequest == keyUpdateRequested {
1437 c.keyUpdateRequested = true
1438 }
David Benjamin21c00282016-07-18 21:56:23 +02001439 return nil
1440 }
1441
David Benjamind5a4ecb2016-07-18 01:17:13 +02001442 // TODO(davidben): Add support for KeyUpdate.
1443 c.sendAlert(alertUnexpectedMessage)
1444 return alertUnexpectedMessage
Adam Langley2ae77d22014-10-28 17:29:33 -07001445}
1446
Adam Langleycf2d4f42014-10-28 19:06:14 -07001447func (c *Conn) Renegotiate() error {
1448 if !c.isClient {
David Benjaminef5dfd22015-12-06 13:17:07 -05001449 helloReq := new(helloRequestMsg).marshal()
1450 if c.config.Bugs.BadHelloRequest != nil {
1451 helloReq = c.config.Bugs.BadHelloRequest
1452 }
1453 c.writeRecord(recordTypeHandshake, helloReq)
David Benjamin582ba042016-07-07 12:33:25 -07001454 c.flushHandshake()
Adam Langleycf2d4f42014-10-28 19:06:14 -07001455 }
1456
1457 c.handshakeComplete = false
1458 return c.Handshake()
1459}
1460
Adam Langley95c29f32014-06-20 12:00:00 -07001461// Read can be made to time out and return a net.Error with Timeout() == true
1462// after a fixed time limit; see SetDeadline and SetReadDeadline.
1463func (c *Conn) Read(b []byte) (n int, err error) {
1464 if err = c.Handshake(); err != nil {
1465 return
1466 }
1467
1468 c.in.Lock()
1469 defer c.in.Unlock()
1470
1471 // Some OpenSSL servers send empty records in order to randomize the
1472 // CBC IV. So this loop ignores a limited number of empty records.
1473 const maxConsecutiveEmptyRecords = 100
1474 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1475 for c.input == nil && c.in.err == nil {
1476 if err := c.readRecord(recordTypeApplicationData); err != nil {
1477 // Soft error, like EAGAIN
1478 return 0, err
1479 }
David Benjamind9b091b2015-01-27 01:10:54 -05001480 if c.hand.Len() > 0 {
David Benjamind5a4ecb2016-07-18 01:17:13 +02001481 // We received handshake bytes, indicating a
1482 // post-handshake message.
1483 if err := c.handlePostHandshakeMessage(); err != nil {
Adam Langley2ae77d22014-10-28 17:29:33 -07001484 return 0, err
1485 }
1486 continue
1487 }
Adam Langley95c29f32014-06-20 12:00:00 -07001488 }
1489 if err := c.in.err; err != nil {
1490 return 0, err
1491 }
1492
1493 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001494 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001495 c.in.freeBlock(c.input)
1496 c.input = nil
1497 }
1498
1499 // If a close-notify alert is waiting, read it so that
1500 // we can return (n, EOF) instead of (n, nil), to signal
1501 // to the HTTP response reading goroutine that the
1502 // connection is now closed. This eliminates a race
1503 // where the HTTP response reading goroutine would
1504 // otherwise not observe the EOF until its next read,
1505 // by which time a client goroutine might have already
1506 // tried to reuse the HTTP connection for a new
1507 // request.
1508 // See https://codereview.appspot.com/76400046
1509 // and http://golang.org/issue/3514
1510 if ri := c.rawInput; ri != nil &&
1511 n != 0 && err == nil &&
1512 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1513 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1514 err = recErr // will be io.EOF on closeNotify
1515 }
1516 }
1517
1518 if n != 0 || err != nil {
1519 return n, err
1520 }
1521 }
1522
1523 return 0, io.ErrNoProgress
1524}
1525
1526// Close closes the connection.
1527func (c *Conn) Close() error {
1528 var alertErr error
1529
1530 c.handshakeMutex.Lock()
1531 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001532 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
David Benjaminfa214e42016-05-10 17:03:10 -04001533 alert := alertCloseNotify
1534 if c.config.Bugs.SendAlertOnShutdown != 0 {
1535 alert = c.config.Bugs.SendAlertOnShutdown
1536 }
1537 alertErr = c.sendAlert(alert)
David Benjamin4d559612016-05-18 14:31:51 -04001538 // Clear local alerts when sending alerts so we continue to wait
1539 // for the peer rather than closing the socket early.
1540 if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1541 alertErr = nil
1542 }
Adam Langley95c29f32014-06-20 12:00:00 -07001543 }
1544
David Benjamin30789da2015-08-29 22:56:45 -04001545 // Consume a close_notify from the peer if one hasn't been received
1546 // already. This avoids the peer from failing |SSL_shutdown| due to a
1547 // write failing.
1548 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1549 for c.in.error() == nil {
1550 c.readRecord(recordTypeAlert)
1551 }
1552 if c.in.error() != io.EOF {
1553 alertErr = c.in.error()
1554 }
1555 }
1556
Adam Langley95c29f32014-06-20 12:00:00 -07001557 if err := c.conn.Close(); err != nil {
1558 return err
1559 }
1560 return alertErr
1561}
1562
1563// Handshake runs the client or server handshake
1564// protocol if it has not yet been run.
1565// Most uses of this package need not call Handshake
1566// explicitly: the first Read or Write will call it automatically.
1567func (c *Conn) Handshake() error {
1568 c.handshakeMutex.Lock()
1569 defer c.handshakeMutex.Unlock()
1570 if err := c.handshakeErr; err != nil {
1571 return err
1572 }
1573 if c.handshakeComplete {
1574 return nil
1575 }
1576
David Benjamin9a41d1b2015-05-16 01:30:09 -04001577 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1578 c.conn.Write([]byte{
1579 byte(recordTypeAlert), // type
1580 0xfe, 0xff, // version
1581 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1582 0x0, 0x2, // length
1583 })
1584 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1585 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001586 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1587 c.writeRecord(recordTypeApplicationData, data)
1588 }
Adam Langley95c29f32014-06-20 12:00:00 -07001589 if c.isClient {
1590 c.handshakeErr = c.clientHandshake()
1591 } else {
1592 c.handshakeErr = c.serverHandshake()
1593 }
David Benjaminddb9f152015-02-03 15:44:39 -05001594 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1595 c.writeRecord(recordType(42), []byte("invalid record"))
1596 }
Adam Langley95c29f32014-06-20 12:00:00 -07001597 return c.handshakeErr
1598}
1599
1600// ConnectionState returns basic TLS details about the connection.
1601func (c *Conn) ConnectionState() ConnectionState {
1602 c.handshakeMutex.Lock()
1603 defer c.handshakeMutex.Unlock()
1604
1605 var state ConnectionState
1606 state.HandshakeComplete = c.handshakeComplete
1607 if c.handshakeComplete {
1608 state.Version = c.vers
1609 state.NegotiatedProtocol = c.clientProtocol
1610 state.DidResume = c.didResume
1611 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001612 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001613 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001614 state.PeerCertificates = c.peerCertificates
1615 state.VerifiedChains = c.verifiedChains
1616 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001617 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001618 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001619 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001620 state.SCTList = c.sctList
Nick Harper60edffd2016-06-21 15:19:24 -07001621 state.PeerSignatureAlgorithm = c.peerSignatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -04001622 state.CurveID = c.curveID
Adam Langley95c29f32014-06-20 12:00:00 -07001623 }
1624
1625 return state
1626}
1627
1628// OCSPResponse returns the stapled OCSP response from the TLS server, if
1629// any. (Only valid for client connections.)
1630func (c *Conn) OCSPResponse() []byte {
1631 c.handshakeMutex.Lock()
1632 defer c.handshakeMutex.Unlock()
1633
1634 return c.ocspResponse
1635}
1636
1637// VerifyHostname checks that the peer certificate chain is valid for
1638// connecting to host. If so, it returns nil; if not, it returns an error
1639// describing the problem.
1640func (c *Conn) VerifyHostname(host string) error {
1641 c.handshakeMutex.Lock()
1642 defer c.handshakeMutex.Unlock()
1643 if !c.isClient {
1644 return errors.New("tls: VerifyHostname called on TLS server connection")
1645 }
1646 if !c.handshakeComplete {
1647 return errors.New("tls: handshake has not yet been performed")
1648 }
1649 return c.peerCertificates[0].VerifyHostname(host)
1650}
David Benjaminc565ebb2015-04-03 04:06:36 -04001651
1652// ExportKeyingMaterial exports keying material from the current connection
1653// state, as per RFC 5705.
1654func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1655 c.handshakeMutex.Lock()
1656 defer c.handshakeMutex.Unlock()
1657 if !c.handshakeComplete {
1658 return nil, errors.New("tls: handshake has not yet been performed")
1659 }
1660
David Benjamin8d315d72016-07-18 01:03:18 +02001661 if c.vers >= VersionTLS13 {
David Benjamin97a0a082016-07-13 17:57:35 -04001662 // TODO(davidben): What should we do with useContext? See
1663 // https://github.com/tlswg/tls13-spec/issues/546
1664 return hkdfExpandLabel(c.cipherSuite.hash(), c.exporterSecret, label, context, length), nil
1665 }
1666
David Benjaminc565ebb2015-04-03 04:06:36 -04001667 seedLen := len(c.clientRandom) + len(c.serverRandom)
1668 if useContext {
1669 seedLen += 2 + len(context)
1670 }
1671 seed := make([]byte, 0, seedLen)
1672 seed = append(seed, c.clientRandom[:]...)
1673 seed = append(seed, c.serverRandom[:]...)
1674 if useContext {
1675 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1676 seed = append(seed, context...)
1677 }
1678 result := make([]byte, length)
David Benjamin97a0a082016-07-13 17:57:35 -04001679 prfForVersion(c.vers, c.cipherSuite)(result, c.exporterSecret, label, seed)
David Benjaminc565ebb2015-04-03 04:06:36 -04001680 return result, nil
1681}
David Benjamin3e052de2015-11-25 20:10:31 -05001682
1683// noRenegotiationInfo returns true if the renegotiation info extension
1684// should be supported in the current handshake.
1685func (c *Conn) noRenegotiationInfo() bool {
1686 if c.config.Bugs.NoRenegotiationInfo {
1687 return true
1688 }
1689 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1690 return true
1691 }
1692 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1693 return true
1694 }
1695 return false
1696}
David Benjamin58104882016-07-18 01:25:41 +02001697
1698func (c *Conn) SendNewSessionTicket() error {
1699 if c.isClient || c.vers < VersionTLS13 {
1700 return errors.New("tls: cannot send post-handshake NewSessionTicket")
1701 }
1702
1703 var peerCertificatesRaw [][]byte
1704 for _, cert := range c.peerCertificates {
1705 peerCertificatesRaw = append(peerCertificatesRaw, cert.Raw)
1706 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001707
Steven Valdeza833c352016-11-01 13:39:36 -04001708 addBuffer := make([]byte, 4)
1709 _, err := io.ReadFull(c.config.rand(), addBuffer)
1710 if err != nil {
1711 c.sendAlert(alertInternalError)
1712 return errors.New("tls: short read from Rand: " + err.Error())
1713 }
1714 ticketAgeAdd := uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0])
1715
David Benjamin58104882016-07-18 01:25:41 +02001716 // TODO(davidben): Allow configuring these values.
1717 m := &newSessionTicketMsg{
David Benjamin1286bee2016-10-07 15:25:06 -04001718 version: c.vers,
1719 ticketLifetime: uint32(24 * time.Hour / time.Second),
David Benjamin1286bee2016-10-07 15:25:06 -04001720 customExtension: c.config.Bugs.CustomTicketExtension,
Steven Valdeza833c352016-11-01 13:39:36 -04001721 ticketAgeAdd: ticketAgeAdd,
David Benjamin58104882016-07-18 01:25:41 +02001722 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001723
1724 state := sessionState{
1725 vers: c.vers,
1726 cipherSuite: c.cipherSuite.id,
1727 masterSecret: c.resumptionSecret,
1728 certificates: peerCertificatesRaw,
1729 ticketCreationTime: c.config.time(),
1730 ticketExpiration: c.config.time().Add(time.Duration(m.ticketLifetime) * time.Second),
Steven Valdeza833c352016-11-01 13:39:36 -04001731 ticketAgeAdd: uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0]),
Nick Harper0b3625b2016-07-25 16:16:28 -07001732 }
1733
David Benjamin58104882016-07-18 01:25:41 +02001734 if !c.config.Bugs.SendEmptySessionTicket {
1735 var err error
1736 m.ticket, err = c.encryptTicket(&state)
1737 if err != nil {
1738 return err
1739 }
1740 }
1741
1742 c.out.Lock()
1743 defer c.out.Unlock()
Steven Valdeza833c352016-11-01 13:39:36 -04001744 _, err = c.writeRecord(recordTypeHandshake, m.marshal())
David Benjamin58104882016-07-18 01:25:41 +02001745 return err
1746}
David Benjamin21c00282016-07-18 21:56:23 +02001747
Steven Valdezc4aa7272016-10-03 12:25:56 -04001748func (c *Conn) SendKeyUpdate(keyUpdateRequest byte) error {
David Benjamin21c00282016-07-18 21:56:23 +02001749 c.out.Lock()
1750 defer c.out.Unlock()
Steven Valdezc4aa7272016-10-03 12:25:56 -04001751 return c.sendKeyUpdateLocked(keyUpdateRequest)
David Benjamin21c00282016-07-18 21:56:23 +02001752}
1753
Steven Valdezc4aa7272016-10-03 12:25:56 -04001754func (c *Conn) sendKeyUpdateLocked(keyUpdateRequest byte) error {
David Benjamin7f0965a2016-09-30 15:14:01 -04001755 if c.vers < VersionTLS13 {
1756 return errors.New("tls: attempted to send KeyUpdate before TLS 1.3")
1757 }
1758
Steven Valdezc4aa7272016-10-03 12:25:56 -04001759 m := keyUpdateMsg{
1760 keyUpdateRequest: keyUpdateRequest,
1761 }
David Benjamin21c00282016-07-18 21:56:23 +02001762 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
1763 return err
1764 }
1765 if err := c.flushHandshake(); err != nil {
1766 return err
1767 }
Steven Valdez1dc53d22016-07-26 12:27:38 -04001768 c.out.doKeyUpdate(c, true)
David Benjamin21c00282016-07-18 21:56:23 +02001769 return nil
1770}