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