blob: 86a7b7de9b3e0a511ca0978172d2603dc2bc1f04 [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
40 cipherSuite uint16
41 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.
47 serverName string
48
49 clientProtocol string
50 clientProtocolFallback bool
David Benjaminfc7b0862014-09-06 13:21:53 -040051 usedALPN bool
Adam Langley95c29f32014-06-20 12:00:00 -070052
Adam Langley2ae77d22014-10-28 17:29:33 -070053 // verify_data values for the renegotiation extension.
54 clientVerify []byte
55 serverVerify []byte
56
David Benjamind30a9902014-08-24 01:44:23 -040057 channelID *ecdsa.PublicKey
58
David Benjaminca6c8262014-11-15 19:06:08 -050059 srtpProtectionProfile uint16
60
David Benjaminc44b1df2014-11-23 12:11:01 -050061 clientVersion uint16
62
Adam Langley95c29f32014-06-20 12:00:00 -070063 // input/output
64 in, out halfConn // in.Mutex < out.Mutex
65 rawInput *block // raw input, right off the wire
David Benjamin83c0bc92014-08-04 01:23:53 -040066 input *block // application record waiting to be read
67 hand bytes.Buffer // handshake record waiting to be read
68
69 // DTLS state
70 sendHandshakeSeq uint16
71 recvHandshakeSeq uint16
David Benjaminb3774b92015-01-31 17:16:01 -050072 handMsg []byte // pending assembled handshake message
73 handMsgLen int // handshake message length, not including the header
74 pendingFragments [][]byte // pending outgoing handshake fragments.
Adam Langley95c29f32014-06-20 12:00:00 -070075
76 tmp [16]byte
77}
78
David Benjamin5e961c12014-11-07 01:48:35 -050079func (c *Conn) init() {
80 c.in.isDTLS = c.isDTLS
81 c.out.isDTLS = c.isDTLS
82 c.in.config = c.config
83 c.out.config = c.config
84}
85
Adam Langley95c29f32014-06-20 12:00:00 -070086// Access to net.Conn methods.
87// Cannot just embed net.Conn because that would
88// export the struct field too.
89
90// LocalAddr returns the local network address.
91func (c *Conn) LocalAddr() net.Addr {
92 return c.conn.LocalAddr()
93}
94
95// RemoteAddr returns the remote network address.
96func (c *Conn) RemoteAddr() net.Addr {
97 return c.conn.RemoteAddr()
98}
99
100// SetDeadline sets the read and write deadlines associated with the connection.
101// A zero value for t means Read and Write will not time out.
102// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
103func (c *Conn) SetDeadline(t time.Time) error {
104 return c.conn.SetDeadline(t)
105}
106
107// SetReadDeadline sets the read deadline on the underlying connection.
108// A zero value for t means Read will not time out.
109func (c *Conn) SetReadDeadline(t time.Time) error {
110 return c.conn.SetReadDeadline(t)
111}
112
113// SetWriteDeadline sets the write deadline on the underlying conneciton.
114// A zero value for t means Write will not time out.
115// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
116func (c *Conn) SetWriteDeadline(t time.Time) error {
117 return c.conn.SetWriteDeadline(t)
118}
119
120// A halfConn represents one direction of the record layer
121// connection, either sending or receiving.
122type halfConn struct {
123 sync.Mutex
124
David Benjamin83c0bc92014-08-04 01:23:53 -0400125 err error // first permanent error
126 version uint16 // protocol version
127 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -0700128 cipher interface{} // cipher algorithm
129 mac macFunction
130 seq [8]byte // 64-bit sequence number
131 bfree *block // list of free blocks
132
133 nextCipher interface{} // next encryption state
134 nextMac macFunction // next MAC algorithm
David Benjamin83f90402015-01-27 01:09:43 -0500135 nextSeq [6]byte // next epoch's starting sequence number in DTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700136
137 // used to save allocating a new buffer for each MAC.
138 inDigestBuf, outDigestBuf []byte
Adam Langley80842bd2014-06-20 12:00:00 -0700139
140 config *Config
Adam Langley95c29f32014-06-20 12:00:00 -0700141}
142
143func (hc *halfConn) setErrorLocked(err error) error {
144 hc.err = err
145 return err
146}
147
148func (hc *halfConn) error() error {
Adam Langley2ae77d22014-10-28 17:29:33 -0700149 // This should be locked, but I've removed it for the renegotiation
150 // tests since we don't concurrently read and write the same tls.Conn
151 // in any case during testing.
Adam Langley95c29f32014-06-20 12:00:00 -0700152 err := hc.err
Adam Langley95c29f32014-06-20 12:00:00 -0700153 return err
154}
155
156// prepareCipherSpec sets the encryption and MAC states
157// that a subsequent changeCipherSpec will use.
158func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
159 hc.version = version
160 hc.nextCipher = cipher
161 hc.nextMac = mac
162}
163
164// changeCipherSpec changes the encryption and MAC states
165// to the ones previously passed to prepareCipherSpec.
Adam Langley80842bd2014-06-20 12:00:00 -0700166func (hc *halfConn) changeCipherSpec(config *Config) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700167 if hc.nextCipher == nil {
168 return alertInternalError
169 }
170 hc.cipher = hc.nextCipher
171 hc.mac = hc.nextMac
172 hc.nextCipher = nil
173 hc.nextMac = nil
Adam Langley80842bd2014-06-20 12:00:00 -0700174 hc.config = config
David Benjamin83c0bc92014-08-04 01:23:53 -0400175 hc.incEpoch()
Adam Langley95c29f32014-06-20 12:00:00 -0700176 return nil
177}
178
179// incSeq increments the sequence number.
David Benjamin5e961c12014-11-07 01:48:35 -0500180func (hc *halfConn) incSeq(isOutgoing bool) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400181 limit := 0
David Benjamin5e961c12014-11-07 01:48:35 -0500182 increment := uint64(1)
David Benjamin83c0bc92014-08-04 01:23:53 -0400183 if hc.isDTLS {
184 // Increment up to the epoch in DTLS.
185 limit = 2
David Benjamin5e961c12014-11-07 01:48:35 -0500186
187 if isOutgoing && hc.config.Bugs.SequenceNumberIncrement != 0 {
188 increment = hc.config.Bugs.SequenceNumberIncrement
189 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400190 }
191 for i := 7; i >= limit; i-- {
David Benjamin5e961c12014-11-07 01:48:35 -0500192 increment += uint64(hc.seq[i])
193 hc.seq[i] = byte(increment)
194 increment >>= 8
Adam Langley95c29f32014-06-20 12:00:00 -0700195 }
196
197 // Not allowed to let sequence number wrap.
198 // Instead, must renegotiate before it does.
199 // Not likely enough to bother.
David Benjamin5e961c12014-11-07 01:48:35 -0500200 if increment != 0 {
201 panic("TLS: sequence number wraparound")
202 }
Adam Langley95c29f32014-06-20 12:00:00 -0700203}
204
David Benjamin83f90402015-01-27 01:09:43 -0500205// incNextSeq increments the starting sequence number for the next epoch.
206func (hc *halfConn) incNextSeq() {
207 for i := len(hc.nextSeq) - 1; i >= 0; i-- {
208 hc.nextSeq[i]++
209 if hc.nextSeq[i] != 0 {
210 return
211 }
212 }
213 panic("TLS: sequence number wraparound")
214}
215
216// incEpoch resets the sequence number. In DTLS, it also increments the epoch
217// half of the sequence number.
David Benjamin83c0bc92014-08-04 01:23:53 -0400218func (hc *halfConn) incEpoch() {
David Benjamin83c0bc92014-08-04 01:23:53 -0400219 if hc.isDTLS {
220 for i := 1; i >= 0; i-- {
221 hc.seq[i]++
222 if hc.seq[i] != 0 {
223 break
224 }
225 if i == 0 {
226 panic("TLS: epoch number wraparound")
227 }
228 }
David Benjamin83f90402015-01-27 01:09:43 -0500229 copy(hc.seq[2:], hc.nextSeq[:])
230 for i := range hc.nextSeq {
231 hc.nextSeq[i] = 0
232 }
233 } else {
234 for i := range hc.seq {
235 hc.seq[i] = 0
236 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400237 }
238}
239
240func (hc *halfConn) recordHeaderLen() int {
241 if hc.isDTLS {
242 return dtlsRecordHeaderLen
243 }
244 return tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700245}
246
247// removePadding returns an unpadded slice, in constant time, which is a prefix
248// of the input. It also returns a byte which is equal to 255 if the padding
249// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
250func removePadding(payload []byte) ([]byte, byte) {
251 if len(payload) < 1 {
252 return payload, 0
253 }
254
255 paddingLen := payload[len(payload)-1]
256 t := uint(len(payload)-1) - uint(paddingLen)
257 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
258 good := byte(int32(^t) >> 31)
259
260 toCheck := 255 // the maximum possible padding length
261 // The length of the padded data is public, so we can use an if here
262 if toCheck+1 > len(payload) {
263 toCheck = len(payload) - 1
264 }
265
266 for i := 0; i < toCheck; i++ {
267 t := uint(paddingLen) - uint(i)
268 // if i <= paddingLen then the MSB of t is zero
269 mask := byte(int32(^t) >> 31)
270 b := payload[len(payload)-1-i]
271 good &^= mask&paddingLen ^ mask&b
272 }
273
274 // We AND together the bits of good and replicate the result across
275 // all the bits.
276 good &= good << 4
277 good &= good << 2
278 good &= good << 1
279 good = uint8(int8(good) >> 7)
280
281 toRemove := good&paddingLen + 1
282 return payload[:len(payload)-int(toRemove)], good
283}
284
285// removePaddingSSL30 is a replacement for removePadding in the case that the
286// protocol version is SSLv3. In this version, the contents of the padding
287// are random and cannot be checked.
288func removePaddingSSL30(payload []byte) ([]byte, byte) {
289 if len(payload) < 1 {
290 return payload, 0
291 }
292
293 paddingLen := int(payload[len(payload)-1]) + 1
294 if paddingLen > len(payload) {
295 return payload, 0
296 }
297
298 return payload[:len(payload)-paddingLen], 255
299}
300
301func roundUp(a, b int) int {
302 return a + (b-a%b)%b
303}
304
305// cbcMode is an interface for block ciphers using cipher block chaining.
306type cbcMode interface {
307 cipher.BlockMode
308 SetIV([]byte)
309}
310
311// decrypt checks and strips the mac and decrypts the data in b. Returns a
312// success boolean, the number of bytes to skip from the start of the record in
313// order to get the application payload, and an optional alert value.
314func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, alertValue alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400315 recordHeaderLen := hc.recordHeaderLen()
316
Adam Langley95c29f32014-06-20 12:00:00 -0700317 // pull out payload
318 payload := b.data[recordHeaderLen:]
319
320 macSize := 0
321 if hc.mac != nil {
322 macSize = hc.mac.Size()
323 }
324
325 paddingGood := byte(255)
326 explicitIVLen := 0
327
David Benjamin83c0bc92014-08-04 01:23:53 -0400328 seq := hc.seq[:]
329 if hc.isDTLS {
330 // DTLS sequence numbers are explicit.
331 seq = b.data[3:11]
332 }
333
Adam Langley95c29f32014-06-20 12:00:00 -0700334 // decrypt
335 if hc.cipher != nil {
336 switch c := hc.cipher.(type) {
337 case cipher.Stream:
338 c.XORKeyStream(payload, payload)
339 case cipher.AEAD:
340 explicitIVLen = 8
341 if len(payload) < explicitIVLen {
342 return false, 0, alertBadRecordMAC
343 }
344 nonce := payload[:8]
345 payload = payload[8:]
346
347 var additionalData [13]byte
David Benjamin83c0bc92014-08-04 01:23:53 -0400348 copy(additionalData[:], seq)
Adam Langley95c29f32014-06-20 12:00:00 -0700349 copy(additionalData[8:], b.data[:3])
350 n := len(payload) - c.Overhead()
351 additionalData[11] = byte(n >> 8)
352 additionalData[12] = byte(n)
353 var err error
354 payload, err = c.Open(payload[:0], nonce, payload, additionalData[:])
355 if err != nil {
356 return false, 0, alertBadRecordMAC
357 }
358 b.resize(recordHeaderLen + explicitIVLen + len(payload))
359 case cbcMode:
360 blockSize := c.BlockSize()
David Benjamin83c0bc92014-08-04 01:23:53 -0400361 if hc.version >= VersionTLS11 || hc.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700362 explicitIVLen = blockSize
363 }
364
365 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
366 return false, 0, alertBadRecordMAC
367 }
368
369 if explicitIVLen > 0 {
370 c.SetIV(payload[:explicitIVLen])
371 payload = payload[explicitIVLen:]
372 }
373 c.CryptBlocks(payload, payload)
374 if hc.version == VersionSSL30 {
375 payload, paddingGood = removePaddingSSL30(payload)
376 } else {
377 payload, paddingGood = removePadding(payload)
378 }
379 b.resize(recordHeaderLen + explicitIVLen + len(payload))
380
381 // note that we still have a timing side-channel in the
382 // MAC check, below. An attacker can align the record
383 // so that a correct padding will cause one less hash
384 // block to be calculated. Then they can iteratively
385 // decrypt a record by breaking each byte. See
386 // "Password Interception in a SSL/TLS Channel", Brice
387 // Canvel et al.
388 //
389 // However, our behavior matches OpenSSL, so we leak
390 // only as much as they do.
391 default:
392 panic("unknown cipher type")
393 }
394 }
395
396 // check, strip mac
397 if hc.mac != nil {
398 if len(payload) < macSize {
399 return false, 0, alertBadRecordMAC
400 }
401
402 // strip mac off payload, b.data
403 n := len(payload) - macSize
David Benjamin83c0bc92014-08-04 01:23:53 -0400404 b.data[recordHeaderLen-2] = byte(n >> 8)
405 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700406 b.resize(recordHeaderLen + explicitIVLen + n)
407 remoteMAC := payload[n:]
David Benjamin83c0bc92014-08-04 01:23:53 -0400408 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
Adam Langley95c29f32014-06-20 12:00:00 -0700409
410 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
411 return false, 0, alertBadRecordMAC
412 }
413 hc.inDigestBuf = localMAC
414 }
David Benjamin5e961c12014-11-07 01:48:35 -0500415 hc.incSeq(false)
Adam Langley95c29f32014-06-20 12:00:00 -0700416
417 return true, recordHeaderLen + explicitIVLen, 0
418}
419
420// padToBlockSize calculates the needed padding block, if any, for a payload.
421// On exit, prefix aliases payload and extends to the end of the last full
422// block of payload. finalBlock is a fresh slice which contains the contents of
423// any suffix of payload as well as the needed padding to make finalBlock a
424// full block.
Adam Langley80842bd2014-06-20 12:00:00 -0700425func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
Adam Langley95c29f32014-06-20 12:00:00 -0700426 overrun := len(payload) % blockSize
Adam Langley95c29f32014-06-20 12:00:00 -0700427 prefix = payload[:len(payload)-overrun]
Adam Langley80842bd2014-06-20 12:00:00 -0700428
429 paddingLen := blockSize - overrun
430 finalSize := blockSize
431 if config.Bugs.MaxPadding {
432 for paddingLen+blockSize <= 256 {
433 paddingLen += blockSize
434 }
435 finalSize = 256
436 }
437 finalBlock = make([]byte, finalSize)
438 for i := range finalBlock {
Adam Langley95c29f32014-06-20 12:00:00 -0700439 finalBlock[i] = byte(paddingLen - 1)
440 }
Adam Langley80842bd2014-06-20 12:00:00 -0700441 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
442 finalBlock[overrun] ^= 0xff
443 }
444 copy(finalBlock, payload[len(payload)-overrun:])
Adam Langley95c29f32014-06-20 12:00:00 -0700445 return
446}
447
448// encrypt encrypts and macs the data in b.
449func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400450 recordHeaderLen := hc.recordHeaderLen()
451
Adam Langley95c29f32014-06-20 12:00:00 -0700452 // mac
453 if hc.mac != nil {
David Benjamin83c0bc92014-08-04 01:23:53 -0400454 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 -0700455
456 n := len(b.data)
457 b.resize(n + len(mac))
458 copy(b.data[n:], mac)
459 hc.outDigestBuf = mac
460 }
461
462 payload := b.data[recordHeaderLen:]
463
464 // encrypt
465 if hc.cipher != nil {
466 switch c := hc.cipher.(type) {
467 case cipher.Stream:
468 c.XORKeyStream(payload, payload)
469 case cipher.AEAD:
470 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
471 b.resize(len(b.data) + c.Overhead())
472 nonce := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
473 payload := b.data[recordHeaderLen+explicitIVLen:]
474 payload = payload[:payloadLen]
475
476 var additionalData [13]byte
477 copy(additionalData[:], hc.seq[:])
478 copy(additionalData[8:], b.data[:3])
479 additionalData[11] = byte(payloadLen >> 8)
480 additionalData[12] = byte(payloadLen)
481
482 c.Seal(payload[:0], nonce, payload, additionalData[:])
483 case cbcMode:
484 blockSize := c.BlockSize()
485 if explicitIVLen > 0 {
486 c.SetIV(payload[:explicitIVLen])
487 payload = payload[explicitIVLen:]
488 }
Adam Langley80842bd2014-06-20 12:00:00 -0700489 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700490 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
491 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
492 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
493 default:
494 panic("unknown cipher type")
495 }
496 }
497
498 // update length to include MAC and any block padding needed.
499 n := len(b.data) - recordHeaderLen
David Benjamin83c0bc92014-08-04 01:23:53 -0400500 b.data[recordHeaderLen-2] = byte(n >> 8)
501 b.data[recordHeaderLen-1] = byte(n)
David Benjamin5e961c12014-11-07 01:48:35 -0500502 hc.incSeq(true)
Adam Langley95c29f32014-06-20 12:00:00 -0700503
504 return true, 0
505}
506
507// A block is a simple data buffer.
508type block struct {
509 data []byte
510 off int // index for Read
511 link *block
512}
513
514// resize resizes block to be n bytes, growing if necessary.
515func (b *block) resize(n int) {
516 if n > cap(b.data) {
517 b.reserve(n)
518 }
519 b.data = b.data[0:n]
520}
521
522// reserve makes sure that block contains a capacity of at least n bytes.
523func (b *block) reserve(n int) {
524 if cap(b.data) >= n {
525 return
526 }
527 m := cap(b.data)
528 if m == 0 {
529 m = 1024
530 }
531 for m < n {
532 m *= 2
533 }
534 data := make([]byte, len(b.data), m)
535 copy(data, b.data)
536 b.data = data
537}
538
539// readFromUntil reads from r into b until b contains at least n bytes
540// or else returns an error.
541func (b *block) readFromUntil(r io.Reader, n int) error {
542 // quick case
543 if len(b.data) >= n {
544 return nil
545 }
546
547 // read until have enough.
548 b.reserve(n)
549 for {
550 m, err := r.Read(b.data[len(b.data):cap(b.data)])
551 b.data = b.data[0 : len(b.data)+m]
552 if len(b.data) >= n {
553 // TODO(bradfitz,agl): slightly suspicious
554 // that we're throwing away r.Read's err here.
555 break
556 }
557 if err != nil {
558 return err
559 }
560 }
561 return nil
562}
563
564func (b *block) Read(p []byte) (n int, err error) {
565 n = copy(p, b.data[b.off:])
566 b.off += n
567 return
568}
569
570// newBlock allocates a new block, from hc's free list if possible.
571func (hc *halfConn) newBlock() *block {
572 b := hc.bfree
573 if b == nil {
574 return new(block)
575 }
576 hc.bfree = b.link
577 b.link = nil
578 b.resize(0)
579 return b
580}
581
582// freeBlock returns a block to hc's free list.
583// The protocol is such that each side only has a block or two on
584// its free list at a time, so there's no need to worry about
585// trimming the list, etc.
586func (hc *halfConn) freeBlock(b *block) {
587 b.link = hc.bfree
588 hc.bfree = b
589}
590
591// splitBlock splits a block after the first n bytes,
592// returning a block with those n bytes and a
593// block with the remainder. the latter may be nil.
594func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
595 if len(b.data) <= n {
596 return b, nil
597 }
598 bb := hc.newBlock()
599 bb.resize(len(b.data) - n)
600 copy(bb.data, b.data[n:])
601 b.data = b.data[0:n]
602 return b, bb
603}
604
David Benjamin83c0bc92014-08-04 01:23:53 -0400605func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
606 if c.isDTLS {
607 return c.dtlsDoReadRecord(want)
608 }
609
610 recordHeaderLen := tlsRecordHeaderLen
611
612 if c.rawInput == nil {
613 c.rawInput = c.in.newBlock()
614 }
615 b := c.rawInput
616
617 // Read header, payload.
618 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
619 // RFC suggests that EOF without an alertCloseNotify is
620 // an error, but popular web sites seem to do this,
621 // so we can't make it an error.
622 // if err == io.EOF {
623 // err = io.ErrUnexpectedEOF
624 // }
625 if e, ok := err.(net.Error); !ok || !e.Temporary() {
626 c.in.setErrorLocked(err)
627 }
628 return 0, nil, err
629 }
630 typ := recordType(b.data[0])
631
632 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
633 // start with a uint16 length where the MSB is set and the first record
634 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
635 // an SSLv2 client.
636 if want == recordTypeHandshake && typ == 0x80 {
637 c.sendAlert(alertProtocolVersion)
638 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
639 }
640
641 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
642 n := int(b.data[3])<<8 | int(b.data[4])
David Benjamin1e29a6b2014-12-10 02:27:24 -0500643 if c.haveVers {
644 if vers != c.vers {
645 c.sendAlert(alertProtocolVersion)
646 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers))
647 }
648 } else {
649 if expect := c.config.Bugs.ExpectInitialRecordVersion; expect != 0 && vers != expect {
650 c.sendAlert(alertProtocolVersion)
651 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
652 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400653 }
654 if n > maxCiphertext {
655 c.sendAlert(alertRecordOverflow)
656 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
657 }
658 if !c.haveVers {
659 // First message, be extra suspicious:
660 // this might not be a TLS client.
661 // Bail out before reading a full 'body', if possible.
662 // The current max version is 3.1.
663 // If the version is >= 16.0, it's probably not real.
664 // Similarly, a clientHello message encodes in
665 // well under a kilobyte. If the length is >= 12 kB,
666 // it's probably not real.
667 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
668 c.sendAlert(alertUnexpectedMessage)
669 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
670 }
671 }
672 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
673 if err == io.EOF {
674 err = io.ErrUnexpectedEOF
675 }
676 if e, ok := err.(net.Error); !ok || !e.Temporary() {
677 c.in.setErrorLocked(err)
678 }
679 return 0, nil, err
680 }
681
682 // Process message.
683 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
684 ok, off, err := c.in.decrypt(b)
685 if !ok {
686 c.in.setErrorLocked(c.sendAlert(err))
687 }
688 b.off = off
689 return typ, b, nil
690}
691
Adam Langley95c29f32014-06-20 12:00:00 -0700692// readRecord reads the next TLS record from the connection
693// and updates the record layer state.
694// c.in.Mutex <= L; c.input == nil.
695func (c *Conn) readRecord(want recordType) error {
696 // Caller must be in sync with connection:
697 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700698 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700699 switch want {
700 default:
701 c.sendAlert(alertInternalError)
702 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
703 case recordTypeHandshake, recordTypeChangeCipherSpec:
704 if c.handshakeComplete {
705 c.sendAlert(alertInternalError)
706 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
707 }
708 case recordTypeApplicationData:
David Benjamine58c4f52014-08-24 03:47:07 -0400709 if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart {
Adam Langley95c29f32014-06-20 12:00:00 -0700710 c.sendAlert(alertInternalError)
711 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
712 }
713 }
714
715Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400716 typ, b, err := c.doReadRecord(want)
717 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700718 return err
719 }
Adam Langley95c29f32014-06-20 12:00:00 -0700720 data := b.data[b.off:]
721 if len(data) > maxPlaintext {
722 err := c.sendAlert(alertRecordOverflow)
723 c.in.freeBlock(b)
724 return c.in.setErrorLocked(err)
725 }
726
727 switch typ {
728 default:
729 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
730
731 case recordTypeAlert:
732 if len(data) != 2 {
733 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
734 break
735 }
736 if alert(data[1]) == alertCloseNotify {
737 c.in.setErrorLocked(io.EOF)
738 break
739 }
740 switch data[0] {
741 case alertLevelWarning:
742 // drop on the floor
743 c.in.freeBlock(b)
744 goto Again
745 case alertLevelError:
746 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
747 default:
748 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
749 }
750
751 case recordTypeChangeCipherSpec:
752 if typ != want || len(data) != 1 || data[0] != 1 {
753 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
754 break
755 }
Adam Langley80842bd2014-06-20 12:00:00 -0700756 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700757 if err != nil {
758 c.in.setErrorLocked(c.sendAlert(err.(alert)))
759 }
760
761 case recordTypeApplicationData:
762 if typ != want {
763 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
764 break
765 }
766 c.input = b
767 b = nil
768
769 case recordTypeHandshake:
770 // TODO(rsc): Should at least pick off connection close.
771 if typ != want {
Adam Langley2ae77d22014-10-28 17:29:33 -0700772 // A client might need to process a HelloRequest from
773 // the server, thus receiving a handshake message when
David Benjamind9b091b2015-01-27 01:10:54 -0500774 // application data is expected is ok.
775 if !c.isClient {
Adam Langley2ae77d22014-10-28 17:29:33 -0700776 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
777 }
Adam Langley95c29f32014-06-20 12:00:00 -0700778 }
779 c.hand.Write(data)
780 }
781
782 if b != nil {
783 c.in.freeBlock(b)
784 }
785 return c.in.err
786}
787
788// sendAlert sends a TLS alert message.
789// c.out.Mutex <= L.
790func (c *Conn) sendAlertLocked(err alert) error {
791 switch err {
792 case alertNoRenegotiation, alertCloseNotify:
793 c.tmp[0] = alertLevelWarning
794 default:
795 c.tmp[0] = alertLevelError
796 }
797 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400798 if c.config.Bugs.FragmentAlert {
799 c.writeRecord(recordTypeAlert, c.tmp[0:1])
800 c.writeRecord(recordTypeAlert, c.tmp[1:2])
801 } else {
802 c.writeRecord(recordTypeAlert, c.tmp[0:2])
803 }
Adam Langley95c29f32014-06-20 12:00:00 -0700804 // closeNotify is a special case in that it isn't an error:
805 if err != alertCloseNotify {
806 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
807 }
808 return nil
809}
810
811// sendAlert sends a TLS alert message.
812// L < c.out.Mutex.
813func (c *Conn) sendAlert(err alert) error {
814 c.out.Lock()
815 defer c.out.Unlock()
816 return c.sendAlertLocked(err)
817}
818
David Benjamind86c7672014-08-02 04:07:12 -0400819// writeV2Record writes a record for a V2ClientHello.
820func (c *Conn) writeV2Record(data []byte) (n int, err error) {
821 record := make([]byte, 2+len(data))
822 record[0] = uint8(len(data)>>8) | 0x80
823 record[1] = uint8(len(data))
824 copy(record[2:], data)
825 return c.conn.Write(record)
826}
827
Adam Langley95c29f32014-06-20 12:00:00 -0700828// writeRecord writes a TLS record with the given type and payload
829// to the connection and updates the record layer state.
830// c.out.Mutex <= L.
831func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400832 if c.isDTLS {
833 return c.dtlsWriteRecord(typ, data)
834 }
835
836 recordHeaderLen := tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700837 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -0400838 first := true
839 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
Adam Langley95c29f32014-06-20 12:00:00 -0700840 for len(data) > 0 {
841 m := len(data)
842 if m > maxPlaintext {
843 m = maxPlaintext
844 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400845 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
846 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -0400847 // By default, do not fragment the client_version or
848 // server_version, which are located in the first 6
849 // bytes.
850 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
851 m = 6
852 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400853 }
Adam Langley95c29f32014-06-20 12:00:00 -0700854 explicitIVLen := 0
855 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -0400856 first = false
Adam Langley95c29f32014-06-20 12:00:00 -0700857
858 var cbc cbcMode
859 if c.out.version >= VersionTLS11 {
860 var ok bool
861 if cbc, ok = c.out.cipher.(cbcMode); ok {
862 explicitIVLen = cbc.BlockSize()
863 }
864 }
865 if explicitIVLen == 0 {
866 if _, ok := c.out.cipher.(cipher.AEAD); ok {
867 explicitIVLen = 8
868 // The AES-GCM construction in TLS has an
869 // explicit nonce so that the nonce can be
870 // random. However, the nonce is only 8 bytes
871 // which is too small for a secure, random
872 // nonce. Therefore we use the sequence number
873 // as the nonce.
874 explicitIVIsSeq = true
875 }
876 }
877 b.resize(recordHeaderLen + explicitIVLen + m)
878 b.data[0] = byte(typ)
879 vers := c.vers
880 if vers == 0 {
881 // Some TLS servers fail if the record version is
882 // greater than TLS 1.0 for the initial ClientHello.
883 vers = VersionTLS10
884 }
885 b.data[1] = byte(vers >> 8)
886 b.data[2] = byte(vers)
887 b.data[3] = byte(m >> 8)
888 b.data[4] = byte(m)
889 if explicitIVLen > 0 {
890 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
891 if explicitIVIsSeq {
892 copy(explicitIV, c.out.seq[:])
893 } else {
894 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
895 break
896 }
897 }
898 }
899 copy(b.data[recordHeaderLen+explicitIVLen:], data)
900 c.out.encrypt(b, explicitIVLen)
901 _, err = c.conn.Write(b.data)
902 if err != nil {
903 break
904 }
905 n += m
906 data = data[m:]
907 }
908 c.out.freeBlock(b)
909
910 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -0700911 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700912 if err != nil {
913 // Cannot call sendAlert directly,
914 // because we already hold c.out.Mutex.
915 c.tmp[0] = alertLevelError
916 c.tmp[1] = byte(err.(alert))
917 c.writeRecord(recordTypeAlert, c.tmp[0:2])
918 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
919 }
920 }
921 return
922}
923
David Benjamin83c0bc92014-08-04 01:23:53 -0400924func (c *Conn) doReadHandshake() ([]byte, error) {
925 if c.isDTLS {
926 return c.dtlsDoReadHandshake()
927 }
928
Adam Langley95c29f32014-06-20 12:00:00 -0700929 for c.hand.Len() < 4 {
930 if err := c.in.err; err != nil {
931 return nil, err
932 }
933 if err := c.readRecord(recordTypeHandshake); err != nil {
934 return nil, err
935 }
936 }
937
938 data := c.hand.Bytes()
939 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
940 if n > maxHandshake {
941 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
942 }
943 for c.hand.Len() < 4+n {
944 if err := c.in.err; err != nil {
945 return nil, err
946 }
947 if err := c.readRecord(recordTypeHandshake); err != nil {
948 return nil, err
949 }
950 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400951 return c.hand.Next(4 + n), nil
952}
953
954// readHandshake reads the next handshake message from
955// the record layer.
956// c.in.Mutex < L; c.out.Mutex < L.
957func (c *Conn) readHandshake() (interface{}, error) {
958 data, err := c.doReadHandshake()
959 if err != nil {
960 return nil, err
961 }
962
Adam Langley95c29f32014-06-20 12:00:00 -0700963 var m handshakeMessage
964 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -0700965 case typeHelloRequest:
966 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -0700967 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -0400968 m = &clientHelloMsg{
969 isDTLS: c.isDTLS,
970 }
Adam Langley95c29f32014-06-20 12:00:00 -0700971 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -0400972 m = &serverHelloMsg{
973 isDTLS: c.isDTLS,
974 }
Adam Langley95c29f32014-06-20 12:00:00 -0700975 case typeNewSessionTicket:
976 m = new(newSessionTicketMsg)
977 case typeCertificate:
978 m = new(certificateMsg)
979 case typeCertificateRequest:
980 m = &certificateRequestMsg{
981 hasSignatureAndHash: c.vers >= VersionTLS12,
982 }
983 case typeCertificateStatus:
984 m = new(certificateStatusMsg)
985 case typeServerKeyExchange:
986 m = new(serverKeyExchangeMsg)
987 case typeServerHelloDone:
988 m = new(serverHelloDoneMsg)
989 case typeClientKeyExchange:
990 m = new(clientKeyExchangeMsg)
991 case typeCertificateVerify:
992 m = &certificateVerifyMsg{
993 hasSignatureAndHash: c.vers >= VersionTLS12,
994 }
995 case typeNextProtocol:
996 m = new(nextProtoMsg)
997 case typeFinished:
998 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400999 case typeHelloVerifyRequest:
1000 m = new(helloVerifyRequestMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001001 case typeEncryptedExtensions:
1002 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001003 default:
1004 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1005 }
1006
1007 // The handshake message unmarshallers
1008 // expect to be able to keep references to data,
1009 // so pass in a fresh copy that won't be overwritten.
1010 data = append([]byte(nil), data...)
1011
1012 if !m.unmarshal(data) {
1013 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1014 }
1015 return m, nil
1016}
1017
David Benjamin83f90402015-01-27 01:09:43 -05001018// skipPacket processes all the DTLS records in packet. It updates
1019// sequence number expectations but otherwise ignores them.
1020func (c *Conn) skipPacket(packet []byte) error {
1021 for len(packet) > 0 {
1022 // Dropped packets are completely ignored save to update
1023 // expected sequence numbers for this and the next epoch. (We
1024 // don't assert on the contents of the packets both for
1025 // simplicity and because a previous test with one shorter
1026 // timeout schedule would have done so.)
1027 epoch := packet[3:5]
1028 seq := packet[5:11]
1029 length := uint16(packet[11])<<8 | uint16(packet[12])
1030 if bytes.Equal(c.in.seq[:2], epoch) {
1031 if !bytes.Equal(c.in.seq[2:], seq) {
1032 return errors.New("tls: sequence mismatch")
1033 }
1034 c.in.incSeq(false)
1035 } else {
1036 if !bytes.Equal(c.in.nextSeq[:], seq) {
1037 return errors.New("tls: sequence mismatch")
1038 }
1039 c.in.incNextSeq()
1040 }
1041 packet = packet[13+length:]
1042 }
1043 return nil
1044}
1045
1046// simulatePacketLoss simulates the loss of a handshake leg from the
1047// peer based on the schedule in c.config.Bugs. If resendFunc is
1048// non-nil, it is called after each simulated timeout to retransmit
1049// handshake messages from the local end. This is used in cases where
1050// the peer retransmits on a stale Finished rather than a timeout.
1051func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1052 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1053 return nil
1054 }
1055 if !c.isDTLS {
1056 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1057 }
1058 if c.config.Bugs.PacketAdaptor == nil {
1059 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1060 }
1061 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1062 // Simulate a timeout.
1063 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1064 if err != nil {
1065 return err
1066 }
1067 for _, packet := range packets {
1068 if err := c.skipPacket(packet); err != nil {
1069 return err
1070 }
1071 }
1072 if resendFunc != nil {
1073 resendFunc()
1074 }
1075 }
1076 return nil
1077}
1078
Adam Langley95c29f32014-06-20 12:00:00 -07001079// Write writes data to the connection.
1080func (c *Conn) Write(b []byte) (int, error) {
1081 if err := c.Handshake(); err != nil {
1082 return 0, err
1083 }
1084
1085 c.out.Lock()
1086 defer c.out.Unlock()
1087
1088 if err := c.out.err; err != nil {
1089 return 0, err
1090 }
1091
1092 if !c.handshakeComplete {
1093 return 0, alertInternalError
1094 }
1095
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001096 if c.config.Bugs.SendSpuriousAlert {
1097 c.sendAlertLocked(alertRecordOverflow)
1098 }
1099
Adam Langley95c29f32014-06-20 12:00:00 -07001100 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1101 // attack when using block mode ciphers due to predictable IVs.
1102 // This can be prevented by splitting each Application Data
1103 // record into two records, effectively randomizing the IV.
1104 //
1105 // http://www.openssl.org/~bodo/tls-cbc.txt
1106 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1107 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1108
1109 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001110 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001111 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1112 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1113 if err != nil {
1114 return n, c.out.setErrorLocked(err)
1115 }
1116 m, b = 1, b[1:]
1117 }
1118 }
1119
1120 n, err := c.writeRecord(recordTypeApplicationData, b)
1121 return n + m, c.out.setErrorLocked(err)
1122}
1123
Adam Langley2ae77d22014-10-28 17:29:33 -07001124func (c *Conn) handleRenegotiation() error {
1125 c.handshakeComplete = false
1126 if !c.isClient {
1127 panic("renegotiation should only happen for a client")
1128 }
1129
1130 msg, err := c.readHandshake()
1131 if err != nil {
1132 return err
1133 }
1134 _, ok := msg.(*helloRequestMsg)
1135 if !ok {
1136 c.sendAlert(alertUnexpectedMessage)
1137 return alertUnexpectedMessage
1138 }
1139
1140 return c.Handshake()
1141}
1142
Adam Langleycf2d4f42014-10-28 19:06:14 -07001143func (c *Conn) Renegotiate() error {
1144 if !c.isClient {
1145 helloReq := new(helloRequestMsg)
1146 c.writeRecord(recordTypeHandshake, helloReq.marshal())
1147 }
1148
1149 c.handshakeComplete = false
1150 return c.Handshake()
1151}
1152
Adam Langley95c29f32014-06-20 12:00:00 -07001153// Read can be made to time out and return a net.Error with Timeout() == true
1154// after a fixed time limit; see SetDeadline and SetReadDeadline.
1155func (c *Conn) Read(b []byte) (n int, err error) {
1156 if err = c.Handshake(); err != nil {
1157 return
1158 }
1159
1160 c.in.Lock()
1161 defer c.in.Unlock()
1162
1163 // Some OpenSSL servers send empty records in order to randomize the
1164 // CBC IV. So this loop ignores a limited number of empty records.
1165 const maxConsecutiveEmptyRecords = 100
1166 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1167 for c.input == nil && c.in.err == nil {
1168 if err := c.readRecord(recordTypeApplicationData); err != nil {
1169 // Soft error, like EAGAIN
1170 return 0, err
1171 }
David Benjamind9b091b2015-01-27 01:10:54 -05001172 if c.hand.Len() > 0 {
Adam Langley2ae77d22014-10-28 17:29:33 -07001173 // We received handshake bytes, indicating the
David Benjamind9b091b2015-01-27 01:10:54 -05001174 // start of a renegotiation.
Adam Langley2ae77d22014-10-28 17:29:33 -07001175 if err := c.handleRenegotiation(); err != nil {
1176 return 0, err
1177 }
1178 continue
1179 }
Adam Langley95c29f32014-06-20 12:00:00 -07001180 }
1181 if err := c.in.err; err != nil {
1182 return 0, err
1183 }
1184
1185 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001186 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001187 c.in.freeBlock(c.input)
1188 c.input = nil
1189 }
1190
1191 // If a close-notify alert is waiting, read it so that
1192 // we can return (n, EOF) instead of (n, nil), to signal
1193 // to the HTTP response reading goroutine that the
1194 // connection is now closed. This eliminates a race
1195 // where the HTTP response reading goroutine would
1196 // otherwise not observe the EOF until its next read,
1197 // by which time a client goroutine might have already
1198 // tried to reuse the HTTP connection for a new
1199 // request.
1200 // See https://codereview.appspot.com/76400046
1201 // and http://golang.org/issue/3514
1202 if ri := c.rawInput; ri != nil &&
1203 n != 0 && err == nil &&
1204 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1205 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1206 err = recErr // will be io.EOF on closeNotify
1207 }
1208 }
1209
1210 if n != 0 || err != nil {
1211 return n, err
1212 }
1213 }
1214
1215 return 0, io.ErrNoProgress
1216}
1217
1218// Close closes the connection.
1219func (c *Conn) Close() error {
1220 var alertErr error
1221
1222 c.handshakeMutex.Lock()
1223 defer c.handshakeMutex.Unlock()
1224 if c.handshakeComplete {
1225 alertErr = c.sendAlert(alertCloseNotify)
1226 }
1227
1228 if err := c.conn.Close(); err != nil {
1229 return err
1230 }
1231 return alertErr
1232}
1233
1234// Handshake runs the client or server handshake
1235// protocol if it has not yet been run.
1236// Most uses of this package need not call Handshake
1237// explicitly: the first Read or Write will call it automatically.
1238func (c *Conn) Handshake() error {
1239 c.handshakeMutex.Lock()
1240 defer c.handshakeMutex.Unlock()
1241 if err := c.handshakeErr; err != nil {
1242 return err
1243 }
1244 if c.handshakeComplete {
1245 return nil
1246 }
1247
1248 if c.isClient {
1249 c.handshakeErr = c.clientHandshake()
1250 } else {
1251 c.handshakeErr = c.serverHandshake()
1252 }
1253 return c.handshakeErr
1254}
1255
1256// ConnectionState returns basic TLS details about the connection.
1257func (c *Conn) ConnectionState() ConnectionState {
1258 c.handshakeMutex.Lock()
1259 defer c.handshakeMutex.Unlock()
1260
1261 var state ConnectionState
1262 state.HandshakeComplete = c.handshakeComplete
1263 if c.handshakeComplete {
1264 state.Version = c.vers
1265 state.NegotiatedProtocol = c.clientProtocol
1266 state.DidResume = c.didResume
1267 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001268 state.NegotiatedProtocolFromALPN = c.usedALPN
Adam Langley95c29f32014-06-20 12:00:00 -07001269 state.CipherSuite = c.cipherSuite
1270 state.PeerCertificates = c.peerCertificates
1271 state.VerifiedChains = c.verifiedChains
1272 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001273 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001274 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langley95c29f32014-06-20 12:00:00 -07001275 }
1276
1277 return state
1278}
1279
1280// OCSPResponse returns the stapled OCSP response from the TLS server, if
1281// any. (Only valid for client connections.)
1282func (c *Conn) OCSPResponse() []byte {
1283 c.handshakeMutex.Lock()
1284 defer c.handshakeMutex.Unlock()
1285
1286 return c.ocspResponse
1287}
1288
1289// VerifyHostname checks that the peer certificate chain is valid for
1290// connecting to host. If so, it returns nil; if not, it returns an error
1291// describing the problem.
1292func (c *Conn) VerifyHostname(host string) error {
1293 c.handshakeMutex.Lock()
1294 defer c.handshakeMutex.Unlock()
1295 if !c.isClient {
1296 return errors.New("tls: VerifyHostname called on TLS server connection")
1297 }
1298 if !c.handshakeComplete {
1299 return errors.New("tls: handshake has not yet been performed")
1300 }
1301 return c.peerCertificates[0].VerifyHostname(host)
1302}