blob: ed016e0f94f0542daa7fcfbba735143f25280b3d [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"
David Benjamin8e6db492015-07-25 18:29:23 -040015 "encoding/binary"
Adam Langley95c29f32014-06-20 12:00:00 -070016 "errors"
17 "fmt"
18 "io"
19 "net"
20 "sync"
21 "time"
22)
23
24// A Conn represents a secured connection.
25// It implements the net.Conn interface.
26type Conn struct {
27 // constant
28 conn net.Conn
David Benjamin83c0bc92014-08-04 01:23:53 -040029 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -070030 isClient bool
31
32 // constant after handshake; protected by handshakeMutex
Adam Langley75712922014-10-10 16:23:43 -070033 handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
34 handshakeErr error // error resulting from handshake
35 vers uint16 // TLS version
36 haveVers bool // version has been negotiated
37 config *Config // configuration passed to constructor
38 handshakeComplete bool
39 didResume bool // whether this connection was a session resumption
40 extendedMasterSecret bool // whether this session used an extended master secret
David Benjaminc565ebb2015-04-03 04:06:36 -040041 cipherSuite *cipherSuite
Adam Langley75712922014-10-10 16:23:43 -070042 ocspResponse []byte // stapled OCSP response
Paul Lietar4fac72e2015-09-09 13:44:55 +010043 sctList []byte // signed certificate timestamp list
Adam Langley75712922014-10-10 16:23:43 -070044 peerCertificates []*x509.Certificate
Adam Langley95c29f32014-06-20 12:00:00 -070045 // verifiedChains contains the certificate chains that we built, as
46 // opposed to the ones presented by the server.
47 verifiedChains [][]*x509.Certificate
48 // serverName contains the server name indicated by the client, if any.
Adam Langleyaf0e32c2015-06-03 09:57:23 -070049 serverName string
50 // firstFinished contains the first Finished hash sent during the
51 // handshake. This is the "tls-unique" channel binding value.
52 firstFinished [12]byte
53
David Benjaminc565ebb2015-04-03 04:06:36 -040054 clientRandom, serverRandom [32]byte
55 masterSecret [48]byte
Adam Langley95c29f32014-06-20 12:00:00 -070056
57 clientProtocol string
58 clientProtocolFallback bool
David Benjaminfc7b0862014-09-06 13:21:53 -040059 usedALPN bool
Adam Langley95c29f32014-06-20 12:00:00 -070060
Adam Langley2ae77d22014-10-28 17:29:33 -070061 // verify_data values for the renegotiation extension.
62 clientVerify []byte
63 serverVerify []byte
64
David Benjamind30a9902014-08-24 01:44:23 -040065 channelID *ecdsa.PublicKey
66
David Benjaminca6c8262014-11-15 19:06:08 -050067 srtpProtectionProfile uint16
68
David Benjaminc44b1df2014-11-23 12:11:01 -050069 clientVersion uint16
70
Adam Langley95c29f32014-06-20 12:00:00 -070071 // input/output
72 in, out halfConn // in.Mutex < out.Mutex
73 rawInput *block // raw input, right off the wire
David Benjamin83c0bc92014-08-04 01:23:53 -040074 input *block // application record waiting to be read
75 hand bytes.Buffer // handshake record waiting to be read
76
77 // DTLS state
78 sendHandshakeSeq uint16
79 recvHandshakeSeq uint16
David Benjaminb3774b92015-01-31 17:16:01 -050080 handMsg []byte // pending assembled handshake message
81 handMsgLen int // handshake message length, not including the header
82 pendingFragments [][]byte // pending outgoing handshake fragments.
Adam Langley95c29f32014-06-20 12:00:00 -070083
84 tmp [16]byte
85}
86
David Benjamin5e961c12014-11-07 01:48:35 -050087func (c *Conn) init() {
88 c.in.isDTLS = c.isDTLS
89 c.out.isDTLS = c.isDTLS
90 c.in.config = c.config
91 c.out.config = c.config
David Benjamin8e6db492015-07-25 18:29:23 -040092
93 c.out.updateOutSeq()
David Benjamin5e961c12014-11-07 01:48:35 -050094}
95
Adam Langley95c29f32014-06-20 12:00:00 -070096// Access to net.Conn methods.
97// Cannot just embed net.Conn because that would
98// export the struct field too.
99
100// LocalAddr returns the local network address.
101func (c *Conn) LocalAddr() net.Addr {
102 return c.conn.LocalAddr()
103}
104
105// RemoteAddr returns the remote network address.
106func (c *Conn) RemoteAddr() net.Addr {
107 return c.conn.RemoteAddr()
108}
109
110// SetDeadline sets the read and write deadlines associated with the connection.
111// A zero value for t means Read and Write will not time out.
112// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
113func (c *Conn) SetDeadline(t time.Time) error {
114 return c.conn.SetDeadline(t)
115}
116
117// SetReadDeadline sets the read deadline on the underlying connection.
118// A zero value for t means Read will not time out.
119func (c *Conn) SetReadDeadline(t time.Time) error {
120 return c.conn.SetReadDeadline(t)
121}
122
123// SetWriteDeadline sets the write deadline on the underlying conneciton.
124// A zero value for t means Write will not time out.
125// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
126func (c *Conn) SetWriteDeadline(t time.Time) error {
127 return c.conn.SetWriteDeadline(t)
128}
129
130// A halfConn represents one direction of the record layer
131// connection, either sending or receiving.
132type halfConn struct {
133 sync.Mutex
134
David Benjamin83c0bc92014-08-04 01:23:53 -0400135 err error // first permanent error
136 version uint16 // protocol version
137 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -0700138 cipher interface{} // cipher algorithm
139 mac macFunction
140 seq [8]byte // 64-bit sequence number
David Benjamin8e6db492015-07-25 18:29:23 -0400141 outSeq [8]byte // Mapped sequence number
Adam Langley95c29f32014-06-20 12:00:00 -0700142 bfree *block // list of free blocks
143
144 nextCipher interface{} // next encryption state
145 nextMac macFunction // next MAC algorithm
David Benjamin83f90402015-01-27 01:09:43 -0500146 nextSeq [6]byte // next epoch's starting sequence number in DTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700147
148 // used to save allocating a new buffer for each MAC.
149 inDigestBuf, outDigestBuf []byte
Adam Langley80842bd2014-06-20 12:00:00 -0700150
151 config *Config
Adam Langley95c29f32014-06-20 12:00:00 -0700152}
153
154func (hc *halfConn) setErrorLocked(err error) error {
155 hc.err = err
156 return err
157}
158
159func (hc *halfConn) error() error {
Adam Langley2ae77d22014-10-28 17:29:33 -0700160 // This should be locked, but I've removed it for the renegotiation
161 // tests since we don't concurrently read and write the same tls.Conn
162 // in any case during testing.
Adam Langley95c29f32014-06-20 12:00:00 -0700163 err := hc.err
Adam Langley95c29f32014-06-20 12:00:00 -0700164 return err
165}
166
167// prepareCipherSpec sets the encryption and MAC states
168// that a subsequent changeCipherSpec will use.
169func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
170 hc.version = version
171 hc.nextCipher = cipher
172 hc.nextMac = mac
173}
174
175// changeCipherSpec changes the encryption and MAC states
176// to the ones previously passed to prepareCipherSpec.
Adam Langley80842bd2014-06-20 12:00:00 -0700177func (hc *halfConn) changeCipherSpec(config *Config) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700178 if hc.nextCipher == nil {
179 return alertInternalError
180 }
181 hc.cipher = hc.nextCipher
182 hc.mac = hc.nextMac
183 hc.nextCipher = nil
184 hc.nextMac = nil
Adam Langley80842bd2014-06-20 12:00:00 -0700185 hc.config = config
David Benjamin83c0bc92014-08-04 01:23:53 -0400186 hc.incEpoch()
Adam Langley95c29f32014-06-20 12:00:00 -0700187 return nil
188}
189
190// incSeq increments the sequence number.
David Benjamin5e961c12014-11-07 01:48:35 -0500191func (hc *halfConn) incSeq(isOutgoing bool) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400192 limit := 0
David Benjamin5e961c12014-11-07 01:48:35 -0500193 increment := uint64(1)
David Benjamin83c0bc92014-08-04 01:23:53 -0400194 if hc.isDTLS {
195 // Increment up to the epoch in DTLS.
196 limit = 2
197 }
198 for i := 7; i >= limit; i-- {
David Benjamin5e961c12014-11-07 01:48:35 -0500199 increment += uint64(hc.seq[i])
200 hc.seq[i] = byte(increment)
201 increment >>= 8
Adam Langley95c29f32014-06-20 12:00:00 -0700202 }
203
204 // Not allowed to let sequence number wrap.
205 // Instead, must renegotiate before it does.
206 // Not likely enough to bother.
David Benjamin5e961c12014-11-07 01:48:35 -0500207 if increment != 0 {
208 panic("TLS: sequence number wraparound")
209 }
David Benjamin8e6db492015-07-25 18:29:23 -0400210
211 hc.updateOutSeq()
Adam Langley95c29f32014-06-20 12:00:00 -0700212}
213
David Benjamin83f90402015-01-27 01:09:43 -0500214// incNextSeq increments the starting sequence number for the next epoch.
215func (hc *halfConn) incNextSeq() {
216 for i := len(hc.nextSeq) - 1; i >= 0; i-- {
217 hc.nextSeq[i]++
218 if hc.nextSeq[i] != 0 {
219 return
220 }
221 }
222 panic("TLS: sequence number wraparound")
223}
224
225// incEpoch resets the sequence number. In DTLS, it also increments the epoch
226// half of the sequence number.
David Benjamin83c0bc92014-08-04 01:23:53 -0400227func (hc *halfConn) incEpoch() {
David Benjamin83c0bc92014-08-04 01:23:53 -0400228 if hc.isDTLS {
229 for i := 1; i >= 0; i-- {
230 hc.seq[i]++
231 if hc.seq[i] != 0 {
232 break
233 }
234 if i == 0 {
235 panic("TLS: epoch number wraparound")
236 }
237 }
David Benjamin83f90402015-01-27 01:09:43 -0500238 copy(hc.seq[2:], hc.nextSeq[:])
239 for i := range hc.nextSeq {
240 hc.nextSeq[i] = 0
241 }
242 } else {
243 for i := range hc.seq {
244 hc.seq[i] = 0
245 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400246 }
David Benjamin8e6db492015-07-25 18:29:23 -0400247
248 hc.updateOutSeq()
249}
250
251func (hc *halfConn) updateOutSeq() {
252 if hc.config.Bugs.SequenceNumberMapping != nil {
253 seqU64 := binary.BigEndian.Uint64(hc.seq[:])
254 seqU64 = hc.config.Bugs.SequenceNumberMapping(seqU64)
255 binary.BigEndian.PutUint64(hc.outSeq[:], seqU64)
256
257 // The DTLS epoch cannot be changed.
258 copy(hc.outSeq[:2], hc.seq[:2])
259 return
260 }
261
262 copy(hc.outSeq[:], hc.seq[:])
David Benjamin83c0bc92014-08-04 01:23:53 -0400263}
264
265func (hc *halfConn) recordHeaderLen() int {
266 if hc.isDTLS {
267 return dtlsRecordHeaderLen
268 }
269 return tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700270}
271
272// removePadding returns an unpadded slice, in constant time, which is a prefix
273// of the input. It also returns a byte which is equal to 255 if the padding
274// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
275func removePadding(payload []byte) ([]byte, byte) {
276 if len(payload) < 1 {
277 return payload, 0
278 }
279
280 paddingLen := payload[len(payload)-1]
281 t := uint(len(payload)-1) - uint(paddingLen)
282 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
283 good := byte(int32(^t) >> 31)
284
285 toCheck := 255 // the maximum possible padding length
286 // The length of the padded data is public, so we can use an if here
287 if toCheck+1 > len(payload) {
288 toCheck = len(payload) - 1
289 }
290
291 for i := 0; i < toCheck; i++ {
292 t := uint(paddingLen) - uint(i)
293 // if i <= paddingLen then the MSB of t is zero
294 mask := byte(int32(^t) >> 31)
295 b := payload[len(payload)-1-i]
296 good &^= mask&paddingLen ^ mask&b
297 }
298
299 // We AND together the bits of good and replicate the result across
300 // all the bits.
301 good &= good << 4
302 good &= good << 2
303 good &= good << 1
304 good = uint8(int8(good) >> 7)
305
306 toRemove := good&paddingLen + 1
307 return payload[:len(payload)-int(toRemove)], good
308}
309
310// removePaddingSSL30 is a replacement for removePadding in the case that the
311// protocol version is SSLv3. In this version, the contents of the padding
312// are random and cannot be checked.
313func removePaddingSSL30(payload []byte) ([]byte, byte) {
314 if len(payload) < 1 {
315 return payload, 0
316 }
317
318 paddingLen := int(payload[len(payload)-1]) + 1
319 if paddingLen > len(payload) {
320 return payload, 0
321 }
322
323 return payload[:len(payload)-paddingLen], 255
324}
325
326func roundUp(a, b int) int {
327 return a + (b-a%b)%b
328}
329
330// cbcMode is an interface for block ciphers using cipher block chaining.
331type cbcMode interface {
332 cipher.BlockMode
333 SetIV([]byte)
334}
335
336// decrypt checks and strips the mac and decrypts the data in b. Returns a
337// success boolean, the number of bytes to skip from the start of the record in
338// order to get the application payload, and an optional alert value.
339func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, alertValue alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400340 recordHeaderLen := hc.recordHeaderLen()
341
Adam Langley95c29f32014-06-20 12:00:00 -0700342 // pull out payload
343 payload := b.data[recordHeaderLen:]
344
345 macSize := 0
346 if hc.mac != nil {
347 macSize = hc.mac.Size()
348 }
349
350 paddingGood := byte(255)
351 explicitIVLen := 0
352
David Benjamin83c0bc92014-08-04 01:23:53 -0400353 seq := hc.seq[:]
354 if hc.isDTLS {
355 // DTLS sequence numbers are explicit.
356 seq = b.data[3:11]
357 }
358
Adam Langley95c29f32014-06-20 12:00:00 -0700359 // decrypt
360 if hc.cipher != nil {
361 switch c := hc.cipher.(type) {
362 case cipher.Stream:
363 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400364 case *tlsAead:
365 nonce := seq
366 if c.explicitNonce {
367 explicitIVLen = 8
368 if len(payload) < explicitIVLen {
369 return false, 0, alertBadRecordMAC
370 }
371 nonce = payload[:8]
372 payload = payload[8:]
Adam Langley95c29f32014-06-20 12:00:00 -0700373 }
Adam Langley95c29f32014-06-20 12:00:00 -0700374
375 var additionalData [13]byte
David Benjamin83c0bc92014-08-04 01:23:53 -0400376 copy(additionalData[:], seq)
Adam Langley95c29f32014-06-20 12:00:00 -0700377 copy(additionalData[8:], b.data[:3])
378 n := len(payload) - c.Overhead()
379 additionalData[11] = byte(n >> 8)
380 additionalData[12] = byte(n)
381 var err error
382 payload, err = c.Open(payload[:0], nonce, payload, additionalData[:])
383 if err != nil {
384 return false, 0, alertBadRecordMAC
385 }
386 b.resize(recordHeaderLen + explicitIVLen + len(payload))
387 case cbcMode:
388 blockSize := c.BlockSize()
David Benjamin83c0bc92014-08-04 01:23:53 -0400389 if hc.version >= VersionTLS11 || hc.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700390 explicitIVLen = blockSize
391 }
392
393 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
394 return false, 0, alertBadRecordMAC
395 }
396
397 if explicitIVLen > 0 {
398 c.SetIV(payload[:explicitIVLen])
399 payload = payload[explicitIVLen:]
400 }
401 c.CryptBlocks(payload, payload)
402 if hc.version == VersionSSL30 {
403 payload, paddingGood = removePaddingSSL30(payload)
404 } else {
405 payload, paddingGood = removePadding(payload)
406 }
407 b.resize(recordHeaderLen + explicitIVLen + len(payload))
408
409 // note that we still have a timing side-channel in the
410 // MAC check, below. An attacker can align the record
411 // so that a correct padding will cause one less hash
412 // block to be calculated. Then they can iteratively
413 // decrypt a record by breaking each byte. See
414 // "Password Interception in a SSL/TLS Channel", Brice
415 // Canvel et al.
416 //
417 // However, our behavior matches OpenSSL, so we leak
418 // only as much as they do.
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700419 case nullCipher:
420 break
Adam Langley95c29f32014-06-20 12:00:00 -0700421 default:
422 panic("unknown cipher type")
423 }
424 }
425
426 // check, strip mac
427 if hc.mac != nil {
428 if len(payload) < macSize {
429 return false, 0, alertBadRecordMAC
430 }
431
432 // strip mac off payload, b.data
433 n := len(payload) - macSize
David Benjamin83c0bc92014-08-04 01:23:53 -0400434 b.data[recordHeaderLen-2] = byte(n >> 8)
435 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700436 b.resize(recordHeaderLen + explicitIVLen + n)
437 remoteMAC := payload[n:]
David Benjamin83c0bc92014-08-04 01:23:53 -0400438 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
Adam Langley95c29f32014-06-20 12:00:00 -0700439
440 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
441 return false, 0, alertBadRecordMAC
442 }
443 hc.inDigestBuf = localMAC
444 }
David Benjamin5e961c12014-11-07 01:48:35 -0500445 hc.incSeq(false)
Adam Langley95c29f32014-06-20 12:00:00 -0700446
447 return true, recordHeaderLen + explicitIVLen, 0
448}
449
450// padToBlockSize calculates the needed padding block, if any, for a payload.
451// On exit, prefix aliases payload and extends to the end of the last full
452// block of payload. finalBlock is a fresh slice which contains the contents of
453// any suffix of payload as well as the needed padding to make finalBlock a
454// full block.
Adam Langley80842bd2014-06-20 12:00:00 -0700455func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
Adam Langley95c29f32014-06-20 12:00:00 -0700456 overrun := len(payload) % blockSize
Adam Langley95c29f32014-06-20 12:00:00 -0700457 prefix = payload[:len(payload)-overrun]
Adam Langley80842bd2014-06-20 12:00:00 -0700458
459 paddingLen := blockSize - overrun
460 finalSize := blockSize
461 if config.Bugs.MaxPadding {
462 for paddingLen+blockSize <= 256 {
463 paddingLen += blockSize
464 }
465 finalSize = 256
466 }
467 finalBlock = make([]byte, finalSize)
468 for i := range finalBlock {
Adam Langley95c29f32014-06-20 12:00:00 -0700469 finalBlock[i] = byte(paddingLen - 1)
470 }
Adam Langley80842bd2014-06-20 12:00:00 -0700471 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
472 finalBlock[overrun] ^= 0xff
473 }
474 copy(finalBlock, payload[len(payload)-overrun:])
Adam Langley95c29f32014-06-20 12:00:00 -0700475 return
476}
477
478// encrypt encrypts and macs the data in b.
479func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400480 recordHeaderLen := hc.recordHeaderLen()
481
Adam Langley95c29f32014-06-20 12:00:00 -0700482 // mac
483 if hc.mac != nil {
David Benjamin8e6db492015-07-25 18:29:23 -0400484 mac := hc.mac.MAC(hc.outDigestBuf, hc.outSeq[0:], b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], b.data[recordHeaderLen+explicitIVLen:])
Adam Langley95c29f32014-06-20 12:00:00 -0700485
486 n := len(b.data)
487 b.resize(n + len(mac))
488 copy(b.data[n:], mac)
489 hc.outDigestBuf = mac
490 }
491
492 payload := b.data[recordHeaderLen:]
493
494 // encrypt
495 if hc.cipher != nil {
496 switch c := hc.cipher.(type) {
497 case cipher.Stream:
498 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400499 case *tlsAead:
Adam Langley95c29f32014-06-20 12:00:00 -0700500 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
501 b.resize(len(b.data) + c.Overhead())
David Benjamin8e6db492015-07-25 18:29:23 -0400502 nonce := hc.outSeq[:]
David Benjamine9a80ff2015-04-07 00:46:46 -0400503 if c.explicitNonce {
504 nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
505 }
Adam Langley95c29f32014-06-20 12:00:00 -0700506 payload := b.data[recordHeaderLen+explicitIVLen:]
507 payload = payload[:payloadLen]
508
509 var additionalData [13]byte
David Benjamin8e6db492015-07-25 18:29:23 -0400510 copy(additionalData[:], hc.outSeq[:])
Adam Langley95c29f32014-06-20 12:00:00 -0700511 copy(additionalData[8:], b.data[:3])
512 additionalData[11] = byte(payloadLen >> 8)
513 additionalData[12] = byte(payloadLen)
514
515 c.Seal(payload[:0], nonce, payload, additionalData[:])
516 case cbcMode:
517 blockSize := c.BlockSize()
518 if explicitIVLen > 0 {
519 c.SetIV(payload[:explicitIVLen])
520 payload = payload[explicitIVLen:]
521 }
Adam Langley80842bd2014-06-20 12:00:00 -0700522 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700523 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
524 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
525 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700526 case nullCipher:
527 break
Adam Langley95c29f32014-06-20 12:00:00 -0700528 default:
529 panic("unknown cipher type")
530 }
531 }
532
533 // update length to include MAC and any block padding needed.
534 n := len(b.data) - recordHeaderLen
David Benjamin83c0bc92014-08-04 01:23:53 -0400535 b.data[recordHeaderLen-2] = byte(n >> 8)
536 b.data[recordHeaderLen-1] = byte(n)
David Benjamin5e961c12014-11-07 01:48:35 -0500537 hc.incSeq(true)
Adam Langley95c29f32014-06-20 12:00:00 -0700538
539 return true, 0
540}
541
542// A block is a simple data buffer.
543type block struct {
544 data []byte
545 off int // index for Read
546 link *block
547}
548
549// resize resizes block to be n bytes, growing if necessary.
550func (b *block) resize(n int) {
551 if n > cap(b.data) {
552 b.reserve(n)
553 }
554 b.data = b.data[0:n]
555}
556
557// reserve makes sure that block contains a capacity of at least n bytes.
558func (b *block) reserve(n int) {
559 if cap(b.data) >= n {
560 return
561 }
562 m := cap(b.data)
563 if m == 0 {
564 m = 1024
565 }
566 for m < n {
567 m *= 2
568 }
569 data := make([]byte, len(b.data), m)
570 copy(data, b.data)
571 b.data = data
572}
573
574// readFromUntil reads from r into b until b contains at least n bytes
575// or else returns an error.
576func (b *block) readFromUntil(r io.Reader, n int) error {
577 // quick case
578 if len(b.data) >= n {
579 return nil
580 }
581
582 // read until have enough.
583 b.reserve(n)
584 for {
585 m, err := r.Read(b.data[len(b.data):cap(b.data)])
586 b.data = b.data[0 : len(b.data)+m]
587 if len(b.data) >= n {
588 // TODO(bradfitz,agl): slightly suspicious
589 // that we're throwing away r.Read's err here.
590 break
591 }
592 if err != nil {
593 return err
594 }
595 }
596 return nil
597}
598
599func (b *block) Read(p []byte) (n int, err error) {
600 n = copy(p, b.data[b.off:])
601 b.off += n
602 return
603}
604
605// newBlock allocates a new block, from hc's free list if possible.
606func (hc *halfConn) newBlock() *block {
607 b := hc.bfree
608 if b == nil {
609 return new(block)
610 }
611 hc.bfree = b.link
612 b.link = nil
613 b.resize(0)
614 return b
615}
616
617// freeBlock returns a block to hc's free list.
618// The protocol is such that each side only has a block or two on
619// its free list at a time, so there's no need to worry about
620// trimming the list, etc.
621func (hc *halfConn) freeBlock(b *block) {
622 b.link = hc.bfree
623 hc.bfree = b
624}
625
626// splitBlock splits a block after the first n bytes,
627// returning a block with those n bytes and a
628// block with the remainder. the latter may be nil.
629func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
630 if len(b.data) <= n {
631 return b, nil
632 }
633 bb := hc.newBlock()
634 bb.resize(len(b.data) - n)
635 copy(bb.data, b.data[n:])
636 b.data = b.data[0:n]
637 return b, bb
638}
639
David Benjamin83c0bc92014-08-04 01:23:53 -0400640func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
641 if c.isDTLS {
642 return c.dtlsDoReadRecord(want)
643 }
644
645 recordHeaderLen := tlsRecordHeaderLen
646
647 if c.rawInput == nil {
648 c.rawInput = c.in.newBlock()
649 }
650 b := c.rawInput
651
652 // Read header, payload.
653 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
654 // RFC suggests that EOF without an alertCloseNotify is
655 // an error, but popular web sites seem to do this,
David Benjamin30789da2015-08-29 22:56:45 -0400656 // so we can't make it an error, outside of tests.
657 if err == io.EOF && c.config.Bugs.ExpectCloseNotify {
658 err = io.ErrUnexpectedEOF
659 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400660 if e, ok := err.(net.Error); !ok || !e.Temporary() {
661 c.in.setErrorLocked(err)
662 }
663 return 0, nil, err
664 }
665 typ := recordType(b.data[0])
666
667 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
668 // start with a uint16 length where the MSB is set and the first record
669 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
670 // an SSLv2 client.
671 if want == recordTypeHandshake && typ == 0x80 {
672 c.sendAlert(alertProtocolVersion)
673 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
674 }
675
676 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
677 n := int(b.data[3])<<8 | int(b.data[4])
David Benjamin1e29a6b2014-12-10 02:27:24 -0500678 if c.haveVers {
679 if vers != c.vers {
680 c.sendAlert(alertProtocolVersion)
681 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers))
682 }
683 } else {
684 if expect := c.config.Bugs.ExpectInitialRecordVersion; expect != 0 && vers != expect {
685 c.sendAlert(alertProtocolVersion)
686 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
687 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400688 }
689 if n > maxCiphertext {
690 c.sendAlert(alertRecordOverflow)
691 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
692 }
693 if !c.haveVers {
694 // First message, be extra suspicious:
695 // this might not be a TLS client.
696 // Bail out before reading a full 'body', if possible.
697 // The current max version is 3.1.
698 // If the version is >= 16.0, it's probably not real.
699 // Similarly, a clientHello message encodes in
700 // well under a kilobyte. If the length is >= 12 kB,
701 // it's probably not real.
702 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
703 c.sendAlert(alertUnexpectedMessage)
704 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
705 }
706 }
707 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
708 if err == io.EOF {
709 err = io.ErrUnexpectedEOF
710 }
711 if e, ok := err.(net.Error); !ok || !e.Temporary() {
712 c.in.setErrorLocked(err)
713 }
714 return 0, nil, err
715 }
716
717 // Process message.
718 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
719 ok, off, err := c.in.decrypt(b)
720 if !ok {
721 c.in.setErrorLocked(c.sendAlert(err))
722 }
723 b.off = off
724 return typ, b, nil
725}
726
Adam Langley95c29f32014-06-20 12:00:00 -0700727// readRecord reads the next TLS record from the connection
728// and updates the record layer state.
729// c.in.Mutex <= L; c.input == nil.
730func (c *Conn) readRecord(want recordType) error {
731 // Caller must be in sync with connection:
732 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700733 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700734 switch want {
735 default:
736 c.sendAlert(alertInternalError)
737 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
738 case recordTypeHandshake, recordTypeChangeCipherSpec:
739 if c.handshakeComplete {
740 c.sendAlert(alertInternalError)
741 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
742 }
743 case recordTypeApplicationData:
David Benjamine58c4f52014-08-24 03:47:07 -0400744 if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart {
Adam Langley95c29f32014-06-20 12:00:00 -0700745 c.sendAlert(alertInternalError)
746 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
747 }
David Benjamin30789da2015-08-29 22:56:45 -0400748 case recordTypeAlert:
749 // Looking for a close_notify. Note: unlike a real
750 // implementation, this is not tolerant of additional records.
751 // See the documentation for ExpectCloseNotify.
Adam Langley95c29f32014-06-20 12:00:00 -0700752 }
753
754Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400755 typ, b, err := c.doReadRecord(want)
756 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700757 return err
758 }
Adam Langley95c29f32014-06-20 12:00:00 -0700759 data := b.data[b.off:]
760 if len(data) > maxPlaintext {
761 err := c.sendAlert(alertRecordOverflow)
762 c.in.freeBlock(b)
763 return c.in.setErrorLocked(err)
764 }
765
766 switch typ {
767 default:
768 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
769
770 case recordTypeAlert:
771 if len(data) != 2 {
772 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
773 break
774 }
775 if alert(data[1]) == alertCloseNotify {
776 c.in.setErrorLocked(io.EOF)
777 break
778 }
779 switch data[0] {
780 case alertLevelWarning:
781 // drop on the floor
782 c.in.freeBlock(b)
783 goto Again
784 case alertLevelError:
785 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
786 default:
787 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
788 }
789
790 case recordTypeChangeCipherSpec:
791 if typ != want || len(data) != 1 || data[0] != 1 {
792 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
793 break
794 }
Adam Langley80842bd2014-06-20 12:00:00 -0700795 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700796 if err != nil {
797 c.in.setErrorLocked(c.sendAlert(err.(alert)))
798 }
799
800 case recordTypeApplicationData:
801 if typ != want {
802 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
803 break
804 }
805 c.input = b
806 b = nil
807
808 case recordTypeHandshake:
809 // TODO(rsc): Should at least pick off connection close.
810 if typ != want {
Adam Langley2ae77d22014-10-28 17:29:33 -0700811 // A client might need to process a HelloRequest from
812 // the server, thus receiving a handshake message when
David Benjamind9b091b2015-01-27 01:10:54 -0500813 // application data is expected is ok.
David Benjamin30789da2015-08-29 22:56:45 -0400814 if !c.isClient || want != recordTypeApplicationData {
Adam Langley2ae77d22014-10-28 17:29:33 -0700815 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
816 }
Adam Langley95c29f32014-06-20 12:00:00 -0700817 }
818 c.hand.Write(data)
819 }
820
821 if b != nil {
822 c.in.freeBlock(b)
823 }
824 return c.in.err
825}
826
827// sendAlert sends a TLS alert message.
828// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400829func (c *Conn) sendAlertLocked(level byte, err alert) error {
830 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700831 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400832 if c.config.Bugs.FragmentAlert {
833 c.writeRecord(recordTypeAlert, c.tmp[0:1])
834 c.writeRecord(recordTypeAlert, c.tmp[1:2])
835 } else {
836 c.writeRecord(recordTypeAlert, c.tmp[0:2])
837 }
David Benjamin24f346d2015-06-06 03:28:08 -0400838 // Error alerts are fatal to the connection.
839 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700840 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
841 }
842 return nil
843}
844
845// sendAlert sends a TLS alert message.
846// L < c.out.Mutex.
847func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400848 level := byte(alertLevelError)
849 if err == alertNoRenegotiation || err == alertCloseNotify {
850 level = alertLevelWarning
851 }
852 return c.SendAlert(level, err)
853}
854
855func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700856 c.out.Lock()
857 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -0400858 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -0700859}
860
David Benjamind86c7672014-08-02 04:07:12 -0400861// writeV2Record writes a record for a V2ClientHello.
862func (c *Conn) writeV2Record(data []byte) (n int, err error) {
863 record := make([]byte, 2+len(data))
864 record[0] = uint8(len(data)>>8) | 0x80
865 record[1] = uint8(len(data))
866 copy(record[2:], data)
867 return c.conn.Write(record)
868}
869
Adam Langley95c29f32014-06-20 12:00:00 -0700870// writeRecord writes a TLS record with the given type and payload
871// to the connection and updates the record layer state.
872// c.out.Mutex <= L.
873func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400874 if c.isDTLS {
875 return c.dtlsWriteRecord(typ, data)
876 }
877
878 recordHeaderLen := tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700879 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -0400880 first := true
881 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -0400882 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -0700883 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -0400884 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -0700885 m = maxPlaintext
886 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400887 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
888 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -0400889 // By default, do not fragment the client_version or
890 // server_version, which are located in the first 6
891 // bytes.
892 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
893 m = 6
894 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400895 }
Adam Langley95c29f32014-06-20 12:00:00 -0700896 explicitIVLen := 0
897 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -0400898 first = false
Adam Langley95c29f32014-06-20 12:00:00 -0700899
900 var cbc cbcMode
901 if c.out.version >= VersionTLS11 {
902 var ok bool
903 if cbc, ok = c.out.cipher.(cbcMode); ok {
904 explicitIVLen = cbc.BlockSize()
905 }
906 }
907 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -0400908 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -0700909 explicitIVLen = 8
910 // The AES-GCM construction in TLS has an
911 // explicit nonce so that the nonce can be
912 // random. However, the nonce is only 8 bytes
913 // which is too small for a secure, random
914 // nonce. Therefore we use the sequence number
915 // as the nonce.
916 explicitIVIsSeq = true
917 }
918 }
919 b.resize(recordHeaderLen + explicitIVLen + m)
920 b.data[0] = byte(typ)
921 vers := c.vers
922 if vers == 0 {
923 // Some TLS servers fail if the record version is
924 // greater than TLS 1.0 for the initial ClientHello.
925 vers = VersionTLS10
926 }
927 b.data[1] = byte(vers >> 8)
928 b.data[2] = byte(vers)
929 b.data[3] = byte(m >> 8)
930 b.data[4] = byte(m)
931 if explicitIVLen > 0 {
932 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
933 if explicitIVIsSeq {
934 copy(explicitIV, c.out.seq[:])
935 } else {
936 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
937 break
938 }
939 }
940 }
941 copy(b.data[recordHeaderLen+explicitIVLen:], data)
942 c.out.encrypt(b, explicitIVLen)
943 _, err = c.conn.Write(b.data)
944 if err != nil {
945 break
946 }
947 n += m
948 data = data[m:]
949 }
950 c.out.freeBlock(b)
951
952 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -0700953 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700954 if err != nil {
955 // Cannot call sendAlert directly,
956 // because we already hold c.out.Mutex.
957 c.tmp[0] = alertLevelError
958 c.tmp[1] = byte(err.(alert))
959 c.writeRecord(recordTypeAlert, c.tmp[0:2])
960 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
961 }
962 }
963 return
964}
965
David Benjamin83c0bc92014-08-04 01:23:53 -0400966func (c *Conn) doReadHandshake() ([]byte, error) {
967 if c.isDTLS {
968 return c.dtlsDoReadHandshake()
969 }
970
Adam Langley95c29f32014-06-20 12:00:00 -0700971 for c.hand.Len() < 4 {
972 if err := c.in.err; err != nil {
973 return nil, err
974 }
975 if err := c.readRecord(recordTypeHandshake); err != nil {
976 return nil, err
977 }
978 }
979
980 data := c.hand.Bytes()
981 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
982 if n > maxHandshake {
983 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
984 }
985 for c.hand.Len() < 4+n {
986 if err := c.in.err; err != nil {
987 return nil, err
988 }
989 if err := c.readRecord(recordTypeHandshake); err != nil {
990 return nil, err
991 }
992 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400993 return c.hand.Next(4 + n), nil
994}
995
996// readHandshake reads the next handshake message from
997// the record layer.
998// c.in.Mutex < L; c.out.Mutex < L.
999func (c *Conn) readHandshake() (interface{}, error) {
1000 data, err := c.doReadHandshake()
1001 if err != nil {
1002 return nil, err
1003 }
1004
Adam Langley95c29f32014-06-20 12:00:00 -07001005 var m handshakeMessage
1006 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001007 case typeHelloRequest:
1008 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001009 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001010 m = &clientHelloMsg{
1011 isDTLS: c.isDTLS,
1012 }
Adam Langley95c29f32014-06-20 12:00:00 -07001013 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001014 m = &serverHelloMsg{
1015 isDTLS: c.isDTLS,
1016 }
Adam Langley95c29f32014-06-20 12:00:00 -07001017 case typeNewSessionTicket:
1018 m = new(newSessionTicketMsg)
1019 case typeCertificate:
1020 m = new(certificateMsg)
1021 case typeCertificateRequest:
1022 m = &certificateRequestMsg{
1023 hasSignatureAndHash: c.vers >= VersionTLS12,
1024 }
1025 case typeCertificateStatus:
1026 m = new(certificateStatusMsg)
1027 case typeServerKeyExchange:
1028 m = new(serverKeyExchangeMsg)
1029 case typeServerHelloDone:
1030 m = new(serverHelloDoneMsg)
1031 case typeClientKeyExchange:
1032 m = new(clientKeyExchangeMsg)
1033 case typeCertificateVerify:
1034 m = &certificateVerifyMsg{
1035 hasSignatureAndHash: c.vers >= VersionTLS12,
1036 }
1037 case typeNextProtocol:
1038 m = new(nextProtoMsg)
1039 case typeFinished:
1040 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001041 case typeHelloVerifyRequest:
1042 m = new(helloVerifyRequestMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001043 case typeEncryptedExtensions:
1044 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001045 default:
1046 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1047 }
1048
1049 // The handshake message unmarshallers
1050 // expect to be able to keep references to data,
1051 // so pass in a fresh copy that won't be overwritten.
1052 data = append([]byte(nil), data...)
1053
1054 if !m.unmarshal(data) {
1055 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1056 }
1057 return m, nil
1058}
1059
David Benjamin83f90402015-01-27 01:09:43 -05001060// skipPacket processes all the DTLS records in packet. It updates
1061// sequence number expectations but otherwise ignores them.
1062func (c *Conn) skipPacket(packet []byte) error {
1063 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001064 if len(packet) < 13 {
1065 return errors.New("tls: bad packet")
1066 }
David Benjamin83f90402015-01-27 01:09:43 -05001067 // Dropped packets are completely ignored save to update
1068 // expected sequence numbers for this and the next epoch. (We
1069 // don't assert on the contents of the packets both for
1070 // simplicity and because a previous test with one shorter
1071 // timeout schedule would have done so.)
1072 epoch := packet[3:5]
1073 seq := packet[5:11]
1074 length := uint16(packet[11])<<8 | uint16(packet[12])
1075 if bytes.Equal(c.in.seq[:2], epoch) {
1076 if !bytes.Equal(c.in.seq[2:], seq) {
1077 return errors.New("tls: sequence mismatch")
1078 }
1079 c.in.incSeq(false)
1080 } else {
1081 if !bytes.Equal(c.in.nextSeq[:], seq) {
1082 return errors.New("tls: sequence mismatch")
1083 }
1084 c.in.incNextSeq()
1085 }
David Benjamin6ca93552015-08-28 16:16:25 -04001086 if len(packet) < 13+int(length) {
1087 return errors.New("tls: bad packet")
1088 }
David Benjamin83f90402015-01-27 01:09:43 -05001089 packet = packet[13+length:]
1090 }
1091 return nil
1092}
1093
1094// simulatePacketLoss simulates the loss of a handshake leg from the
1095// peer based on the schedule in c.config.Bugs. If resendFunc is
1096// non-nil, it is called after each simulated timeout to retransmit
1097// handshake messages from the local end. This is used in cases where
1098// the peer retransmits on a stale Finished rather than a timeout.
1099func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1100 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1101 return nil
1102 }
1103 if !c.isDTLS {
1104 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1105 }
1106 if c.config.Bugs.PacketAdaptor == nil {
1107 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1108 }
1109 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1110 // Simulate a timeout.
1111 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1112 if err != nil {
1113 return err
1114 }
1115 for _, packet := range packets {
1116 if err := c.skipPacket(packet); err != nil {
1117 return err
1118 }
1119 }
1120 if resendFunc != nil {
1121 resendFunc()
1122 }
1123 }
1124 return nil
1125}
1126
Adam Langley95c29f32014-06-20 12:00:00 -07001127// Write writes data to the connection.
1128func (c *Conn) Write(b []byte) (int, error) {
1129 if err := c.Handshake(); err != nil {
1130 return 0, err
1131 }
1132
1133 c.out.Lock()
1134 defer c.out.Unlock()
1135
1136 if err := c.out.err; err != nil {
1137 return 0, err
1138 }
1139
1140 if !c.handshakeComplete {
1141 return 0, alertInternalError
1142 }
1143
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001144 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001145 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001146 }
1147
Adam Langley95c29f32014-06-20 12:00:00 -07001148 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1149 // attack when using block mode ciphers due to predictable IVs.
1150 // This can be prevented by splitting each Application Data
1151 // record into two records, effectively randomizing the IV.
1152 //
1153 // http://www.openssl.org/~bodo/tls-cbc.txt
1154 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1155 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1156
1157 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001158 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001159 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1160 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1161 if err != nil {
1162 return n, c.out.setErrorLocked(err)
1163 }
1164 m, b = 1, b[1:]
1165 }
1166 }
1167
1168 n, err := c.writeRecord(recordTypeApplicationData, b)
1169 return n + m, c.out.setErrorLocked(err)
1170}
1171
Adam Langley2ae77d22014-10-28 17:29:33 -07001172func (c *Conn) handleRenegotiation() error {
1173 c.handshakeComplete = false
1174 if !c.isClient {
1175 panic("renegotiation should only happen for a client")
1176 }
1177
1178 msg, err := c.readHandshake()
1179 if err != nil {
1180 return err
1181 }
1182 _, ok := msg.(*helloRequestMsg)
1183 if !ok {
1184 c.sendAlert(alertUnexpectedMessage)
1185 return alertUnexpectedMessage
1186 }
1187
1188 return c.Handshake()
1189}
1190
Adam Langleycf2d4f42014-10-28 19:06:14 -07001191func (c *Conn) Renegotiate() error {
1192 if !c.isClient {
1193 helloReq := new(helloRequestMsg)
1194 c.writeRecord(recordTypeHandshake, helloReq.marshal())
1195 }
1196
1197 c.handshakeComplete = false
1198 return c.Handshake()
1199}
1200
Adam Langley95c29f32014-06-20 12:00:00 -07001201// Read can be made to time out and return a net.Error with Timeout() == true
1202// after a fixed time limit; see SetDeadline and SetReadDeadline.
1203func (c *Conn) Read(b []byte) (n int, err error) {
1204 if err = c.Handshake(); err != nil {
1205 return
1206 }
1207
1208 c.in.Lock()
1209 defer c.in.Unlock()
1210
1211 // Some OpenSSL servers send empty records in order to randomize the
1212 // CBC IV. So this loop ignores a limited number of empty records.
1213 const maxConsecutiveEmptyRecords = 100
1214 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1215 for c.input == nil && c.in.err == nil {
1216 if err := c.readRecord(recordTypeApplicationData); err != nil {
1217 // Soft error, like EAGAIN
1218 return 0, err
1219 }
David Benjamind9b091b2015-01-27 01:10:54 -05001220 if c.hand.Len() > 0 {
Adam Langley2ae77d22014-10-28 17:29:33 -07001221 // We received handshake bytes, indicating the
David Benjamind9b091b2015-01-27 01:10:54 -05001222 // start of a renegotiation.
Adam Langley2ae77d22014-10-28 17:29:33 -07001223 if err := c.handleRenegotiation(); err != nil {
1224 return 0, err
1225 }
1226 continue
1227 }
Adam Langley95c29f32014-06-20 12:00:00 -07001228 }
1229 if err := c.in.err; err != nil {
1230 return 0, err
1231 }
1232
1233 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001234 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001235 c.in.freeBlock(c.input)
1236 c.input = nil
1237 }
1238
1239 // If a close-notify alert is waiting, read it so that
1240 // we can return (n, EOF) instead of (n, nil), to signal
1241 // to the HTTP response reading goroutine that the
1242 // connection is now closed. This eliminates a race
1243 // where the HTTP response reading goroutine would
1244 // otherwise not observe the EOF until its next read,
1245 // by which time a client goroutine might have already
1246 // tried to reuse the HTTP connection for a new
1247 // request.
1248 // See https://codereview.appspot.com/76400046
1249 // and http://golang.org/issue/3514
1250 if ri := c.rawInput; ri != nil &&
1251 n != 0 && err == nil &&
1252 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1253 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1254 err = recErr // will be io.EOF on closeNotify
1255 }
1256 }
1257
1258 if n != 0 || err != nil {
1259 return n, err
1260 }
1261 }
1262
1263 return 0, io.ErrNoProgress
1264}
1265
1266// Close closes the connection.
1267func (c *Conn) Close() error {
1268 var alertErr error
1269
1270 c.handshakeMutex.Lock()
1271 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001272 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
Adam Langley95c29f32014-06-20 12:00:00 -07001273 alertErr = c.sendAlert(alertCloseNotify)
1274 }
1275
David Benjamin30789da2015-08-29 22:56:45 -04001276 // Consume a close_notify from the peer if one hasn't been received
1277 // already. This avoids the peer from failing |SSL_shutdown| due to a
1278 // write failing.
1279 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1280 for c.in.error() == nil {
1281 c.readRecord(recordTypeAlert)
1282 }
1283 if c.in.error() != io.EOF {
1284 alertErr = c.in.error()
1285 }
1286 }
1287
Adam Langley95c29f32014-06-20 12:00:00 -07001288 if err := c.conn.Close(); err != nil {
1289 return err
1290 }
1291 return alertErr
1292}
1293
1294// Handshake runs the client or server handshake
1295// protocol if it has not yet been run.
1296// Most uses of this package need not call Handshake
1297// explicitly: the first Read or Write will call it automatically.
1298func (c *Conn) Handshake() error {
1299 c.handshakeMutex.Lock()
1300 defer c.handshakeMutex.Unlock()
1301 if err := c.handshakeErr; err != nil {
1302 return err
1303 }
1304 if c.handshakeComplete {
1305 return nil
1306 }
1307
David Benjamin9a41d1b2015-05-16 01:30:09 -04001308 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1309 c.conn.Write([]byte{
1310 byte(recordTypeAlert), // type
1311 0xfe, 0xff, // version
1312 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1313 0x0, 0x2, // length
1314 })
1315 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1316 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001317 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1318 c.writeRecord(recordTypeApplicationData, data)
1319 }
Adam Langley95c29f32014-06-20 12:00:00 -07001320 if c.isClient {
1321 c.handshakeErr = c.clientHandshake()
1322 } else {
1323 c.handshakeErr = c.serverHandshake()
1324 }
David Benjaminddb9f152015-02-03 15:44:39 -05001325 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1326 c.writeRecord(recordType(42), []byte("invalid record"))
1327 }
Adam Langley95c29f32014-06-20 12:00:00 -07001328 return c.handshakeErr
1329}
1330
1331// ConnectionState returns basic TLS details about the connection.
1332func (c *Conn) ConnectionState() ConnectionState {
1333 c.handshakeMutex.Lock()
1334 defer c.handshakeMutex.Unlock()
1335
1336 var state ConnectionState
1337 state.HandshakeComplete = c.handshakeComplete
1338 if c.handshakeComplete {
1339 state.Version = c.vers
1340 state.NegotiatedProtocol = c.clientProtocol
1341 state.DidResume = c.didResume
1342 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001343 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001344 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001345 state.PeerCertificates = c.peerCertificates
1346 state.VerifiedChains = c.verifiedChains
1347 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001348 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001349 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001350 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001351 state.SCTList = c.sctList
Adam Langley95c29f32014-06-20 12:00:00 -07001352 }
1353
1354 return state
1355}
1356
1357// OCSPResponse returns the stapled OCSP response from the TLS server, if
1358// any. (Only valid for client connections.)
1359func (c *Conn) OCSPResponse() []byte {
1360 c.handshakeMutex.Lock()
1361 defer c.handshakeMutex.Unlock()
1362
1363 return c.ocspResponse
1364}
1365
1366// VerifyHostname checks that the peer certificate chain is valid for
1367// connecting to host. If so, it returns nil; if not, it returns an error
1368// describing the problem.
1369func (c *Conn) VerifyHostname(host string) error {
1370 c.handshakeMutex.Lock()
1371 defer c.handshakeMutex.Unlock()
1372 if !c.isClient {
1373 return errors.New("tls: VerifyHostname called on TLS server connection")
1374 }
1375 if !c.handshakeComplete {
1376 return errors.New("tls: handshake has not yet been performed")
1377 }
1378 return c.peerCertificates[0].VerifyHostname(host)
1379}
David Benjaminc565ebb2015-04-03 04:06:36 -04001380
1381// ExportKeyingMaterial exports keying material from the current connection
1382// state, as per RFC 5705.
1383func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1384 c.handshakeMutex.Lock()
1385 defer c.handshakeMutex.Unlock()
1386 if !c.handshakeComplete {
1387 return nil, errors.New("tls: handshake has not yet been performed")
1388 }
1389
1390 seedLen := len(c.clientRandom) + len(c.serverRandom)
1391 if useContext {
1392 seedLen += 2 + len(context)
1393 }
1394 seed := make([]byte, 0, seedLen)
1395 seed = append(seed, c.clientRandom[:]...)
1396 seed = append(seed, c.serverRandom[:]...)
1397 if useContext {
1398 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1399 seed = append(seed, context...)
1400 }
1401 result := make([]byte, length)
1402 prfForVersion(c.vers, c.cipherSuite)(result, c.masterSecret[:], label, seed)
1403 return result, nil
1404}