blob: f5014d4417db976473cedd5f1eac630c265b165b [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.
211func (hc *halfConn) useTrafficSecret(version uint16, suite *cipherSuite, secret, phase []byte, side trafficDirection) {
Nick Harperb41d2e42016-07-01 17:50:32 -0400212 hc.version = version
David Benjamin21c00282016-07-18 21:56:23 +0200213 hc.cipher = deriveTrafficAEAD(version, suite, secret, phase, 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 }
226 hc.useTrafficSecret(hc.version, c.cipherSuite, updateTrafficSecret(c.cipherSuite.hash(), hc.trafficSecret), applicationPhase, 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 {
756 if c.haveVers {
757 if vers != c.vers && c.vers < VersionTLS13 {
758 c.sendAlert(alertProtocolVersion)
759 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers))
760 }
761 } else {
762 if expect := c.config.Bugs.ExpectInitialRecordVersion; expect != 0 && vers != expect {
763 c.sendAlert(alertProtocolVersion)
764 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
765 }
David Benjamin1e29a6b2014-12-10 02:27:24 -0500766 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400767 }
768 if n > maxCiphertext {
769 c.sendAlert(alertRecordOverflow)
770 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
771 }
772 if !c.haveVers {
773 // First message, be extra suspicious:
774 // this might not be a TLS client.
775 // Bail out before reading a full 'body', if possible.
776 // The current max version is 3.1.
777 // If the version is >= 16.0, it's probably not real.
778 // Similarly, a clientHello message encodes in
779 // well under a kilobyte. If the length is >= 12 kB,
780 // it's probably not real.
781 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
782 c.sendAlert(alertUnexpectedMessage)
783 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
784 }
785 }
786 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
787 if err == io.EOF {
788 err = io.ErrUnexpectedEOF
789 }
790 if e, ok := err.(net.Error); !ok || !e.Temporary() {
791 c.in.setErrorLocked(err)
792 }
793 return 0, nil, err
794 }
795
796 // Process message.
797 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
David Benjaminff26f092016-07-01 16:13:42 -0400798 ok, off, encTyp, alertValue := c.in.decrypt(b)
799 if !ok {
800 return 0, nil, c.in.setErrorLocked(c.sendAlert(alertValue))
801 }
802 b.off = off
803
Nick Harper1fd39d82016-06-14 18:14:35 -0700804 if c.vers >= VersionTLS13 && c.in.cipher != nil {
David Benjaminc9ae27c2016-06-24 22:56:37 -0400805 if typ != recordTypeApplicationData {
806 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: outer record type is not application data"))
807 }
Nick Harper1fd39d82016-06-14 18:14:35 -0700808 typ = encTyp
809 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400810 return typ, b, nil
811}
812
Adam Langley95c29f32014-06-20 12:00:00 -0700813// readRecord reads the next TLS record from the connection
814// and updates the record layer state.
815// c.in.Mutex <= L; c.input == nil.
816func (c *Conn) readRecord(want recordType) error {
817 // Caller must be in sync with connection:
818 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700819 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700820 switch want {
821 default:
822 c.sendAlert(alertInternalError)
823 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
824 case recordTypeHandshake, recordTypeChangeCipherSpec:
825 if c.handshakeComplete {
826 c.sendAlert(alertInternalError)
827 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
828 }
829 case recordTypeApplicationData:
David Benjamine58c4f52014-08-24 03:47:07 -0400830 if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart {
Adam Langley95c29f32014-06-20 12:00:00 -0700831 c.sendAlert(alertInternalError)
832 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
833 }
David Benjamin30789da2015-08-29 22:56:45 -0400834 case recordTypeAlert:
835 // Looking for a close_notify. Note: unlike a real
836 // implementation, this is not tolerant of additional records.
837 // See the documentation for ExpectCloseNotify.
Adam Langley95c29f32014-06-20 12:00:00 -0700838 }
839
840Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400841 typ, b, err := c.doReadRecord(want)
842 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700843 return err
844 }
Adam Langley95c29f32014-06-20 12:00:00 -0700845 data := b.data[b.off:]
846 if len(data) > maxPlaintext {
847 err := c.sendAlert(alertRecordOverflow)
848 c.in.freeBlock(b)
849 return c.in.setErrorLocked(err)
850 }
851
852 switch typ {
853 default:
854 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
855
856 case recordTypeAlert:
857 if len(data) != 2 {
858 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
859 break
860 }
861 if alert(data[1]) == alertCloseNotify {
862 c.in.setErrorLocked(io.EOF)
863 break
864 }
865 switch data[0] {
866 case alertLevelWarning:
867 // drop on the floor
868 c.in.freeBlock(b)
869 goto Again
870 case alertLevelError:
871 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
872 default:
873 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
874 }
875
876 case recordTypeChangeCipherSpec:
877 if typ != want || len(data) != 1 || data[0] != 1 {
878 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
879 break
880 }
Adam Langley80842bd2014-06-20 12:00:00 -0700881 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700882 if err != nil {
883 c.in.setErrorLocked(c.sendAlert(err.(alert)))
884 }
885
886 case recordTypeApplicationData:
887 if typ != want {
888 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
889 break
890 }
891 c.input = b
892 b = nil
893
894 case recordTypeHandshake:
David Benjamind5a4ecb2016-07-18 01:17:13 +0200895 // Allow handshake data while reading application data to
896 // trigger post-handshake messages.
Adam Langley95c29f32014-06-20 12:00:00 -0700897 // TODO(rsc): Should at least pick off connection close.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200898 if typ != want && want != recordTypeApplicationData {
899 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
Adam Langley95c29f32014-06-20 12:00:00 -0700900 }
901 c.hand.Write(data)
902 }
903
904 if b != nil {
905 c.in.freeBlock(b)
906 }
907 return c.in.err
908}
909
910// sendAlert sends a TLS alert message.
911// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400912func (c *Conn) sendAlertLocked(level byte, err alert) error {
913 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700914 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400915 if c.config.Bugs.FragmentAlert {
916 c.writeRecord(recordTypeAlert, c.tmp[0:1])
917 c.writeRecord(recordTypeAlert, c.tmp[1:2])
David Benjamin0d3a8c62016-03-11 22:25:18 -0500918 } else if c.config.Bugs.DoubleAlert {
919 copy(c.tmp[2:4], c.tmp[0:2])
920 c.writeRecord(recordTypeAlert, c.tmp[0:4])
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400921 } else {
922 c.writeRecord(recordTypeAlert, c.tmp[0:2])
923 }
David Benjamin24f346d2015-06-06 03:28:08 -0400924 // Error alerts are fatal to the connection.
925 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700926 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
927 }
928 return nil
929}
930
931// sendAlert sends a TLS alert message.
932// L < c.out.Mutex.
933func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400934 level := byte(alertLevelError)
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500935 if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertficate {
David Benjamin24f346d2015-06-06 03:28:08 -0400936 level = alertLevelWarning
937 }
938 return c.SendAlert(level, err)
939}
940
941func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700942 c.out.Lock()
943 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -0400944 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -0700945}
946
David Benjamind86c7672014-08-02 04:07:12 -0400947// writeV2Record writes a record for a V2ClientHello.
948func (c *Conn) writeV2Record(data []byte) (n int, err error) {
949 record := make([]byte, 2+len(data))
950 record[0] = uint8(len(data)>>8) | 0x80
951 record[1] = uint8(len(data))
952 copy(record[2:], data)
953 return c.conn.Write(record)
954}
955
Adam Langley95c29f32014-06-20 12:00:00 -0700956// writeRecord writes a TLS record with the given type and payload
957// to the connection and updates the record layer state.
958// c.out.Mutex <= L.
959func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin639846e2016-09-09 11:41:18 -0400960 if msgType := c.config.Bugs.SendWrongMessageType; msgType != 0 {
961 if typ == recordTypeHandshake && data[0] == msgType {
David Benjamin0b8d5da2016-07-15 00:39:56 -0400962 newData := make([]byte, len(data))
963 copy(newData, data)
964 newData[0] += 42
965 data = newData
966 }
967 }
968
David Benjamin639846e2016-09-09 11:41:18 -0400969 if msgType := c.config.Bugs.SendTrailingMessageData; msgType != 0 {
970 if typ == recordTypeHandshake && data[0] == msgType {
971 newData := make([]byte, len(data))
972 copy(newData, data)
973
974 // Add a 0 to the body.
975 newData = append(newData, 0)
976 // Fix the header.
977 newLen := len(newData) - 4
978 newData[1] = byte(newLen >> 16)
979 newData[2] = byte(newLen >> 8)
980 newData[3] = byte(newLen)
981
982 data = newData
983 }
984 }
985
David Benjamin83c0bc92014-08-04 01:23:53 -0400986 if c.isDTLS {
987 return c.dtlsWriteRecord(typ, data)
988 }
989
David Benjamin71dd6662016-07-08 14:10:48 -0700990 if typ == recordTypeHandshake {
991 if c.config.Bugs.SendHelloRequestBeforeEveryHandshakeMessage {
992 newData := make([]byte, 0, 4+len(data))
993 newData = append(newData, typeHelloRequest, 0, 0, 0)
994 newData = append(newData, data...)
995 data = newData
996 }
997
998 if c.config.Bugs.PackHandshakeFlight {
999 c.pendingFlight.Write(data)
1000 return len(data), nil
1001 }
David Benjamin582ba042016-07-07 12:33:25 -07001002 }
1003
1004 return c.doWriteRecord(typ, data)
1005}
1006
1007func (c *Conn) doWriteRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin83c0bc92014-08-04 01:23:53 -04001008 recordHeaderLen := tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -07001009 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -04001010 first := true
1011 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -04001012 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -07001013 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -04001014 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -07001015 m = maxPlaintext
1016 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001017 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
1018 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -04001019 // By default, do not fragment the client_version or
1020 // server_version, which are located in the first 6
1021 // bytes.
1022 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
1023 m = 6
1024 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001025 }
Adam Langley95c29f32014-06-20 12:00:00 -07001026 explicitIVLen := 0
1027 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -04001028 first = false
Adam Langley95c29f32014-06-20 12:00:00 -07001029
1030 var cbc cbcMode
1031 if c.out.version >= VersionTLS11 {
1032 var ok bool
1033 if cbc, ok = c.out.cipher.(cbcMode); ok {
1034 explicitIVLen = cbc.BlockSize()
1035 }
1036 }
1037 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -04001038 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -07001039 explicitIVLen = 8
1040 // The AES-GCM construction in TLS has an
1041 // explicit nonce so that the nonce can be
1042 // random. However, the nonce is only 8 bytes
1043 // which is too small for a secure, random
1044 // nonce. Therefore we use the sequence number
1045 // as the nonce.
1046 explicitIVIsSeq = true
1047 }
1048 }
1049 b.resize(recordHeaderLen + explicitIVLen + m)
1050 b.data[0] = byte(typ)
Nick Harper1fd39d82016-06-14 18:14:35 -07001051 if c.vers >= VersionTLS13 && c.out.cipher != nil {
Nick Harper1fd39d82016-06-14 18:14:35 -07001052 b.data[0] = byte(recordTypeApplicationData)
David Benjaminc9ae27c2016-06-24 22:56:37 -04001053 if outerType := c.config.Bugs.OuterRecordType; outerType != 0 {
1054 b.data[0] = byte(outerType)
1055 }
Nick Harper1fd39d82016-06-14 18:14:35 -07001056 }
Adam Langley95c29f32014-06-20 12:00:00 -07001057 vers := c.vers
Nick Harper1fd39d82016-06-14 18:14:35 -07001058 if vers == 0 || vers >= VersionTLS13 {
Adam Langley95c29f32014-06-20 12:00:00 -07001059 // Some TLS servers fail if the record version is
1060 // greater than TLS 1.0 for the initial ClientHello.
Nick Harper1fd39d82016-06-14 18:14:35 -07001061 //
1062 // TLS 1.3 fixes the version number in the record
1063 // layer to {3, 1}.
Adam Langley95c29f32014-06-20 12:00:00 -07001064 vers = VersionTLS10
1065 }
1066 b.data[1] = byte(vers >> 8)
1067 b.data[2] = byte(vers)
1068 b.data[3] = byte(m >> 8)
1069 b.data[4] = byte(m)
1070 if explicitIVLen > 0 {
1071 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
1072 if explicitIVIsSeq {
1073 copy(explicitIV, c.out.seq[:])
1074 } else {
1075 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
1076 break
1077 }
1078 }
1079 }
1080 copy(b.data[recordHeaderLen+explicitIVLen:], data)
Nick Harper1fd39d82016-06-14 18:14:35 -07001081 c.out.encrypt(b, explicitIVLen, typ)
Adam Langley95c29f32014-06-20 12:00:00 -07001082 _, err = c.conn.Write(b.data)
1083 if err != nil {
1084 break
1085 }
1086 n += m
1087 data = data[m:]
1088 }
1089 c.out.freeBlock(b)
1090
1091 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -07001092 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -07001093 if err != nil {
1094 // Cannot call sendAlert directly,
1095 // because we already hold c.out.Mutex.
1096 c.tmp[0] = alertLevelError
1097 c.tmp[1] = byte(err.(alert))
1098 c.writeRecord(recordTypeAlert, c.tmp[0:2])
1099 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
1100 }
1101 }
1102 return
1103}
1104
David Benjamin582ba042016-07-07 12:33:25 -07001105func (c *Conn) flushHandshake() error {
1106 if c.isDTLS {
1107 return c.dtlsFlushHandshake()
1108 }
1109
1110 for c.pendingFlight.Len() > 0 {
1111 var buf [maxPlaintext]byte
1112 n, _ := c.pendingFlight.Read(buf[:])
1113 if _, err := c.doWriteRecord(recordTypeHandshake, buf[:n]); err != nil {
1114 return err
1115 }
1116 }
1117
1118 c.pendingFlight.Reset()
1119 return nil
1120}
1121
David Benjamin83c0bc92014-08-04 01:23:53 -04001122func (c *Conn) doReadHandshake() ([]byte, error) {
1123 if c.isDTLS {
1124 return c.dtlsDoReadHandshake()
1125 }
1126
Adam Langley95c29f32014-06-20 12:00:00 -07001127 for c.hand.Len() < 4 {
1128 if err := c.in.err; err != nil {
1129 return nil, err
1130 }
1131 if err := c.readRecord(recordTypeHandshake); err != nil {
1132 return nil, err
1133 }
1134 }
1135
1136 data := c.hand.Bytes()
1137 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1138 if n > maxHandshake {
1139 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
1140 }
1141 for c.hand.Len() < 4+n {
1142 if err := c.in.err; err != nil {
1143 return nil, err
1144 }
1145 if err := c.readRecord(recordTypeHandshake); err != nil {
1146 return nil, err
1147 }
1148 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001149 return c.hand.Next(4 + n), nil
1150}
1151
1152// readHandshake reads the next handshake message from
1153// the record layer.
1154// c.in.Mutex < L; c.out.Mutex < L.
1155func (c *Conn) readHandshake() (interface{}, error) {
1156 data, err := c.doReadHandshake()
1157 if err != nil {
1158 return nil, err
1159 }
1160
Adam Langley95c29f32014-06-20 12:00:00 -07001161 var m handshakeMessage
1162 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001163 case typeHelloRequest:
1164 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001165 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001166 m = &clientHelloMsg{
1167 isDTLS: c.isDTLS,
1168 }
Adam Langley95c29f32014-06-20 12:00:00 -07001169 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001170 m = &serverHelloMsg{
1171 isDTLS: c.isDTLS,
1172 }
Nick Harperdcfbc672016-07-16 17:47:31 +02001173 case typeHelloRetryRequest:
1174 m = new(helloRetryRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001175 case typeNewSessionTicket:
David Benjamin58104882016-07-18 01:25:41 +02001176 m = &newSessionTicketMsg{
1177 version: c.vers,
1178 }
Nick Harperb41d2e42016-07-01 17:50:32 -04001179 case typeEncryptedExtensions:
1180 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001181 case typeCertificate:
Nick Harperb41d2e42016-07-01 17:50:32 -04001182 m = &certificateMsg{
David Benjamin8d315d72016-07-18 01:03:18 +02001183 hasRequestContext: c.vers >= VersionTLS13,
Nick Harperb41d2e42016-07-01 17:50:32 -04001184 }
Adam Langley95c29f32014-06-20 12:00:00 -07001185 case typeCertificateRequest:
1186 m = &certificateRequestMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001187 hasSignatureAlgorithm: c.vers >= VersionTLS12,
David Benjamin8d315d72016-07-18 01:03:18 +02001188 hasRequestContext: c.vers >= VersionTLS13,
Adam Langley95c29f32014-06-20 12:00:00 -07001189 }
1190 case typeCertificateStatus:
1191 m = new(certificateStatusMsg)
1192 case typeServerKeyExchange:
1193 m = new(serverKeyExchangeMsg)
1194 case typeServerHelloDone:
1195 m = new(serverHelloDoneMsg)
1196 case typeClientKeyExchange:
1197 m = new(clientKeyExchangeMsg)
1198 case typeCertificateVerify:
1199 m = &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001200 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001201 }
1202 case typeNextProtocol:
1203 m = new(nextProtoMsg)
1204 case typeFinished:
1205 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001206 case typeHelloVerifyRequest:
1207 m = new(helloVerifyRequestMsg)
David Benjamin24599a82016-06-30 18:56:53 -04001208 case typeChannelID:
1209 m = new(channelIDMsg)
David Benjamin21c00282016-07-18 21:56:23 +02001210 case typeKeyUpdate:
1211 m = new(keyUpdateMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001212 default:
1213 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1214 }
1215
1216 // The handshake message unmarshallers
1217 // expect to be able to keep references to data,
1218 // so pass in a fresh copy that won't be overwritten.
1219 data = append([]byte(nil), data...)
1220
1221 if !m.unmarshal(data) {
1222 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1223 }
1224 return m, nil
1225}
1226
David Benjamin83f90402015-01-27 01:09:43 -05001227// skipPacket processes all the DTLS records in packet. It updates
1228// sequence number expectations but otherwise ignores them.
1229func (c *Conn) skipPacket(packet []byte) error {
1230 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001231 if len(packet) < 13 {
1232 return errors.New("tls: bad packet")
1233 }
David Benjamin83f90402015-01-27 01:09:43 -05001234 // Dropped packets are completely ignored save to update
1235 // expected sequence numbers for this and the next epoch. (We
1236 // don't assert on the contents of the packets both for
1237 // simplicity and because a previous test with one shorter
1238 // timeout schedule would have done so.)
1239 epoch := packet[3:5]
1240 seq := packet[5:11]
1241 length := uint16(packet[11])<<8 | uint16(packet[12])
1242 if bytes.Equal(c.in.seq[:2], epoch) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001243 if bytes.Compare(seq, c.in.seq[2:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001244 return errors.New("tls: sequence mismatch")
1245 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001246 copy(c.in.seq[2:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001247 c.in.incSeq(false)
1248 } else {
David Benjamin13e81fc2015-11-02 17:16:13 -05001249 if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001250 return errors.New("tls: sequence mismatch")
1251 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001252 copy(c.in.nextSeq[:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001253 c.in.incNextSeq()
1254 }
David Benjamin6ca93552015-08-28 16:16:25 -04001255 if len(packet) < 13+int(length) {
1256 return errors.New("tls: bad packet")
1257 }
David Benjamin83f90402015-01-27 01:09:43 -05001258 packet = packet[13+length:]
1259 }
1260 return nil
1261}
1262
1263// simulatePacketLoss simulates the loss of a handshake leg from the
1264// peer based on the schedule in c.config.Bugs. If resendFunc is
1265// non-nil, it is called after each simulated timeout to retransmit
1266// handshake messages from the local end. This is used in cases where
1267// the peer retransmits on a stale Finished rather than a timeout.
1268func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1269 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1270 return nil
1271 }
1272 if !c.isDTLS {
1273 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1274 }
1275 if c.config.Bugs.PacketAdaptor == nil {
1276 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1277 }
1278 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1279 // Simulate a timeout.
1280 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1281 if err != nil {
1282 return err
1283 }
1284 for _, packet := range packets {
1285 if err := c.skipPacket(packet); err != nil {
1286 return err
1287 }
1288 }
1289 if resendFunc != nil {
1290 resendFunc()
1291 }
1292 }
1293 return nil
1294}
1295
David Benjamin47921102016-07-28 11:29:18 -04001296func (c *Conn) SendHalfHelloRequest() error {
1297 if err := c.Handshake(); err != nil {
1298 return err
1299 }
1300
1301 c.out.Lock()
1302 defer c.out.Unlock()
1303
1304 if _, err := c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0}); err != nil {
1305 return err
1306 }
1307 return c.flushHandshake()
1308}
1309
Adam Langley95c29f32014-06-20 12:00:00 -07001310// Write writes data to the connection.
1311func (c *Conn) Write(b []byte) (int, error) {
1312 if err := c.Handshake(); err != nil {
1313 return 0, err
1314 }
1315
1316 c.out.Lock()
1317 defer c.out.Unlock()
1318
David Benjamin12d2c482016-07-24 10:56:51 -04001319 // Flush any pending handshake data. PackHelloRequestWithFinished may
1320 // have been set and the handshake not followed by Renegotiate.
1321 c.flushHandshake()
1322
Adam Langley95c29f32014-06-20 12:00:00 -07001323 if err := c.out.err; err != nil {
1324 return 0, err
1325 }
1326
1327 if !c.handshakeComplete {
1328 return 0, alertInternalError
1329 }
1330
Steven Valdezc4aa7272016-10-03 12:25:56 -04001331 if c.keyUpdateRequested {
1332 if err := c.sendKeyUpdateLocked(keyUpdateNotRequested); err != nil {
David Benjamin21c00282016-07-18 21:56:23 +02001333 return 0, err
1334 }
Steven Valdezc4aa7272016-10-03 12:25:56 -04001335 c.keyUpdateRequested = false
David Benjamin21c00282016-07-18 21:56:23 +02001336 }
1337
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001338 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001339 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001340 }
1341
Adam Langley27a0d082015-11-03 13:34:10 -08001342 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1343 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
David Benjamin582ba042016-07-07 12:33:25 -07001344 c.flushHandshake()
Adam Langley27a0d082015-11-03 13:34:10 -08001345 }
1346
Adam Langley95c29f32014-06-20 12:00:00 -07001347 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1348 // attack when using block mode ciphers due to predictable IVs.
1349 // This can be prevented by splitting each Application Data
1350 // record into two records, effectively randomizing the IV.
1351 //
1352 // http://www.openssl.org/~bodo/tls-cbc.txt
1353 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1354 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1355
1356 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001357 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001358 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1359 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1360 if err != nil {
1361 return n, c.out.setErrorLocked(err)
1362 }
1363 m, b = 1, b[1:]
1364 }
1365 }
1366
1367 n, err := c.writeRecord(recordTypeApplicationData, b)
1368 return n + m, c.out.setErrorLocked(err)
1369}
1370
David Benjamind5a4ecb2016-07-18 01:17:13 +02001371func (c *Conn) handlePostHandshakeMessage() error {
Adam Langley2ae77d22014-10-28 17:29:33 -07001372 msg, err := c.readHandshake()
1373 if err != nil {
1374 return err
1375 }
David Benjamind5a4ecb2016-07-18 01:17:13 +02001376
1377 if c.vers < VersionTLS13 {
1378 if !c.isClient {
1379 c.sendAlert(alertUnexpectedMessage)
1380 return errors.New("tls: unexpected post-handshake message")
1381 }
1382
1383 _, ok := msg.(*helloRequestMsg)
1384 if !ok {
1385 c.sendAlert(alertUnexpectedMessage)
1386 return alertUnexpectedMessage
1387 }
1388
1389 c.handshakeComplete = false
1390 return c.Handshake()
Adam Langley2ae77d22014-10-28 17:29:33 -07001391 }
1392
David Benjamind5a4ecb2016-07-18 01:17:13 +02001393 if c.isClient {
1394 if newSessionTicket, ok := msg.(*newSessionTicketMsg); ok {
David Benjamin1a5e8ec2016-10-07 15:19:18 -04001395 if c.config.Bugs.ExpectGREASE && !newSessionTicket.hasGREASEExtension {
1396 return errors.New("tls: no GREASE ticket extension found")
1397 }
1398
David Benjamind5a4ecb2016-07-18 01:17:13 +02001399 if c.config.ClientSessionCache == nil || newSessionTicket.ticketLifetime == 0 {
1400 return nil
1401 }
1402
Steven Valdez5b986082016-09-01 12:29:49 -04001403 var foundKE, foundAuth bool
1404 for _, mode := range newSessionTicket.keModes {
1405 if mode == pskDHEKEMode {
1406 foundKE = true
1407 }
1408 }
1409 for _, mode := range newSessionTicket.authModes {
1410 if mode == pskAuthMode {
1411 foundAuth = true
1412 }
1413 }
1414
1415 // Ignore the ticket if the server preferences do not match a mode we implement.
1416 if !foundKE || !foundAuth {
1417 return nil
1418 }
1419
David Benjamind5a4ecb2016-07-18 01:17:13 +02001420 session := &ClientSessionState{
1421 sessionTicket: newSessionTicket.ticket,
1422 vers: c.vers,
1423 cipherSuite: c.cipherSuite.id,
1424 masterSecret: c.resumptionSecret,
1425 serverCertificates: c.peerCertificates,
1426 sctList: c.sctList,
1427 ocspResponse: c.ocspResponse,
Nick Harper0b3625b2016-07-25 16:16:28 -07001428 ticketCreationTime: c.config.time(),
1429 ticketExpiration: c.config.time().Add(time.Duration(newSessionTicket.ticketLifetime) * time.Second),
David Benjamind5a4ecb2016-07-18 01:17:13 +02001430 }
1431
1432 cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
1433 c.config.ClientSessionCache.Put(cacheKey, session)
1434 return nil
1435 }
1436 }
1437
Steven Valdezc4aa7272016-10-03 12:25:56 -04001438 if keyUpdate, ok := msg.(*keyUpdateMsg); ok {
Steven Valdez1dc53d22016-07-26 12:27:38 -04001439 c.in.doKeyUpdate(c, false)
Steven Valdezc4aa7272016-10-03 12:25:56 -04001440 if keyUpdate.keyUpdateRequest == keyUpdateRequested {
1441 c.keyUpdateRequested = true
1442 }
David Benjamin21c00282016-07-18 21:56:23 +02001443 return nil
1444 }
1445
David Benjamind5a4ecb2016-07-18 01:17:13 +02001446 // TODO(davidben): Add support for KeyUpdate.
1447 c.sendAlert(alertUnexpectedMessage)
1448 return alertUnexpectedMessage
Adam Langley2ae77d22014-10-28 17:29:33 -07001449}
1450
Adam Langleycf2d4f42014-10-28 19:06:14 -07001451func (c *Conn) Renegotiate() error {
1452 if !c.isClient {
David Benjaminef5dfd22015-12-06 13:17:07 -05001453 helloReq := new(helloRequestMsg).marshal()
1454 if c.config.Bugs.BadHelloRequest != nil {
1455 helloReq = c.config.Bugs.BadHelloRequest
1456 }
1457 c.writeRecord(recordTypeHandshake, helloReq)
David Benjamin582ba042016-07-07 12:33:25 -07001458 c.flushHandshake()
Adam Langleycf2d4f42014-10-28 19:06:14 -07001459 }
1460
1461 c.handshakeComplete = false
1462 return c.Handshake()
1463}
1464
Adam Langley95c29f32014-06-20 12:00:00 -07001465// Read can be made to time out and return a net.Error with Timeout() == true
1466// after a fixed time limit; see SetDeadline and SetReadDeadline.
1467func (c *Conn) Read(b []byte) (n int, err error) {
1468 if err = c.Handshake(); err != nil {
1469 return
1470 }
1471
1472 c.in.Lock()
1473 defer c.in.Unlock()
1474
1475 // Some OpenSSL servers send empty records in order to randomize the
1476 // CBC IV. So this loop ignores a limited number of empty records.
1477 const maxConsecutiveEmptyRecords = 100
1478 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1479 for c.input == nil && c.in.err == nil {
1480 if err := c.readRecord(recordTypeApplicationData); err != nil {
1481 // Soft error, like EAGAIN
1482 return 0, err
1483 }
David Benjamind9b091b2015-01-27 01:10:54 -05001484 if c.hand.Len() > 0 {
David Benjamind5a4ecb2016-07-18 01:17:13 +02001485 // We received handshake bytes, indicating a
1486 // post-handshake message.
1487 if err := c.handlePostHandshakeMessage(); err != nil {
Adam Langley2ae77d22014-10-28 17:29:33 -07001488 return 0, err
1489 }
1490 continue
1491 }
Adam Langley95c29f32014-06-20 12:00:00 -07001492 }
1493 if err := c.in.err; err != nil {
1494 return 0, err
1495 }
1496
1497 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001498 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001499 c.in.freeBlock(c.input)
1500 c.input = nil
1501 }
1502
1503 // If a close-notify alert is waiting, read it so that
1504 // we can return (n, EOF) instead of (n, nil), to signal
1505 // to the HTTP response reading goroutine that the
1506 // connection is now closed. This eliminates a race
1507 // where the HTTP response reading goroutine would
1508 // otherwise not observe the EOF until its next read,
1509 // by which time a client goroutine might have already
1510 // tried to reuse the HTTP connection for a new
1511 // request.
1512 // See https://codereview.appspot.com/76400046
1513 // and http://golang.org/issue/3514
1514 if ri := c.rawInput; ri != nil &&
1515 n != 0 && err == nil &&
1516 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1517 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1518 err = recErr // will be io.EOF on closeNotify
1519 }
1520 }
1521
1522 if n != 0 || err != nil {
1523 return n, err
1524 }
1525 }
1526
1527 return 0, io.ErrNoProgress
1528}
1529
1530// Close closes the connection.
1531func (c *Conn) Close() error {
1532 var alertErr error
1533
1534 c.handshakeMutex.Lock()
1535 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001536 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
David Benjaminfa214e42016-05-10 17:03:10 -04001537 alert := alertCloseNotify
1538 if c.config.Bugs.SendAlertOnShutdown != 0 {
1539 alert = c.config.Bugs.SendAlertOnShutdown
1540 }
1541 alertErr = c.sendAlert(alert)
David Benjamin4d559612016-05-18 14:31:51 -04001542 // Clear local alerts when sending alerts so we continue to wait
1543 // for the peer rather than closing the socket early.
1544 if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1545 alertErr = nil
1546 }
Adam Langley95c29f32014-06-20 12:00:00 -07001547 }
1548
David Benjamin30789da2015-08-29 22:56:45 -04001549 // Consume a close_notify from the peer if one hasn't been received
1550 // already. This avoids the peer from failing |SSL_shutdown| due to a
1551 // write failing.
1552 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1553 for c.in.error() == nil {
1554 c.readRecord(recordTypeAlert)
1555 }
1556 if c.in.error() != io.EOF {
1557 alertErr = c.in.error()
1558 }
1559 }
1560
Adam Langley95c29f32014-06-20 12:00:00 -07001561 if err := c.conn.Close(); err != nil {
1562 return err
1563 }
1564 return alertErr
1565}
1566
1567// Handshake runs the client or server handshake
1568// protocol if it has not yet been run.
1569// Most uses of this package need not call Handshake
1570// explicitly: the first Read or Write will call it automatically.
1571func (c *Conn) Handshake() error {
1572 c.handshakeMutex.Lock()
1573 defer c.handshakeMutex.Unlock()
1574 if err := c.handshakeErr; err != nil {
1575 return err
1576 }
1577 if c.handshakeComplete {
1578 return nil
1579 }
1580
David Benjamin9a41d1b2015-05-16 01:30:09 -04001581 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1582 c.conn.Write([]byte{
1583 byte(recordTypeAlert), // type
1584 0xfe, 0xff, // version
1585 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1586 0x0, 0x2, // length
1587 })
1588 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1589 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001590 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1591 c.writeRecord(recordTypeApplicationData, data)
1592 }
Adam Langley95c29f32014-06-20 12:00:00 -07001593 if c.isClient {
1594 c.handshakeErr = c.clientHandshake()
1595 } else {
1596 c.handshakeErr = c.serverHandshake()
1597 }
David Benjaminddb9f152015-02-03 15:44:39 -05001598 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1599 c.writeRecord(recordType(42), []byte("invalid record"))
1600 }
Adam Langley95c29f32014-06-20 12:00:00 -07001601 return c.handshakeErr
1602}
1603
1604// ConnectionState returns basic TLS details about the connection.
1605func (c *Conn) ConnectionState() ConnectionState {
1606 c.handshakeMutex.Lock()
1607 defer c.handshakeMutex.Unlock()
1608
1609 var state ConnectionState
1610 state.HandshakeComplete = c.handshakeComplete
1611 if c.handshakeComplete {
1612 state.Version = c.vers
1613 state.NegotiatedProtocol = c.clientProtocol
1614 state.DidResume = c.didResume
1615 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001616 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001617 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001618 state.PeerCertificates = c.peerCertificates
1619 state.VerifiedChains = c.verifiedChains
1620 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001621 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001622 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001623 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001624 state.SCTList = c.sctList
Nick Harper60edffd2016-06-21 15:19:24 -07001625 state.PeerSignatureAlgorithm = c.peerSignatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -04001626 state.CurveID = c.curveID
Adam Langley95c29f32014-06-20 12:00:00 -07001627 }
1628
1629 return state
1630}
1631
1632// OCSPResponse returns the stapled OCSP response from the TLS server, if
1633// any. (Only valid for client connections.)
1634func (c *Conn) OCSPResponse() []byte {
1635 c.handshakeMutex.Lock()
1636 defer c.handshakeMutex.Unlock()
1637
1638 return c.ocspResponse
1639}
1640
1641// VerifyHostname checks that the peer certificate chain is valid for
1642// connecting to host. If so, it returns nil; if not, it returns an error
1643// describing the problem.
1644func (c *Conn) VerifyHostname(host string) error {
1645 c.handshakeMutex.Lock()
1646 defer c.handshakeMutex.Unlock()
1647 if !c.isClient {
1648 return errors.New("tls: VerifyHostname called on TLS server connection")
1649 }
1650 if !c.handshakeComplete {
1651 return errors.New("tls: handshake has not yet been performed")
1652 }
1653 return c.peerCertificates[0].VerifyHostname(host)
1654}
David Benjaminc565ebb2015-04-03 04:06:36 -04001655
1656// ExportKeyingMaterial exports keying material from the current connection
1657// state, as per RFC 5705.
1658func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1659 c.handshakeMutex.Lock()
1660 defer c.handshakeMutex.Unlock()
1661 if !c.handshakeComplete {
1662 return nil, errors.New("tls: handshake has not yet been performed")
1663 }
1664
David Benjamin8d315d72016-07-18 01:03:18 +02001665 if c.vers >= VersionTLS13 {
David Benjamin97a0a082016-07-13 17:57:35 -04001666 // TODO(davidben): What should we do with useContext? See
1667 // https://github.com/tlswg/tls13-spec/issues/546
1668 return hkdfExpandLabel(c.cipherSuite.hash(), c.exporterSecret, label, context, length), nil
1669 }
1670
David Benjaminc565ebb2015-04-03 04:06:36 -04001671 seedLen := len(c.clientRandom) + len(c.serverRandom)
1672 if useContext {
1673 seedLen += 2 + len(context)
1674 }
1675 seed := make([]byte, 0, seedLen)
1676 seed = append(seed, c.clientRandom[:]...)
1677 seed = append(seed, c.serverRandom[:]...)
1678 if useContext {
1679 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1680 seed = append(seed, context...)
1681 }
1682 result := make([]byte, length)
David Benjamin97a0a082016-07-13 17:57:35 -04001683 prfForVersion(c.vers, c.cipherSuite)(result, c.exporterSecret, label, seed)
David Benjaminc565ebb2015-04-03 04:06:36 -04001684 return result, nil
1685}
David Benjamin3e052de2015-11-25 20:10:31 -05001686
1687// noRenegotiationInfo returns true if the renegotiation info extension
1688// should be supported in the current handshake.
1689func (c *Conn) noRenegotiationInfo() bool {
1690 if c.config.Bugs.NoRenegotiationInfo {
1691 return true
1692 }
1693 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1694 return true
1695 }
1696 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1697 return true
1698 }
1699 return false
1700}
David Benjamin58104882016-07-18 01:25:41 +02001701
1702func (c *Conn) SendNewSessionTicket() error {
1703 if c.isClient || c.vers < VersionTLS13 {
1704 return errors.New("tls: cannot send post-handshake NewSessionTicket")
1705 }
1706
1707 var peerCertificatesRaw [][]byte
1708 for _, cert := range c.peerCertificates {
1709 peerCertificatesRaw = append(peerCertificatesRaw, cert.Raw)
1710 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001711
David Benjamin58104882016-07-18 01:25:41 +02001712 // TODO(davidben): Allow configuring these values.
1713 m := &newSessionTicketMsg{
David Benjamin1286bee2016-10-07 15:25:06 -04001714 version: c.vers,
1715 ticketLifetime: uint32(24 * time.Hour / time.Second),
1716 keModes: []byte{pskDHEKEMode},
1717 authModes: []byte{pskAuthMode},
1718 customExtension: c.config.Bugs.CustomTicketExtension,
Steven Valdez5b986082016-09-01 12:29:49 -04001719 }
1720
1721 if len(c.config.Bugs.SendPSKKeyExchangeModes) != 0 {
1722 m.keModes = c.config.Bugs.SendPSKKeyExchangeModes
1723 }
1724 if len(c.config.Bugs.SendPSKAuthModes) != 0 {
1725 m.authModes = c.config.Bugs.SendPSKAuthModes
David Benjamin58104882016-07-18 01:25:41 +02001726 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001727
1728 state := sessionState{
1729 vers: c.vers,
1730 cipherSuite: c.cipherSuite.id,
1731 masterSecret: c.resumptionSecret,
1732 certificates: peerCertificatesRaw,
1733 ticketCreationTime: c.config.time(),
1734 ticketExpiration: c.config.time().Add(time.Duration(m.ticketLifetime) * time.Second),
Nick Harper0b3625b2016-07-25 16:16:28 -07001735 }
1736
David Benjamin58104882016-07-18 01:25:41 +02001737 if !c.config.Bugs.SendEmptySessionTicket {
1738 var err error
1739 m.ticket, err = c.encryptTicket(&state)
1740 if err != nil {
1741 return err
1742 }
1743 }
1744
1745 c.out.Lock()
1746 defer c.out.Unlock()
1747 _, err := c.writeRecord(recordTypeHandshake, m.marshal())
1748 return err
1749}
David Benjamin21c00282016-07-18 21:56:23 +02001750
Steven Valdezc4aa7272016-10-03 12:25:56 -04001751func (c *Conn) SendKeyUpdate(keyUpdateRequest byte) error {
David Benjamin21c00282016-07-18 21:56:23 +02001752 c.out.Lock()
1753 defer c.out.Unlock()
Steven Valdezc4aa7272016-10-03 12:25:56 -04001754 return c.sendKeyUpdateLocked(keyUpdateRequest)
David Benjamin21c00282016-07-18 21:56:23 +02001755}
1756
Steven Valdezc4aa7272016-10-03 12:25:56 -04001757func (c *Conn) sendKeyUpdateLocked(keyUpdateRequest byte) error {
David Benjamin7f0965a2016-09-30 15:14:01 -04001758 if c.vers < VersionTLS13 {
1759 return errors.New("tls: attempted to send KeyUpdate before TLS 1.3")
1760 }
1761
Steven Valdezc4aa7272016-10-03 12:25:56 -04001762 m := keyUpdateMsg{
1763 keyUpdateRequest: keyUpdateRequest,
1764 }
David Benjamin21c00282016-07-18 21:56:23 +02001765 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
1766 return err
1767 }
1768 if err := c.flushHandshake(); err != nil {
1769 return err
1770 }
Steven Valdez1dc53d22016-07-26 12:27:38 -04001771 c.out.doKeyUpdate(c, true)
David Benjamin21c00282016-07-18 21:56:23 +02001772 return nil
1773}