blob: adbc1c3dd55c0ee042b37c6404d72e8238de9452 [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"
15 "errors"
16 "fmt"
17 "io"
18 "net"
19 "sync"
20 "time"
21)
22
23// A Conn represents a secured connection.
24// It implements the net.Conn interface.
25type Conn struct {
26 // constant
27 conn net.Conn
David Benjamin83c0bc92014-08-04 01:23:53 -040028 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -070029 isClient bool
30
31 // constant after handshake; protected by handshakeMutex
Adam Langley75712922014-10-10 16:23:43 -070032 handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
33 handshakeErr error // error resulting from handshake
34 vers uint16 // TLS version
35 haveVers bool // version has been negotiated
36 config *Config // configuration passed to constructor
37 handshakeComplete bool
38 didResume bool // whether this connection was a session resumption
39 extendedMasterSecret bool // whether this session used an extended master secret
David Benjaminc565ebb2015-04-03 04:06:36 -040040 cipherSuite *cipherSuite
Adam Langley75712922014-10-10 16:23:43 -070041 ocspResponse []byte // stapled OCSP response
42 peerCertificates []*x509.Certificate
Adam Langley95c29f32014-06-20 12:00:00 -070043 // verifiedChains contains the certificate chains that we built, as
44 // opposed to the ones presented by the server.
45 verifiedChains [][]*x509.Certificate
46 // serverName contains the server name indicated by the client, if any.
Adam Langleyaf0e32c2015-06-03 09:57:23 -070047 serverName string
48 // firstFinished contains the first Finished hash sent during the
49 // handshake. This is the "tls-unique" channel binding value.
50 firstFinished [12]byte
51
David Benjaminc565ebb2015-04-03 04:06:36 -040052 clientRandom, serverRandom [32]byte
53 masterSecret [48]byte
Adam Langley95c29f32014-06-20 12:00:00 -070054
55 clientProtocol string
56 clientProtocolFallback bool
David Benjaminfc7b0862014-09-06 13:21:53 -040057 usedALPN bool
Adam Langley95c29f32014-06-20 12:00:00 -070058
Adam Langley2ae77d22014-10-28 17:29:33 -070059 // verify_data values for the renegotiation extension.
60 clientVerify []byte
61 serverVerify []byte
62
David Benjamind30a9902014-08-24 01:44:23 -040063 channelID *ecdsa.PublicKey
64
David Benjaminca6c8262014-11-15 19:06:08 -050065 srtpProtectionProfile uint16
66
David Benjaminc44b1df2014-11-23 12:11:01 -050067 clientVersion uint16
68
Adam Langley95c29f32014-06-20 12:00:00 -070069 // input/output
70 in, out halfConn // in.Mutex < out.Mutex
71 rawInput *block // raw input, right off the wire
David Benjamin83c0bc92014-08-04 01:23:53 -040072 input *block // application record waiting to be read
73 hand bytes.Buffer // handshake record waiting to be read
74
75 // DTLS state
76 sendHandshakeSeq uint16
77 recvHandshakeSeq uint16
David Benjaminb3774b92015-01-31 17:16:01 -050078 handMsg []byte // pending assembled handshake message
79 handMsgLen int // handshake message length, not including the header
80 pendingFragments [][]byte // pending outgoing handshake fragments.
Adam Langley95c29f32014-06-20 12:00:00 -070081
82 tmp [16]byte
83}
84
David Benjamin5e961c12014-11-07 01:48:35 -050085func (c *Conn) init() {
86 c.in.isDTLS = c.isDTLS
87 c.out.isDTLS = c.isDTLS
88 c.in.config = c.config
89 c.out.config = c.config
90}
91
Adam Langley95c29f32014-06-20 12:00:00 -070092// Access to net.Conn methods.
93// Cannot just embed net.Conn because that would
94// export the struct field too.
95
96// LocalAddr returns the local network address.
97func (c *Conn) LocalAddr() net.Addr {
98 return c.conn.LocalAddr()
99}
100
101// RemoteAddr returns the remote network address.
102func (c *Conn) RemoteAddr() net.Addr {
103 return c.conn.RemoteAddr()
104}
105
106// SetDeadline sets the read and write deadlines associated with the connection.
107// A zero value for t means Read and Write will not time out.
108// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
109func (c *Conn) SetDeadline(t time.Time) error {
110 return c.conn.SetDeadline(t)
111}
112
113// SetReadDeadline sets the read deadline on the underlying connection.
114// A zero value for t means Read will not time out.
115func (c *Conn) SetReadDeadline(t time.Time) error {
116 return c.conn.SetReadDeadline(t)
117}
118
119// SetWriteDeadline sets the write deadline on the underlying conneciton.
120// A zero value for t means Write will not time out.
121// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
122func (c *Conn) SetWriteDeadline(t time.Time) error {
123 return c.conn.SetWriteDeadline(t)
124}
125
126// A halfConn represents one direction of the record layer
127// connection, either sending or receiving.
128type halfConn struct {
129 sync.Mutex
130
David Benjamin83c0bc92014-08-04 01:23:53 -0400131 err error // first permanent error
132 version uint16 // protocol version
133 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -0700134 cipher interface{} // cipher algorithm
135 mac macFunction
136 seq [8]byte // 64-bit sequence number
137 bfree *block // list of free blocks
138
139 nextCipher interface{} // next encryption state
140 nextMac macFunction // next MAC algorithm
David Benjamin83f90402015-01-27 01:09:43 -0500141 nextSeq [6]byte // next epoch's starting sequence number in DTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700142
143 // used to save allocating a new buffer for each MAC.
144 inDigestBuf, outDigestBuf []byte
Adam Langley80842bd2014-06-20 12:00:00 -0700145
146 config *Config
Adam Langley95c29f32014-06-20 12:00:00 -0700147}
148
149func (hc *halfConn) setErrorLocked(err error) error {
150 hc.err = err
151 return err
152}
153
154func (hc *halfConn) error() error {
Adam Langley2ae77d22014-10-28 17:29:33 -0700155 // This should be locked, but I've removed it for the renegotiation
156 // tests since we don't concurrently read and write the same tls.Conn
157 // in any case during testing.
Adam Langley95c29f32014-06-20 12:00:00 -0700158 err := hc.err
Adam Langley95c29f32014-06-20 12:00:00 -0700159 return err
160}
161
162// prepareCipherSpec sets the encryption and MAC states
163// that a subsequent changeCipherSpec will use.
164func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
165 hc.version = version
166 hc.nextCipher = cipher
167 hc.nextMac = mac
168}
169
170// changeCipherSpec changes the encryption and MAC states
171// to the ones previously passed to prepareCipherSpec.
Adam Langley80842bd2014-06-20 12:00:00 -0700172func (hc *halfConn) changeCipherSpec(config *Config) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700173 if hc.nextCipher == nil {
174 return alertInternalError
175 }
176 hc.cipher = hc.nextCipher
177 hc.mac = hc.nextMac
178 hc.nextCipher = nil
179 hc.nextMac = nil
Adam Langley80842bd2014-06-20 12:00:00 -0700180 hc.config = config
David Benjamin83c0bc92014-08-04 01:23:53 -0400181 hc.incEpoch()
Adam Langley95c29f32014-06-20 12:00:00 -0700182 return nil
183}
184
185// incSeq increments the sequence number.
David Benjamin5e961c12014-11-07 01:48:35 -0500186func (hc *halfConn) incSeq(isOutgoing bool) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400187 limit := 0
David Benjamin5e961c12014-11-07 01:48:35 -0500188 increment := uint64(1)
David Benjamin83c0bc92014-08-04 01:23:53 -0400189 if hc.isDTLS {
190 // Increment up to the epoch in DTLS.
191 limit = 2
David Benjamin5e961c12014-11-07 01:48:35 -0500192
193 if isOutgoing && hc.config.Bugs.SequenceNumberIncrement != 0 {
194 increment = hc.config.Bugs.SequenceNumberIncrement
195 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400196 }
197 for i := 7; i >= limit; i-- {
David Benjamin5e961c12014-11-07 01:48:35 -0500198 increment += uint64(hc.seq[i])
199 hc.seq[i] = byte(increment)
200 increment >>= 8
Adam Langley95c29f32014-06-20 12:00:00 -0700201 }
202
203 // Not allowed to let sequence number wrap.
204 // Instead, must renegotiate before it does.
205 // Not likely enough to bother.
David Benjamin5e961c12014-11-07 01:48:35 -0500206 if increment != 0 {
207 panic("TLS: sequence number wraparound")
208 }
Adam Langley95c29f32014-06-20 12:00:00 -0700209}
210
David Benjamin83f90402015-01-27 01:09:43 -0500211// incNextSeq increments the starting sequence number for the next epoch.
212func (hc *halfConn) incNextSeq() {
213 for i := len(hc.nextSeq) - 1; i >= 0; i-- {
214 hc.nextSeq[i]++
215 if hc.nextSeq[i] != 0 {
216 return
217 }
218 }
219 panic("TLS: sequence number wraparound")
220}
221
222// incEpoch resets the sequence number. In DTLS, it also increments the epoch
223// half of the sequence number.
David Benjamin83c0bc92014-08-04 01:23:53 -0400224func (hc *halfConn) incEpoch() {
David Benjamin83c0bc92014-08-04 01:23:53 -0400225 if hc.isDTLS {
226 for i := 1; i >= 0; i-- {
227 hc.seq[i]++
228 if hc.seq[i] != 0 {
229 break
230 }
231 if i == 0 {
232 panic("TLS: epoch number wraparound")
233 }
234 }
David Benjamin83f90402015-01-27 01:09:43 -0500235 copy(hc.seq[2:], hc.nextSeq[:])
236 for i := range hc.nextSeq {
237 hc.nextSeq[i] = 0
238 }
239 } else {
240 for i := range hc.seq {
241 hc.seq[i] = 0
242 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400243 }
244}
245
246func (hc *halfConn) recordHeaderLen() int {
247 if hc.isDTLS {
248 return dtlsRecordHeaderLen
249 }
250 return tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700251}
252
253// removePadding returns an unpadded slice, in constant time, which is a prefix
254// of the input. It also returns a byte which is equal to 255 if the padding
255// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
256func removePadding(payload []byte) ([]byte, byte) {
257 if len(payload) < 1 {
258 return payload, 0
259 }
260
261 paddingLen := payload[len(payload)-1]
262 t := uint(len(payload)-1) - uint(paddingLen)
263 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
264 good := byte(int32(^t) >> 31)
265
266 toCheck := 255 // the maximum possible padding length
267 // The length of the padded data is public, so we can use an if here
268 if toCheck+1 > len(payload) {
269 toCheck = len(payload) - 1
270 }
271
272 for i := 0; i < toCheck; i++ {
273 t := uint(paddingLen) - uint(i)
274 // if i <= paddingLen then the MSB of t is zero
275 mask := byte(int32(^t) >> 31)
276 b := payload[len(payload)-1-i]
277 good &^= mask&paddingLen ^ mask&b
278 }
279
280 // We AND together the bits of good and replicate the result across
281 // all the bits.
282 good &= good << 4
283 good &= good << 2
284 good &= good << 1
285 good = uint8(int8(good) >> 7)
286
287 toRemove := good&paddingLen + 1
288 return payload[:len(payload)-int(toRemove)], good
289}
290
291// removePaddingSSL30 is a replacement for removePadding in the case that the
292// protocol version is SSLv3. In this version, the contents of the padding
293// are random and cannot be checked.
294func removePaddingSSL30(payload []byte) ([]byte, byte) {
295 if len(payload) < 1 {
296 return payload, 0
297 }
298
299 paddingLen := int(payload[len(payload)-1]) + 1
300 if paddingLen > len(payload) {
301 return payload, 0
302 }
303
304 return payload[:len(payload)-paddingLen], 255
305}
306
307func roundUp(a, b int) int {
308 return a + (b-a%b)%b
309}
310
311// cbcMode is an interface for block ciphers using cipher block chaining.
312type cbcMode interface {
313 cipher.BlockMode
314 SetIV([]byte)
315}
316
317// decrypt checks and strips the mac and decrypts the data in b. Returns a
318// success boolean, the number of bytes to skip from the start of the record in
319// order to get the application payload, and an optional alert value.
320func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, alertValue alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400321 recordHeaderLen := hc.recordHeaderLen()
322
Adam Langley95c29f32014-06-20 12:00:00 -0700323 // pull out payload
324 payload := b.data[recordHeaderLen:]
325
326 macSize := 0
327 if hc.mac != nil {
328 macSize = hc.mac.Size()
329 }
330
331 paddingGood := byte(255)
332 explicitIVLen := 0
333
David Benjamin83c0bc92014-08-04 01:23:53 -0400334 seq := hc.seq[:]
335 if hc.isDTLS {
336 // DTLS sequence numbers are explicit.
337 seq = b.data[3:11]
338 }
339
Adam Langley95c29f32014-06-20 12:00:00 -0700340 // decrypt
341 if hc.cipher != nil {
342 switch c := hc.cipher.(type) {
343 case cipher.Stream:
344 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400345 case *tlsAead:
346 nonce := seq
347 if c.explicitNonce {
348 explicitIVLen = 8
349 if len(payload) < explicitIVLen {
350 return false, 0, alertBadRecordMAC
351 }
352 nonce = payload[:8]
353 payload = payload[8:]
Adam Langley95c29f32014-06-20 12:00:00 -0700354 }
Adam Langley95c29f32014-06-20 12:00:00 -0700355
356 var additionalData [13]byte
David Benjamin83c0bc92014-08-04 01:23:53 -0400357 copy(additionalData[:], seq)
Adam Langley95c29f32014-06-20 12:00:00 -0700358 copy(additionalData[8:], b.data[:3])
359 n := len(payload) - c.Overhead()
360 additionalData[11] = byte(n >> 8)
361 additionalData[12] = byte(n)
362 var err error
363 payload, err = c.Open(payload[:0], nonce, payload, additionalData[:])
364 if err != nil {
365 return false, 0, alertBadRecordMAC
366 }
367 b.resize(recordHeaderLen + explicitIVLen + len(payload))
368 case cbcMode:
369 blockSize := c.BlockSize()
David Benjamin83c0bc92014-08-04 01:23:53 -0400370 if hc.version >= VersionTLS11 || hc.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700371 explicitIVLen = blockSize
372 }
373
374 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
375 return false, 0, alertBadRecordMAC
376 }
377
378 if explicitIVLen > 0 {
379 c.SetIV(payload[:explicitIVLen])
380 payload = payload[explicitIVLen:]
381 }
382 c.CryptBlocks(payload, payload)
383 if hc.version == VersionSSL30 {
384 payload, paddingGood = removePaddingSSL30(payload)
385 } else {
386 payload, paddingGood = removePadding(payload)
387 }
388 b.resize(recordHeaderLen + explicitIVLen + len(payload))
389
390 // note that we still have a timing side-channel in the
391 // MAC check, below. An attacker can align the record
392 // so that a correct padding will cause one less hash
393 // block to be calculated. Then they can iteratively
394 // decrypt a record by breaking each byte. See
395 // "Password Interception in a SSL/TLS Channel", Brice
396 // Canvel et al.
397 //
398 // However, our behavior matches OpenSSL, so we leak
399 // only as much as they do.
400 default:
401 panic("unknown cipher type")
402 }
403 }
404
405 // check, strip mac
406 if hc.mac != nil {
407 if len(payload) < macSize {
408 return false, 0, alertBadRecordMAC
409 }
410
411 // strip mac off payload, b.data
412 n := len(payload) - macSize
David Benjamin83c0bc92014-08-04 01:23:53 -0400413 b.data[recordHeaderLen-2] = byte(n >> 8)
414 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700415 b.resize(recordHeaderLen + explicitIVLen + n)
416 remoteMAC := payload[n:]
David Benjamin83c0bc92014-08-04 01:23:53 -0400417 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
Adam Langley95c29f32014-06-20 12:00:00 -0700418
419 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
420 return false, 0, alertBadRecordMAC
421 }
422 hc.inDigestBuf = localMAC
423 }
David Benjamin5e961c12014-11-07 01:48:35 -0500424 hc.incSeq(false)
Adam Langley95c29f32014-06-20 12:00:00 -0700425
426 return true, recordHeaderLen + explicitIVLen, 0
427}
428
429// padToBlockSize calculates the needed padding block, if any, for a payload.
430// On exit, prefix aliases payload and extends to the end of the last full
431// block of payload. finalBlock is a fresh slice which contains the contents of
432// any suffix of payload as well as the needed padding to make finalBlock a
433// full block.
Adam Langley80842bd2014-06-20 12:00:00 -0700434func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
Adam Langley95c29f32014-06-20 12:00:00 -0700435 overrun := len(payload) % blockSize
Adam Langley95c29f32014-06-20 12:00:00 -0700436 prefix = payload[:len(payload)-overrun]
Adam Langley80842bd2014-06-20 12:00:00 -0700437
438 paddingLen := blockSize - overrun
439 finalSize := blockSize
440 if config.Bugs.MaxPadding {
441 for paddingLen+blockSize <= 256 {
442 paddingLen += blockSize
443 }
444 finalSize = 256
445 }
446 finalBlock = make([]byte, finalSize)
447 for i := range finalBlock {
Adam Langley95c29f32014-06-20 12:00:00 -0700448 finalBlock[i] = byte(paddingLen - 1)
449 }
Adam Langley80842bd2014-06-20 12:00:00 -0700450 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
451 finalBlock[overrun] ^= 0xff
452 }
453 copy(finalBlock, payload[len(payload)-overrun:])
Adam Langley95c29f32014-06-20 12:00:00 -0700454 return
455}
456
457// encrypt encrypts and macs the data in b.
458func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400459 recordHeaderLen := hc.recordHeaderLen()
460
Adam Langley95c29f32014-06-20 12:00:00 -0700461 // mac
462 if hc.mac != nil {
David Benjamin83c0bc92014-08-04 01:23:53 -0400463 mac := hc.mac.MAC(hc.outDigestBuf, hc.seq[0:], b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], b.data[recordHeaderLen+explicitIVLen:])
Adam Langley95c29f32014-06-20 12:00:00 -0700464
465 n := len(b.data)
466 b.resize(n + len(mac))
467 copy(b.data[n:], mac)
468 hc.outDigestBuf = mac
469 }
470
471 payload := b.data[recordHeaderLen:]
472
473 // encrypt
474 if hc.cipher != nil {
475 switch c := hc.cipher.(type) {
476 case cipher.Stream:
477 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400478 case *tlsAead:
Adam Langley95c29f32014-06-20 12:00:00 -0700479 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
480 b.resize(len(b.data) + c.Overhead())
David Benjamine9a80ff2015-04-07 00:46:46 -0400481 nonce := hc.seq[:]
482 if c.explicitNonce {
483 nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
484 }
Adam Langley95c29f32014-06-20 12:00:00 -0700485 payload := b.data[recordHeaderLen+explicitIVLen:]
486 payload = payload[:payloadLen]
487
488 var additionalData [13]byte
489 copy(additionalData[:], hc.seq[:])
490 copy(additionalData[8:], b.data[:3])
491 additionalData[11] = byte(payloadLen >> 8)
492 additionalData[12] = byte(payloadLen)
493
494 c.Seal(payload[:0], nonce, payload, additionalData[:])
495 case cbcMode:
496 blockSize := c.BlockSize()
497 if explicitIVLen > 0 {
498 c.SetIV(payload[:explicitIVLen])
499 payload = payload[explicitIVLen:]
500 }
Adam Langley80842bd2014-06-20 12:00:00 -0700501 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700502 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
503 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
504 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
505 default:
506 panic("unknown cipher type")
507 }
508 }
509
510 // update length to include MAC and any block padding needed.
511 n := len(b.data) - recordHeaderLen
David Benjamin83c0bc92014-08-04 01:23:53 -0400512 b.data[recordHeaderLen-2] = byte(n >> 8)
513 b.data[recordHeaderLen-1] = byte(n)
David Benjamin5e961c12014-11-07 01:48:35 -0500514 hc.incSeq(true)
Adam Langley95c29f32014-06-20 12:00:00 -0700515
516 return true, 0
517}
518
519// A block is a simple data buffer.
520type block struct {
521 data []byte
522 off int // index for Read
523 link *block
524}
525
526// resize resizes block to be n bytes, growing if necessary.
527func (b *block) resize(n int) {
528 if n > cap(b.data) {
529 b.reserve(n)
530 }
531 b.data = b.data[0:n]
532}
533
534// reserve makes sure that block contains a capacity of at least n bytes.
535func (b *block) reserve(n int) {
536 if cap(b.data) >= n {
537 return
538 }
539 m := cap(b.data)
540 if m == 0 {
541 m = 1024
542 }
543 for m < n {
544 m *= 2
545 }
546 data := make([]byte, len(b.data), m)
547 copy(data, b.data)
548 b.data = data
549}
550
551// readFromUntil reads from r into b until b contains at least n bytes
552// or else returns an error.
553func (b *block) readFromUntil(r io.Reader, n int) error {
554 // quick case
555 if len(b.data) >= n {
556 return nil
557 }
558
559 // read until have enough.
560 b.reserve(n)
561 for {
562 m, err := r.Read(b.data[len(b.data):cap(b.data)])
563 b.data = b.data[0 : len(b.data)+m]
564 if len(b.data) >= n {
565 // TODO(bradfitz,agl): slightly suspicious
566 // that we're throwing away r.Read's err here.
567 break
568 }
569 if err != nil {
570 return err
571 }
572 }
573 return nil
574}
575
576func (b *block) Read(p []byte) (n int, err error) {
577 n = copy(p, b.data[b.off:])
578 b.off += n
579 return
580}
581
582// newBlock allocates a new block, from hc's free list if possible.
583func (hc *halfConn) newBlock() *block {
584 b := hc.bfree
585 if b == nil {
586 return new(block)
587 }
588 hc.bfree = b.link
589 b.link = nil
590 b.resize(0)
591 return b
592}
593
594// freeBlock returns a block to hc's free list.
595// The protocol is such that each side only has a block or two on
596// its free list at a time, so there's no need to worry about
597// trimming the list, etc.
598func (hc *halfConn) freeBlock(b *block) {
599 b.link = hc.bfree
600 hc.bfree = b
601}
602
603// splitBlock splits a block after the first n bytes,
604// returning a block with those n bytes and a
605// block with the remainder. the latter may be nil.
606func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
607 if len(b.data) <= n {
608 return b, nil
609 }
610 bb := hc.newBlock()
611 bb.resize(len(b.data) - n)
612 copy(bb.data, b.data[n:])
613 b.data = b.data[0:n]
614 return b, bb
615}
616
David Benjamin83c0bc92014-08-04 01:23:53 -0400617func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
618 if c.isDTLS {
619 return c.dtlsDoReadRecord(want)
620 }
621
622 recordHeaderLen := tlsRecordHeaderLen
623
624 if c.rawInput == nil {
625 c.rawInput = c.in.newBlock()
626 }
627 b := c.rawInput
628
629 // Read header, payload.
630 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
631 // RFC suggests that EOF without an alertCloseNotify is
632 // an error, but popular web sites seem to do this,
633 // so we can't make it an error.
634 // if err == io.EOF {
635 // err = io.ErrUnexpectedEOF
636 // }
637 if e, ok := err.(net.Error); !ok || !e.Temporary() {
638 c.in.setErrorLocked(err)
639 }
640 return 0, nil, err
641 }
642 typ := recordType(b.data[0])
643
644 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
645 // start with a uint16 length where the MSB is set and the first record
646 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
647 // an SSLv2 client.
648 if want == recordTypeHandshake && typ == 0x80 {
649 c.sendAlert(alertProtocolVersion)
650 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
651 }
652
653 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
654 n := int(b.data[3])<<8 | int(b.data[4])
David Benjamin1e29a6b2014-12-10 02:27:24 -0500655 if c.haveVers {
656 if vers != c.vers {
657 c.sendAlert(alertProtocolVersion)
658 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers))
659 }
660 } else {
661 if expect := c.config.Bugs.ExpectInitialRecordVersion; expect != 0 && vers != expect {
662 c.sendAlert(alertProtocolVersion)
663 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
664 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400665 }
666 if n > maxCiphertext {
667 c.sendAlert(alertRecordOverflow)
668 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
669 }
670 if !c.haveVers {
671 // First message, be extra suspicious:
672 // this might not be a TLS client.
673 // Bail out before reading a full 'body', if possible.
674 // The current max version is 3.1.
675 // If the version is >= 16.0, it's probably not real.
676 // Similarly, a clientHello message encodes in
677 // well under a kilobyte. If the length is >= 12 kB,
678 // it's probably not real.
679 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
680 c.sendAlert(alertUnexpectedMessage)
681 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
682 }
683 }
684 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
685 if err == io.EOF {
686 err = io.ErrUnexpectedEOF
687 }
688 if e, ok := err.(net.Error); !ok || !e.Temporary() {
689 c.in.setErrorLocked(err)
690 }
691 return 0, nil, err
692 }
693
694 // Process message.
695 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
696 ok, off, err := c.in.decrypt(b)
697 if !ok {
698 c.in.setErrorLocked(c.sendAlert(err))
699 }
700 b.off = off
701 return typ, b, nil
702}
703
Adam Langley95c29f32014-06-20 12:00:00 -0700704// readRecord reads the next TLS record from the connection
705// and updates the record layer state.
706// c.in.Mutex <= L; c.input == nil.
707func (c *Conn) readRecord(want recordType) error {
708 // Caller must be in sync with connection:
709 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700710 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700711 switch want {
712 default:
713 c.sendAlert(alertInternalError)
714 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
715 case recordTypeHandshake, recordTypeChangeCipherSpec:
716 if c.handshakeComplete {
717 c.sendAlert(alertInternalError)
718 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
719 }
720 case recordTypeApplicationData:
David Benjamine58c4f52014-08-24 03:47:07 -0400721 if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart {
Adam Langley95c29f32014-06-20 12:00:00 -0700722 c.sendAlert(alertInternalError)
723 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
724 }
725 }
726
727Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400728 typ, b, err := c.doReadRecord(want)
729 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700730 return err
731 }
Adam Langley95c29f32014-06-20 12:00:00 -0700732 data := b.data[b.off:]
733 if len(data) > maxPlaintext {
734 err := c.sendAlert(alertRecordOverflow)
735 c.in.freeBlock(b)
736 return c.in.setErrorLocked(err)
737 }
738
739 switch typ {
740 default:
741 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
742
743 case recordTypeAlert:
744 if len(data) != 2 {
745 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
746 break
747 }
748 if alert(data[1]) == alertCloseNotify {
749 c.in.setErrorLocked(io.EOF)
750 break
751 }
752 switch data[0] {
753 case alertLevelWarning:
754 // drop on the floor
755 c.in.freeBlock(b)
756 goto Again
757 case alertLevelError:
758 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
759 default:
760 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
761 }
762
763 case recordTypeChangeCipherSpec:
764 if typ != want || len(data) != 1 || data[0] != 1 {
765 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
766 break
767 }
Adam Langley80842bd2014-06-20 12:00:00 -0700768 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700769 if err != nil {
770 c.in.setErrorLocked(c.sendAlert(err.(alert)))
771 }
772
773 case recordTypeApplicationData:
774 if typ != want {
775 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
776 break
777 }
778 c.input = b
779 b = nil
780
781 case recordTypeHandshake:
782 // TODO(rsc): Should at least pick off connection close.
783 if typ != want {
Adam Langley2ae77d22014-10-28 17:29:33 -0700784 // A client might need to process a HelloRequest from
785 // the server, thus receiving a handshake message when
David Benjamind9b091b2015-01-27 01:10:54 -0500786 // application data is expected is ok.
787 if !c.isClient {
Adam Langley2ae77d22014-10-28 17:29:33 -0700788 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
789 }
Adam Langley95c29f32014-06-20 12:00:00 -0700790 }
791 c.hand.Write(data)
792 }
793
794 if b != nil {
795 c.in.freeBlock(b)
796 }
797 return c.in.err
798}
799
800// sendAlert sends a TLS alert message.
801// c.out.Mutex <= L.
802func (c *Conn) sendAlertLocked(err alert) error {
803 switch err {
804 case alertNoRenegotiation, alertCloseNotify:
805 c.tmp[0] = alertLevelWarning
806 default:
807 c.tmp[0] = alertLevelError
808 }
809 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400810 if c.config.Bugs.FragmentAlert {
811 c.writeRecord(recordTypeAlert, c.tmp[0:1])
812 c.writeRecord(recordTypeAlert, c.tmp[1:2])
813 } else {
814 c.writeRecord(recordTypeAlert, c.tmp[0:2])
815 }
Adam Langley95c29f32014-06-20 12:00:00 -0700816 // closeNotify is a special case in that it isn't an error:
817 if err != alertCloseNotify {
818 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
819 }
820 return nil
821}
822
823// sendAlert sends a TLS alert message.
824// L < c.out.Mutex.
825func (c *Conn) sendAlert(err alert) error {
826 c.out.Lock()
827 defer c.out.Unlock()
828 return c.sendAlertLocked(err)
829}
830
David Benjamind86c7672014-08-02 04:07:12 -0400831// writeV2Record writes a record for a V2ClientHello.
832func (c *Conn) writeV2Record(data []byte) (n int, err error) {
833 record := make([]byte, 2+len(data))
834 record[0] = uint8(len(data)>>8) | 0x80
835 record[1] = uint8(len(data))
836 copy(record[2:], data)
837 return c.conn.Write(record)
838}
839
Adam Langley95c29f32014-06-20 12:00:00 -0700840// writeRecord writes a TLS record with the given type and payload
841// to the connection and updates the record layer state.
842// c.out.Mutex <= L.
843func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin340d5ed2015-03-21 02:21:37 -0400844 if typ != recordTypeAlert && c.config.Bugs.SendWarningAlerts != 0 {
845 alert := make([]byte, 2)
846 alert[0] = alertLevelWarning
847 alert[1] = byte(c.config.Bugs.SendWarningAlerts)
848 c.writeRecord(recordTypeAlert, alert)
849 }
850
David Benjamin83c0bc92014-08-04 01:23:53 -0400851 if c.isDTLS {
852 return c.dtlsWriteRecord(typ, data)
853 }
854
855 recordHeaderLen := tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700856 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -0400857 first := true
858 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
Adam Langley95c29f32014-06-20 12:00:00 -0700859 for len(data) > 0 {
860 m := len(data)
861 if m > maxPlaintext {
862 m = maxPlaintext
863 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400864 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
865 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -0400866 // By default, do not fragment the client_version or
867 // server_version, which are located in the first 6
868 // bytes.
869 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
870 m = 6
871 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400872 }
Adam Langley95c29f32014-06-20 12:00:00 -0700873 explicitIVLen := 0
874 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -0400875 first = false
Adam Langley95c29f32014-06-20 12:00:00 -0700876
877 var cbc cbcMode
878 if c.out.version >= VersionTLS11 {
879 var ok bool
880 if cbc, ok = c.out.cipher.(cbcMode); ok {
881 explicitIVLen = cbc.BlockSize()
882 }
883 }
884 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -0400885 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -0700886 explicitIVLen = 8
887 // The AES-GCM construction in TLS has an
888 // explicit nonce so that the nonce can be
889 // random. However, the nonce is only 8 bytes
890 // which is too small for a secure, random
891 // nonce. Therefore we use the sequence number
892 // as the nonce.
893 explicitIVIsSeq = true
894 }
895 }
896 b.resize(recordHeaderLen + explicitIVLen + m)
897 b.data[0] = byte(typ)
898 vers := c.vers
899 if vers == 0 {
900 // Some TLS servers fail if the record version is
901 // greater than TLS 1.0 for the initial ClientHello.
902 vers = VersionTLS10
903 }
904 b.data[1] = byte(vers >> 8)
905 b.data[2] = byte(vers)
906 b.data[3] = byte(m >> 8)
907 b.data[4] = byte(m)
908 if explicitIVLen > 0 {
909 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
910 if explicitIVIsSeq {
911 copy(explicitIV, c.out.seq[:])
912 } else {
913 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
914 break
915 }
916 }
917 }
918 copy(b.data[recordHeaderLen+explicitIVLen:], data)
919 c.out.encrypt(b, explicitIVLen)
920 _, err = c.conn.Write(b.data)
921 if err != nil {
922 break
923 }
924 n += m
925 data = data[m:]
926 }
927 c.out.freeBlock(b)
928
929 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -0700930 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700931 if err != nil {
932 // Cannot call sendAlert directly,
933 // because we already hold c.out.Mutex.
934 c.tmp[0] = alertLevelError
935 c.tmp[1] = byte(err.(alert))
936 c.writeRecord(recordTypeAlert, c.tmp[0:2])
937 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
938 }
939 }
940 return
941}
942
David Benjamin83c0bc92014-08-04 01:23:53 -0400943func (c *Conn) doReadHandshake() ([]byte, error) {
944 if c.isDTLS {
945 return c.dtlsDoReadHandshake()
946 }
947
Adam Langley95c29f32014-06-20 12:00:00 -0700948 for c.hand.Len() < 4 {
949 if err := c.in.err; err != nil {
950 return nil, err
951 }
952 if err := c.readRecord(recordTypeHandshake); err != nil {
953 return nil, err
954 }
955 }
956
957 data := c.hand.Bytes()
958 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
959 if n > maxHandshake {
960 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
961 }
962 for c.hand.Len() < 4+n {
963 if err := c.in.err; err != nil {
964 return nil, err
965 }
966 if err := c.readRecord(recordTypeHandshake); err != nil {
967 return nil, err
968 }
969 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400970 return c.hand.Next(4 + n), nil
971}
972
973// readHandshake reads the next handshake message from
974// the record layer.
975// c.in.Mutex < L; c.out.Mutex < L.
976func (c *Conn) readHandshake() (interface{}, error) {
977 data, err := c.doReadHandshake()
978 if err != nil {
979 return nil, err
980 }
981
Adam Langley95c29f32014-06-20 12:00:00 -0700982 var m handshakeMessage
983 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -0700984 case typeHelloRequest:
985 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -0700986 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -0400987 m = &clientHelloMsg{
988 isDTLS: c.isDTLS,
989 }
Adam Langley95c29f32014-06-20 12:00:00 -0700990 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -0400991 m = &serverHelloMsg{
992 isDTLS: c.isDTLS,
993 }
Adam Langley95c29f32014-06-20 12:00:00 -0700994 case typeNewSessionTicket:
995 m = new(newSessionTicketMsg)
996 case typeCertificate:
997 m = new(certificateMsg)
998 case typeCertificateRequest:
999 m = &certificateRequestMsg{
1000 hasSignatureAndHash: c.vers >= VersionTLS12,
1001 }
1002 case typeCertificateStatus:
1003 m = new(certificateStatusMsg)
1004 case typeServerKeyExchange:
1005 m = new(serverKeyExchangeMsg)
1006 case typeServerHelloDone:
1007 m = new(serverHelloDoneMsg)
1008 case typeClientKeyExchange:
1009 m = new(clientKeyExchangeMsg)
1010 case typeCertificateVerify:
1011 m = &certificateVerifyMsg{
1012 hasSignatureAndHash: c.vers >= VersionTLS12,
1013 }
1014 case typeNextProtocol:
1015 m = new(nextProtoMsg)
1016 case typeFinished:
1017 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001018 case typeHelloVerifyRequest:
1019 m = new(helloVerifyRequestMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001020 case typeEncryptedExtensions:
1021 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001022 default:
1023 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1024 }
1025
1026 // The handshake message unmarshallers
1027 // expect to be able to keep references to data,
1028 // so pass in a fresh copy that won't be overwritten.
1029 data = append([]byte(nil), data...)
1030
1031 if !m.unmarshal(data) {
1032 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1033 }
1034 return m, nil
1035}
1036
David Benjamin83f90402015-01-27 01:09:43 -05001037// skipPacket processes all the DTLS records in packet. It updates
1038// sequence number expectations but otherwise ignores them.
1039func (c *Conn) skipPacket(packet []byte) error {
1040 for len(packet) > 0 {
1041 // Dropped packets are completely ignored save to update
1042 // expected sequence numbers for this and the next epoch. (We
1043 // don't assert on the contents of the packets both for
1044 // simplicity and because a previous test with one shorter
1045 // timeout schedule would have done so.)
1046 epoch := packet[3:5]
1047 seq := packet[5:11]
1048 length := uint16(packet[11])<<8 | uint16(packet[12])
1049 if bytes.Equal(c.in.seq[:2], epoch) {
1050 if !bytes.Equal(c.in.seq[2:], seq) {
1051 return errors.New("tls: sequence mismatch")
1052 }
1053 c.in.incSeq(false)
1054 } else {
1055 if !bytes.Equal(c.in.nextSeq[:], seq) {
1056 return errors.New("tls: sequence mismatch")
1057 }
1058 c.in.incNextSeq()
1059 }
1060 packet = packet[13+length:]
1061 }
1062 return nil
1063}
1064
1065// simulatePacketLoss simulates the loss of a handshake leg from the
1066// peer based on the schedule in c.config.Bugs. If resendFunc is
1067// non-nil, it is called after each simulated timeout to retransmit
1068// handshake messages from the local end. This is used in cases where
1069// the peer retransmits on a stale Finished rather than a timeout.
1070func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1071 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1072 return nil
1073 }
1074 if !c.isDTLS {
1075 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1076 }
1077 if c.config.Bugs.PacketAdaptor == nil {
1078 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1079 }
1080 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1081 // Simulate a timeout.
1082 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1083 if err != nil {
1084 return err
1085 }
1086 for _, packet := range packets {
1087 if err := c.skipPacket(packet); err != nil {
1088 return err
1089 }
1090 }
1091 if resendFunc != nil {
1092 resendFunc()
1093 }
1094 }
1095 return nil
1096}
1097
Adam Langley95c29f32014-06-20 12:00:00 -07001098// Write writes data to the connection.
1099func (c *Conn) Write(b []byte) (int, error) {
1100 if err := c.Handshake(); err != nil {
1101 return 0, err
1102 }
1103
1104 c.out.Lock()
1105 defer c.out.Unlock()
1106
1107 if err := c.out.err; err != nil {
1108 return 0, err
1109 }
1110
1111 if !c.handshakeComplete {
1112 return 0, alertInternalError
1113 }
1114
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001115 if c.config.Bugs.SendSpuriousAlert != 0 {
1116 c.sendAlertLocked(c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001117 }
1118
Adam Langley95c29f32014-06-20 12:00:00 -07001119 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1120 // attack when using block mode ciphers due to predictable IVs.
1121 // This can be prevented by splitting each Application Data
1122 // record into two records, effectively randomizing the IV.
1123 //
1124 // http://www.openssl.org/~bodo/tls-cbc.txt
1125 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1126 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1127
1128 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001129 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001130 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1131 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1132 if err != nil {
1133 return n, c.out.setErrorLocked(err)
1134 }
1135 m, b = 1, b[1:]
1136 }
1137 }
1138
1139 n, err := c.writeRecord(recordTypeApplicationData, b)
1140 return n + m, c.out.setErrorLocked(err)
1141}
1142
Adam Langley2ae77d22014-10-28 17:29:33 -07001143func (c *Conn) handleRenegotiation() error {
1144 c.handshakeComplete = false
1145 if !c.isClient {
1146 panic("renegotiation should only happen for a client")
1147 }
1148
1149 msg, err := c.readHandshake()
1150 if err != nil {
1151 return err
1152 }
1153 _, ok := msg.(*helloRequestMsg)
1154 if !ok {
1155 c.sendAlert(alertUnexpectedMessage)
1156 return alertUnexpectedMessage
1157 }
1158
1159 return c.Handshake()
1160}
1161
Adam Langleycf2d4f42014-10-28 19:06:14 -07001162func (c *Conn) Renegotiate() error {
1163 if !c.isClient {
1164 helloReq := new(helloRequestMsg)
1165 c.writeRecord(recordTypeHandshake, helloReq.marshal())
1166 }
1167
1168 c.handshakeComplete = false
1169 return c.Handshake()
1170}
1171
Adam Langley95c29f32014-06-20 12:00:00 -07001172// Read can be made to time out and return a net.Error with Timeout() == true
1173// after a fixed time limit; see SetDeadline and SetReadDeadline.
1174func (c *Conn) Read(b []byte) (n int, err error) {
1175 if err = c.Handshake(); err != nil {
1176 return
1177 }
1178
1179 c.in.Lock()
1180 defer c.in.Unlock()
1181
1182 // Some OpenSSL servers send empty records in order to randomize the
1183 // CBC IV. So this loop ignores a limited number of empty records.
1184 const maxConsecutiveEmptyRecords = 100
1185 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1186 for c.input == nil && c.in.err == nil {
1187 if err := c.readRecord(recordTypeApplicationData); err != nil {
1188 // Soft error, like EAGAIN
1189 return 0, err
1190 }
David Benjamind9b091b2015-01-27 01:10:54 -05001191 if c.hand.Len() > 0 {
Adam Langley2ae77d22014-10-28 17:29:33 -07001192 // We received handshake bytes, indicating the
David Benjamind9b091b2015-01-27 01:10:54 -05001193 // start of a renegotiation.
Adam Langley2ae77d22014-10-28 17:29:33 -07001194 if err := c.handleRenegotiation(); err != nil {
1195 return 0, err
1196 }
1197 continue
1198 }
Adam Langley95c29f32014-06-20 12:00:00 -07001199 }
1200 if err := c.in.err; err != nil {
1201 return 0, err
1202 }
1203
1204 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001205 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001206 c.in.freeBlock(c.input)
1207 c.input = nil
1208 }
1209
1210 // If a close-notify alert is waiting, read it so that
1211 // we can return (n, EOF) instead of (n, nil), to signal
1212 // to the HTTP response reading goroutine that the
1213 // connection is now closed. This eliminates a race
1214 // where the HTTP response reading goroutine would
1215 // otherwise not observe the EOF until its next read,
1216 // by which time a client goroutine might have already
1217 // tried to reuse the HTTP connection for a new
1218 // request.
1219 // See https://codereview.appspot.com/76400046
1220 // and http://golang.org/issue/3514
1221 if ri := c.rawInput; ri != nil &&
1222 n != 0 && err == nil &&
1223 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1224 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1225 err = recErr // will be io.EOF on closeNotify
1226 }
1227 }
1228
1229 if n != 0 || err != nil {
1230 return n, err
1231 }
1232 }
1233
1234 return 0, io.ErrNoProgress
1235}
1236
1237// Close closes the connection.
1238func (c *Conn) Close() error {
1239 var alertErr error
1240
1241 c.handshakeMutex.Lock()
1242 defer c.handshakeMutex.Unlock()
1243 if c.handshakeComplete {
1244 alertErr = c.sendAlert(alertCloseNotify)
1245 }
1246
1247 if err := c.conn.Close(); err != nil {
1248 return err
1249 }
1250 return alertErr
1251}
1252
1253// Handshake runs the client or server handshake
1254// protocol if it has not yet been run.
1255// Most uses of this package need not call Handshake
1256// explicitly: the first Read or Write will call it automatically.
1257func (c *Conn) Handshake() error {
1258 c.handshakeMutex.Lock()
1259 defer c.handshakeMutex.Unlock()
1260 if err := c.handshakeErr; err != nil {
1261 return err
1262 }
1263 if c.handshakeComplete {
1264 return nil
1265 }
1266
David Benjamin9a41d1b2015-05-16 01:30:09 -04001267 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1268 c.conn.Write([]byte{
1269 byte(recordTypeAlert), // type
1270 0xfe, 0xff, // version
1271 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1272 0x0, 0x2, // length
1273 })
1274 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1275 }
Adam Langley95c29f32014-06-20 12:00:00 -07001276 if c.isClient {
1277 c.handshakeErr = c.clientHandshake()
1278 } else {
1279 c.handshakeErr = c.serverHandshake()
1280 }
David Benjaminddb9f152015-02-03 15:44:39 -05001281 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1282 c.writeRecord(recordType(42), []byte("invalid record"))
1283 }
Adam Langley95c29f32014-06-20 12:00:00 -07001284 return c.handshakeErr
1285}
1286
1287// ConnectionState returns basic TLS details about the connection.
1288func (c *Conn) ConnectionState() ConnectionState {
1289 c.handshakeMutex.Lock()
1290 defer c.handshakeMutex.Unlock()
1291
1292 var state ConnectionState
1293 state.HandshakeComplete = c.handshakeComplete
1294 if c.handshakeComplete {
1295 state.Version = c.vers
1296 state.NegotiatedProtocol = c.clientProtocol
1297 state.DidResume = c.didResume
1298 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001299 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001300 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001301 state.PeerCertificates = c.peerCertificates
1302 state.VerifiedChains = c.verifiedChains
1303 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001304 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001305 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001306 state.TLSUnique = c.firstFinished[:]
Adam Langley95c29f32014-06-20 12:00:00 -07001307 }
1308
1309 return state
1310}
1311
1312// OCSPResponse returns the stapled OCSP response from the TLS server, if
1313// any. (Only valid for client connections.)
1314func (c *Conn) OCSPResponse() []byte {
1315 c.handshakeMutex.Lock()
1316 defer c.handshakeMutex.Unlock()
1317
1318 return c.ocspResponse
1319}
1320
1321// VerifyHostname checks that the peer certificate chain is valid for
1322// connecting to host. If so, it returns nil; if not, it returns an error
1323// describing the problem.
1324func (c *Conn) VerifyHostname(host string) error {
1325 c.handshakeMutex.Lock()
1326 defer c.handshakeMutex.Unlock()
1327 if !c.isClient {
1328 return errors.New("tls: VerifyHostname called on TLS server connection")
1329 }
1330 if !c.handshakeComplete {
1331 return errors.New("tls: handshake has not yet been performed")
1332 }
1333 return c.peerCertificates[0].VerifyHostname(host)
1334}
David Benjaminc565ebb2015-04-03 04:06:36 -04001335
1336// ExportKeyingMaterial exports keying material from the current connection
1337// state, as per RFC 5705.
1338func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1339 c.handshakeMutex.Lock()
1340 defer c.handshakeMutex.Unlock()
1341 if !c.handshakeComplete {
1342 return nil, errors.New("tls: handshake has not yet been performed")
1343 }
1344
1345 seedLen := len(c.clientRandom) + len(c.serverRandom)
1346 if useContext {
1347 seedLen += 2 + len(context)
1348 }
1349 seed := make([]byte, 0, seedLen)
1350 seed = append(seed, c.clientRandom[:]...)
1351 seed = append(seed, c.serverRandom[:]...)
1352 if useContext {
1353 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1354 seed = append(seed, context...)
1355 }
1356 result := make([]byte, length)
1357 prfForVersion(c.vers, c.cipherSuite)(result, c.masterSecret[:], label, seed)
1358 return result, nil
1359}