blob: 42bc840afe8d6d17cd5f6f4a0ac8e8de3a445493 [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
43 peerCertificates []*x509.Certificate
Adam Langley95c29f32014-06-20 12:00:00 -070044 // verifiedChains contains the certificate chains that we built, as
45 // opposed to the ones presented by the server.
46 verifiedChains [][]*x509.Certificate
47 // serverName contains the server name indicated by the client, if any.
Adam Langleyaf0e32c2015-06-03 09:57:23 -070048 serverName string
49 // firstFinished contains the first Finished hash sent during the
50 // handshake. This is the "tls-unique" channel binding value.
51 firstFinished [12]byte
52
David Benjaminc565ebb2015-04-03 04:06:36 -040053 clientRandom, serverRandom [32]byte
54 masterSecret [48]byte
Adam Langley95c29f32014-06-20 12:00:00 -070055
56 clientProtocol string
57 clientProtocolFallback bool
David Benjaminfc7b0862014-09-06 13:21:53 -040058 usedALPN bool
Adam Langley95c29f32014-06-20 12:00:00 -070059
Adam Langley2ae77d22014-10-28 17:29:33 -070060 // verify_data values for the renegotiation extension.
61 clientVerify []byte
62 serverVerify []byte
63
David Benjamind30a9902014-08-24 01:44:23 -040064 channelID *ecdsa.PublicKey
65
David Benjaminca6c8262014-11-15 19:06:08 -050066 srtpProtectionProfile uint16
67
David Benjaminc44b1df2014-11-23 12:11:01 -050068 clientVersion uint16
69
Adam Langley95c29f32014-06-20 12:00:00 -070070 // input/output
71 in, out halfConn // in.Mutex < out.Mutex
72 rawInput *block // raw input, right off the wire
David Benjamin83c0bc92014-08-04 01:23:53 -040073 input *block // application record waiting to be read
74 hand bytes.Buffer // handshake record waiting to be read
75
76 // DTLS state
77 sendHandshakeSeq uint16
78 recvHandshakeSeq uint16
David Benjaminb3774b92015-01-31 17:16:01 -050079 handMsg []byte // pending assembled handshake message
80 handMsgLen int // handshake message length, not including the header
81 pendingFragments [][]byte // pending outgoing handshake fragments.
Adam Langley95c29f32014-06-20 12:00:00 -070082
83 tmp [16]byte
84}
85
David Benjamin5e961c12014-11-07 01:48:35 -050086func (c *Conn) init() {
87 c.in.isDTLS = c.isDTLS
88 c.out.isDTLS = c.isDTLS
89 c.in.config = c.config
90 c.out.config = c.config
David Benjamin8e6db492015-07-25 18:29:23 -040091
92 c.out.updateOutSeq()
David Benjamin5e961c12014-11-07 01:48:35 -050093}
94
Adam Langley95c29f32014-06-20 12:00:00 -070095// Access to net.Conn methods.
96// Cannot just embed net.Conn because that would
97// export the struct field too.
98
99// LocalAddr returns the local network address.
100func (c *Conn) LocalAddr() net.Addr {
101 return c.conn.LocalAddr()
102}
103
104// RemoteAddr returns the remote network address.
105func (c *Conn) RemoteAddr() net.Addr {
106 return c.conn.RemoteAddr()
107}
108
109// SetDeadline sets the read and write deadlines associated with the connection.
110// A zero value for t means Read and Write will not time out.
111// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
112func (c *Conn) SetDeadline(t time.Time) error {
113 return c.conn.SetDeadline(t)
114}
115
116// SetReadDeadline sets the read deadline on the underlying connection.
117// A zero value for t means Read will not time out.
118func (c *Conn) SetReadDeadline(t time.Time) error {
119 return c.conn.SetReadDeadline(t)
120}
121
122// SetWriteDeadline sets the write deadline on the underlying conneciton.
123// A zero value for t means Write will not time out.
124// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
125func (c *Conn) SetWriteDeadline(t time.Time) error {
126 return c.conn.SetWriteDeadline(t)
127}
128
129// A halfConn represents one direction of the record layer
130// connection, either sending or receiving.
131type halfConn struct {
132 sync.Mutex
133
David Benjamin83c0bc92014-08-04 01:23:53 -0400134 err error // first permanent error
135 version uint16 // protocol version
136 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -0700137 cipher interface{} // cipher algorithm
138 mac macFunction
139 seq [8]byte // 64-bit sequence number
David Benjamin8e6db492015-07-25 18:29:23 -0400140 outSeq [8]byte // Mapped sequence number
Adam Langley95c29f32014-06-20 12:00:00 -0700141 bfree *block // list of free blocks
142
143 nextCipher interface{} // next encryption state
144 nextMac macFunction // next MAC algorithm
David Benjamin83f90402015-01-27 01:09:43 -0500145 nextSeq [6]byte // next epoch's starting sequence number in DTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700146
147 // used to save allocating a new buffer for each MAC.
148 inDigestBuf, outDigestBuf []byte
Adam Langley80842bd2014-06-20 12:00:00 -0700149
150 config *Config
Adam Langley95c29f32014-06-20 12:00:00 -0700151}
152
153func (hc *halfConn) setErrorLocked(err error) error {
154 hc.err = err
155 return err
156}
157
158func (hc *halfConn) error() error {
Adam Langley2ae77d22014-10-28 17:29:33 -0700159 // This should be locked, but I've removed it for the renegotiation
160 // tests since we don't concurrently read and write the same tls.Conn
161 // in any case during testing.
Adam Langley95c29f32014-06-20 12:00:00 -0700162 err := hc.err
Adam Langley95c29f32014-06-20 12:00:00 -0700163 return err
164}
165
166// prepareCipherSpec sets the encryption and MAC states
167// that a subsequent changeCipherSpec will use.
168func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
169 hc.version = version
170 hc.nextCipher = cipher
171 hc.nextMac = mac
172}
173
174// changeCipherSpec changes the encryption and MAC states
175// to the ones previously passed to prepareCipherSpec.
Adam Langley80842bd2014-06-20 12:00:00 -0700176func (hc *halfConn) changeCipherSpec(config *Config) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700177 if hc.nextCipher == nil {
178 return alertInternalError
179 }
180 hc.cipher = hc.nextCipher
181 hc.mac = hc.nextMac
182 hc.nextCipher = nil
183 hc.nextMac = nil
Adam Langley80842bd2014-06-20 12:00:00 -0700184 hc.config = config
David Benjamin83c0bc92014-08-04 01:23:53 -0400185 hc.incEpoch()
Adam Langley95c29f32014-06-20 12:00:00 -0700186 return nil
187}
188
189// incSeq increments the sequence number.
David Benjamin5e961c12014-11-07 01:48:35 -0500190func (hc *halfConn) incSeq(isOutgoing bool) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400191 limit := 0
David Benjamin5e961c12014-11-07 01:48:35 -0500192 increment := uint64(1)
David Benjamin83c0bc92014-08-04 01:23:53 -0400193 if hc.isDTLS {
194 // Increment up to the epoch in DTLS.
195 limit = 2
196 }
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 }
David Benjamin8e6db492015-07-25 18:29:23 -0400209
210 hc.updateOutSeq()
Adam Langley95c29f32014-06-20 12:00:00 -0700211}
212
David Benjamin83f90402015-01-27 01:09:43 -0500213// incNextSeq increments the starting sequence number for the next epoch.
214func (hc *halfConn) incNextSeq() {
215 for i := len(hc.nextSeq) - 1; i >= 0; i-- {
216 hc.nextSeq[i]++
217 if hc.nextSeq[i] != 0 {
218 return
219 }
220 }
221 panic("TLS: sequence number wraparound")
222}
223
224// incEpoch resets the sequence number. In DTLS, it also increments the epoch
225// half of the sequence number.
David Benjamin83c0bc92014-08-04 01:23:53 -0400226func (hc *halfConn) incEpoch() {
David Benjamin83c0bc92014-08-04 01:23:53 -0400227 if hc.isDTLS {
228 for i := 1; i >= 0; i-- {
229 hc.seq[i]++
230 if hc.seq[i] != 0 {
231 break
232 }
233 if i == 0 {
234 panic("TLS: epoch number wraparound")
235 }
236 }
David Benjamin83f90402015-01-27 01:09:43 -0500237 copy(hc.seq[2:], hc.nextSeq[:])
238 for i := range hc.nextSeq {
239 hc.nextSeq[i] = 0
240 }
241 } else {
242 for i := range hc.seq {
243 hc.seq[i] = 0
244 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400245 }
David Benjamin8e6db492015-07-25 18:29:23 -0400246
247 hc.updateOutSeq()
248}
249
250func (hc *halfConn) updateOutSeq() {
251 if hc.config.Bugs.SequenceNumberMapping != nil {
252 seqU64 := binary.BigEndian.Uint64(hc.seq[:])
253 seqU64 = hc.config.Bugs.SequenceNumberMapping(seqU64)
254 binary.BigEndian.PutUint64(hc.outSeq[:], seqU64)
255
256 // The DTLS epoch cannot be changed.
257 copy(hc.outSeq[:2], hc.seq[:2])
258 return
259 }
260
261 copy(hc.outSeq[:], hc.seq[:])
David Benjamin83c0bc92014-08-04 01:23:53 -0400262}
263
264func (hc *halfConn) recordHeaderLen() int {
265 if hc.isDTLS {
266 return dtlsRecordHeaderLen
267 }
268 return tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700269}
270
271// removePadding returns an unpadded slice, in constant time, which is a prefix
272// of the input. It also returns a byte which is equal to 255 if the padding
273// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
274func removePadding(payload []byte) ([]byte, byte) {
275 if len(payload) < 1 {
276 return payload, 0
277 }
278
279 paddingLen := payload[len(payload)-1]
280 t := uint(len(payload)-1) - uint(paddingLen)
281 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
282 good := byte(int32(^t) >> 31)
283
284 toCheck := 255 // the maximum possible padding length
285 // The length of the padded data is public, so we can use an if here
286 if toCheck+1 > len(payload) {
287 toCheck = len(payload) - 1
288 }
289
290 for i := 0; i < toCheck; i++ {
291 t := uint(paddingLen) - uint(i)
292 // if i <= paddingLen then the MSB of t is zero
293 mask := byte(int32(^t) >> 31)
294 b := payload[len(payload)-1-i]
295 good &^= mask&paddingLen ^ mask&b
296 }
297
298 // We AND together the bits of good and replicate the result across
299 // all the bits.
300 good &= good << 4
301 good &= good << 2
302 good &= good << 1
303 good = uint8(int8(good) >> 7)
304
305 toRemove := good&paddingLen + 1
306 return payload[:len(payload)-int(toRemove)], good
307}
308
309// removePaddingSSL30 is a replacement for removePadding in the case that the
310// protocol version is SSLv3. In this version, the contents of the padding
311// are random and cannot be checked.
312func removePaddingSSL30(payload []byte) ([]byte, byte) {
313 if len(payload) < 1 {
314 return payload, 0
315 }
316
317 paddingLen := int(payload[len(payload)-1]) + 1
318 if paddingLen > len(payload) {
319 return payload, 0
320 }
321
322 return payload[:len(payload)-paddingLen], 255
323}
324
325func roundUp(a, b int) int {
326 return a + (b-a%b)%b
327}
328
329// cbcMode is an interface for block ciphers using cipher block chaining.
330type cbcMode interface {
331 cipher.BlockMode
332 SetIV([]byte)
333}
334
335// decrypt checks and strips the mac and decrypts the data in b. Returns a
336// success boolean, the number of bytes to skip from the start of the record in
337// order to get the application payload, and an optional alert value.
338func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, alertValue alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400339 recordHeaderLen := hc.recordHeaderLen()
340
Adam Langley95c29f32014-06-20 12:00:00 -0700341 // pull out payload
342 payload := b.data[recordHeaderLen:]
343
344 macSize := 0
345 if hc.mac != nil {
346 macSize = hc.mac.Size()
347 }
348
349 paddingGood := byte(255)
350 explicitIVLen := 0
351
David Benjamin83c0bc92014-08-04 01:23:53 -0400352 seq := hc.seq[:]
353 if hc.isDTLS {
354 // DTLS sequence numbers are explicit.
355 seq = b.data[3:11]
356 }
357
Adam Langley95c29f32014-06-20 12:00:00 -0700358 // decrypt
359 if hc.cipher != nil {
360 switch c := hc.cipher.(type) {
361 case cipher.Stream:
362 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400363 case *tlsAead:
364 nonce := seq
365 if c.explicitNonce {
366 explicitIVLen = 8
367 if len(payload) < explicitIVLen {
368 return false, 0, alertBadRecordMAC
369 }
370 nonce = payload[:8]
371 payload = payload[8:]
Adam Langley95c29f32014-06-20 12:00:00 -0700372 }
Adam Langley95c29f32014-06-20 12:00:00 -0700373
374 var additionalData [13]byte
David Benjamin83c0bc92014-08-04 01:23:53 -0400375 copy(additionalData[:], seq)
Adam Langley95c29f32014-06-20 12:00:00 -0700376 copy(additionalData[8:], b.data[:3])
377 n := len(payload) - c.Overhead()
378 additionalData[11] = byte(n >> 8)
379 additionalData[12] = byte(n)
380 var err error
381 payload, err = c.Open(payload[:0], nonce, payload, additionalData[:])
382 if err != nil {
383 return false, 0, alertBadRecordMAC
384 }
385 b.resize(recordHeaderLen + explicitIVLen + len(payload))
386 case cbcMode:
387 blockSize := c.BlockSize()
David Benjamin83c0bc92014-08-04 01:23:53 -0400388 if hc.version >= VersionTLS11 || hc.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700389 explicitIVLen = blockSize
390 }
391
392 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
393 return false, 0, alertBadRecordMAC
394 }
395
396 if explicitIVLen > 0 {
397 c.SetIV(payload[:explicitIVLen])
398 payload = payload[explicitIVLen:]
399 }
400 c.CryptBlocks(payload, payload)
401 if hc.version == VersionSSL30 {
402 payload, paddingGood = removePaddingSSL30(payload)
403 } else {
404 payload, paddingGood = removePadding(payload)
405 }
406 b.resize(recordHeaderLen + explicitIVLen + len(payload))
407
408 // note that we still have a timing side-channel in the
409 // MAC check, below. An attacker can align the record
410 // so that a correct padding will cause one less hash
411 // block to be calculated. Then they can iteratively
412 // decrypt a record by breaking each byte. See
413 // "Password Interception in a SSL/TLS Channel", Brice
414 // Canvel et al.
415 //
416 // However, our behavior matches OpenSSL, so we leak
417 // only as much as they do.
418 default:
419 panic("unknown cipher type")
420 }
421 }
422
423 // check, strip mac
424 if hc.mac != nil {
425 if len(payload) < macSize {
426 return false, 0, alertBadRecordMAC
427 }
428
429 // strip mac off payload, b.data
430 n := len(payload) - macSize
David Benjamin83c0bc92014-08-04 01:23:53 -0400431 b.data[recordHeaderLen-2] = byte(n >> 8)
432 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700433 b.resize(recordHeaderLen + explicitIVLen + n)
434 remoteMAC := payload[n:]
David Benjamin83c0bc92014-08-04 01:23:53 -0400435 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
Adam Langley95c29f32014-06-20 12:00:00 -0700436
437 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
438 return false, 0, alertBadRecordMAC
439 }
440 hc.inDigestBuf = localMAC
441 }
David Benjamin5e961c12014-11-07 01:48:35 -0500442 hc.incSeq(false)
Adam Langley95c29f32014-06-20 12:00:00 -0700443
444 return true, recordHeaderLen + explicitIVLen, 0
445}
446
447// padToBlockSize calculates the needed padding block, if any, for a payload.
448// On exit, prefix aliases payload and extends to the end of the last full
449// block of payload. finalBlock is a fresh slice which contains the contents of
450// any suffix of payload as well as the needed padding to make finalBlock a
451// full block.
Adam Langley80842bd2014-06-20 12:00:00 -0700452func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
Adam Langley95c29f32014-06-20 12:00:00 -0700453 overrun := len(payload) % blockSize
Adam Langley95c29f32014-06-20 12:00:00 -0700454 prefix = payload[:len(payload)-overrun]
Adam Langley80842bd2014-06-20 12:00:00 -0700455
456 paddingLen := blockSize - overrun
457 finalSize := blockSize
458 if config.Bugs.MaxPadding {
459 for paddingLen+blockSize <= 256 {
460 paddingLen += blockSize
461 }
462 finalSize = 256
463 }
464 finalBlock = make([]byte, finalSize)
465 for i := range finalBlock {
Adam Langley95c29f32014-06-20 12:00:00 -0700466 finalBlock[i] = byte(paddingLen - 1)
467 }
Adam Langley80842bd2014-06-20 12:00:00 -0700468 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
469 finalBlock[overrun] ^= 0xff
470 }
471 copy(finalBlock, payload[len(payload)-overrun:])
Adam Langley95c29f32014-06-20 12:00:00 -0700472 return
473}
474
475// encrypt encrypts and macs the data in b.
476func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400477 recordHeaderLen := hc.recordHeaderLen()
478
Adam Langley95c29f32014-06-20 12:00:00 -0700479 // mac
480 if hc.mac != nil {
David Benjamin8e6db492015-07-25 18:29:23 -0400481 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 -0700482
483 n := len(b.data)
484 b.resize(n + len(mac))
485 copy(b.data[n:], mac)
486 hc.outDigestBuf = mac
487 }
488
489 payload := b.data[recordHeaderLen:]
490
491 // encrypt
492 if hc.cipher != nil {
493 switch c := hc.cipher.(type) {
494 case cipher.Stream:
495 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400496 case *tlsAead:
Adam Langley95c29f32014-06-20 12:00:00 -0700497 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
498 b.resize(len(b.data) + c.Overhead())
David Benjamin8e6db492015-07-25 18:29:23 -0400499 nonce := hc.outSeq[:]
David Benjamine9a80ff2015-04-07 00:46:46 -0400500 if c.explicitNonce {
501 nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
502 }
Adam Langley95c29f32014-06-20 12:00:00 -0700503 payload := b.data[recordHeaderLen+explicitIVLen:]
504 payload = payload[:payloadLen]
505
506 var additionalData [13]byte
David Benjamin8e6db492015-07-25 18:29:23 -0400507 copy(additionalData[:], hc.outSeq[:])
Adam Langley95c29f32014-06-20 12:00:00 -0700508 copy(additionalData[8:], b.data[:3])
509 additionalData[11] = byte(payloadLen >> 8)
510 additionalData[12] = byte(payloadLen)
511
512 c.Seal(payload[:0], nonce, payload, additionalData[:])
513 case cbcMode:
514 blockSize := c.BlockSize()
515 if explicitIVLen > 0 {
516 c.SetIV(payload[:explicitIVLen])
517 payload = payload[explicitIVLen:]
518 }
Adam Langley80842bd2014-06-20 12:00:00 -0700519 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700520 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
521 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
522 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
523 default:
524 panic("unknown cipher type")
525 }
526 }
527
528 // update length to include MAC and any block padding needed.
529 n := len(b.data) - recordHeaderLen
David Benjamin83c0bc92014-08-04 01:23:53 -0400530 b.data[recordHeaderLen-2] = byte(n >> 8)
531 b.data[recordHeaderLen-1] = byte(n)
David Benjamin5e961c12014-11-07 01:48:35 -0500532 hc.incSeq(true)
Adam Langley95c29f32014-06-20 12:00:00 -0700533
534 return true, 0
535}
536
537// A block is a simple data buffer.
538type block struct {
539 data []byte
540 off int // index for Read
541 link *block
542}
543
544// resize resizes block to be n bytes, growing if necessary.
545func (b *block) resize(n int) {
546 if n > cap(b.data) {
547 b.reserve(n)
548 }
549 b.data = b.data[0:n]
550}
551
552// reserve makes sure that block contains a capacity of at least n bytes.
553func (b *block) reserve(n int) {
554 if cap(b.data) >= n {
555 return
556 }
557 m := cap(b.data)
558 if m == 0 {
559 m = 1024
560 }
561 for m < n {
562 m *= 2
563 }
564 data := make([]byte, len(b.data), m)
565 copy(data, b.data)
566 b.data = data
567}
568
569// readFromUntil reads from r into b until b contains at least n bytes
570// or else returns an error.
571func (b *block) readFromUntil(r io.Reader, n int) error {
572 // quick case
573 if len(b.data) >= n {
574 return nil
575 }
576
577 // read until have enough.
578 b.reserve(n)
579 for {
580 m, err := r.Read(b.data[len(b.data):cap(b.data)])
581 b.data = b.data[0 : len(b.data)+m]
582 if len(b.data) >= n {
583 // TODO(bradfitz,agl): slightly suspicious
584 // that we're throwing away r.Read's err here.
585 break
586 }
587 if err != nil {
588 return err
589 }
590 }
591 return nil
592}
593
594func (b *block) Read(p []byte) (n int, err error) {
595 n = copy(p, b.data[b.off:])
596 b.off += n
597 return
598}
599
600// newBlock allocates a new block, from hc's free list if possible.
601func (hc *halfConn) newBlock() *block {
602 b := hc.bfree
603 if b == nil {
604 return new(block)
605 }
606 hc.bfree = b.link
607 b.link = nil
608 b.resize(0)
609 return b
610}
611
612// freeBlock returns a block to hc's free list.
613// The protocol is such that each side only has a block or two on
614// its free list at a time, so there's no need to worry about
615// trimming the list, etc.
616func (hc *halfConn) freeBlock(b *block) {
617 b.link = hc.bfree
618 hc.bfree = b
619}
620
621// splitBlock splits a block after the first n bytes,
622// returning a block with those n bytes and a
623// block with the remainder. the latter may be nil.
624func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
625 if len(b.data) <= n {
626 return b, nil
627 }
628 bb := hc.newBlock()
629 bb.resize(len(b.data) - n)
630 copy(bb.data, b.data[n:])
631 b.data = b.data[0:n]
632 return b, bb
633}
634
David Benjamin83c0bc92014-08-04 01:23:53 -0400635func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
636 if c.isDTLS {
637 return c.dtlsDoReadRecord(want)
638 }
639
640 recordHeaderLen := tlsRecordHeaderLen
641
642 if c.rawInput == nil {
643 c.rawInput = c.in.newBlock()
644 }
645 b := c.rawInput
646
647 // Read header, payload.
648 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
649 // RFC suggests that EOF without an alertCloseNotify is
650 // an error, but popular web sites seem to do this,
David Benjamin30789da2015-08-29 22:56:45 -0400651 // so we can't make it an error, outside of tests.
652 if err == io.EOF && c.config.Bugs.ExpectCloseNotify {
653 err = io.ErrUnexpectedEOF
654 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400655 if e, ok := err.(net.Error); !ok || !e.Temporary() {
656 c.in.setErrorLocked(err)
657 }
658 return 0, nil, err
659 }
660 typ := recordType(b.data[0])
661
662 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
663 // start with a uint16 length where the MSB is set and the first record
664 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
665 // an SSLv2 client.
666 if want == recordTypeHandshake && typ == 0x80 {
667 c.sendAlert(alertProtocolVersion)
668 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
669 }
670
671 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
672 n := int(b.data[3])<<8 | int(b.data[4])
David Benjamin1e29a6b2014-12-10 02:27:24 -0500673 if c.haveVers {
674 if vers != c.vers {
675 c.sendAlert(alertProtocolVersion)
676 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers))
677 }
678 } else {
679 if expect := c.config.Bugs.ExpectInitialRecordVersion; expect != 0 && vers != expect {
680 c.sendAlert(alertProtocolVersion)
681 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
682 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400683 }
684 if n > maxCiphertext {
685 c.sendAlert(alertRecordOverflow)
686 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
687 }
688 if !c.haveVers {
689 // First message, be extra suspicious:
690 // this might not be a TLS client.
691 // Bail out before reading a full 'body', if possible.
692 // The current max version is 3.1.
693 // If the version is >= 16.0, it's probably not real.
694 // Similarly, a clientHello message encodes in
695 // well under a kilobyte. If the length is >= 12 kB,
696 // it's probably not real.
697 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
698 c.sendAlert(alertUnexpectedMessage)
699 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
700 }
701 }
702 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
703 if err == io.EOF {
704 err = io.ErrUnexpectedEOF
705 }
706 if e, ok := err.(net.Error); !ok || !e.Temporary() {
707 c.in.setErrorLocked(err)
708 }
709 return 0, nil, err
710 }
711
712 // Process message.
713 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
714 ok, off, err := c.in.decrypt(b)
715 if !ok {
716 c.in.setErrorLocked(c.sendAlert(err))
717 }
718 b.off = off
719 return typ, b, nil
720}
721
Adam Langley95c29f32014-06-20 12:00:00 -0700722// readRecord reads the next TLS record from the connection
723// and updates the record layer state.
724// c.in.Mutex <= L; c.input == nil.
725func (c *Conn) readRecord(want recordType) error {
726 // Caller must be in sync with connection:
727 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700728 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700729 switch want {
730 default:
731 c.sendAlert(alertInternalError)
732 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
733 case recordTypeHandshake, recordTypeChangeCipherSpec:
734 if c.handshakeComplete {
735 c.sendAlert(alertInternalError)
736 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
737 }
738 case recordTypeApplicationData:
David Benjamine58c4f52014-08-24 03:47:07 -0400739 if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart {
Adam Langley95c29f32014-06-20 12:00:00 -0700740 c.sendAlert(alertInternalError)
741 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
742 }
David Benjamin30789da2015-08-29 22:56:45 -0400743 case recordTypeAlert:
744 // Looking for a close_notify. Note: unlike a real
745 // implementation, this is not tolerant of additional records.
746 // See the documentation for ExpectCloseNotify.
Adam Langley95c29f32014-06-20 12:00:00 -0700747 }
748
749Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400750 typ, b, err := c.doReadRecord(want)
751 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700752 return err
753 }
Adam Langley95c29f32014-06-20 12:00:00 -0700754 data := b.data[b.off:]
755 if len(data) > maxPlaintext {
756 err := c.sendAlert(alertRecordOverflow)
757 c.in.freeBlock(b)
758 return c.in.setErrorLocked(err)
759 }
760
761 switch typ {
762 default:
763 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
764
765 case recordTypeAlert:
766 if len(data) != 2 {
767 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
768 break
769 }
770 if alert(data[1]) == alertCloseNotify {
771 c.in.setErrorLocked(io.EOF)
772 break
773 }
774 switch data[0] {
775 case alertLevelWarning:
776 // drop on the floor
777 c.in.freeBlock(b)
778 goto Again
779 case alertLevelError:
780 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
781 default:
782 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
783 }
784
785 case recordTypeChangeCipherSpec:
786 if typ != want || len(data) != 1 || data[0] != 1 {
787 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
788 break
789 }
Adam Langley80842bd2014-06-20 12:00:00 -0700790 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700791 if err != nil {
792 c.in.setErrorLocked(c.sendAlert(err.(alert)))
793 }
794
795 case recordTypeApplicationData:
796 if typ != want {
797 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
798 break
799 }
800 c.input = b
801 b = nil
802
803 case recordTypeHandshake:
804 // TODO(rsc): Should at least pick off connection close.
805 if typ != want {
Adam Langley2ae77d22014-10-28 17:29:33 -0700806 // A client might need to process a HelloRequest from
807 // the server, thus receiving a handshake message when
David Benjamind9b091b2015-01-27 01:10:54 -0500808 // application data is expected is ok.
David Benjamin30789da2015-08-29 22:56:45 -0400809 if !c.isClient || want != recordTypeApplicationData {
Adam Langley2ae77d22014-10-28 17:29:33 -0700810 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
811 }
Adam Langley95c29f32014-06-20 12:00:00 -0700812 }
813 c.hand.Write(data)
814 }
815
816 if b != nil {
817 c.in.freeBlock(b)
818 }
819 return c.in.err
820}
821
822// sendAlert sends a TLS alert message.
823// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400824func (c *Conn) sendAlertLocked(level byte, err alert) error {
825 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700826 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400827 if c.config.Bugs.FragmentAlert {
828 c.writeRecord(recordTypeAlert, c.tmp[0:1])
829 c.writeRecord(recordTypeAlert, c.tmp[1:2])
830 } else {
831 c.writeRecord(recordTypeAlert, c.tmp[0:2])
832 }
David Benjamin24f346d2015-06-06 03:28:08 -0400833 // Error alerts are fatal to the connection.
834 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700835 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
836 }
837 return nil
838}
839
840// sendAlert sends a TLS alert message.
841// L < c.out.Mutex.
842func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400843 level := byte(alertLevelError)
844 if err == alertNoRenegotiation || err == alertCloseNotify {
845 level = alertLevelWarning
846 }
847 return c.SendAlert(level, err)
848}
849
850func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700851 c.out.Lock()
852 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -0400853 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -0700854}
855
David Benjamind86c7672014-08-02 04:07:12 -0400856// writeV2Record writes a record for a V2ClientHello.
857func (c *Conn) writeV2Record(data []byte) (n int, err error) {
858 record := make([]byte, 2+len(data))
859 record[0] = uint8(len(data)>>8) | 0x80
860 record[1] = uint8(len(data))
861 copy(record[2:], data)
862 return c.conn.Write(record)
863}
864
Adam Langley95c29f32014-06-20 12:00:00 -0700865// writeRecord writes a TLS record with the given type and payload
866// to the connection and updates the record layer state.
867// c.out.Mutex <= L.
868func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400869 if c.isDTLS {
870 return c.dtlsWriteRecord(typ, data)
871 }
872
873 recordHeaderLen := tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700874 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -0400875 first := true
876 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -0400877 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -0700878 m := len(data)
879 if m > maxPlaintext {
880 m = maxPlaintext
881 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400882 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
883 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -0400884 // By default, do not fragment the client_version or
885 // server_version, which are located in the first 6
886 // bytes.
887 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
888 m = 6
889 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400890 }
Adam Langley95c29f32014-06-20 12:00:00 -0700891 explicitIVLen := 0
892 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -0400893 first = false
Adam Langley95c29f32014-06-20 12:00:00 -0700894
895 var cbc cbcMode
896 if c.out.version >= VersionTLS11 {
897 var ok bool
898 if cbc, ok = c.out.cipher.(cbcMode); ok {
899 explicitIVLen = cbc.BlockSize()
900 }
901 }
902 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -0400903 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -0700904 explicitIVLen = 8
905 // The AES-GCM construction in TLS has an
906 // explicit nonce so that the nonce can be
907 // random. However, the nonce is only 8 bytes
908 // which is too small for a secure, random
909 // nonce. Therefore we use the sequence number
910 // as the nonce.
911 explicitIVIsSeq = true
912 }
913 }
914 b.resize(recordHeaderLen + explicitIVLen + m)
915 b.data[0] = byte(typ)
916 vers := c.vers
917 if vers == 0 {
918 // Some TLS servers fail if the record version is
919 // greater than TLS 1.0 for the initial ClientHello.
920 vers = VersionTLS10
921 }
922 b.data[1] = byte(vers >> 8)
923 b.data[2] = byte(vers)
924 b.data[3] = byte(m >> 8)
925 b.data[4] = byte(m)
926 if explicitIVLen > 0 {
927 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
928 if explicitIVIsSeq {
929 copy(explicitIV, c.out.seq[:])
930 } else {
931 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
932 break
933 }
934 }
935 }
936 copy(b.data[recordHeaderLen+explicitIVLen:], data)
937 c.out.encrypt(b, explicitIVLen)
938 _, err = c.conn.Write(b.data)
939 if err != nil {
940 break
941 }
942 n += m
943 data = data[m:]
944 }
945 c.out.freeBlock(b)
946
947 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -0700948 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700949 if err != nil {
950 // Cannot call sendAlert directly,
951 // because we already hold c.out.Mutex.
952 c.tmp[0] = alertLevelError
953 c.tmp[1] = byte(err.(alert))
954 c.writeRecord(recordTypeAlert, c.tmp[0:2])
955 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
956 }
957 }
958 return
959}
960
David Benjamin83c0bc92014-08-04 01:23:53 -0400961func (c *Conn) doReadHandshake() ([]byte, error) {
962 if c.isDTLS {
963 return c.dtlsDoReadHandshake()
964 }
965
Adam Langley95c29f32014-06-20 12:00:00 -0700966 for c.hand.Len() < 4 {
967 if err := c.in.err; err != nil {
968 return nil, err
969 }
970 if err := c.readRecord(recordTypeHandshake); err != nil {
971 return nil, err
972 }
973 }
974
975 data := c.hand.Bytes()
976 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
977 if n > maxHandshake {
978 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
979 }
980 for c.hand.Len() < 4+n {
981 if err := c.in.err; err != nil {
982 return nil, err
983 }
984 if err := c.readRecord(recordTypeHandshake); err != nil {
985 return nil, err
986 }
987 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400988 return c.hand.Next(4 + n), nil
989}
990
991// readHandshake reads the next handshake message from
992// the record layer.
993// c.in.Mutex < L; c.out.Mutex < L.
994func (c *Conn) readHandshake() (interface{}, error) {
995 data, err := c.doReadHandshake()
996 if err != nil {
997 return nil, err
998 }
999
Adam Langley95c29f32014-06-20 12:00:00 -07001000 var m handshakeMessage
1001 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001002 case typeHelloRequest:
1003 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001004 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001005 m = &clientHelloMsg{
1006 isDTLS: c.isDTLS,
1007 }
Adam Langley95c29f32014-06-20 12:00:00 -07001008 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001009 m = &serverHelloMsg{
1010 isDTLS: c.isDTLS,
1011 }
Adam Langley95c29f32014-06-20 12:00:00 -07001012 case typeNewSessionTicket:
1013 m = new(newSessionTicketMsg)
1014 case typeCertificate:
1015 m = new(certificateMsg)
1016 case typeCertificateRequest:
1017 m = &certificateRequestMsg{
1018 hasSignatureAndHash: c.vers >= VersionTLS12,
1019 }
1020 case typeCertificateStatus:
1021 m = new(certificateStatusMsg)
1022 case typeServerKeyExchange:
1023 m = new(serverKeyExchangeMsg)
1024 case typeServerHelloDone:
1025 m = new(serverHelloDoneMsg)
1026 case typeClientKeyExchange:
1027 m = new(clientKeyExchangeMsg)
1028 case typeCertificateVerify:
1029 m = &certificateVerifyMsg{
1030 hasSignatureAndHash: c.vers >= VersionTLS12,
1031 }
1032 case typeNextProtocol:
1033 m = new(nextProtoMsg)
1034 case typeFinished:
1035 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001036 case typeHelloVerifyRequest:
1037 m = new(helloVerifyRequestMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001038 case typeEncryptedExtensions:
1039 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001040 default:
1041 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1042 }
1043
1044 // The handshake message unmarshallers
1045 // expect to be able to keep references to data,
1046 // so pass in a fresh copy that won't be overwritten.
1047 data = append([]byte(nil), data...)
1048
1049 if !m.unmarshal(data) {
1050 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1051 }
1052 return m, nil
1053}
1054
David Benjamin83f90402015-01-27 01:09:43 -05001055// skipPacket processes all the DTLS records in packet. It updates
1056// sequence number expectations but otherwise ignores them.
1057func (c *Conn) skipPacket(packet []byte) error {
1058 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001059 if len(packet) < 13 {
1060 return errors.New("tls: bad packet")
1061 }
David Benjamin83f90402015-01-27 01:09:43 -05001062 // Dropped packets are completely ignored save to update
1063 // expected sequence numbers for this and the next epoch. (We
1064 // don't assert on the contents of the packets both for
1065 // simplicity and because a previous test with one shorter
1066 // timeout schedule would have done so.)
1067 epoch := packet[3:5]
1068 seq := packet[5:11]
1069 length := uint16(packet[11])<<8 | uint16(packet[12])
1070 if bytes.Equal(c.in.seq[:2], epoch) {
1071 if !bytes.Equal(c.in.seq[2:], seq) {
1072 return errors.New("tls: sequence mismatch")
1073 }
1074 c.in.incSeq(false)
1075 } else {
1076 if !bytes.Equal(c.in.nextSeq[:], seq) {
1077 return errors.New("tls: sequence mismatch")
1078 }
1079 c.in.incNextSeq()
1080 }
David Benjamin6ca93552015-08-28 16:16:25 -04001081 if len(packet) < 13+int(length) {
1082 return errors.New("tls: bad packet")
1083 }
David Benjamin83f90402015-01-27 01:09:43 -05001084 packet = packet[13+length:]
1085 }
1086 return nil
1087}
1088
1089// simulatePacketLoss simulates the loss of a handshake leg from the
1090// peer based on the schedule in c.config.Bugs. If resendFunc is
1091// non-nil, it is called after each simulated timeout to retransmit
1092// handshake messages from the local end. This is used in cases where
1093// the peer retransmits on a stale Finished rather than a timeout.
1094func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1095 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1096 return nil
1097 }
1098 if !c.isDTLS {
1099 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1100 }
1101 if c.config.Bugs.PacketAdaptor == nil {
1102 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1103 }
1104 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1105 // Simulate a timeout.
1106 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1107 if err != nil {
1108 return err
1109 }
1110 for _, packet := range packets {
1111 if err := c.skipPacket(packet); err != nil {
1112 return err
1113 }
1114 }
1115 if resendFunc != nil {
1116 resendFunc()
1117 }
1118 }
1119 return nil
1120}
1121
Adam Langley95c29f32014-06-20 12:00:00 -07001122// Write writes data to the connection.
1123func (c *Conn) Write(b []byte) (int, error) {
1124 if err := c.Handshake(); err != nil {
1125 return 0, err
1126 }
1127
1128 c.out.Lock()
1129 defer c.out.Unlock()
1130
1131 if err := c.out.err; err != nil {
1132 return 0, err
1133 }
1134
1135 if !c.handshakeComplete {
1136 return 0, alertInternalError
1137 }
1138
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001139 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001140 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001141 }
1142
Adam Langley95c29f32014-06-20 12:00:00 -07001143 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1144 // attack when using block mode ciphers due to predictable IVs.
1145 // This can be prevented by splitting each Application Data
1146 // record into two records, effectively randomizing the IV.
1147 //
1148 // http://www.openssl.org/~bodo/tls-cbc.txt
1149 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1150 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1151
1152 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001153 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001154 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1155 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1156 if err != nil {
1157 return n, c.out.setErrorLocked(err)
1158 }
1159 m, b = 1, b[1:]
1160 }
1161 }
1162
1163 n, err := c.writeRecord(recordTypeApplicationData, b)
1164 return n + m, c.out.setErrorLocked(err)
1165}
1166
Adam Langley2ae77d22014-10-28 17:29:33 -07001167func (c *Conn) handleRenegotiation() error {
1168 c.handshakeComplete = false
1169 if !c.isClient {
1170 panic("renegotiation should only happen for a client")
1171 }
1172
1173 msg, err := c.readHandshake()
1174 if err != nil {
1175 return err
1176 }
1177 _, ok := msg.(*helloRequestMsg)
1178 if !ok {
1179 c.sendAlert(alertUnexpectedMessage)
1180 return alertUnexpectedMessage
1181 }
1182
1183 return c.Handshake()
1184}
1185
Adam Langleycf2d4f42014-10-28 19:06:14 -07001186func (c *Conn) Renegotiate() error {
1187 if !c.isClient {
1188 helloReq := new(helloRequestMsg)
1189 c.writeRecord(recordTypeHandshake, helloReq.marshal())
1190 }
1191
1192 c.handshakeComplete = false
1193 return c.Handshake()
1194}
1195
Adam Langley95c29f32014-06-20 12:00:00 -07001196// Read can be made to time out and return a net.Error with Timeout() == true
1197// after a fixed time limit; see SetDeadline and SetReadDeadline.
1198func (c *Conn) Read(b []byte) (n int, err error) {
1199 if err = c.Handshake(); err != nil {
1200 return
1201 }
1202
1203 c.in.Lock()
1204 defer c.in.Unlock()
1205
1206 // Some OpenSSL servers send empty records in order to randomize the
1207 // CBC IV. So this loop ignores a limited number of empty records.
1208 const maxConsecutiveEmptyRecords = 100
1209 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1210 for c.input == nil && c.in.err == nil {
1211 if err := c.readRecord(recordTypeApplicationData); err != nil {
1212 // Soft error, like EAGAIN
1213 return 0, err
1214 }
David Benjamind9b091b2015-01-27 01:10:54 -05001215 if c.hand.Len() > 0 {
Adam Langley2ae77d22014-10-28 17:29:33 -07001216 // We received handshake bytes, indicating the
David Benjamind9b091b2015-01-27 01:10:54 -05001217 // start of a renegotiation.
Adam Langley2ae77d22014-10-28 17:29:33 -07001218 if err := c.handleRenegotiation(); err != nil {
1219 return 0, err
1220 }
1221 continue
1222 }
Adam Langley95c29f32014-06-20 12:00:00 -07001223 }
1224 if err := c.in.err; err != nil {
1225 return 0, err
1226 }
1227
1228 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001229 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001230 c.in.freeBlock(c.input)
1231 c.input = nil
1232 }
1233
1234 // If a close-notify alert is waiting, read it so that
1235 // we can return (n, EOF) instead of (n, nil), to signal
1236 // to the HTTP response reading goroutine that the
1237 // connection is now closed. This eliminates a race
1238 // where the HTTP response reading goroutine would
1239 // otherwise not observe the EOF until its next read,
1240 // by which time a client goroutine might have already
1241 // tried to reuse the HTTP connection for a new
1242 // request.
1243 // See https://codereview.appspot.com/76400046
1244 // and http://golang.org/issue/3514
1245 if ri := c.rawInput; ri != nil &&
1246 n != 0 && err == nil &&
1247 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1248 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1249 err = recErr // will be io.EOF on closeNotify
1250 }
1251 }
1252
1253 if n != 0 || err != nil {
1254 return n, err
1255 }
1256 }
1257
1258 return 0, io.ErrNoProgress
1259}
1260
1261// Close closes the connection.
1262func (c *Conn) Close() error {
1263 var alertErr error
1264
1265 c.handshakeMutex.Lock()
1266 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001267 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
Adam Langley95c29f32014-06-20 12:00:00 -07001268 alertErr = c.sendAlert(alertCloseNotify)
1269 }
1270
David Benjamin30789da2015-08-29 22:56:45 -04001271 // Consume a close_notify from the peer if one hasn't been received
1272 // already. This avoids the peer from failing |SSL_shutdown| due to a
1273 // write failing.
1274 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1275 for c.in.error() == nil {
1276 c.readRecord(recordTypeAlert)
1277 }
1278 if c.in.error() != io.EOF {
1279 alertErr = c.in.error()
1280 }
1281 }
1282
Adam Langley95c29f32014-06-20 12:00:00 -07001283 if err := c.conn.Close(); err != nil {
1284 return err
1285 }
1286 return alertErr
1287}
1288
1289// Handshake runs the client or server handshake
1290// protocol if it has not yet been run.
1291// Most uses of this package need not call Handshake
1292// explicitly: the first Read or Write will call it automatically.
1293func (c *Conn) Handshake() error {
1294 c.handshakeMutex.Lock()
1295 defer c.handshakeMutex.Unlock()
1296 if err := c.handshakeErr; err != nil {
1297 return err
1298 }
1299 if c.handshakeComplete {
1300 return nil
1301 }
1302
David Benjamin9a41d1b2015-05-16 01:30:09 -04001303 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1304 c.conn.Write([]byte{
1305 byte(recordTypeAlert), // type
1306 0xfe, 0xff, // version
1307 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1308 0x0, 0x2, // length
1309 })
1310 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1311 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001312 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1313 c.writeRecord(recordTypeApplicationData, data)
1314 }
Adam Langley95c29f32014-06-20 12:00:00 -07001315 if c.isClient {
1316 c.handshakeErr = c.clientHandshake()
1317 } else {
1318 c.handshakeErr = c.serverHandshake()
1319 }
David Benjaminddb9f152015-02-03 15:44:39 -05001320 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1321 c.writeRecord(recordType(42), []byte("invalid record"))
1322 }
Adam Langley95c29f32014-06-20 12:00:00 -07001323 return c.handshakeErr
1324}
1325
1326// ConnectionState returns basic TLS details about the connection.
1327func (c *Conn) ConnectionState() ConnectionState {
1328 c.handshakeMutex.Lock()
1329 defer c.handshakeMutex.Unlock()
1330
1331 var state ConnectionState
1332 state.HandshakeComplete = c.handshakeComplete
1333 if c.handshakeComplete {
1334 state.Version = c.vers
1335 state.NegotiatedProtocol = c.clientProtocol
1336 state.DidResume = c.didResume
1337 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001338 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001339 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001340 state.PeerCertificates = c.peerCertificates
1341 state.VerifiedChains = c.verifiedChains
1342 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001343 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001344 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001345 state.TLSUnique = c.firstFinished[:]
Adam Langley95c29f32014-06-20 12:00:00 -07001346 }
1347
1348 return state
1349}
1350
1351// OCSPResponse returns the stapled OCSP response from the TLS server, if
1352// any. (Only valid for client connections.)
1353func (c *Conn) OCSPResponse() []byte {
1354 c.handshakeMutex.Lock()
1355 defer c.handshakeMutex.Unlock()
1356
1357 return c.ocspResponse
1358}
1359
1360// VerifyHostname checks that the peer certificate chain is valid for
1361// connecting to host. If so, it returns nil; if not, it returns an error
1362// describing the problem.
1363func (c *Conn) VerifyHostname(host string) error {
1364 c.handshakeMutex.Lock()
1365 defer c.handshakeMutex.Unlock()
1366 if !c.isClient {
1367 return errors.New("tls: VerifyHostname called on TLS server connection")
1368 }
1369 if !c.handshakeComplete {
1370 return errors.New("tls: handshake has not yet been performed")
1371 }
1372 return c.peerCertificates[0].VerifyHostname(host)
1373}
David Benjaminc565ebb2015-04-03 04:06:36 -04001374
1375// ExportKeyingMaterial exports keying material from the current connection
1376// state, as per RFC 5705.
1377func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1378 c.handshakeMutex.Lock()
1379 defer c.handshakeMutex.Unlock()
1380 if !c.handshakeComplete {
1381 return nil, errors.New("tls: handshake has not yet been performed")
1382 }
1383
1384 seedLen := len(c.clientRandom) + len(c.serverRandom)
1385 if useContext {
1386 seedLen += 2 + len(context)
1387 }
1388 seed := make([]byte, 0, seedLen)
1389 seed = append(seed, c.clientRandom[:]...)
1390 seed = append(seed, c.serverRandom[:]...)
1391 if useContext {
1392 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1393 seed = append(seed, context...)
1394 }
1395 result := make([]byte, length)
1396 prfForVersion(c.vers, c.cipherSuite)(result, c.masterSecret[:], label, seed)
1397 return result, nil
1398}