blob: 0fe34b776519506096338f99c13bc3bfb0ab12e5 [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)
341 case cipher.AEAD:
342 explicitIVLen = 8
343 if len(payload) < explicitIVLen {
344 return false, 0, alertBadRecordMAC
345 }
346 nonce := payload[:8]
347 payload = payload[8:]
348
349 var additionalData [13]byte
David Benjamin83c0bc92014-08-04 01:23:53 -0400350 copy(additionalData[:], seq)
Adam Langley95c29f32014-06-20 12:00:00 -0700351 copy(additionalData[8:], b.data[:3])
352 n := len(payload) - c.Overhead()
353 additionalData[11] = byte(n >> 8)
354 additionalData[12] = byte(n)
355 var err error
356 payload, err = c.Open(payload[:0], nonce, payload, additionalData[:])
357 if err != nil {
358 return false, 0, alertBadRecordMAC
359 }
360 b.resize(recordHeaderLen + explicitIVLen + len(payload))
361 case cbcMode:
362 blockSize := c.BlockSize()
David Benjamin83c0bc92014-08-04 01:23:53 -0400363 if hc.version >= VersionTLS11 || hc.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700364 explicitIVLen = blockSize
365 }
366
367 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
368 return false, 0, alertBadRecordMAC
369 }
370
371 if explicitIVLen > 0 {
372 c.SetIV(payload[:explicitIVLen])
373 payload = payload[explicitIVLen:]
374 }
375 c.CryptBlocks(payload, payload)
376 if hc.version == VersionSSL30 {
377 payload, paddingGood = removePaddingSSL30(payload)
378 } else {
379 payload, paddingGood = removePadding(payload)
380 }
381 b.resize(recordHeaderLen + explicitIVLen + len(payload))
382
383 // note that we still have a timing side-channel in the
384 // MAC check, below. An attacker can align the record
385 // so that a correct padding will cause one less hash
386 // block to be calculated. Then they can iteratively
387 // decrypt a record by breaking each byte. See
388 // "Password Interception in a SSL/TLS Channel", Brice
389 // Canvel et al.
390 //
391 // However, our behavior matches OpenSSL, so we leak
392 // only as much as they do.
393 default:
394 panic("unknown cipher type")
395 }
396 }
397
398 // check, strip mac
399 if hc.mac != nil {
400 if len(payload) < macSize {
401 return false, 0, alertBadRecordMAC
402 }
403
404 // strip mac off payload, b.data
405 n := len(payload) - macSize
David Benjamin83c0bc92014-08-04 01:23:53 -0400406 b.data[recordHeaderLen-2] = byte(n >> 8)
407 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700408 b.resize(recordHeaderLen + explicitIVLen + n)
409 remoteMAC := payload[n:]
David Benjamin83c0bc92014-08-04 01:23:53 -0400410 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
Adam Langley95c29f32014-06-20 12:00:00 -0700411
412 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
413 return false, 0, alertBadRecordMAC
414 }
415 hc.inDigestBuf = localMAC
416 }
David Benjamin5e961c12014-11-07 01:48:35 -0500417 hc.incSeq(false)
Adam Langley95c29f32014-06-20 12:00:00 -0700418
419 return true, recordHeaderLen + explicitIVLen, 0
420}
421
422// padToBlockSize calculates the needed padding block, if any, for a payload.
423// On exit, prefix aliases payload and extends to the end of the last full
424// block of payload. finalBlock is a fresh slice which contains the contents of
425// any suffix of payload as well as the needed padding to make finalBlock a
426// full block.
Adam Langley80842bd2014-06-20 12:00:00 -0700427func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
Adam Langley95c29f32014-06-20 12:00:00 -0700428 overrun := len(payload) % blockSize
Adam Langley95c29f32014-06-20 12:00:00 -0700429 prefix = payload[:len(payload)-overrun]
Adam Langley80842bd2014-06-20 12:00:00 -0700430
431 paddingLen := blockSize - overrun
432 finalSize := blockSize
433 if config.Bugs.MaxPadding {
434 for paddingLen+blockSize <= 256 {
435 paddingLen += blockSize
436 }
437 finalSize = 256
438 }
439 finalBlock = make([]byte, finalSize)
440 for i := range finalBlock {
Adam Langley95c29f32014-06-20 12:00:00 -0700441 finalBlock[i] = byte(paddingLen - 1)
442 }
Adam Langley80842bd2014-06-20 12:00:00 -0700443 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
444 finalBlock[overrun] ^= 0xff
445 }
446 copy(finalBlock, payload[len(payload)-overrun:])
Adam Langley95c29f32014-06-20 12:00:00 -0700447 return
448}
449
450// encrypt encrypts and macs the data in b.
451func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400452 recordHeaderLen := hc.recordHeaderLen()
453
Adam Langley95c29f32014-06-20 12:00:00 -0700454 // mac
455 if hc.mac != nil {
David Benjamin83c0bc92014-08-04 01:23:53 -0400456 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 -0700457
458 n := len(b.data)
459 b.resize(n + len(mac))
460 copy(b.data[n:], mac)
461 hc.outDigestBuf = mac
462 }
463
464 payload := b.data[recordHeaderLen:]
465
466 // encrypt
467 if hc.cipher != nil {
468 switch c := hc.cipher.(type) {
469 case cipher.Stream:
470 c.XORKeyStream(payload, payload)
471 case cipher.AEAD:
472 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
473 b.resize(len(b.data) + c.Overhead())
474 nonce := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
475 payload := b.data[recordHeaderLen+explicitIVLen:]
476 payload = payload[:payloadLen]
477
478 var additionalData [13]byte
479 copy(additionalData[:], hc.seq[:])
480 copy(additionalData[8:], b.data[:3])
481 additionalData[11] = byte(payloadLen >> 8)
482 additionalData[12] = byte(payloadLen)
483
484 c.Seal(payload[:0], nonce, payload, additionalData[:])
485 case cbcMode:
486 blockSize := c.BlockSize()
487 if explicitIVLen > 0 {
488 c.SetIV(payload[:explicitIVLen])
489 payload = payload[explicitIVLen:]
490 }
Adam Langley80842bd2014-06-20 12:00:00 -0700491 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700492 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
493 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
494 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
495 default:
496 panic("unknown cipher type")
497 }
498 }
499
500 // update length to include MAC and any block padding needed.
501 n := len(b.data) - recordHeaderLen
David Benjamin83c0bc92014-08-04 01:23:53 -0400502 b.data[recordHeaderLen-2] = byte(n >> 8)
503 b.data[recordHeaderLen-1] = byte(n)
David Benjamin5e961c12014-11-07 01:48:35 -0500504 hc.incSeq(true)
Adam Langley95c29f32014-06-20 12:00:00 -0700505
506 return true, 0
507}
508
509// A block is a simple data buffer.
510type block struct {
511 data []byte
512 off int // index for Read
513 link *block
514}
515
516// resize resizes block to be n bytes, growing if necessary.
517func (b *block) resize(n int) {
518 if n > cap(b.data) {
519 b.reserve(n)
520 }
521 b.data = b.data[0:n]
522}
523
524// reserve makes sure that block contains a capacity of at least n bytes.
525func (b *block) reserve(n int) {
526 if cap(b.data) >= n {
527 return
528 }
529 m := cap(b.data)
530 if m == 0 {
531 m = 1024
532 }
533 for m < n {
534 m *= 2
535 }
536 data := make([]byte, len(b.data), m)
537 copy(data, b.data)
538 b.data = data
539}
540
541// readFromUntil reads from r into b until b contains at least n bytes
542// or else returns an error.
543func (b *block) readFromUntil(r io.Reader, n int) error {
544 // quick case
545 if len(b.data) >= n {
546 return nil
547 }
548
549 // read until have enough.
550 b.reserve(n)
551 for {
552 m, err := r.Read(b.data[len(b.data):cap(b.data)])
553 b.data = b.data[0 : len(b.data)+m]
554 if len(b.data) >= n {
555 // TODO(bradfitz,agl): slightly suspicious
556 // that we're throwing away r.Read's err here.
557 break
558 }
559 if err != nil {
560 return err
561 }
562 }
563 return nil
564}
565
566func (b *block) Read(p []byte) (n int, err error) {
567 n = copy(p, b.data[b.off:])
568 b.off += n
569 return
570}
571
572// newBlock allocates a new block, from hc's free list if possible.
573func (hc *halfConn) newBlock() *block {
574 b := hc.bfree
575 if b == nil {
576 return new(block)
577 }
578 hc.bfree = b.link
579 b.link = nil
580 b.resize(0)
581 return b
582}
583
584// freeBlock returns a block to hc's free list.
585// The protocol is such that each side only has a block or two on
586// its free list at a time, so there's no need to worry about
587// trimming the list, etc.
588func (hc *halfConn) freeBlock(b *block) {
589 b.link = hc.bfree
590 hc.bfree = b
591}
592
593// splitBlock splits a block after the first n bytes,
594// returning a block with those n bytes and a
595// block with the remainder. the latter may be nil.
596func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
597 if len(b.data) <= n {
598 return b, nil
599 }
600 bb := hc.newBlock()
601 bb.resize(len(b.data) - n)
602 copy(bb.data, b.data[n:])
603 b.data = b.data[0:n]
604 return b, bb
605}
606
David Benjamin83c0bc92014-08-04 01:23:53 -0400607func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
608 if c.isDTLS {
609 return c.dtlsDoReadRecord(want)
610 }
611
612 recordHeaderLen := tlsRecordHeaderLen
613
614 if c.rawInput == nil {
615 c.rawInput = c.in.newBlock()
616 }
617 b := c.rawInput
618
619 // Read header, payload.
620 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
621 // RFC suggests that EOF without an alertCloseNotify is
622 // an error, but popular web sites seem to do this,
623 // so we can't make it an error.
624 // if err == io.EOF {
625 // err = io.ErrUnexpectedEOF
626 // }
627 if e, ok := err.(net.Error); !ok || !e.Temporary() {
628 c.in.setErrorLocked(err)
629 }
630 return 0, nil, err
631 }
632 typ := recordType(b.data[0])
633
634 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
635 // start with a uint16 length where the MSB is set and the first record
636 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
637 // an SSLv2 client.
638 if want == recordTypeHandshake && typ == 0x80 {
639 c.sendAlert(alertProtocolVersion)
640 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
641 }
642
643 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
644 n := int(b.data[3])<<8 | int(b.data[4])
David Benjamin1e29a6b2014-12-10 02:27:24 -0500645 if c.haveVers {
646 if vers != c.vers {
647 c.sendAlert(alertProtocolVersion)
648 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers))
649 }
650 } else {
651 if expect := c.config.Bugs.ExpectInitialRecordVersion; expect != 0 && vers != expect {
652 c.sendAlert(alertProtocolVersion)
653 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
654 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400655 }
656 if n > maxCiphertext {
657 c.sendAlert(alertRecordOverflow)
658 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
659 }
660 if !c.haveVers {
661 // First message, be extra suspicious:
662 // this might not be a TLS client.
663 // Bail out before reading a full 'body', if possible.
664 // The current max version is 3.1.
665 // If the version is >= 16.0, it's probably not real.
666 // Similarly, a clientHello message encodes in
667 // well under a kilobyte. If the length is >= 12 kB,
668 // it's probably not real.
669 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
670 c.sendAlert(alertUnexpectedMessage)
671 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
672 }
673 }
674 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
675 if err == io.EOF {
676 err = io.ErrUnexpectedEOF
677 }
678 if e, ok := err.(net.Error); !ok || !e.Temporary() {
679 c.in.setErrorLocked(err)
680 }
681 return 0, nil, err
682 }
683
684 // Process message.
685 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
686 ok, off, err := c.in.decrypt(b)
687 if !ok {
688 c.in.setErrorLocked(c.sendAlert(err))
689 }
690 b.off = off
691 return typ, b, nil
692}
693
Adam Langley95c29f32014-06-20 12:00:00 -0700694// readRecord reads the next TLS record from the connection
695// and updates the record layer state.
696// c.in.Mutex <= L; c.input == nil.
697func (c *Conn) readRecord(want recordType) error {
698 // Caller must be in sync with connection:
699 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700700 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700701 switch want {
702 default:
703 c.sendAlert(alertInternalError)
704 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
705 case recordTypeHandshake, recordTypeChangeCipherSpec:
706 if c.handshakeComplete {
707 c.sendAlert(alertInternalError)
708 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
709 }
710 case recordTypeApplicationData:
David Benjamine58c4f52014-08-24 03:47:07 -0400711 if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart {
Adam Langley95c29f32014-06-20 12:00:00 -0700712 c.sendAlert(alertInternalError)
713 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
714 }
715 }
716
717Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400718 typ, b, err := c.doReadRecord(want)
719 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700720 return err
721 }
Adam Langley95c29f32014-06-20 12:00:00 -0700722 data := b.data[b.off:]
723 if len(data) > maxPlaintext {
724 err := c.sendAlert(alertRecordOverflow)
725 c.in.freeBlock(b)
726 return c.in.setErrorLocked(err)
727 }
728
729 switch typ {
730 default:
731 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
732
733 case recordTypeAlert:
734 if len(data) != 2 {
735 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
736 break
737 }
738 if alert(data[1]) == alertCloseNotify {
739 c.in.setErrorLocked(io.EOF)
740 break
741 }
742 switch data[0] {
743 case alertLevelWarning:
744 // drop on the floor
745 c.in.freeBlock(b)
746 goto Again
747 case alertLevelError:
748 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
749 default:
750 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
751 }
752
753 case recordTypeChangeCipherSpec:
754 if typ != want || len(data) != 1 || data[0] != 1 {
755 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
756 break
757 }
Adam Langley80842bd2014-06-20 12:00:00 -0700758 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700759 if err != nil {
760 c.in.setErrorLocked(c.sendAlert(err.(alert)))
761 }
762
763 case recordTypeApplicationData:
764 if typ != want {
765 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
766 break
767 }
768 c.input = b
769 b = nil
770
771 case recordTypeHandshake:
772 // TODO(rsc): Should at least pick off connection close.
773 if typ != want {
Adam Langley2ae77d22014-10-28 17:29:33 -0700774 // A client might need to process a HelloRequest from
775 // the server, thus receiving a handshake message when
David Benjamind9b091b2015-01-27 01:10:54 -0500776 // application data is expected is ok.
777 if !c.isClient {
Adam Langley2ae77d22014-10-28 17:29:33 -0700778 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
779 }
Adam Langley95c29f32014-06-20 12:00:00 -0700780 }
781 c.hand.Write(data)
782 }
783
784 if b != nil {
785 c.in.freeBlock(b)
786 }
787 return c.in.err
788}
789
790// sendAlert sends a TLS alert message.
791// c.out.Mutex <= L.
792func (c *Conn) sendAlertLocked(err alert) error {
793 switch err {
794 case alertNoRenegotiation, alertCloseNotify:
795 c.tmp[0] = alertLevelWarning
796 default:
797 c.tmp[0] = alertLevelError
798 }
799 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400800 if c.config.Bugs.FragmentAlert {
801 c.writeRecord(recordTypeAlert, c.tmp[0:1])
802 c.writeRecord(recordTypeAlert, c.tmp[1:2])
803 } else {
804 c.writeRecord(recordTypeAlert, c.tmp[0:2])
805 }
Adam Langley95c29f32014-06-20 12:00:00 -0700806 // closeNotify is a special case in that it isn't an error:
807 if err != alertCloseNotify {
808 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
809 }
810 return nil
811}
812
813// sendAlert sends a TLS alert message.
814// L < c.out.Mutex.
815func (c *Conn) sendAlert(err alert) error {
816 c.out.Lock()
817 defer c.out.Unlock()
818 return c.sendAlertLocked(err)
819}
820
David Benjamind86c7672014-08-02 04:07:12 -0400821// writeV2Record writes a record for a V2ClientHello.
822func (c *Conn) writeV2Record(data []byte) (n int, err error) {
823 record := make([]byte, 2+len(data))
824 record[0] = uint8(len(data)>>8) | 0x80
825 record[1] = uint8(len(data))
826 copy(record[2:], data)
827 return c.conn.Write(record)
828}
829
Adam Langley95c29f32014-06-20 12:00:00 -0700830// writeRecord writes a TLS record with the given type and payload
831// to the connection and updates the record layer state.
832// c.out.Mutex <= L.
833func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin340d5ed2015-03-21 02:21:37 -0400834 if typ != recordTypeAlert && c.config.Bugs.SendWarningAlerts != 0 {
835 alert := make([]byte, 2)
836 alert[0] = alertLevelWarning
837 alert[1] = byte(c.config.Bugs.SendWarningAlerts)
838 c.writeRecord(recordTypeAlert, alert)
839 }
840
David Benjamin83c0bc92014-08-04 01:23:53 -0400841 if c.isDTLS {
842 return c.dtlsWriteRecord(typ, data)
843 }
844
845 recordHeaderLen := tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700846 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -0400847 first := true
848 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
Adam Langley95c29f32014-06-20 12:00:00 -0700849 for len(data) > 0 {
850 m := len(data)
851 if m > maxPlaintext {
852 m = maxPlaintext
853 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400854 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
855 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -0400856 // By default, do not fragment the client_version or
857 // server_version, which are located in the first 6
858 // bytes.
859 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
860 m = 6
861 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400862 }
Adam Langley95c29f32014-06-20 12:00:00 -0700863 explicitIVLen := 0
864 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -0400865 first = false
Adam Langley95c29f32014-06-20 12:00:00 -0700866
867 var cbc cbcMode
868 if c.out.version >= VersionTLS11 {
869 var ok bool
870 if cbc, ok = c.out.cipher.(cbcMode); ok {
871 explicitIVLen = cbc.BlockSize()
872 }
873 }
874 if explicitIVLen == 0 {
875 if _, ok := c.out.cipher.(cipher.AEAD); ok {
876 explicitIVLen = 8
877 // The AES-GCM construction in TLS has an
878 // explicit nonce so that the nonce can be
879 // random. However, the nonce is only 8 bytes
880 // which is too small for a secure, random
881 // nonce. Therefore we use the sequence number
882 // as the nonce.
883 explicitIVIsSeq = true
884 }
885 }
886 b.resize(recordHeaderLen + explicitIVLen + m)
887 b.data[0] = byte(typ)
888 vers := c.vers
889 if vers == 0 {
890 // Some TLS servers fail if the record version is
891 // greater than TLS 1.0 for the initial ClientHello.
892 vers = VersionTLS10
893 }
894 b.data[1] = byte(vers >> 8)
895 b.data[2] = byte(vers)
896 b.data[3] = byte(m >> 8)
897 b.data[4] = byte(m)
898 if explicitIVLen > 0 {
899 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
900 if explicitIVIsSeq {
901 copy(explicitIV, c.out.seq[:])
902 } else {
903 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
904 break
905 }
906 }
907 }
908 copy(b.data[recordHeaderLen+explicitIVLen:], data)
909 c.out.encrypt(b, explicitIVLen)
910 _, err = c.conn.Write(b.data)
911 if err != nil {
912 break
913 }
914 n += m
915 data = data[m:]
916 }
917 c.out.freeBlock(b)
918
919 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -0700920 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700921 if err != nil {
922 // Cannot call sendAlert directly,
923 // because we already hold c.out.Mutex.
924 c.tmp[0] = alertLevelError
925 c.tmp[1] = byte(err.(alert))
926 c.writeRecord(recordTypeAlert, c.tmp[0:2])
927 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
928 }
929 }
930 return
931}
932
David Benjamin83c0bc92014-08-04 01:23:53 -0400933func (c *Conn) doReadHandshake() ([]byte, error) {
934 if c.isDTLS {
935 return c.dtlsDoReadHandshake()
936 }
937
Adam Langley95c29f32014-06-20 12:00:00 -0700938 for c.hand.Len() < 4 {
939 if err := c.in.err; err != nil {
940 return nil, err
941 }
942 if err := c.readRecord(recordTypeHandshake); err != nil {
943 return nil, err
944 }
945 }
946
947 data := c.hand.Bytes()
948 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
949 if n > maxHandshake {
950 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
951 }
952 for c.hand.Len() < 4+n {
953 if err := c.in.err; err != nil {
954 return nil, err
955 }
956 if err := c.readRecord(recordTypeHandshake); err != nil {
957 return nil, err
958 }
959 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400960 return c.hand.Next(4 + n), nil
961}
962
963// readHandshake reads the next handshake message from
964// the record layer.
965// c.in.Mutex < L; c.out.Mutex < L.
966func (c *Conn) readHandshake() (interface{}, error) {
967 data, err := c.doReadHandshake()
968 if err != nil {
969 return nil, err
970 }
971
Adam Langley95c29f32014-06-20 12:00:00 -0700972 var m handshakeMessage
973 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -0700974 case typeHelloRequest:
975 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -0700976 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -0400977 m = &clientHelloMsg{
978 isDTLS: c.isDTLS,
979 }
Adam Langley95c29f32014-06-20 12:00:00 -0700980 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -0400981 m = &serverHelloMsg{
982 isDTLS: c.isDTLS,
983 }
Adam Langley95c29f32014-06-20 12:00:00 -0700984 case typeNewSessionTicket:
985 m = new(newSessionTicketMsg)
986 case typeCertificate:
987 m = new(certificateMsg)
988 case typeCertificateRequest:
989 m = &certificateRequestMsg{
990 hasSignatureAndHash: c.vers >= VersionTLS12,
991 }
992 case typeCertificateStatus:
993 m = new(certificateStatusMsg)
994 case typeServerKeyExchange:
995 m = new(serverKeyExchangeMsg)
996 case typeServerHelloDone:
997 m = new(serverHelloDoneMsg)
998 case typeClientKeyExchange:
999 m = new(clientKeyExchangeMsg)
1000 case typeCertificateVerify:
1001 m = &certificateVerifyMsg{
1002 hasSignatureAndHash: c.vers >= VersionTLS12,
1003 }
1004 case typeNextProtocol:
1005 m = new(nextProtoMsg)
1006 case typeFinished:
1007 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001008 case typeHelloVerifyRequest:
1009 m = new(helloVerifyRequestMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001010 case typeEncryptedExtensions:
1011 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001012 default:
1013 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1014 }
1015
1016 // The handshake message unmarshallers
1017 // expect to be able to keep references to data,
1018 // so pass in a fresh copy that won't be overwritten.
1019 data = append([]byte(nil), data...)
1020
1021 if !m.unmarshal(data) {
1022 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1023 }
1024 return m, nil
1025}
1026
David Benjamin83f90402015-01-27 01:09:43 -05001027// skipPacket processes all the DTLS records in packet. It updates
1028// sequence number expectations but otherwise ignores them.
1029func (c *Conn) skipPacket(packet []byte) error {
1030 for len(packet) > 0 {
1031 // Dropped packets are completely ignored save to update
1032 // expected sequence numbers for this and the next epoch. (We
1033 // don't assert on the contents of the packets both for
1034 // simplicity and because a previous test with one shorter
1035 // timeout schedule would have done so.)
1036 epoch := packet[3:5]
1037 seq := packet[5:11]
1038 length := uint16(packet[11])<<8 | uint16(packet[12])
1039 if bytes.Equal(c.in.seq[:2], epoch) {
1040 if !bytes.Equal(c.in.seq[2:], seq) {
1041 return errors.New("tls: sequence mismatch")
1042 }
1043 c.in.incSeq(false)
1044 } else {
1045 if !bytes.Equal(c.in.nextSeq[:], seq) {
1046 return errors.New("tls: sequence mismatch")
1047 }
1048 c.in.incNextSeq()
1049 }
1050 packet = packet[13+length:]
1051 }
1052 return nil
1053}
1054
1055// simulatePacketLoss simulates the loss of a handshake leg from the
1056// peer based on the schedule in c.config.Bugs. If resendFunc is
1057// non-nil, it is called after each simulated timeout to retransmit
1058// handshake messages from the local end. This is used in cases where
1059// the peer retransmits on a stale Finished rather than a timeout.
1060func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1061 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1062 return nil
1063 }
1064 if !c.isDTLS {
1065 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1066 }
1067 if c.config.Bugs.PacketAdaptor == nil {
1068 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1069 }
1070 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1071 // Simulate a timeout.
1072 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1073 if err != nil {
1074 return err
1075 }
1076 for _, packet := range packets {
1077 if err := c.skipPacket(packet); err != nil {
1078 return err
1079 }
1080 }
1081 if resendFunc != nil {
1082 resendFunc()
1083 }
1084 }
1085 return nil
1086}
1087
Adam Langley95c29f32014-06-20 12:00:00 -07001088// Write writes data to the connection.
1089func (c *Conn) Write(b []byte) (int, error) {
1090 if err := c.Handshake(); err != nil {
1091 return 0, err
1092 }
1093
1094 c.out.Lock()
1095 defer c.out.Unlock()
1096
1097 if err := c.out.err; err != nil {
1098 return 0, err
1099 }
1100
1101 if !c.handshakeComplete {
1102 return 0, alertInternalError
1103 }
1104
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001105 if c.config.Bugs.SendSpuriousAlert != 0 {
1106 c.sendAlertLocked(c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001107 }
1108
Adam Langley95c29f32014-06-20 12:00:00 -07001109 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1110 // attack when using block mode ciphers due to predictable IVs.
1111 // This can be prevented by splitting each Application Data
1112 // record into two records, effectively randomizing the IV.
1113 //
1114 // http://www.openssl.org/~bodo/tls-cbc.txt
1115 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1116 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1117
1118 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001119 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001120 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1121 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1122 if err != nil {
1123 return n, c.out.setErrorLocked(err)
1124 }
1125 m, b = 1, b[1:]
1126 }
1127 }
1128
1129 n, err := c.writeRecord(recordTypeApplicationData, b)
1130 return n + m, c.out.setErrorLocked(err)
1131}
1132
Adam Langley2ae77d22014-10-28 17:29:33 -07001133func (c *Conn) handleRenegotiation() error {
1134 c.handshakeComplete = false
1135 if !c.isClient {
1136 panic("renegotiation should only happen for a client")
1137 }
1138
1139 msg, err := c.readHandshake()
1140 if err != nil {
1141 return err
1142 }
1143 _, ok := msg.(*helloRequestMsg)
1144 if !ok {
1145 c.sendAlert(alertUnexpectedMessage)
1146 return alertUnexpectedMessage
1147 }
1148
1149 return c.Handshake()
1150}
1151
Adam Langleycf2d4f42014-10-28 19:06:14 -07001152func (c *Conn) Renegotiate() error {
1153 if !c.isClient {
1154 helloReq := new(helloRequestMsg)
1155 c.writeRecord(recordTypeHandshake, helloReq.marshal())
1156 }
1157
1158 c.handshakeComplete = false
1159 return c.Handshake()
1160}
1161
Adam Langley95c29f32014-06-20 12:00:00 -07001162// Read can be made to time out and return a net.Error with Timeout() == true
1163// after a fixed time limit; see SetDeadline and SetReadDeadline.
1164func (c *Conn) Read(b []byte) (n int, err error) {
1165 if err = c.Handshake(); err != nil {
1166 return
1167 }
1168
1169 c.in.Lock()
1170 defer c.in.Unlock()
1171
1172 // Some OpenSSL servers send empty records in order to randomize the
1173 // CBC IV. So this loop ignores a limited number of empty records.
1174 const maxConsecutiveEmptyRecords = 100
1175 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1176 for c.input == nil && c.in.err == nil {
1177 if err := c.readRecord(recordTypeApplicationData); err != nil {
1178 // Soft error, like EAGAIN
1179 return 0, err
1180 }
David Benjamind9b091b2015-01-27 01:10:54 -05001181 if c.hand.Len() > 0 {
Adam Langley2ae77d22014-10-28 17:29:33 -07001182 // We received handshake bytes, indicating the
David Benjamind9b091b2015-01-27 01:10:54 -05001183 // start of a renegotiation.
Adam Langley2ae77d22014-10-28 17:29:33 -07001184 if err := c.handleRenegotiation(); err != nil {
1185 return 0, err
1186 }
1187 continue
1188 }
Adam Langley95c29f32014-06-20 12:00:00 -07001189 }
1190 if err := c.in.err; err != nil {
1191 return 0, err
1192 }
1193
1194 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001195 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001196 c.in.freeBlock(c.input)
1197 c.input = nil
1198 }
1199
1200 // If a close-notify alert is waiting, read it so that
1201 // we can return (n, EOF) instead of (n, nil), to signal
1202 // to the HTTP response reading goroutine that the
1203 // connection is now closed. This eliminates a race
1204 // where the HTTP response reading goroutine would
1205 // otherwise not observe the EOF until its next read,
1206 // by which time a client goroutine might have already
1207 // tried to reuse the HTTP connection for a new
1208 // request.
1209 // See https://codereview.appspot.com/76400046
1210 // and http://golang.org/issue/3514
1211 if ri := c.rawInput; ri != nil &&
1212 n != 0 && err == nil &&
1213 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1214 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1215 err = recErr // will be io.EOF on closeNotify
1216 }
1217 }
1218
1219 if n != 0 || err != nil {
1220 return n, err
1221 }
1222 }
1223
1224 return 0, io.ErrNoProgress
1225}
1226
1227// Close closes the connection.
1228func (c *Conn) Close() error {
1229 var alertErr error
1230
1231 c.handshakeMutex.Lock()
1232 defer c.handshakeMutex.Unlock()
1233 if c.handshakeComplete {
1234 alertErr = c.sendAlert(alertCloseNotify)
1235 }
1236
1237 if err := c.conn.Close(); err != nil {
1238 return err
1239 }
1240 return alertErr
1241}
1242
1243// Handshake runs the client or server handshake
1244// protocol if it has not yet been run.
1245// Most uses of this package need not call Handshake
1246// explicitly: the first Read or Write will call it automatically.
1247func (c *Conn) Handshake() error {
1248 c.handshakeMutex.Lock()
1249 defer c.handshakeMutex.Unlock()
1250 if err := c.handshakeErr; err != nil {
1251 return err
1252 }
1253 if c.handshakeComplete {
1254 return nil
1255 }
1256
1257 if c.isClient {
1258 c.handshakeErr = c.clientHandshake()
1259 } else {
1260 c.handshakeErr = c.serverHandshake()
1261 }
David Benjaminddb9f152015-02-03 15:44:39 -05001262 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1263 c.writeRecord(recordType(42), []byte("invalid record"))
1264 }
Adam Langley95c29f32014-06-20 12:00:00 -07001265 return c.handshakeErr
1266}
1267
1268// ConnectionState returns basic TLS details about the connection.
1269func (c *Conn) ConnectionState() ConnectionState {
1270 c.handshakeMutex.Lock()
1271 defer c.handshakeMutex.Unlock()
1272
1273 var state ConnectionState
1274 state.HandshakeComplete = c.handshakeComplete
1275 if c.handshakeComplete {
1276 state.Version = c.vers
1277 state.NegotiatedProtocol = c.clientProtocol
1278 state.DidResume = c.didResume
1279 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001280 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001281 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001282 state.PeerCertificates = c.peerCertificates
1283 state.VerifiedChains = c.verifiedChains
1284 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001285 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001286 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langley95c29f32014-06-20 12:00:00 -07001287 }
1288
1289 return state
1290}
1291
1292// OCSPResponse returns the stapled OCSP response from the TLS server, if
1293// any. (Only valid for client connections.)
1294func (c *Conn) OCSPResponse() []byte {
1295 c.handshakeMutex.Lock()
1296 defer c.handshakeMutex.Unlock()
1297
1298 return c.ocspResponse
1299}
1300
1301// VerifyHostname checks that the peer certificate chain is valid for
1302// connecting to host. If so, it returns nil; if not, it returns an error
1303// describing the problem.
1304func (c *Conn) VerifyHostname(host string) error {
1305 c.handshakeMutex.Lock()
1306 defer c.handshakeMutex.Unlock()
1307 if !c.isClient {
1308 return errors.New("tls: VerifyHostname called on TLS server connection")
1309 }
1310 if !c.handshakeComplete {
1311 return errors.New("tls: handshake has not yet been performed")
1312 }
1313 return c.peerCertificates[0].VerifyHostname(host)
1314}
David Benjaminc565ebb2015-04-03 04:06:36 -04001315
1316// ExportKeyingMaterial exports keying material from the current connection
1317// state, as per RFC 5705.
1318func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1319 c.handshakeMutex.Lock()
1320 defer c.handshakeMutex.Unlock()
1321 if !c.handshakeComplete {
1322 return nil, errors.New("tls: handshake has not yet been performed")
1323 }
1324
1325 seedLen := len(c.clientRandom) + len(c.serverRandom)
1326 if useContext {
1327 seedLen += 2 + len(context)
1328 }
1329 seed := make([]byte, 0, seedLen)
1330 seed = append(seed, c.clientRandom[:]...)
1331 seed = append(seed, c.serverRandom[:]...)
1332 if useContext {
1333 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1334 seed = append(seed, context...)
1335 }
1336 result := make([]byte, length)
1337 prfForVersion(c.vers, c.cipherSuite)(result, c.masterSecret[:], label, seed)
1338 return result, nil
1339}