blob: b23a104a7c045d69307a36b3d873758caadf81cb [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
7package main
8
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
53
David Benjaminc565ebb2015-04-03 04:06:36 -040054 clientRandom, serverRandom [32]byte
55 masterSecret [48]byte
Adam Langley95c29f32014-06-20 12:00:00 -070056
57 clientProtocol string
58 clientProtocolFallback bool
David Benjaminfc7b0862014-09-06 13:21:53 -040059 usedALPN bool
Adam Langley95c29f32014-06-20 12:00:00 -070060
Adam Langley2ae77d22014-10-28 17:29:33 -070061 // verify_data values for the renegotiation extension.
62 clientVerify []byte
63 serverVerify []byte
64
David Benjamind30a9902014-08-24 01:44:23 -040065 channelID *ecdsa.PublicKey
66
David Benjaminca6c8262014-11-15 19:06:08 -050067 srtpProtectionProfile uint16
68
David Benjaminc44b1df2014-11-23 12:11:01 -050069 clientVersion uint16
70
Adam Langley95c29f32014-06-20 12:00:00 -070071 // input/output
72 in, out halfConn // in.Mutex < out.Mutex
73 rawInput *block // raw input, right off the wire
David Benjamin83c0bc92014-08-04 01:23:53 -040074 input *block // application record waiting to be read
75 hand bytes.Buffer // handshake record waiting to be read
76
77 // DTLS state
78 sendHandshakeSeq uint16
79 recvHandshakeSeq uint16
David Benjaminb3774b92015-01-31 17:16:01 -050080 handMsg []byte // pending assembled handshake message
81 handMsgLen int // handshake message length, not including the header
82 pendingFragments [][]byte // pending outgoing handshake fragments.
Adam Langley95c29f32014-06-20 12:00:00 -070083
84 tmp [16]byte
85}
86
David Benjamin5e961c12014-11-07 01:48:35 -050087func (c *Conn) init() {
88 c.in.isDTLS = c.isDTLS
89 c.out.isDTLS = c.isDTLS
90 c.in.config = c.config
91 c.out.config = c.config
David Benjamin8e6db492015-07-25 18:29:23 -040092
93 c.out.updateOutSeq()
David Benjamin5e961c12014-11-07 01:48:35 -050094}
95
Adam Langley95c29f32014-06-20 12:00:00 -070096// Access to net.Conn methods.
97// Cannot just embed net.Conn because that would
98// export the struct field too.
99
100// LocalAddr returns the local network address.
101func (c *Conn) LocalAddr() net.Addr {
102 return c.conn.LocalAddr()
103}
104
105// RemoteAddr returns the remote network address.
106func (c *Conn) RemoteAddr() net.Addr {
107 return c.conn.RemoteAddr()
108}
109
110// SetDeadline sets the read and write deadlines associated with the connection.
111// A zero value for t means Read and Write will not time out.
112// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
113func (c *Conn) SetDeadline(t time.Time) error {
114 return c.conn.SetDeadline(t)
115}
116
117// SetReadDeadline sets the read deadline on the underlying connection.
118// A zero value for t means Read will not time out.
119func (c *Conn) SetReadDeadline(t time.Time) error {
120 return c.conn.SetReadDeadline(t)
121}
122
123// SetWriteDeadline sets the write deadline on the underlying conneciton.
124// A zero value for t means 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) SetWriteDeadline(t time.Time) error {
127 return c.conn.SetWriteDeadline(t)
128}
129
130// A halfConn represents one direction of the record layer
131// connection, either sending or receiving.
132type halfConn struct {
133 sync.Mutex
134
David Benjamin83c0bc92014-08-04 01:23:53 -0400135 err error // first permanent error
136 version uint16 // protocol version
137 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -0700138 cipher interface{} // cipher algorithm
139 mac macFunction
140 seq [8]byte // 64-bit sequence number
David Benjamin8e6db492015-07-25 18:29:23 -0400141 outSeq [8]byte // Mapped sequence number
Adam Langley95c29f32014-06-20 12:00:00 -0700142 bfree *block // list of free blocks
143
144 nextCipher interface{} // next encryption state
145 nextMac macFunction // next MAC algorithm
David Benjamin83f90402015-01-27 01:09:43 -0500146 nextSeq [6]byte // next epoch's starting sequence number in DTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700147
148 // used to save allocating a new buffer for each MAC.
149 inDigestBuf, outDigestBuf []byte
Adam Langley80842bd2014-06-20 12:00:00 -0700150
151 config *Config
Adam Langley95c29f32014-06-20 12:00:00 -0700152}
153
154func (hc *halfConn) setErrorLocked(err error) error {
155 hc.err = err
156 return err
157}
158
159func (hc *halfConn) error() error {
Adam Langley2ae77d22014-10-28 17:29:33 -0700160 // This should be locked, but I've removed it for the renegotiation
161 // tests since we don't concurrently read and write the same tls.Conn
162 // in any case during testing.
Adam Langley95c29f32014-06-20 12:00:00 -0700163 err := hc.err
Adam Langley95c29f32014-06-20 12:00:00 -0700164 return err
165}
166
167// prepareCipherSpec sets the encryption and MAC states
168// that a subsequent changeCipherSpec will use.
169func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
170 hc.version = version
171 hc.nextCipher = cipher
172 hc.nextMac = mac
173}
174
175// changeCipherSpec changes the encryption and MAC states
176// to the ones previously passed to prepareCipherSpec.
Adam Langley80842bd2014-06-20 12:00:00 -0700177func (hc *halfConn) changeCipherSpec(config *Config) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700178 if hc.nextCipher == nil {
179 return alertInternalError
180 }
181 hc.cipher = hc.nextCipher
182 hc.mac = hc.nextMac
183 hc.nextCipher = nil
184 hc.nextMac = nil
Adam Langley80842bd2014-06-20 12:00:00 -0700185 hc.config = config
David Benjamin83c0bc92014-08-04 01:23:53 -0400186 hc.incEpoch()
Adam Langley95c29f32014-06-20 12:00:00 -0700187 return nil
188}
189
190// incSeq increments the sequence number.
David Benjamin5e961c12014-11-07 01:48:35 -0500191func (hc *halfConn) incSeq(isOutgoing bool) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400192 limit := 0
David Benjamin5e961c12014-11-07 01:48:35 -0500193 increment := uint64(1)
David Benjamin83c0bc92014-08-04 01:23:53 -0400194 if hc.isDTLS {
195 // Increment up to the epoch in DTLS.
196 limit = 2
197 }
198 for i := 7; i >= limit; i-- {
David Benjamin5e961c12014-11-07 01:48:35 -0500199 increment += uint64(hc.seq[i])
200 hc.seq[i] = byte(increment)
201 increment >>= 8
Adam Langley95c29f32014-06-20 12:00:00 -0700202 }
203
204 // Not allowed to let sequence number wrap.
205 // Instead, must renegotiate before it does.
206 // Not likely enough to bother.
David Benjamin5e961c12014-11-07 01:48:35 -0500207 if increment != 0 {
208 panic("TLS: sequence number wraparound")
209 }
David Benjamin8e6db492015-07-25 18:29:23 -0400210
211 hc.updateOutSeq()
Adam Langley95c29f32014-06-20 12:00:00 -0700212}
213
David Benjamin83f90402015-01-27 01:09:43 -0500214// incNextSeq increments the starting sequence number for the next epoch.
215func (hc *halfConn) incNextSeq() {
216 for i := len(hc.nextSeq) - 1; i >= 0; i-- {
217 hc.nextSeq[i]++
218 if hc.nextSeq[i] != 0 {
219 return
220 }
221 }
222 panic("TLS: sequence number wraparound")
223}
224
225// incEpoch resets the sequence number. In DTLS, it also increments the epoch
226// half of the sequence number.
David Benjamin83c0bc92014-08-04 01:23:53 -0400227func (hc *halfConn) incEpoch() {
David Benjamin83c0bc92014-08-04 01:23:53 -0400228 if hc.isDTLS {
229 for i := 1; i >= 0; i-- {
230 hc.seq[i]++
231 if hc.seq[i] != 0 {
232 break
233 }
234 if i == 0 {
235 panic("TLS: epoch number wraparound")
236 }
237 }
David Benjamin83f90402015-01-27 01:09:43 -0500238 copy(hc.seq[2:], hc.nextSeq[:])
239 for i := range hc.nextSeq {
240 hc.nextSeq[i] = 0
241 }
242 } else {
243 for i := range hc.seq {
244 hc.seq[i] = 0
245 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400246 }
David Benjamin8e6db492015-07-25 18:29:23 -0400247
248 hc.updateOutSeq()
249}
250
251func (hc *halfConn) updateOutSeq() {
252 if hc.config.Bugs.SequenceNumberMapping != nil {
253 seqU64 := binary.BigEndian.Uint64(hc.seq[:])
254 seqU64 = hc.config.Bugs.SequenceNumberMapping(seqU64)
255 binary.BigEndian.PutUint64(hc.outSeq[:], seqU64)
256
257 // The DTLS epoch cannot be changed.
258 copy(hc.outSeq[:2], hc.seq[:2])
259 return
260 }
261
262 copy(hc.outSeq[:], hc.seq[:])
David Benjamin83c0bc92014-08-04 01:23:53 -0400263}
264
265func (hc *halfConn) recordHeaderLen() int {
266 if hc.isDTLS {
267 return dtlsRecordHeaderLen
268 }
269 return tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700270}
271
272// removePadding returns an unpadded slice, in constant time, which is a prefix
273// of the input. It also returns a byte which is equal to 255 if the padding
274// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
275func removePadding(payload []byte) ([]byte, byte) {
276 if len(payload) < 1 {
277 return payload, 0
278 }
279
280 paddingLen := payload[len(payload)-1]
281 t := uint(len(payload)-1) - uint(paddingLen)
282 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
283 good := byte(int32(^t) >> 31)
284
285 toCheck := 255 // the maximum possible padding length
286 // The length of the padded data is public, so we can use an if here
287 if toCheck+1 > len(payload) {
288 toCheck = len(payload) - 1
289 }
290
291 for i := 0; i < toCheck; i++ {
292 t := uint(paddingLen) - uint(i)
293 // if i <= paddingLen then the MSB of t is zero
294 mask := byte(int32(^t) >> 31)
295 b := payload[len(payload)-1-i]
296 good &^= mask&paddingLen ^ mask&b
297 }
298
299 // We AND together the bits of good and replicate the result across
300 // all the bits.
301 good &= good << 4
302 good &= good << 2
303 good &= good << 1
304 good = uint8(int8(good) >> 7)
305
306 toRemove := good&paddingLen + 1
307 return payload[:len(payload)-int(toRemove)], good
308}
309
310// removePaddingSSL30 is a replacement for removePadding in the case that the
311// protocol version is SSLv3. In this version, the contents of the padding
312// are random and cannot be checked.
313func removePaddingSSL30(payload []byte) ([]byte, byte) {
314 if len(payload) < 1 {
315 return payload, 0
316 }
317
318 paddingLen := int(payload[len(payload)-1]) + 1
319 if paddingLen > len(payload) {
320 return payload, 0
321 }
322
323 return payload[:len(payload)-paddingLen], 255
324}
325
326func roundUp(a, b int) int {
327 return a + (b-a%b)%b
328}
329
330// cbcMode is an interface for block ciphers using cipher block chaining.
331type cbcMode interface {
332 cipher.BlockMode
333 SetIV([]byte)
334}
335
336// decrypt checks and strips the mac and decrypts the data in b. Returns a
337// success boolean, the number of bytes to skip from the start of the record in
338// order to get the application payload, and an optional alert value.
339func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, alertValue alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400340 recordHeaderLen := hc.recordHeaderLen()
341
Adam Langley95c29f32014-06-20 12:00:00 -0700342 // pull out payload
343 payload := b.data[recordHeaderLen:]
344
345 macSize := 0
346 if hc.mac != nil {
347 macSize = hc.mac.Size()
348 }
349
350 paddingGood := byte(255)
351 explicitIVLen := 0
352
David Benjamin83c0bc92014-08-04 01:23:53 -0400353 seq := hc.seq[:]
354 if hc.isDTLS {
355 // DTLS sequence numbers are explicit.
356 seq = b.data[3:11]
357 }
358
Adam Langley95c29f32014-06-20 12:00:00 -0700359 // decrypt
360 if hc.cipher != nil {
361 switch c := hc.cipher.(type) {
362 case cipher.Stream:
363 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400364 case *tlsAead:
365 nonce := seq
366 if c.explicitNonce {
367 explicitIVLen = 8
368 if len(payload) < explicitIVLen {
369 return false, 0, alertBadRecordMAC
370 }
371 nonce = payload[:8]
372 payload = payload[8:]
Adam Langley95c29f32014-06-20 12:00:00 -0700373 }
Adam Langley95c29f32014-06-20 12:00:00 -0700374
375 var additionalData [13]byte
David Benjamin83c0bc92014-08-04 01:23:53 -0400376 copy(additionalData[:], seq)
Adam Langley95c29f32014-06-20 12:00:00 -0700377 copy(additionalData[8:], b.data[:3])
378 n := len(payload) - c.Overhead()
379 additionalData[11] = byte(n >> 8)
380 additionalData[12] = byte(n)
381 var err error
382 payload, err = c.Open(payload[:0], nonce, payload, additionalData[:])
383 if err != nil {
384 return false, 0, alertBadRecordMAC
385 }
386 b.resize(recordHeaderLen + explicitIVLen + len(payload))
387 case cbcMode:
388 blockSize := c.BlockSize()
David Benjamin83c0bc92014-08-04 01:23:53 -0400389 if hc.version >= VersionTLS11 || hc.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700390 explicitIVLen = blockSize
391 }
392
393 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
394 return false, 0, alertBadRecordMAC
395 }
396
397 if explicitIVLen > 0 {
398 c.SetIV(payload[:explicitIVLen])
399 payload = payload[explicitIVLen:]
400 }
401 c.CryptBlocks(payload, payload)
402 if hc.version == VersionSSL30 {
403 payload, paddingGood = removePaddingSSL30(payload)
404 } else {
405 payload, paddingGood = removePadding(payload)
406 }
407 b.resize(recordHeaderLen + explicitIVLen + len(payload))
408
409 // note that we still have a timing side-channel in the
410 // MAC check, below. An attacker can align the record
411 // so that a correct padding will cause one less hash
412 // block to be calculated. Then they can iteratively
413 // decrypt a record by breaking each byte. See
414 // "Password Interception in a SSL/TLS Channel", Brice
415 // Canvel et al.
416 //
417 // However, our behavior matches OpenSSL, so we leak
418 // only as much as they do.
419 default:
420 panic("unknown cipher type")
421 }
422 }
423
424 // check, strip mac
425 if hc.mac != nil {
426 if len(payload) < macSize {
427 return false, 0, alertBadRecordMAC
428 }
429
430 // strip mac off payload, b.data
431 n := len(payload) - macSize
David Benjamin83c0bc92014-08-04 01:23:53 -0400432 b.data[recordHeaderLen-2] = byte(n >> 8)
433 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700434 b.resize(recordHeaderLen + explicitIVLen + n)
435 remoteMAC := payload[n:]
David Benjamin83c0bc92014-08-04 01:23:53 -0400436 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
Adam Langley95c29f32014-06-20 12:00:00 -0700437
438 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
439 return false, 0, alertBadRecordMAC
440 }
441 hc.inDigestBuf = localMAC
442 }
David Benjamin5e961c12014-11-07 01:48:35 -0500443 hc.incSeq(false)
Adam Langley95c29f32014-06-20 12:00:00 -0700444
445 return true, recordHeaderLen + explicitIVLen, 0
446}
447
448// padToBlockSize calculates the needed padding block, if any, for a payload.
449// On exit, prefix aliases payload and extends to the end of the last full
450// block of payload. finalBlock is a fresh slice which contains the contents of
451// any suffix of payload as well as the needed padding to make finalBlock a
452// full block.
Adam Langley80842bd2014-06-20 12:00:00 -0700453func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
Adam Langley95c29f32014-06-20 12:00:00 -0700454 overrun := len(payload) % blockSize
Adam Langley95c29f32014-06-20 12:00:00 -0700455 prefix = payload[:len(payload)-overrun]
Adam Langley80842bd2014-06-20 12:00:00 -0700456
457 paddingLen := blockSize - overrun
458 finalSize := blockSize
459 if config.Bugs.MaxPadding {
460 for paddingLen+blockSize <= 256 {
461 paddingLen += blockSize
462 }
463 finalSize = 256
464 }
465 finalBlock = make([]byte, finalSize)
466 for i := range finalBlock {
Adam Langley95c29f32014-06-20 12:00:00 -0700467 finalBlock[i] = byte(paddingLen - 1)
468 }
Adam Langley80842bd2014-06-20 12:00:00 -0700469 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
470 finalBlock[overrun] ^= 0xff
471 }
472 copy(finalBlock, payload[len(payload)-overrun:])
Adam Langley95c29f32014-06-20 12:00:00 -0700473 return
474}
475
476// encrypt encrypts and macs the data in b.
477func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400478 recordHeaderLen := hc.recordHeaderLen()
479
Adam Langley95c29f32014-06-20 12:00:00 -0700480 // mac
481 if hc.mac != nil {
David Benjamin8e6db492015-07-25 18:29:23 -0400482 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 -0700483
484 n := len(b.data)
485 b.resize(n + len(mac))
486 copy(b.data[n:], mac)
487 hc.outDigestBuf = mac
488 }
489
490 payload := b.data[recordHeaderLen:]
491
492 // encrypt
493 if hc.cipher != nil {
494 switch c := hc.cipher.(type) {
495 case cipher.Stream:
496 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400497 case *tlsAead:
Adam Langley95c29f32014-06-20 12:00:00 -0700498 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
499 b.resize(len(b.data) + c.Overhead())
David Benjamin8e6db492015-07-25 18:29:23 -0400500 nonce := hc.outSeq[:]
David Benjamine9a80ff2015-04-07 00:46:46 -0400501 if c.explicitNonce {
502 nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
503 }
Adam Langley95c29f32014-06-20 12:00:00 -0700504 payload := b.data[recordHeaderLen+explicitIVLen:]
505 payload = payload[:payloadLen]
506
507 var additionalData [13]byte
David Benjamin8e6db492015-07-25 18:29:23 -0400508 copy(additionalData[:], hc.outSeq[:])
Adam Langley95c29f32014-06-20 12:00:00 -0700509 copy(additionalData[8:], b.data[:3])
510 additionalData[11] = byte(payloadLen >> 8)
511 additionalData[12] = byte(payloadLen)
512
513 c.Seal(payload[:0], nonce, payload, additionalData[:])
514 case cbcMode:
515 blockSize := c.BlockSize()
516 if explicitIVLen > 0 {
517 c.SetIV(payload[:explicitIVLen])
518 payload = payload[explicitIVLen:]
519 }
Adam Langley80842bd2014-06-20 12:00:00 -0700520 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700521 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
522 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
523 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
524 default:
525 panic("unknown cipher type")
526 }
527 }
528
529 // update length to include MAC and any block padding needed.
530 n := len(b.data) - recordHeaderLen
David Benjamin83c0bc92014-08-04 01:23:53 -0400531 b.data[recordHeaderLen-2] = byte(n >> 8)
532 b.data[recordHeaderLen-1] = byte(n)
David Benjamin5e961c12014-11-07 01:48:35 -0500533 hc.incSeq(true)
Adam Langley95c29f32014-06-20 12:00:00 -0700534
535 return true, 0
536}
537
538// A block is a simple data buffer.
539type block struct {
540 data []byte
541 off int // index for Read
542 link *block
543}
544
545// resize resizes block to be n bytes, growing if necessary.
546func (b *block) resize(n int) {
547 if n > cap(b.data) {
548 b.reserve(n)
549 }
550 b.data = b.data[0:n]
551}
552
553// reserve makes sure that block contains a capacity of at least n bytes.
554func (b *block) reserve(n int) {
555 if cap(b.data) >= n {
556 return
557 }
558 m := cap(b.data)
559 if m == 0 {
560 m = 1024
561 }
562 for m < n {
563 m *= 2
564 }
565 data := make([]byte, len(b.data), m)
566 copy(data, b.data)
567 b.data = data
568}
569
570// readFromUntil reads from r into b until b contains at least n bytes
571// or else returns an error.
572func (b *block) readFromUntil(r io.Reader, n int) error {
573 // quick case
574 if len(b.data) >= n {
575 return nil
576 }
577
578 // read until have enough.
579 b.reserve(n)
580 for {
581 m, err := r.Read(b.data[len(b.data):cap(b.data)])
582 b.data = b.data[0 : len(b.data)+m]
583 if len(b.data) >= n {
584 // TODO(bradfitz,agl): slightly suspicious
585 // that we're throwing away r.Read's err here.
586 break
587 }
588 if err != nil {
589 return err
590 }
591 }
592 return nil
593}
594
595func (b *block) Read(p []byte) (n int, err error) {
596 n = copy(p, b.data[b.off:])
597 b.off += n
598 return
599}
600
601// newBlock allocates a new block, from hc's free list if possible.
602func (hc *halfConn) newBlock() *block {
603 b := hc.bfree
604 if b == nil {
605 return new(block)
606 }
607 hc.bfree = b.link
608 b.link = nil
609 b.resize(0)
610 return b
611}
612
613// freeBlock returns a block to hc's free list.
614// The protocol is such that each side only has a block or two on
615// its free list at a time, so there's no need to worry about
616// trimming the list, etc.
617func (hc *halfConn) freeBlock(b *block) {
618 b.link = hc.bfree
619 hc.bfree = b
620}
621
622// splitBlock splits a block after the first n bytes,
623// returning a block with those n bytes and a
624// block with the remainder. the latter may be nil.
625func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
626 if len(b.data) <= n {
627 return b, nil
628 }
629 bb := hc.newBlock()
630 bb.resize(len(b.data) - n)
631 copy(bb.data, b.data[n:])
632 b.data = b.data[0:n]
633 return b, bb
634}
635
David Benjamin83c0bc92014-08-04 01:23:53 -0400636func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
637 if c.isDTLS {
638 return c.dtlsDoReadRecord(want)
639 }
640
641 recordHeaderLen := tlsRecordHeaderLen
642
643 if c.rawInput == nil {
644 c.rawInput = c.in.newBlock()
645 }
646 b := c.rawInput
647
648 // Read header, payload.
649 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
650 // RFC suggests that EOF without an alertCloseNotify is
651 // an error, but popular web sites seem to do this,
David Benjamin30789da2015-08-29 22:56:45 -0400652 // so we can't make it an error, outside of tests.
653 if err == io.EOF && c.config.Bugs.ExpectCloseNotify {
654 err = io.ErrUnexpectedEOF
655 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400656 if e, ok := err.(net.Error); !ok || !e.Temporary() {
657 c.in.setErrorLocked(err)
658 }
659 return 0, nil, err
660 }
661 typ := recordType(b.data[0])
662
663 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
664 // start with a uint16 length where the MSB is set and the first record
665 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
666 // an SSLv2 client.
667 if want == recordTypeHandshake && typ == 0x80 {
668 c.sendAlert(alertProtocolVersion)
669 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
670 }
671
672 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
673 n := int(b.data[3])<<8 | int(b.data[4])
David Benjamin1e29a6b2014-12-10 02:27:24 -0500674 if c.haveVers {
675 if vers != c.vers {
676 c.sendAlert(alertProtocolVersion)
677 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers))
678 }
679 } else {
680 if expect := c.config.Bugs.ExpectInitialRecordVersion; expect != 0 && vers != expect {
681 c.sendAlert(alertProtocolVersion)
682 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
683 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400684 }
685 if n > maxCiphertext {
686 c.sendAlert(alertRecordOverflow)
687 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
688 }
689 if !c.haveVers {
690 // First message, be extra suspicious:
691 // this might not be a TLS client.
692 // Bail out before reading a full 'body', if possible.
693 // The current max version is 3.1.
694 // If the version is >= 16.0, it's probably not real.
695 // Similarly, a clientHello message encodes in
696 // well under a kilobyte. If the length is >= 12 kB,
697 // it's probably not real.
698 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
699 c.sendAlert(alertUnexpectedMessage)
700 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
701 }
702 }
703 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
704 if err == io.EOF {
705 err = io.ErrUnexpectedEOF
706 }
707 if e, ok := err.(net.Error); !ok || !e.Temporary() {
708 c.in.setErrorLocked(err)
709 }
710 return 0, nil, err
711 }
712
713 // Process message.
714 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
715 ok, off, err := c.in.decrypt(b)
716 if !ok {
717 c.in.setErrorLocked(c.sendAlert(err))
718 }
719 b.off = off
720 return typ, b, nil
721}
722
Adam Langley95c29f32014-06-20 12:00:00 -0700723// readRecord reads the next TLS record from the connection
724// and updates the record layer state.
725// c.in.Mutex <= L; c.input == nil.
726func (c *Conn) readRecord(want recordType) error {
727 // Caller must be in sync with connection:
728 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700729 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700730 switch want {
731 default:
732 c.sendAlert(alertInternalError)
733 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
734 case recordTypeHandshake, recordTypeChangeCipherSpec:
735 if c.handshakeComplete {
736 c.sendAlert(alertInternalError)
737 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
738 }
739 case recordTypeApplicationData:
David Benjamine58c4f52014-08-24 03:47:07 -0400740 if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart {
Adam Langley95c29f32014-06-20 12:00:00 -0700741 c.sendAlert(alertInternalError)
742 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
743 }
David Benjamin30789da2015-08-29 22:56:45 -0400744 case recordTypeAlert:
745 // Looking for a close_notify. Note: unlike a real
746 // implementation, this is not tolerant of additional records.
747 // See the documentation for ExpectCloseNotify.
Adam Langley95c29f32014-06-20 12:00:00 -0700748 }
749
750Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400751 typ, b, err := c.doReadRecord(want)
752 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700753 return err
754 }
Adam Langley95c29f32014-06-20 12:00:00 -0700755 data := b.data[b.off:]
756 if len(data) > maxPlaintext {
757 err := c.sendAlert(alertRecordOverflow)
758 c.in.freeBlock(b)
759 return c.in.setErrorLocked(err)
760 }
761
762 switch typ {
763 default:
764 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
765
766 case recordTypeAlert:
767 if len(data) != 2 {
768 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
769 break
770 }
771 if alert(data[1]) == alertCloseNotify {
772 c.in.setErrorLocked(io.EOF)
773 break
774 }
775 switch data[0] {
776 case alertLevelWarning:
777 // drop on the floor
778 c.in.freeBlock(b)
779 goto Again
780 case alertLevelError:
781 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
782 default:
783 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
784 }
785
786 case recordTypeChangeCipherSpec:
787 if typ != want || len(data) != 1 || data[0] != 1 {
788 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
789 break
790 }
Adam Langley80842bd2014-06-20 12:00:00 -0700791 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700792 if err != nil {
793 c.in.setErrorLocked(c.sendAlert(err.(alert)))
794 }
795
796 case recordTypeApplicationData:
797 if typ != want {
798 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
799 break
800 }
801 c.input = b
802 b = nil
803
804 case recordTypeHandshake:
805 // TODO(rsc): Should at least pick off connection close.
806 if typ != want {
Adam Langley2ae77d22014-10-28 17:29:33 -0700807 // A client might need to process a HelloRequest from
808 // the server, thus receiving a handshake message when
David Benjamind9b091b2015-01-27 01:10:54 -0500809 // application data is expected is ok.
David Benjamin30789da2015-08-29 22:56:45 -0400810 if !c.isClient || want != recordTypeApplicationData {
Adam Langley2ae77d22014-10-28 17:29:33 -0700811 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
812 }
Adam Langley95c29f32014-06-20 12:00:00 -0700813 }
814 c.hand.Write(data)
815 }
816
817 if b != nil {
818 c.in.freeBlock(b)
819 }
820 return c.in.err
821}
822
823// sendAlert sends a TLS alert message.
824// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400825func (c *Conn) sendAlertLocked(level byte, err alert) error {
826 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700827 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400828 if c.config.Bugs.FragmentAlert {
829 c.writeRecord(recordTypeAlert, c.tmp[0:1])
830 c.writeRecord(recordTypeAlert, c.tmp[1:2])
831 } else {
832 c.writeRecord(recordTypeAlert, c.tmp[0:2])
833 }
David Benjamin24f346d2015-06-06 03:28:08 -0400834 // Error alerts are fatal to the connection.
835 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700836 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
837 }
838 return nil
839}
840
841// sendAlert sends a TLS alert message.
842// L < c.out.Mutex.
843func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400844 level := byte(alertLevelError)
845 if err == alertNoRenegotiation || err == alertCloseNotify {
846 level = alertLevelWarning
847 }
848 return c.SendAlert(level, err)
849}
850
851func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700852 c.out.Lock()
853 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -0400854 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -0700855}
856
David Benjamind86c7672014-08-02 04:07:12 -0400857// writeV2Record writes a record for a V2ClientHello.
858func (c *Conn) writeV2Record(data []byte) (n int, err error) {
859 record := make([]byte, 2+len(data))
860 record[0] = uint8(len(data)>>8) | 0x80
861 record[1] = uint8(len(data))
862 copy(record[2:], data)
863 return c.conn.Write(record)
864}
865
Adam Langley95c29f32014-06-20 12:00:00 -0700866// writeRecord writes a TLS record with the given type and payload
867// to the connection and updates the record layer state.
868// c.out.Mutex <= L.
869func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400870 if c.isDTLS {
871 return c.dtlsWriteRecord(typ, data)
872 }
873
874 recordHeaderLen := tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700875 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -0400876 first := true
877 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -0400878 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -0700879 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -0400880 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -0700881 m = maxPlaintext
882 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400883 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
884 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -0400885 // By default, do not fragment the client_version or
886 // server_version, which are located in the first 6
887 // bytes.
888 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
889 m = 6
890 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400891 }
Adam Langley95c29f32014-06-20 12:00:00 -0700892 explicitIVLen := 0
893 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -0400894 first = false
Adam Langley95c29f32014-06-20 12:00:00 -0700895
896 var cbc cbcMode
897 if c.out.version >= VersionTLS11 {
898 var ok bool
899 if cbc, ok = c.out.cipher.(cbcMode); ok {
900 explicitIVLen = cbc.BlockSize()
901 }
902 }
903 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -0400904 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -0700905 explicitIVLen = 8
906 // The AES-GCM construction in TLS has an
907 // explicit nonce so that the nonce can be
908 // random. However, the nonce is only 8 bytes
909 // which is too small for a secure, random
910 // nonce. Therefore we use the sequence number
911 // as the nonce.
912 explicitIVIsSeq = true
913 }
914 }
915 b.resize(recordHeaderLen + explicitIVLen + m)
916 b.data[0] = byte(typ)
917 vers := c.vers
918 if vers == 0 {
919 // Some TLS servers fail if the record version is
920 // greater than TLS 1.0 for the initial ClientHello.
921 vers = VersionTLS10
922 }
923 b.data[1] = byte(vers >> 8)
924 b.data[2] = byte(vers)
925 b.data[3] = byte(m >> 8)
926 b.data[4] = byte(m)
927 if explicitIVLen > 0 {
928 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
929 if explicitIVIsSeq {
930 copy(explicitIV, c.out.seq[:])
931 } else {
932 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
933 break
934 }
935 }
936 }
937 copy(b.data[recordHeaderLen+explicitIVLen:], data)
938 c.out.encrypt(b, explicitIVLen)
939 _, err = c.conn.Write(b.data)
940 if err != nil {
941 break
942 }
943 n += m
944 data = data[m:]
945 }
946 c.out.freeBlock(b)
947
948 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -0700949 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700950 if err != nil {
951 // Cannot call sendAlert directly,
952 // because we already hold c.out.Mutex.
953 c.tmp[0] = alertLevelError
954 c.tmp[1] = byte(err.(alert))
955 c.writeRecord(recordTypeAlert, c.tmp[0:2])
956 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
957 }
958 }
959 return
960}
961
David Benjamin83c0bc92014-08-04 01:23:53 -0400962func (c *Conn) doReadHandshake() ([]byte, error) {
963 if c.isDTLS {
964 return c.dtlsDoReadHandshake()
965 }
966
Adam Langley95c29f32014-06-20 12:00:00 -0700967 for c.hand.Len() < 4 {
968 if err := c.in.err; err != nil {
969 return nil, err
970 }
971 if err := c.readRecord(recordTypeHandshake); err != nil {
972 return nil, err
973 }
974 }
975
976 data := c.hand.Bytes()
977 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
978 if n > maxHandshake {
979 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
980 }
981 for c.hand.Len() < 4+n {
982 if err := c.in.err; err != nil {
983 return nil, err
984 }
985 if err := c.readRecord(recordTypeHandshake); err != nil {
986 return nil, err
987 }
988 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400989 return c.hand.Next(4 + n), nil
990}
991
992// readHandshake reads the next handshake message from
993// the record layer.
994// c.in.Mutex < L; c.out.Mutex < L.
995func (c *Conn) readHandshake() (interface{}, error) {
996 data, err := c.doReadHandshake()
997 if err != nil {
998 return nil, err
999 }
1000
Adam Langley95c29f32014-06-20 12:00:00 -07001001 var m handshakeMessage
1002 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001003 case typeHelloRequest:
1004 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001005 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001006 m = &clientHelloMsg{
1007 isDTLS: c.isDTLS,
1008 }
Adam Langley95c29f32014-06-20 12:00:00 -07001009 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001010 m = &serverHelloMsg{
1011 isDTLS: c.isDTLS,
1012 }
Adam Langley95c29f32014-06-20 12:00:00 -07001013 case typeNewSessionTicket:
1014 m = new(newSessionTicketMsg)
1015 case typeCertificate:
1016 m = new(certificateMsg)
1017 case typeCertificateRequest:
1018 m = &certificateRequestMsg{
1019 hasSignatureAndHash: c.vers >= VersionTLS12,
1020 }
1021 case typeCertificateStatus:
1022 m = new(certificateStatusMsg)
1023 case typeServerKeyExchange:
1024 m = new(serverKeyExchangeMsg)
1025 case typeServerHelloDone:
1026 m = new(serverHelloDoneMsg)
1027 case typeClientKeyExchange:
1028 m = new(clientKeyExchangeMsg)
1029 case typeCertificateVerify:
1030 m = &certificateVerifyMsg{
1031 hasSignatureAndHash: c.vers >= VersionTLS12,
1032 }
1033 case typeNextProtocol:
1034 m = new(nextProtoMsg)
1035 case typeFinished:
1036 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001037 case typeHelloVerifyRequest:
1038 m = new(helloVerifyRequestMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001039 case typeEncryptedExtensions:
1040 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001041 default:
1042 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1043 }
1044
1045 // The handshake message unmarshallers
1046 // expect to be able to keep references to data,
1047 // so pass in a fresh copy that won't be overwritten.
1048 data = append([]byte(nil), data...)
1049
1050 if !m.unmarshal(data) {
1051 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1052 }
1053 return m, nil
1054}
1055
David Benjamin83f90402015-01-27 01:09:43 -05001056// skipPacket processes all the DTLS records in packet. It updates
1057// sequence number expectations but otherwise ignores them.
1058func (c *Conn) skipPacket(packet []byte) error {
1059 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001060 if len(packet) < 13 {
1061 return errors.New("tls: bad packet")
1062 }
David Benjamin83f90402015-01-27 01:09:43 -05001063 // Dropped packets are completely ignored save to update
1064 // expected sequence numbers for this and the next epoch. (We
1065 // don't assert on the contents of the packets both for
1066 // simplicity and because a previous test with one shorter
1067 // timeout schedule would have done so.)
1068 epoch := packet[3:5]
1069 seq := packet[5:11]
1070 length := uint16(packet[11])<<8 | uint16(packet[12])
1071 if bytes.Equal(c.in.seq[:2], epoch) {
1072 if !bytes.Equal(c.in.seq[2:], seq) {
1073 return errors.New("tls: sequence mismatch")
1074 }
1075 c.in.incSeq(false)
1076 } else {
1077 if !bytes.Equal(c.in.nextSeq[:], seq) {
1078 return errors.New("tls: sequence mismatch")
1079 }
1080 c.in.incNextSeq()
1081 }
David Benjamin6ca93552015-08-28 16:16:25 -04001082 if len(packet) < 13+int(length) {
1083 return errors.New("tls: bad packet")
1084 }
David Benjamin83f90402015-01-27 01:09:43 -05001085 packet = packet[13+length:]
1086 }
1087 return nil
1088}
1089
1090// simulatePacketLoss simulates the loss of a handshake leg from the
1091// peer based on the schedule in c.config.Bugs. If resendFunc is
1092// non-nil, it is called after each simulated timeout to retransmit
1093// handshake messages from the local end. This is used in cases where
1094// the peer retransmits on a stale Finished rather than a timeout.
1095func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1096 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1097 return nil
1098 }
1099 if !c.isDTLS {
1100 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1101 }
1102 if c.config.Bugs.PacketAdaptor == nil {
1103 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1104 }
1105 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1106 // Simulate a timeout.
1107 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1108 if err != nil {
1109 return err
1110 }
1111 for _, packet := range packets {
1112 if err := c.skipPacket(packet); err != nil {
1113 return err
1114 }
1115 }
1116 if resendFunc != nil {
1117 resendFunc()
1118 }
1119 }
1120 return nil
1121}
1122
Adam Langley95c29f32014-06-20 12:00:00 -07001123// Write writes data to the connection.
1124func (c *Conn) Write(b []byte) (int, error) {
1125 if err := c.Handshake(); err != nil {
1126 return 0, err
1127 }
1128
1129 c.out.Lock()
1130 defer c.out.Unlock()
1131
1132 if err := c.out.err; err != nil {
1133 return 0, err
1134 }
1135
1136 if !c.handshakeComplete {
1137 return 0, alertInternalError
1138 }
1139
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001140 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001141 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001142 }
1143
Adam Langley95c29f32014-06-20 12:00:00 -07001144 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1145 // attack when using block mode ciphers due to predictable IVs.
1146 // This can be prevented by splitting each Application Data
1147 // record into two records, effectively randomizing the IV.
1148 //
1149 // http://www.openssl.org/~bodo/tls-cbc.txt
1150 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1151 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1152
1153 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001154 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001155 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1156 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1157 if err != nil {
1158 return n, c.out.setErrorLocked(err)
1159 }
1160 m, b = 1, b[1:]
1161 }
1162 }
1163
1164 n, err := c.writeRecord(recordTypeApplicationData, b)
1165 return n + m, c.out.setErrorLocked(err)
1166}
1167
Adam Langley2ae77d22014-10-28 17:29:33 -07001168func (c *Conn) handleRenegotiation() error {
1169 c.handshakeComplete = false
1170 if !c.isClient {
1171 panic("renegotiation should only happen for a client")
1172 }
1173
1174 msg, err := c.readHandshake()
1175 if err != nil {
1176 return err
1177 }
1178 _, ok := msg.(*helloRequestMsg)
1179 if !ok {
1180 c.sendAlert(alertUnexpectedMessage)
1181 return alertUnexpectedMessage
1182 }
1183
1184 return c.Handshake()
1185}
1186
Adam Langleycf2d4f42014-10-28 19:06:14 -07001187func (c *Conn) Renegotiate() error {
1188 if !c.isClient {
1189 helloReq := new(helloRequestMsg)
1190 c.writeRecord(recordTypeHandshake, helloReq.marshal())
1191 }
1192
1193 c.handshakeComplete = false
1194 return c.Handshake()
1195}
1196
Adam Langley95c29f32014-06-20 12:00:00 -07001197// Read can be made to time out and return a net.Error with Timeout() == true
1198// after a fixed time limit; see SetDeadline and SetReadDeadline.
1199func (c *Conn) Read(b []byte) (n int, err error) {
1200 if err = c.Handshake(); err != nil {
1201 return
1202 }
1203
1204 c.in.Lock()
1205 defer c.in.Unlock()
1206
1207 // Some OpenSSL servers send empty records in order to randomize the
1208 // CBC IV. So this loop ignores a limited number of empty records.
1209 const maxConsecutiveEmptyRecords = 100
1210 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1211 for c.input == nil && c.in.err == nil {
1212 if err := c.readRecord(recordTypeApplicationData); err != nil {
1213 // Soft error, like EAGAIN
1214 return 0, err
1215 }
David Benjamind9b091b2015-01-27 01:10:54 -05001216 if c.hand.Len() > 0 {
Adam Langley2ae77d22014-10-28 17:29:33 -07001217 // We received handshake bytes, indicating the
David Benjamind9b091b2015-01-27 01:10:54 -05001218 // start of a renegotiation.
Adam Langley2ae77d22014-10-28 17:29:33 -07001219 if err := c.handleRenegotiation(); err != nil {
1220 return 0, err
1221 }
1222 continue
1223 }
Adam Langley95c29f32014-06-20 12:00:00 -07001224 }
1225 if err := c.in.err; err != nil {
1226 return 0, err
1227 }
1228
1229 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001230 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001231 c.in.freeBlock(c.input)
1232 c.input = nil
1233 }
1234
1235 // If a close-notify alert is waiting, read it so that
1236 // we can return (n, EOF) instead of (n, nil), to signal
1237 // to the HTTP response reading goroutine that the
1238 // connection is now closed. This eliminates a race
1239 // where the HTTP response reading goroutine would
1240 // otherwise not observe the EOF until its next read,
1241 // by which time a client goroutine might have already
1242 // tried to reuse the HTTP connection for a new
1243 // request.
1244 // See https://codereview.appspot.com/76400046
1245 // and http://golang.org/issue/3514
1246 if ri := c.rawInput; ri != nil &&
1247 n != 0 && err == nil &&
1248 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1249 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1250 err = recErr // will be io.EOF on closeNotify
1251 }
1252 }
1253
1254 if n != 0 || err != nil {
1255 return n, err
1256 }
1257 }
1258
1259 return 0, io.ErrNoProgress
1260}
1261
1262// Close closes the connection.
1263func (c *Conn) Close() error {
1264 var alertErr error
1265
1266 c.handshakeMutex.Lock()
1267 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001268 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
Adam Langley95c29f32014-06-20 12:00:00 -07001269 alertErr = c.sendAlert(alertCloseNotify)
1270 }
1271
David Benjamin30789da2015-08-29 22:56:45 -04001272 // Consume a close_notify from the peer if one hasn't been received
1273 // already. This avoids the peer from failing |SSL_shutdown| due to a
1274 // write failing.
1275 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1276 for c.in.error() == nil {
1277 c.readRecord(recordTypeAlert)
1278 }
1279 if c.in.error() != io.EOF {
1280 alertErr = c.in.error()
1281 }
1282 }
1283
Adam Langley95c29f32014-06-20 12:00:00 -07001284 if err := c.conn.Close(); err != nil {
1285 return err
1286 }
1287 return alertErr
1288}
1289
1290// Handshake runs the client or server handshake
1291// protocol if it has not yet been run.
1292// Most uses of this package need not call Handshake
1293// explicitly: the first Read or Write will call it automatically.
1294func (c *Conn) Handshake() error {
1295 c.handshakeMutex.Lock()
1296 defer c.handshakeMutex.Unlock()
1297 if err := c.handshakeErr; err != nil {
1298 return err
1299 }
1300 if c.handshakeComplete {
1301 return nil
1302 }
1303
David Benjamin9a41d1b2015-05-16 01:30:09 -04001304 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1305 c.conn.Write([]byte{
1306 byte(recordTypeAlert), // type
1307 0xfe, 0xff, // version
1308 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1309 0x0, 0x2, // length
1310 })
1311 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1312 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001313 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1314 c.writeRecord(recordTypeApplicationData, data)
1315 }
Adam Langley95c29f32014-06-20 12:00:00 -07001316 if c.isClient {
1317 c.handshakeErr = c.clientHandshake()
1318 } else {
1319 c.handshakeErr = c.serverHandshake()
1320 }
David Benjaminddb9f152015-02-03 15:44:39 -05001321 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1322 c.writeRecord(recordType(42), []byte("invalid record"))
1323 }
Adam Langley95c29f32014-06-20 12:00:00 -07001324 return c.handshakeErr
1325}
1326
1327// ConnectionState returns basic TLS details about the connection.
1328func (c *Conn) ConnectionState() ConnectionState {
1329 c.handshakeMutex.Lock()
1330 defer c.handshakeMutex.Unlock()
1331
1332 var state ConnectionState
1333 state.HandshakeComplete = c.handshakeComplete
1334 if c.handshakeComplete {
1335 state.Version = c.vers
1336 state.NegotiatedProtocol = c.clientProtocol
1337 state.DidResume = c.didResume
1338 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001339 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001340 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001341 state.PeerCertificates = c.peerCertificates
1342 state.VerifiedChains = c.verifiedChains
1343 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001344 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001345 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001346 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001347 state.SCTList = c.sctList
Adam Langley95c29f32014-06-20 12:00:00 -07001348 }
1349
1350 return state
1351}
1352
1353// OCSPResponse returns the stapled OCSP response from the TLS server, if
1354// any. (Only valid for client connections.)
1355func (c *Conn) OCSPResponse() []byte {
1356 c.handshakeMutex.Lock()
1357 defer c.handshakeMutex.Unlock()
1358
1359 return c.ocspResponse
1360}
1361
1362// VerifyHostname checks that the peer certificate chain is valid for
1363// connecting to host. If so, it returns nil; if not, it returns an error
1364// describing the problem.
1365func (c *Conn) VerifyHostname(host string) error {
1366 c.handshakeMutex.Lock()
1367 defer c.handshakeMutex.Unlock()
1368 if !c.isClient {
1369 return errors.New("tls: VerifyHostname called on TLS server connection")
1370 }
1371 if !c.handshakeComplete {
1372 return errors.New("tls: handshake has not yet been performed")
1373 }
1374 return c.peerCertificates[0].VerifyHostname(host)
1375}
David Benjaminc565ebb2015-04-03 04:06:36 -04001376
1377// ExportKeyingMaterial exports keying material from the current connection
1378// state, as per RFC 5705.
1379func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1380 c.handshakeMutex.Lock()
1381 defer c.handshakeMutex.Unlock()
1382 if !c.handshakeComplete {
1383 return nil, errors.New("tls: handshake has not yet been performed")
1384 }
1385
1386 seedLen := len(c.clientRandom) + len(c.serverRandom)
1387 if useContext {
1388 seedLen += 2 + len(context)
1389 }
1390 seed := make([]byte, 0, seedLen)
1391 seed = append(seed, c.clientRandom[:]...)
1392 seed = append(seed, c.serverRandom[:]...)
1393 if useContext {
1394 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1395 seed = append(seed, context...)
1396 }
1397 result := make([]byte, length)
1398 prfForVersion(c.vers, c.cipherSuite)(result, c.masterSecret[:], label, seed)
1399 return result, nil
1400}