blob: fd198ca64b068a14561a01c87bb7c9fd5358b363 [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.
David Benjaminc565ebb2015-04-03 04:06:36 -040047 serverName string
48 clientRandom, serverRandom [32]byte
49 masterSecret [48]byte
Adam Langley95c29f32014-06-20 12:00:00 -070050
51 clientProtocol string
52 clientProtocolFallback bool
David Benjaminfc7b0862014-09-06 13:21:53 -040053 usedALPN bool
Adam Langley95c29f32014-06-20 12:00:00 -070054
Adam Langley2ae77d22014-10-28 17:29:33 -070055 // verify_data values for the renegotiation extension.
56 clientVerify []byte
57 serverVerify []byte
58
David Benjamind30a9902014-08-24 01:44:23 -040059 channelID *ecdsa.PublicKey
60
David Benjaminca6c8262014-11-15 19:06:08 -050061 srtpProtectionProfile uint16
62
David Benjaminc44b1df2014-11-23 12:11:01 -050063 clientVersion uint16
64
Adam Langley95c29f32014-06-20 12:00:00 -070065 // input/output
66 in, out halfConn // in.Mutex < out.Mutex
67 rawInput *block // raw input, right off the wire
David Benjamin83c0bc92014-08-04 01:23:53 -040068 input *block // application record waiting to be read
69 hand bytes.Buffer // handshake record waiting to be read
70
71 // DTLS state
72 sendHandshakeSeq uint16
73 recvHandshakeSeq uint16
David Benjaminb3774b92015-01-31 17:16:01 -050074 handMsg []byte // pending assembled handshake message
75 handMsgLen int // handshake message length, not including the header
76 pendingFragments [][]byte // pending outgoing handshake fragments.
Adam Langley95c29f32014-06-20 12:00:00 -070077
78 tmp [16]byte
79}
80
David Benjamin5e961c12014-11-07 01:48:35 -050081func (c *Conn) init() {
82 c.in.isDTLS = c.isDTLS
83 c.out.isDTLS = c.isDTLS
84 c.in.config = c.config
85 c.out.config = c.config
86}
87
Adam Langley95c29f32014-06-20 12:00:00 -070088// Access to net.Conn methods.
89// Cannot just embed net.Conn because that would
90// export the struct field too.
91
92// LocalAddr returns the local network address.
93func (c *Conn) LocalAddr() net.Addr {
94 return c.conn.LocalAddr()
95}
96
97// RemoteAddr returns the remote network address.
98func (c *Conn) RemoteAddr() net.Addr {
99 return c.conn.RemoteAddr()
100}
101
102// SetDeadline sets the read and write deadlines associated with the connection.
103// A zero value for t means Read and Write will not time out.
104// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
105func (c *Conn) SetDeadline(t time.Time) error {
106 return c.conn.SetDeadline(t)
107}
108
109// SetReadDeadline sets the read deadline on the underlying connection.
110// A zero value for t means Read will not time out.
111func (c *Conn) SetReadDeadline(t time.Time) error {
112 return c.conn.SetReadDeadline(t)
113}
114
115// SetWriteDeadline sets the write deadline on the underlying conneciton.
116// A zero value for t means Write will not time out.
117// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
118func (c *Conn) SetWriteDeadline(t time.Time) error {
119 return c.conn.SetWriteDeadline(t)
120}
121
122// A halfConn represents one direction of the record layer
123// connection, either sending or receiving.
124type halfConn struct {
125 sync.Mutex
126
David Benjamin83c0bc92014-08-04 01:23:53 -0400127 err error // first permanent error
128 version uint16 // protocol version
129 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -0700130 cipher interface{} // cipher algorithm
131 mac macFunction
132 seq [8]byte // 64-bit sequence number
133 bfree *block // list of free blocks
134
135 nextCipher interface{} // next encryption state
136 nextMac macFunction // next MAC algorithm
David Benjamin83f90402015-01-27 01:09:43 -0500137 nextSeq [6]byte // next epoch's starting sequence number in DTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700138
139 // used to save allocating a new buffer for each MAC.
140 inDigestBuf, outDigestBuf []byte
Adam Langley80842bd2014-06-20 12:00:00 -0700141
142 config *Config
Adam Langley95c29f32014-06-20 12:00:00 -0700143}
144
145func (hc *halfConn) setErrorLocked(err error) error {
146 hc.err = err
147 return err
148}
149
150func (hc *halfConn) error() error {
Adam Langley2ae77d22014-10-28 17:29:33 -0700151 // This should be locked, but I've removed it for the renegotiation
152 // tests since we don't concurrently read and write the same tls.Conn
153 // in any case during testing.
Adam Langley95c29f32014-06-20 12:00:00 -0700154 err := hc.err
Adam Langley95c29f32014-06-20 12:00:00 -0700155 return err
156}
157
158// prepareCipherSpec sets the encryption and MAC states
159// that a subsequent changeCipherSpec will use.
160func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
161 hc.version = version
162 hc.nextCipher = cipher
163 hc.nextMac = mac
164}
165
166// changeCipherSpec changes the encryption and MAC states
167// to the ones previously passed to prepareCipherSpec.
Adam Langley80842bd2014-06-20 12:00:00 -0700168func (hc *halfConn) changeCipherSpec(config *Config) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700169 if hc.nextCipher == nil {
170 return alertInternalError
171 }
172 hc.cipher = hc.nextCipher
173 hc.mac = hc.nextMac
174 hc.nextCipher = nil
175 hc.nextMac = nil
Adam Langley80842bd2014-06-20 12:00:00 -0700176 hc.config = config
David Benjamin83c0bc92014-08-04 01:23:53 -0400177 hc.incEpoch()
Adam Langley95c29f32014-06-20 12:00:00 -0700178 return nil
179}
180
181// incSeq increments the sequence number.
David Benjamin5e961c12014-11-07 01:48:35 -0500182func (hc *halfConn) incSeq(isOutgoing bool) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400183 limit := 0
David Benjamin5e961c12014-11-07 01:48:35 -0500184 increment := uint64(1)
David Benjamin83c0bc92014-08-04 01:23:53 -0400185 if hc.isDTLS {
186 // Increment up to the epoch in DTLS.
187 limit = 2
David Benjamin5e961c12014-11-07 01:48:35 -0500188
189 if isOutgoing && hc.config.Bugs.SequenceNumberIncrement != 0 {
190 increment = hc.config.Bugs.SequenceNumberIncrement
191 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400192 }
193 for i := 7; i >= limit; i-- {
David Benjamin5e961c12014-11-07 01:48:35 -0500194 increment += uint64(hc.seq[i])
195 hc.seq[i] = byte(increment)
196 increment >>= 8
Adam Langley95c29f32014-06-20 12:00:00 -0700197 }
198
199 // Not allowed to let sequence number wrap.
200 // Instead, must renegotiate before it does.
201 // Not likely enough to bother.
David Benjamin5e961c12014-11-07 01:48:35 -0500202 if increment != 0 {
203 panic("TLS: sequence number wraparound")
204 }
Adam Langley95c29f32014-06-20 12:00:00 -0700205}
206
David Benjamin83f90402015-01-27 01:09:43 -0500207// incNextSeq increments the starting sequence number for the next epoch.
208func (hc *halfConn) incNextSeq() {
209 for i := len(hc.nextSeq) - 1; i >= 0; i-- {
210 hc.nextSeq[i]++
211 if hc.nextSeq[i] != 0 {
212 return
213 }
214 }
215 panic("TLS: sequence number wraparound")
216}
217
218// incEpoch resets the sequence number. In DTLS, it also increments the epoch
219// half of the sequence number.
David Benjamin83c0bc92014-08-04 01:23:53 -0400220func (hc *halfConn) incEpoch() {
David Benjamin83c0bc92014-08-04 01:23:53 -0400221 if hc.isDTLS {
222 for i := 1; i >= 0; i-- {
223 hc.seq[i]++
224 if hc.seq[i] != 0 {
225 break
226 }
227 if i == 0 {
228 panic("TLS: epoch number wraparound")
229 }
230 }
David Benjamin83f90402015-01-27 01:09:43 -0500231 copy(hc.seq[2:], hc.nextSeq[:])
232 for i := range hc.nextSeq {
233 hc.nextSeq[i] = 0
234 }
235 } else {
236 for i := range hc.seq {
237 hc.seq[i] = 0
238 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400239 }
240}
241
242func (hc *halfConn) recordHeaderLen() int {
243 if hc.isDTLS {
244 return dtlsRecordHeaderLen
245 }
246 return tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700247}
248
249// removePadding returns an unpadded slice, in constant time, which is a prefix
250// of the input. It also returns a byte which is equal to 255 if the padding
251// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
252func removePadding(payload []byte) ([]byte, byte) {
253 if len(payload) < 1 {
254 return payload, 0
255 }
256
257 paddingLen := payload[len(payload)-1]
258 t := uint(len(payload)-1) - uint(paddingLen)
259 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
260 good := byte(int32(^t) >> 31)
261
262 toCheck := 255 // the maximum possible padding length
263 // The length of the padded data is public, so we can use an if here
264 if toCheck+1 > len(payload) {
265 toCheck = len(payload) - 1
266 }
267
268 for i := 0; i < toCheck; i++ {
269 t := uint(paddingLen) - uint(i)
270 // if i <= paddingLen then the MSB of t is zero
271 mask := byte(int32(^t) >> 31)
272 b := payload[len(payload)-1-i]
273 good &^= mask&paddingLen ^ mask&b
274 }
275
276 // We AND together the bits of good and replicate the result across
277 // all the bits.
278 good &= good << 4
279 good &= good << 2
280 good &= good << 1
281 good = uint8(int8(good) >> 7)
282
283 toRemove := good&paddingLen + 1
284 return payload[:len(payload)-int(toRemove)], good
285}
286
287// removePaddingSSL30 is a replacement for removePadding in the case that the
288// protocol version is SSLv3. In this version, the contents of the padding
289// are random and cannot be checked.
290func removePaddingSSL30(payload []byte) ([]byte, byte) {
291 if len(payload) < 1 {
292 return payload, 0
293 }
294
295 paddingLen := int(payload[len(payload)-1]) + 1
296 if paddingLen > len(payload) {
297 return payload, 0
298 }
299
300 return payload[:len(payload)-paddingLen], 255
301}
302
303func roundUp(a, b int) int {
304 return a + (b-a%b)%b
305}
306
307// cbcMode is an interface for block ciphers using cipher block chaining.
308type cbcMode interface {
309 cipher.BlockMode
310 SetIV([]byte)
311}
312
313// decrypt checks and strips the mac and decrypts the data in b. Returns a
314// success boolean, the number of bytes to skip from the start of the record in
315// order to get the application payload, and an optional alert value.
316func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, alertValue alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400317 recordHeaderLen := hc.recordHeaderLen()
318
Adam Langley95c29f32014-06-20 12:00:00 -0700319 // pull out payload
320 payload := b.data[recordHeaderLen:]
321
322 macSize := 0
323 if hc.mac != nil {
324 macSize = hc.mac.Size()
325 }
326
327 paddingGood := byte(255)
328 explicitIVLen := 0
329
David Benjamin83c0bc92014-08-04 01:23:53 -0400330 seq := hc.seq[:]
331 if hc.isDTLS {
332 // DTLS sequence numbers are explicit.
333 seq = b.data[3:11]
334 }
335
Adam Langley95c29f32014-06-20 12:00:00 -0700336 // decrypt
337 if hc.cipher != nil {
338 switch c := hc.cipher.(type) {
339 case cipher.Stream:
340 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400341 case *tlsAead:
342 nonce := seq
343 if c.explicitNonce {
344 explicitIVLen = 8
345 if len(payload) < explicitIVLen {
346 return false, 0, alertBadRecordMAC
347 }
348 nonce = payload[:8]
349 payload = payload[8:]
Adam Langley95c29f32014-06-20 12:00:00 -0700350 }
Adam Langley95c29f32014-06-20 12:00:00 -0700351
352 var additionalData [13]byte
David Benjamin83c0bc92014-08-04 01:23:53 -0400353 copy(additionalData[:], seq)
Adam Langley95c29f32014-06-20 12:00:00 -0700354 copy(additionalData[8:], b.data[:3])
355 n := len(payload) - c.Overhead()
356 additionalData[11] = byte(n >> 8)
357 additionalData[12] = byte(n)
358 var err error
359 payload, err = c.Open(payload[:0], nonce, payload, additionalData[:])
360 if err != nil {
361 return false, 0, alertBadRecordMAC
362 }
363 b.resize(recordHeaderLen + explicitIVLen + len(payload))
364 case cbcMode:
365 blockSize := c.BlockSize()
David Benjamin83c0bc92014-08-04 01:23:53 -0400366 if hc.version >= VersionTLS11 || hc.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700367 explicitIVLen = blockSize
368 }
369
370 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
371 return false, 0, alertBadRecordMAC
372 }
373
374 if explicitIVLen > 0 {
375 c.SetIV(payload[:explicitIVLen])
376 payload = payload[explicitIVLen:]
377 }
378 c.CryptBlocks(payload, payload)
379 if hc.version == VersionSSL30 {
380 payload, paddingGood = removePaddingSSL30(payload)
381 } else {
382 payload, paddingGood = removePadding(payload)
383 }
384 b.resize(recordHeaderLen + explicitIVLen + len(payload))
385
386 // note that we still have a timing side-channel in the
387 // MAC check, below. An attacker can align the record
388 // so that a correct padding will cause one less hash
389 // block to be calculated. Then they can iteratively
390 // decrypt a record by breaking each byte. See
391 // "Password Interception in a SSL/TLS Channel", Brice
392 // Canvel et al.
393 //
394 // However, our behavior matches OpenSSL, so we leak
395 // only as much as they do.
396 default:
397 panic("unknown cipher type")
398 }
399 }
400
401 // check, strip mac
402 if hc.mac != nil {
403 if len(payload) < macSize {
404 return false, 0, alertBadRecordMAC
405 }
406
407 // strip mac off payload, b.data
408 n := len(payload) - macSize
David Benjamin83c0bc92014-08-04 01:23:53 -0400409 b.data[recordHeaderLen-2] = byte(n >> 8)
410 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700411 b.resize(recordHeaderLen + explicitIVLen + n)
412 remoteMAC := payload[n:]
David Benjamin83c0bc92014-08-04 01:23:53 -0400413 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
Adam Langley95c29f32014-06-20 12:00:00 -0700414
415 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
416 return false, 0, alertBadRecordMAC
417 }
418 hc.inDigestBuf = localMAC
419 }
David Benjamin5e961c12014-11-07 01:48:35 -0500420 hc.incSeq(false)
Adam Langley95c29f32014-06-20 12:00:00 -0700421
422 return true, recordHeaderLen + explicitIVLen, 0
423}
424
425// padToBlockSize calculates the needed padding block, if any, for a payload.
426// On exit, prefix aliases payload and extends to the end of the last full
427// block of payload. finalBlock is a fresh slice which contains the contents of
428// any suffix of payload as well as the needed padding to make finalBlock a
429// full block.
Adam Langley80842bd2014-06-20 12:00:00 -0700430func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
Adam Langley95c29f32014-06-20 12:00:00 -0700431 overrun := len(payload) % blockSize
Adam Langley95c29f32014-06-20 12:00:00 -0700432 prefix = payload[:len(payload)-overrun]
Adam Langley80842bd2014-06-20 12:00:00 -0700433
434 paddingLen := blockSize - overrun
435 finalSize := blockSize
436 if config.Bugs.MaxPadding {
437 for paddingLen+blockSize <= 256 {
438 paddingLen += blockSize
439 }
440 finalSize = 256
441 }
442 finalBlock = make([]byte, finalSize)
443 for i := range finalBlock {
Adam Langley95c29f32014-06-20 12:00:00 -0700444 finalBlock[i] = byte(paddingLen - 1)
445 }
Adam Langley80842bd2014-06-20 12:00:00 -0700446 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
447 finalBlock[overrun] ^= 0xff
448 }
449 copy(finalBlock, payload[len(payload)-overrun:])
Adam Langley95c29f32014-06-20 12:00:00 -0700450 return
451}
452
453// encrypt encrypts and macs the data in b.
454func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400455 recordHeaderLen := hc.recordHeaderLen()
456
Adam Langley95c29f32014-06-20 12:00:00 -0700457 // mac
458 if hc.mac != nil {
David Benjamin83c0bc92014-08-04 01:23:53 -0400459 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 -0700460
461 n := len(b.data)
462 b.resize(n + len(mac))
463 copy(b.data[n:], mac)
464 hc.outDigestBuf = mac
465 }
466
467 payload := b.data[recordHeaderLen:]
468
469 // encrypt
470 if hc.cipher != nil {
471 switch c := hc.cipher.(type) {
472 case cipher.Stream:
473 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400474 case *tlsAead:
Adam Langley95c29f32014-06-20 12:00:00 -0700475 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
476 b.resize(len(b.data) + c.Overhead())
David Benjamine9a80ff2015-04-07 00:46:46 -0400477 nonce := hc.seq[:]
478 if c.explicitNonce {
479 nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
480 }
Adam Langley95c29f32014-06-20 12:00:00 -0700481 payload := b.data[recordHeaderLen+explicitIVLen:]
482 payload = payload[:payloadLen]
483
484 var additionalData [13]byte
485 copy(additionalData[:], hc.seq[:])
486 copy(additionalData[8:], b.data[:3])
487 additionalData[11] = byte(payloadLen >> 8)
488 additionalData[12] = byte(payloadLen)
489
490 c.Seal(payload[:0], nonce, payload, additionalData[:])
491 case cbcMode:
492 blockSize := c.BlockSize()
493 if explicitIVLen > 0 {
494 c.SetIV(payload[:explicitIVLen])
495 payload = payload[explicitIVLen:]
496 }
Adam Langley80842bd2014-06-20 12:00:00 -0700497 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700498 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
499 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
500 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
501 default:
502 panic("unknown cipher type")
503 }
504 }
505
506 // update length to include MAC and any block padding needed.
507 n := len(b.data) - recordHeaderLen
David Benjamin83c0bc92014-08-04 01:23:53 -0400508 b.data[recordHeaderLen-2] = byte(n >> 8)
509 b.data[recordHeaderLen-1] = byte(n)
David Benjamin5e961c12014-11-07 01:48:35 -0500510 hc.incSeq(true)
Adam Langley95c29f32014-06-20 12:00:00 -0700511
512 return true, 0
513}
514
515// A block is a simple data buffer.
516type block struct {
517 data []byte
518 off int // index for Read
519 link *block
520}
521
522// resize resizes block to be n bytes, growing if necessary.
523func (b *block) resize(n int) {
524 if n > cap(b.data) {
525 b.reserve(n)
526 }
527 b.data = b.data[0:n]
528}
529
530// reserve makes sure that block contains a capacity of at least n bytes.
531func (b *block) reserve(n int) {
532 if cap(b.data) >= n {
533 return
534 }
535 m := cap(b.data)
536 if m == 0 {
537 m = 1024
538 }
539 for m < n {
540 m *= 2
541 }
542 data := make([]byte, len(b.data), m)
543 copy(data, b.data)
544 b.data = data
545}
546
547// readFromUntil reads from r into b until b contains at least n bytes
548// or else returns an error.
549func (b *block) readFromUntil(r io.Reader, n int) error {
550 // quick case
551 if len(b.data) >= n {
552 return nil
553 }
554
555 // read until have enough.
556 b.reserve(n)
557 for {
558 m, err := r.Read(b.data[len(b.data):cap(b.data)])
559 b.data = b.data[0 : len(b.data)+m]
560 if len(b.data) >= n {
561 // TODO(bradfitz,agl): slightly suspicious
562 // that we're throwing away r.Read's err here.
563 break
564 }
565 if err != nil {
566 return err
567 }
568 }
569 return nil
570}
571
572func (b *block) Read(p []byte) (n int, err error) {
573 n = copy(p, b.data[b.off:])
574 b.off += n
575 return
576}
577
578// newBlock allocates a new block, from hc's free list if possible.
579func (hc *halfConn) newBlock() *block {
580 b := hc.bfree
581 if b == nil {
582 return new(block)
583 }
584 hc.bfree = b.link
585 b.link = nil
586 b.resize(0)
587 return b
588}
589
590// freeBlock returns a block to hc's free list.
591// The protocol is such that each side only has a block or two on
592// its free list at a time, so there's no need to worry about
593// trimming the list, etc.
594func (hc *halfConn) freeBlock(b *block) {
595 b.link = hc.bfree
596 hc.bfree = b
597}
598
599// splitBlock splits a block after the first n bytes,
600// returning a block with those n bytes and a
601// block with the remainder. the latter may be nil.
602func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
603 if len(b.data) <= n {
604 return b, nil
605 }
606 bb := hc.newBlock()
607 bb.resize(len(b.data) - n)
608 copy(bb.data, b.data[n:])
609 b.data = b.data[0:n]
610 return b, bb
611}
612
David Benjamin83c0bc92014-08-04 01:23:53 -0400613func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
614 if c.isDTLS {
615 return c.dtlsDoReadRecord(want)
616 }
617
618 recordHeaderLen := tlsRecordHeaderLen
619
620 if c.rawInput == nil {
621 c.rawInput = c.in.newBlock()
622 }
623 b := c.rawInput
624
625 // Read header, payload.
626 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
627 // RFC suggests that EOF without an alertCloseNotify is
628 // an error, but popular web sites seem to do this,
629 // so we can't make it an error.
630 // if err == io.EOF {
631 // err = io.ErrUnexpectedEOF
632 // }
633 if e, ok := err.(net.Error); !ok || !e.Temporary() {
634 c.in.setErrorLocked(err)
635 }
636 return 0, nil, err
637 }
638 typ := recordType(b.data[0])
639
640 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
641 // start with a uint16 length where the MSB is set and the first record
642 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
643 // an SSLv2 client.
644 if want == recordTypeHandshake && typ == 0x80 {
645 c.sendAlert(alertProtocolVersion)
646 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
647 }
648
649 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
650 n := int(b.data[3])<<8 | int(b.data[4])
David Benjamin1e29a6b2014-12-10 02:27:24 -0500651 if c.haveVers {
652 if vers != c.vers {
653 c.sendAlert(alertProtocolVersion)
654 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers))
655 }
656 } else {
657 if expect := c.config.Bugs.ExpectInitialRecordVersion; expect != 0 && vers != expect {
658 c.sendAlert(alertProtocolVersion)
659 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
660 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400661 }
662 if n > maxCiphertext {
663 c.sendAlert(alertRecordOverflow)
664 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
665 }
666 if !c.haveVers {
667 // First message, be extra suspicious:
668 // this might not be a TLS client.
669 // Bail out before reading a full 'body', if possible.
670 // The current max version is 3.1.
671 // If the version is >= 16.0, it's probably not real.
672 // Similarly, a clientHello message encodes in
673 // well under a kilobyte. If the length is >= 12 kB,
674 // it's probably not real.
675 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
676 c.sendAlert(alertUnexpectedMessage)
677 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
678 }
679 }
680 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
681 if err == io.EOF {
682 err = io.ErrUnexpectedEOF
683 }
684 if e, ok := err.(net.Error); !ok || !e.Temporary() {
685 c.in.setErrorLocked(err)
686 }
687 return 0, nil, err
688 }
689
690 // Process message.
691 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
692 ok, off, err := c.in.decrypt(b)
693 if !ok {
694 c.in.setErrorLocked(c.sendAlert(err))
695 }
696 b.off = off
697 return typ, b, nil
698}
699
Adam Langley95c29f32014-06-20 12:00:00 -0700700// readRecord reads the next TLS record from the connection
701// and updates the record layer state.
702// c.in.Mutex <= L; c.input == nil.
703func (c *Conn) readRecord(want recordType) error {
704 // Caller must be in sync with connection:
705 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700706 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700707 switch want {
708 default:
709 c.sendAlert(alertInternalError)
710 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
711 case recordTypeHandshake, recordTypeChangeCipherSpec:
712 if c.handshakeComplete {
713 c.sendAlert(alertInternalError)
714 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
715 }
716 case recordTypeApplicationData:
David Benjamine58c4f52014-08-24 03:47:07 -0400717 if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart {
Adam Langley95c29f32014-06-20 12:00:00 -0700718 c.sendAlert(alertInternalError)
719 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
720 }
721 }
722
723Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400724 typ, b, err := c.doReadRecord(want)
725 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700726 return err
727 }
Adam Langley95c29f32014-06-20 12:00:00 -0700728 data := b.data[b.off:]
729 if len(data) > maxPlaintext {
730 err := c.sendAlert(alertRecordOverflow)
731 c.in.freeBlock(b)
732 return c.in.setErrorLocked(err)
733 }
734
735 switch typ {
736 default:
737 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
738
739 case recordTypeAlert:
740 if len(data) != 2 {
741 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
742 break
743 }
744 if alert(data[1]) == alertCloseNotify {
745 c.in.setErrorLocked(io.EOF)
746 break
747 }
748 switch data[0] {
749 case alertLevelWarning:
750 // drop on the floor
751 c.in.freeBlock(b)
752 goto Again
753 case alertLevelError:
754 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
755 default:
756 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
757 }
758
759 case recordTypeChangeCipherSpec:
760 if typ != want || len(data) != 1 || data[0] != 1 {
761 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
762 break
763 }
Adam Langley80842bd2014-06-20 12:00:00 -0700764 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700765 if err != nil {
766 c.in.setErrorLocked(c.sendAlert(err.(alert)))
767 }
768
769 case recordTypeApplicationData:
770 if typ != want {
771 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
772 break
773 }
774 c.input = b
775 b = nil
776
777 case recordTypeHandshake:
778 // TODO(rsc): Should at least pick off connection close.
779 if typ != want {
Adam Langley2ae77d22014-10-28 17:29:33 -0700780 // A client might need to process a HelloRequest from
781 // the server, thus receiving a handshake message when
David Benjamind9b091b2015-01-27 01:10:54 -0500782 // application data is expected is ok.
783 if !c.isClient {
Adam Langley2ae77d22014-10-28 17:29:33 -0700784 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
785 }
Adam Langley95c29f32014-06-20 12:00:00 -0700786 }
787 c.hand.Write(data)
788 }
789
790 if b != nil {
791 c.in.freeBlock(b)
792 }
793 return c.in.err
794}
795
796// sendAlert sends a TLS alert message.
797// c.out.Mutex <= L.
798func (c *Conn) sendAlertLocked(err alert) error {
799 switch err {
800 case alertNoRenegotiation, alertCloseNotify:
801 c.tmp[0] = alertLevelWarning
802 default:
803 c.tmp[0] = alertLevelError
804 }
805 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400806 if c.config.Bugs.FragmentAlert {
807 c.writeRecord(recordTypeAlert, c.tmp[0:1])
808 c.writeRecord(recordTypeAlert, c.tmp[1:2])
809 } else {
810 c.writeRecord(recordTypeAlert, c.tmp[0:2])
811 }
Adam Langley95c29f32014-06-20 12:00:00 -0700812 // closeNotify is a special case in that it isn't an error:
813 if err != alertCloseNotify {
814 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
815 }
816 return nil
817}
818
819// sendAlert sends a TLS alert message.
820// L < c.out.Mutex.
821func (c *Conn) sendAlert(err alert) error {
822 c.out.Lock()
823 defer c.out.Unlock()
824 return c.sendAlertLocked(err)
825}
826
David Benjamind86c7672014-08-02 04:07:12 -0400827// writeV2Record writes a record for a V2ClientHello.
828func (c *Conn) writeV2Record(data []byte) (n int, err error) {
829 record := make([]byte, 2+len(data))
830 record[0] = uint8(len(data)>>8) | 0x80
831 record[1] = uint8(len(data))
832 copy(record[2:], data)
833 return c.conn.Write(record)
834}
835
Adam Langley95c29f32014-06-20 12:00:00 -0700836// writeRecord writes a TLS record with the given type and payload
837// to the connection and updates the record layer state.
838// c.out.Mutex <= L.
839func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin340d5ed2015-03-21 02:21:37 -0400840 if typ != recordTypeAlert && c.config.Bugs.SendWarningAlerts != 0 {
841 alert := make([]byte, 2)
842 alert[0] = alertLevelWarning
843 alert[1] = byte(c.config.Bugs.SendWarningAlerts)
844 c.writeRecord(recordTypeAlert, alert)
845 }
846
David Benjamin83c0bc92014-08-04 01:23:53 -0400847 if c.isDTLS {
848 return c.dtlsWriteRecord(typ, data)
849 }
850
851 recordHeaderLen := tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700852 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -0400853 first := true
854 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
Adam Langley95c29f32014-06-20 12:00:00 -0700855 for len(data) > 0 {
856 m := len(data)
857 if m > maxPlaintext {
858 m = maxPlaintext
859 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400860 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
861 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -0400862 // By default, do not fragment the client_version or
863 // server_version, which are located in the first 6
864 // bytes.
865 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
866 m = 6
867 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400868 }
Adam Langley95c29f32014-06-20 12:00:00 -0700869 explicitIVLen := 0
870 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -0400871 first = false
Adam Langley95c29f32014-06-20 12:00:00 -0700872
873 var cbc cbcMode
874 if c.out.version >= VersionTLS11 {
875 var ok bool
876 if cbc, ok = c.out.cipher.(cbcMode); ok {
877 explicitIVLen = cbc.BlockSize()
878 }
879 }
880 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -0400881 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -0700882 explicitIVLen = 8
883 // The AES-GCM construction in TLS has an
884 // explicit nonce so that the nonce can be
885 // random. However, the nonce is only 8 bytes
886 // which is too small for a secure, random
887 // nonce. Therefore we use the sequence number
888 // as the nonce.
889 explicitIVIsSeq = true
890 }
891 }
892 b.resize(recordHeaderLen + explicitIVLen + m)
893 b.data[0] = byte(typ)
894 vers := c.vers
895 if vers == 0 {
896 // Some TLS servers fail if the record version is
897 // greater than TLS 1.0 for the initial ClientHello.
898 vers = VersionTLS10
899 }
900 b.data[1] = byte(vers >> 8)
901 b.data[2] = byte(vers)
902 b.data[3] = byte(m >> 8)
903 b.data[4] = byte(m)
904 if explicitIVLen > 0 {
905 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
906 if explicitIVIsSeq {
907 copy(explicitIV, c.out.seq[:])
908 } else {
909 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
910 break
911 }
912 }
913 }
914 copy(b.data[recordHeaderLen+explicitIVLen:], data)
915 c.out.encrypt(b, explicitIVLen)
916 _, err = c.conn.Write(b.data)
917 if err != nil {
918 break
919 }
920 n += m
921 data = data[m:]
922 }
923 c.out.freeBlock(b)
924
925 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -0700926 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700927 if err != nil {
928 // Cannot call sendAlert directly,
929 // because we already hold c.out.Mutex.
930 c.tmp[0] = alertLevelError
931 c.tmp[1] = byte(err.(alert))
932 c.writeRecord(recordTypeAlert, c.tmp[0:2])
933 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
934 }
935 }
936 return
937}
938
David Benjamin83c0bc92014-08-04 01:23:53 -0400939func (c *Conn) doReadHandshake() ([]byte, error) {
940 if c.isDTLS {
941 return c.dtlsDoReadHandshake()
942 }
943
Adam Langley95c29f32014-06-20 12:00:00 -0700944 for c.hand.Len() < 4 {
945 if err := c.in.err; err != nil {
946 return nil, err
947 }
948 if err := c.readRecord(recordTypeHandshake); err != nil {
949 return nil, err
950 }
951 }
952
953 data := c.hand.Bytes()
954 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
955 if n > maxHandshake {
956 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
957 }
958 for c.hand.Len() < 4+n {
959 if err := c.in.err; err != nil {
960 return nil, err
961 }
962 if err := c.readRecord(recordTypeHandshake); err != nil {
963 return nil, err
964 }
965 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400966 return c.hand.Next(4 + n), nil
967}
968
969// readHandshake reads the next handshake message from
970// the record layer.
971// c.in.Mutex < L; c.out.Mutex < L.
972func (c *Conn) readHandshake() (interface{}, error) {
973 data, err := c.doReadHandshake()
974 if err != nil {
975 return nil, err
976 }
977
Adam Langley95c29f32014-06-20 12:00:00 -0700978 var m handshakeMessage
979 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -0700980 case typeHelloRequest:
981 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -0700982 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -0400983 m = &clientHelloMsg{
984 isDTLS: c.isDTLS,
985 }
Adam Langley95c29f32014-06-20 12:00:00 -0700986 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -0400987 m = &serverHelloMsg{
988 isDTLS: c.isDTLS,
989 }
Adam Langley95c29f32014-06-20 12:00:00 -0700990 case typeNewSessionTicket:
991 m = new(newSessionTicketMsg)
992 case typeCertificate:
993 m = new(certificateMsg)
994 case typeCertificateRequest:
995 m = &certificateRequestMsg{
996 hasSignatureAndHash: c.vers >= VersionTLS12,
997 }
998 case typeCertificateStatus:
999 m = new(certificateStatusMsg)
1000 case typeServerKeyExchange:
1001 m = new(serverKeyExchangeMsg)
1002 case typeServerHelloDone:
1003 m = new(serverHelloDoneMsg)
1004 case typeClientKeyExchange:
1005 m = new(clientKeyExchangeMsg)
1006 case typeCertificateVerify:
1007 m = &certificateVerifyMsg{
1008 hasSignatureAndHash: c.vers >= VersionTLS12,
1009 }
1010 case typeNextProtocol:
1011 m = new(nextProtoMsg)
1012 case typeFinished:
1013 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001014 case typeHelloVerifyRequest:
1015 m = new(helloVerifyRequestMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001016 case typeEncryptedExtensions:
1017 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001018 default:
1019 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1020 }
1021
1022 // The handshake message unmarshallers
1023 // expect to be able to keep references to data,
1024 // so pass in a fresh copy that won't be overwritten.
1025 data = append([]byte(nil), data...)
1026
1027 if !m.unmarshal(data) {
1028 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1029 }
1030 return m, nil
1031}
1032
David Benjamin83f90402015-01-27 01:09:43 -05001033// skipPacket processes all the DTLS records in packet. It updates
1034// sequence number expectations but otherwise ignores them.
1035func (c *Conn) skipPacket(packet []byte) error {
1036 for len(packet) > 0 {
1037 // Dropped packets are completely ignored save to update
1038 // expected sequence numbers for this and the next epoch. (We
1039 // don't assert on the contents of the packets both for
1040 // simplicity and because a previous test with one shorter
1041 // timeout schedule would have done so.)
1042 epoch := packet[3:5]
1043 seq := packet[5:11]
1044 length := uint16(packet[11])<<8 | uint16(packet[12])
1045 if bytes.Equal(c.in.seq[:2], epoch) {
1046 if !bytes.Equal(c.in.seq[2:], seq) {
1047 return errors.New("tls: sequence mismatch")
1048 }
1049 c.in.incSeq(false)
1050 } else {
1051 if !bytes.Equal(c.in.nextSeq[:], seq) {
1052 return errors.New("tls: sequence mismatch")
1053 }
1054 c.in.incNextSeq()
1055 }
1056 packet = packet[13+length:]
1057 }
1058 return nil
1059}
1060
1061// simulatePacketLoss simulates the loss of a handshake leg from the
1062// peer based on the schedule in c.config.Bugs. If resendFunc is
1063// non-nil, it is called after each simulated timeout to retransmit
1064// handshake messages from the local end. This is used in cases where
1065// the peer retransmits on a stale Finished rather than a timeout.
1066func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1067 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1068 return nil
1069 }
1070 if !c.isDTLS {
1071 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1072 }
1073 if c.config.Bugs.PacketAdaptor == nil {
1074 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1075 }
1076 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1077 // Simulate a timeout.
1078 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1079 if err != nil {
1080 return err
1081 }
1082 for _, packet := range packets {
1083 if err := c.skipPacket(packet); err != nil {
1084 return err
1085 }
1086 }
1087 if resendFunc != nil {
1088 resendFunc()
1089 }
1090 }
1091 return nil
1092}
1093
Adam Langley95c29f32014-06-20 12:00:00 -07001094// Write writes data to the connection.
1095func (c *Conn) Write(b []byte) (int, error) {
1096 if err := c.Handshake(); err != nil {
1097 return 0, err
1098 }
1099
1100 c.out.Lock()
1101 defer c.out.Unlock()
1102
1103 if err := c.out.err; err != nil {
1104 return 0, err
1105 }
1106
1107 if !c.handshakeComplete {
1108 return 0, alertInternalError
1109 }
1110
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001111 if c.config.Bugs.SendSpuriousAlert != 0 {
1112 c.sendAlertLocked(c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001113 }
1114
Adam Langley95c29f32014-06-20 12:00:00 -07001115 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1116 // attack when using block mode ciphers due to predictable IVs.
1117 // This can be prevented by splitting each Application Data
1118 // record into two records, effectively randomizing the IV.
1119 //
1120 // http://www.openssl.org/~bodo/tls-cbc.txt
1121 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1122 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1123
1124 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001125 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001126 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1127 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1128 if err != nil {
1129 return n, c.out.setErrorLocked(err)
1130 }
1131 m, b = 1, b[1:]
1132 }
1133 }
1134
1135 n, err := c.writeRecord(recordTypeApplicationData, b)
1136 return n + m, c.out.setErrorLocked(err)
1137}
1138
Adam Langley2ae77d22014-10-28 17:29:33 -07001139func (c *Conn) handleRenegotiation() error {
1140 c.handshakeComplete = false
1141 if !c.isClient {
1142 panic("renegotiation should only happen for a client")
1143 }
1144
1145 msg, err := c.readHandshake()
1146 if err != nil {
1147 return err
1148 }
1149 _, ok := msg.(*helloRequestMsg)
1150 if !ok {
1151 c.sendAlert(alertUnexpectedMessage)
1152 return alertUnexpectedMessage
1153 }
1154
1155 return c.Handshake()
1156}
1157
Adam Langleycf2d4f42014-10-28 19:06:14 -07001158func (c *Conn) Renegotiate() error {
1159 if !c.isClient {
1160 helloReq := new(helloRequestMsg)
1161 c.writeRecord(recordTypeHandshake, helloReq.marshal())
1162 }
1163
1164 c.handshakeComplete = false
1165 return c.Handshake()
1166}
1167
Adam Langley95c29f32014-06-20 12:00:00 -07001168// Read can be made to time out and return a net.Error with Timeout() == true
1169// after a fixed time limit; see SetDeadline and SetReadDeadline.
1170func (c *Conn) Read(b []byte) (n int, err error) {
1171 if err = c.Handshake(); err != nil {
1172 return
1173 }
1174
1175 c.in.Lock()
1176 defer c.in.Unlock()
1177
1178 // Some OpenSSL servers send empty records in order to randomize the
1179 // CBC IV. So this loop ignores a limited number of empty records.
1180 const maxConsecutiveEmptyRecords = 100
1181 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1182 for c.input == nil && c.in.err == nil {
1183 if err := c.readRecord(recordTypeApplicationData); err != nil {
1184 // Soft error, like EAGAIN
1185 return 0, err
1186 }
David Benjamind9b091b2015-01-27 01:10:54 -05001187 if c.hand.Len() > 0 {
Adam Langley2ae77d22014-10-28 17:29:33 -07001188 // We received handshake bytes, indicating the
David Benjamind9b091b2015-01-27 01:10:54 -05001189 // start of a renegotiation.
Adam Langley2ae77d22014-10-28 17:29:33 -07001190 if err := c.handleRenegotiation(); err != nil {
1191 return 0, err
1192 }
1193 continue
1194 }
Adam Langley95c29f32014-06-20 12:00:00 -07001195 }
1196 if err := c.in.err; err != nil {
1197 return 0, err
1198 }
1199
1200 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001201 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001202 c.in.freeBlock(c.input)
1203 c.input = nil
1204 }
1205
1206 // If a close-notify alert is waiting, read it so that
1207 // we can return (n, EOF) instead of (n, nil), to signal
1208 // to the HTTP response reading goroutine that the
1209 // connection is now closed. This eliminates a race
1210 // where the HTTP response reading goroutine would
1211 // otherwise not observe the EOF until its next read,
1212 // by which time a client goroutine might have already
1213 // tried to reuse the HTTP connection for a new
1214 // request.
1215 // See https://codereview.appspot.com/76400046
1216 // and http://golang.org/issue/3514
1217 if ri := c.rawInput; ri != nil &&
1218 n != 0 && err == nil &&
1219 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1220 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1221 err = recErr // will be io.EOF on closeNotify
1222 }
1223 }
1224
1225 if n != 0 || err != nil {
1226 return n, err
1227 }
1228 }
1229
1230 return 0, io.ErrNoProgress
1231}
1232
1233// Close closes the connection.
1234func (c *Conn) Close() error {
1235 var alertErr error
1236
1237 c.handshakeMutex.Lock()
1238 defer c.handshakeMutex.Unlock()
1239 if c.handshakeComplete {
1240 alertErr = c.sendAlert(alertCloseNotify)
1241 }
1242
1243 if err := c.conn.Close(); err != nil {
1244 return err
1245 }
1246 return alertErr
1247}
1248
1249// Handshake runs the client or server handshake
1250// protocol if it has not yet been run.
1251// Most uses of this package need not call Handshake
1252// explicitly: the first Read or Write will call it automatically.
1253func (c *Conn) Handshake() error {
1254 c.handshakeMutex.Lock()
1255 defer c.handshakeMutex.Unlock()
1256 if err := c.handshakeErr; err != nil {
1257 return err
1258 }
1259 if c.handshakeComplete {
1260 return nil
1261 }
1262
1263 if c.isClient {
1264 c.handshakeErr = c.clientHandshake()
1265 } else {
1266 c.handshakeErr = c.serverHandshake()
1267 }
David Benjaminddb9f152015-02-03 15:44:39 -05001268 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1269 c.writeRecord(recordType(42), []byte("invalid record"))
1270 }
Adam Langley95c29f32014-06-20 12:00:00 -07001271 return c.handshakeErr
1272}
1273
1274// ConnectionState returns basic TLS details about the connection.
1275func (c *Conn) ConnectionState() ConnectionState {
1276 c.handshakeMutex.Lock()
1277 defer c.handshakeMutex.Unlock()
1278
1279 var state ConnectionState
1280 state.HandshakeComplete = c.handshakeComplete
1281 if c.handshakeComplete {
1282 state.Version = c.vers
1283 state.NegotiatedProtocol = c.clientProtocol
1284 state.DidResume = c.didResume
1285 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001286 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001287 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001288 state.PeerCertificates = c.peerCertificates
1289 state.VerifiedChains = c.verifiedChains
1290 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001291 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001292 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langley95c29f32014-06-20 12:00:00 -07001293 }
1294
1295 return state
1296}
1297
1298// OCSPResponse returns the stapled OCSP response from the TLS server, if
1299// any. (Only valid for client connections.)
1300func (c *Conn) OCSPResponse() []byte {
1301 c.handshakeMutex.Lock()
1302 defer c.handshakeMutex.Unlock()
1303
1304 return c.ocspResponse
1305}
1306
1307// VerifyHostname checks that the peer certificate chain is valid for
1308// connecting to host. If so, it returns nil; if not, it returns an error
1309// describing the problem.
1310func (c *Conn) VerifyHostname(host string) error {
1311 c.handshakeMutex.Lock()
1312 defer c.handshakeMutex.Unlock()
1313 if !c.isClient {
1314 return errors.New("tls: VerifyHostname called on TLS server connection")
1315 }
1316 if !c.handshakeComplete {
1317 return errors.New("tls: handshake has not yet been performed")
1318 }
1319 return c.peerCertificates[0].VerifyHostname(host)
1320}
David Benjaminc565ebb2015-04-03 04:06:36 -04001321
1322// ExportKeyingMaterial exports keying material from the current connection
1323// state, as per RFC 5705.
1324func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1325 c.handshakeMutex.Lock()
1326 defer c.handshakeMutex.Unlock()
1327 if !c.handshakeComplete {
1328 return nil, errors.New("tls: handshake has not yet been performed")
1329 }
1330
1331 seedLen := len(c.clientRandom) + len(c.serverRandom)
1332 if useContext {
1333 seedLen += 2 + len(context)
1334 }
1335 seed := make([]byte, 0, seedLen)
1336 seed = append(seed, c.clientRandom[:]...)
1337 seed = append(seed, c.serverRandom[:]...)
1338 if useContext {
1339 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1340 seed = append(seed, context...)
1341 }
1342 result := make([]byte, length)
1343 prfForVersion(c.vers, c.cipherSuite)(result, c.masterSecret[:], label, seed)
1344 return result, nil
1345}