blob: b755c4678fc7d73b2b6112eac7b58a238782982d [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,
651 // so we can't make it an error.
652 // if err == io.EOF {
653 // err = io.ErrUnexpectedEOF
654 // }
655 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 }
743 }
744
745Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400746 typ, b, err := c.doReadRecord(want)
747 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700748 return err
749 }
Adam Langley95c29f32014-06-20 12:00:00 -0700750 data := b.data[b.off:]
751 if len(data) > maxPlaintext {
752 err := c.sendAlert(alertRecordOverflow)
753 c.in.freeBlock(b)
754 return c.in.setErrorLocked(err)
755 }
756
757 switch typ {
758 default:
759 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
760
761 case recordTypeAlert:
762 if len(data) != 2 {
763 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
764 break
765 }
766 if alert(data[1]) == alertCloseNotify {
767 c.in.setErrorLocked(io.EOF)
768 break
769 }
770 switch data[0] {
771 case alertLevelWarning:
772 // drop on the floor
773 c.in.freeBlock(b)
774 goto Again
775 case alertLevelError:
776 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
777 default:
778 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
779 }
780
781 case recordTypeChangeCipherSpec:
782 if typ != want || len(data) != 1 || data[0] != 1 {
783 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
784 break
785 }
Adam Langley80842bd2014-06-20 12:00:00 -0700786 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700787 if err != nil {
788 c.in.setErrorLocked(c.sendAlert(err.(alert)))
789 }
790
791 case recordTypeApplicationData:
792 if typ != want {
793 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
794 break
795 }
796 c.input = b
797 b = nil
798
799 case recordTypeHandshake:
800 // TODO(rsc): Should at least pick off connection close.
801 if typ != want {
Adam Langley2ae77d22014-10-28 17:29:33 -0700802 // A client might need to process a HelloRequest from
803 // the server, thus receiving a handshake message when
David Benjamind9b091b2015-01-27 01:10:54 -0500804 // application data is expected is ok.
805 if !c.isClient {
Adam Langley2ae77d22014-10-28 17:29:33 -0700806 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
807 }
Adam Langley95c29f32014-06-20 12:00:00 -0700808 }
809 c.hand.Write(data)
810 }
811
812 if b != nil {
813 c.in.freeBlock(b)
814 }
815 return c.in.err
816}
817
818// sendAlert sends a TLS alert message.
819// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400820func (c *Conn) sendAlertLocked(level byte, err alert) error {
821 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700822 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400823 if c.config.Bugs.FragmentAlert {
824 c.writeRecord(recordTypeAlert, c.tmp[0:1])
825 c.writeRecord(recordTypeAlert, c.tmp[1:2])
826 } else {
827 c.writeRecord(recordTypeAlert, c.tmp[0:2])
828 }
David Benjamin24f346d2015-06-06 03:28:08 -0400829 // Error alerts are fatal to the connection.
830 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700831 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
832 }
833 return nil
834}
835
836// sendAlert sends a TLS alert message.
837// L < c.out.Mutex.
838func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400839 level := byte(alertLevelError)
840 if err == alertNoRenegotiation || err == alertCloseNotify {
841 level = alertLevelWarning
842 }
843 return c.SendAlert(level, err)
844}
845
846func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700847 c.out.Lock()
848 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -0400849 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -0700850}
851
David Benjamind86c7672014-08-02 04:07:12 -0400852// writeV2Record writes a record for a V2ClientHello.
853func (c *Conn) writeV2Record(data []byte) (n int, err error) {
854 record := make([]byte, 2+len(data))
855 record[0] = uint8(len(data)>>8) | 0x80
856 record[1] = uint8(len(data))
857 copy(record[2:], data)
858 return c.conn.Write(record)
859}
860
Adam Langley95c29f32014-06-20 12:00:00 -0700861// writeRecord writes a TLS record with the given type and payload
862// to the connection and updates the record layer state.
863// c.out.Mutex <= L.
864func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400865 if c.isDTLS {
866 return c.dtlsWriteRecord(typ, data)
867 }
868
869 recordHeaderLen := tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700870 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -0400871 first := true
872 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -0400873 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -0700874 m := len(data)
875 if m > maxPlaintext {
876 m = maxPlaintext
877 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400878 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
879 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -0400880 // By default, do not fragment the client_version or
881 // server_version, which are located in the first 6
882 // bytes.
883 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
884 m = 6
885 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400886 }
Adam Langley95c29f32014-06-20 12:00:00 -0700887 explicitIVLen := 0
888 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -0400889 first = false
Adam Langley95c29f32014-06-20 12:00:00 -0700890
891 var cbc cbcMode
892 if c.out.version >= VersionTLS11 {
893 var ok bool
894 if cbc, ok = c.out.cipher.(cbcMode); ok {
895 explicitIVLen = cbc.BlockSize()
896 }
897 }
898 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -0400899 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -0700900 explicitIVLen = 8
901 // The AES-GCM construction in TLS has an
902 // explicit nonce so that the nonce can be
903 // random. However, the nonce is only 8 bytes
904 // which is too small for a secure, random
905 // nonce. Therefore we use the sequence number
906 // as the nonce.
907 explicitIVIsSeq = true
908 }
909 }
910 b.resize(recordHeaderLen + explicitIVLen + m)
911 b.data[0] = byte(typ)
912 vers := c.vers
913 if vers == 0 {
914 // Some TLS servers fail if the record version is
915 // greater than TLS 1.0 for the initial ClientHello.
916 vers = VersionTLS10
917 }
918 b.data[1] = byte(vers >> 8)
919 b.data[2] = byte(vers)
920 b.data[3] = byte(m >> 8)
921 b.data[4] = byte(m)
922 if explicitIVLen > 0 {
923 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
924 if explicitIVIsSeq {
925 copy(explicitIV, c.out.seq[:])
926 } else {
927 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
928 break
929 }
930 }
931 }
932 copy(b.data[recordHeaderLen+explicitIVLen:], data)
933 c.out.encrypt(b, explicitIVLen)
934 _, err = c.conn.Write(b.data)
935 if err != nil {
936 break
937 }
938 n += m
939 data = data[m:]
940 }
941 c.out.freeBlock(b)
942
943 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -0700944 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700945 if err != nil {
946 // Cannot call sendAlert directly,
947 // because we already hold c.out.Mutex.
948 c.tmp[0] = alertLevelError
949 c.tmp[1] = byte(err.(alert))
950 c.writeRecord(recordTypeAlert, c.tmp[0:2])
951 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
952 }
953 }
954 return
955}
956
David Benjamin83c0bc92014-08-04 01:23:53 -0400957func (c *Conn) doReadHandshake() ([]byte, error) {
958 if c.isDTLS {
959 return c.dtlsDoReadHandshake()
960 }
961
Adam Langley95c29f32014-06-20 12:00:00 -0700962 for c.hand.Len() < 4 {
963 if err := c.in.err; err != nil {
964 return nil, err
965 }
966 if err := c.readRecord(recordTypeHandshake); err != nil {
967 return nil, err
968 }
969 }
970
971 data := c.hand.Bytes()
972 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
973 if n > maxHandshake {
974 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
975 }
976 for c.hand.Len() < 4+n {
977 if err := c.in.err; err != nil {
978 return nil, err
979 }
980 if err := c.readRecord(recordTypeHandshake); err != nil {
981 return nil, err
982 }
983 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400984 return c.hand.Next(4 + n), nil
985}
986
987// readHandshake reads the next handshake message from
988// the record layer.
989// c.in.Mutex < L; c.out.Mutex < L.
990func (c *Conn) readHandshake() (interface{}, error) {
991 data, err := c.doReadHandshake()
992 if err != nil {
993 return nil, err
994 }
995
Adam Langley95c29f32014-06-20 12:00:00 -0700996 var m handshakeMessage
997 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -0700998 case typeHelloRequest:
999 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001000 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001001 m = &clientHelloMsg{
1002 isDTLS: c.isDTLS,
1003 }
Adam Langley95c29f32014-06-20 12:00:00 -07001004 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001005 m = &serverHelloMsg{
1006 isDTLS: c.isDTLS,
1007 }
Adam Langley95c29f32014-06-20 12:00:00 -07001008 case typeNewSessionTicket:
1009 m = new(newSessionTicketMsg)
1010 case typeCertificate:
1011 m = new(certificateMsg)
1012 case typeCertificateRequest:
1013 m = &certificateRequestMsg{
1014 hasSignatureAndHash: c.vers >= VersionTLS12,
1015 }
1016 case typeCertificateStatus:
1017 m = new(certificateStatusMsg)
1018 case typeServerKeyExchange:
1019 m = new(serverKeyExchangeMsg)
1020 case typeServerHelloDone:
1021 m = new(serverHelloDoneMsg)
1022 case typeClientKeyExchange:
1023 m = new(clientKeyExchangeMsg)
1024 case typeCertificateVerify:
1025 m = &certificateVerifyMsg{
1026 hasSignatureAndHash: c.vers >= VersionTLS12,
1027 }
1028 case typeNextProtocol:
1029 m = new(nextProtoMsg)
1030 case typeFinished:
1031 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001032 case typeHelloVerifyRequest:
1033 m = new(helloVerifyRequestMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001034 case typeEncryptedExtensions:
1035 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001036 default:
1037 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1038 }
1039
1040 // The handshake message unmarshallers
1041 // expect to be able to keep references to data,
1042 // so pass in a fresh copy that won't be overwritten.
1043 data = append([]byte(nil), data...)
1044
1045 if !m.unmarshal(data) {
1046 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1047 }
1048 return m, nil
1049}
1050
David Benjamin83f90402015-01-27 01:09:43 -05001051// skipPacket processes all the DTLS records in packet. It updates
1052// sequence number expectations but otherwise ignores them.
1053func (c *Conn) skipPacket(packet []byte) error {
1054 for len(packet) > 0 {
1055 // Dropped packets are completely ignored save to update
1056 // expected sequence numbers for this and the next epoch. (We
1057 // don't assert on the contents of the packets both for
1058 // simplicity and because a previous test with one shorter
1059 // timeout schedule would have done so.)
1060 epoch := packet[3:5]
1061 seq := packet[5:11]
1062 length := uint16(packet[11])<<8 | uint16(packet[12])
1063 if bytes.Equal(c.in.seq[:2], epoch) {
1064 if !bytes.Equal(c.in.seq[2:], seq) {
1065 return errors.New("tls: sequence mismatch")
1066 }
1067 c.in.incSeq(false)
1068 } else {
1069 if !bytes.Equal(c.in.nextSeq[:], seq) {
1070 return errors.New("tls: sequence mismatch")
1071 }
1072 c.in.incNextSeq()
1073 }
1074 packet = packet[13+length:]
1075 }
1076 return nil
1077}
1078
1079// simulatePacketLoss simulates the loss of a handshake leg from the
1080// peer based on the schedule in c.config.Bugs. If resendFunc is
1081// non-nil, it is called after each simulated timeout to retransmit
1082// handshake messages from the local end. This is used in cases where
1083// the peer retransmits on a stale Finished rather than a timeout.
1084func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1085 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1086 return nil
1087 }
1088 if !c.isDTLS {
1089 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1090 }
1091 if c.config.Bugs.PacketAdaptor == nil {
1092 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1093 }
1094 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1095 // Simulate a timeout.
1096 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1097 if err != nil {
1098 return err
1099 }
1100 for _, packet := range packets {
1101 if err := c.skipPacket(packet); err != nil {
1102 return err
1103 }
1104 }
1105 if resendFunc != nil {
1106 resendFunc()
1107 }
1108 }
1109 return nil
1110}
1111
Adam Langley95c29f32014-06-20 12:00:00 -07001112// Write writes data to the connection.
1113func (c *Conn) Write(b []byte) (int, error) {
1114 if err := c.Handshake(); err != nil {
1115 return 0, err
1116 }
1117
1118 c.out.Lock()
1119 defer c.out.Unlock()
1120
1121 if err := c.out.err; err != nil {
1122 return 0, err
1123 }
1124
1125 if !c.handshakeComplete {
1126 return 0, alertInternalError
1127 }
1128
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001129 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001130 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001131 }
1132
Adam Langley95c29f32014-06-20 12:00:00 -07001133 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1134 // attack when using block mode ciphers due to predictable IVs.
1135 // This can be prevented by splitting each Application Data
1136 // record into two records, effectively randomizing the IV.
1137 //
1138 // http://www.openssl.org/~bodo/tls-cbc.txt
1139 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1140 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1141
1142 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001143 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001144 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1145 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1146 if err != nil {
1147 return n, c.out.setErrorLocked(err)
1148 }
1149 m, b = 1, b[1:]
1150 }
1151 }
1152
1153 n, err := c.writeRecord(recordTypeApplicationData, b)
1154 return n + m, c.out.setErrorLocked(err)
1155}
1156
Adam Langley2ae77d22014-10-28 17:29:33 -07001157func (c *Conn) handleRenegotiation() error {
1158 c.handshakeComplete = false
1159 if !c.isClient {
1160 panic("renegotiation should only happen for a client")
1161 }
1162
1163 msg, err := c.readHandshake()
1164 if err != nil {
1165 return err
1166 }
1167 _, ok := msg.(*helloRequestMsg)
1168 if !ok {
1169 c.sendAlert(alertUnexpectedMessage)
1170 return alertUnexpectedMessage
1171 }
1172
1173 return c.Handshake()
1174}
1175
Adam Langleycf2d4f42014-10-28 19:06:14 -07001176func (c *Conn) Renegotiate() error {
1177 if !c.isClient {
1178 helloReq := new(helloRequestMsg)
1179 c.writeRecord(recordTypeHandshake, helloReq.marshal())
1180 }
1181
1182 c.handshakeComplete = false
1183 return c.Handshake()
1184}
1185
Adam Langley95c29f32014-06-20 12:00:00 -07001186// Read can be made to time out and return a net.Error with Timeout() == true
1187// after a fixed time limit; see SetDeadline and SetReadDeadline.
1188func (c *Conn) Read(b []byte) (n int, err error) {
1189 if err = c.Handshake(); err != nil {
1190 return
1191 }
1192
1193 c.in.Lock()
1194 defer c.in.Unlock()
1195
1196 // Some OpenSSL servers send empty records in order to randomize the
1197 // CBC IV. So this loop ignores a limited number of empty records.
1198 const maxConsecutiveEmptyRecords = 100
1199 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1200 for c.input == nil && c.in.err == nil {
1201 if err := c.readRecord(recordTypeApplicationData); err != nil {
1202 // Soft error, like EAGAIN
1203 return 0, err
1204 }
David Benjamind9b091b2015-01-27 01:10:54 -05001205 if c.hand.Len() > 0 {
Adam Langley2ae77d22014-10-28 17:29:33 -07001206 // We received handshake bytes, indicating the
David Benjamind9b091b2015-01-27 01:10:54 -05001207 // start of a renegotiation.
Adam Langley2ae77d22014-10-28 17:29:33 -07001208 if err := c.handleRenegotiation(); err != nil {
1209 return 0, err
1210 }
1211 continue
1212 }
Adam Langley95c29f32014-06-20 12:00:00 -07001213 }
1214 if err := c.in.err; err != nil {
1215 return 0, err
1216 }
1217
1218 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001219 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001220 c.in.freeBlock(c.input)
1221 c.input = nil
1222 }
1223
1224 // If a close-notify alert is waiting, read it so that
1225 // we can return (n, EOF) instead of (n, nil), to signal
1226 // to the HTTP response reading goroutine that the
1227 // connection is now closed. This eliminates a race
1228 // where the HTTP response reading goroutine would
1229 // otherwise not observe the EOF until its next read,
1230 // by which time a client goroutine might have already
1231 // tried to reuse the HTTP connection for a new
1232 // request.
1233 // See https://codereview.appspot.com/76400046
1234 // and http://golang.org/issue/3514
1235 if ri := c.rawInput; ri != nil &&
1236 n != 0 && err == nil &&
1237 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1238 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1239 err = recErr // will be io.EOF on closeNotify
1240 }
1241 }
1242
1243 if n != 0 || err != nil {
1244 return n, err
1245 }
1246 }
1247
1248 return 0, io.ErrNoProgress
1249}
1250
1251// Close closes the connection.
1252func (c *Conn) Close() error {
1253 var alertErr error
1254
1255 c.handshakeMutex.Lock()
1256 defer c.handshakeMutex.Unlock()
1257 if c.handshakeComplete {
1258 alertErr = c.sendAlert(alertCloseNotify)
1259 }
1260
1261 if err := c.conn.Close(); err != nil {
1262 return err
1263 }
1264 return alertErr
1265}
1266
1267// Handshake runs the client or server handshake
1268// protocol if it has not yet been run.
1269// Most uses of this package need not call Handshake
1270// explicitly: the first Read or Write will call it automatically.
1271func (c *Conn) Handshake() error {
1272 c.handshakeMutex.Lock()
1273 defer c.handshakeMutex.Unlock()
1274 if err := c.handshakeErr; err != nil {
1275 return err
1276 }
1277 if c.handshakeComplete {
1278 return nil
1279 }
1280
David Benjamin9a41d1b2015-05-16 01:30:09 -04001281 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1282 c.conn.Write([]byte{
1283 byte(recordTypeAlert), // type
1284 0xfe, 0xff, // version
1285 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1286 0x0, 0x2, // length
1287 })
1288 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1289 }
Adam Langley95c29f32014-06-20 12:00:00 -07001290 if c.isClient {
1291 c.handshakeErr = c.clientHandshake()
1292 } else {
1293 c.handshakeErr = c.serverHandshake()
1294 }
David Benjaminddb9f152015-02-03 15:44:39 -05001295 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1296 c.writeRecord(recordType(42), []byte("invalid record"))
1297 }
Adam Langley95c29f32014-06-20 12:00:00 -07001298 return c.handshakeErr
1299}
1300
1301// ConnectionState returns basic TLS details about the connection.
1302func (c *Conn) ConnectionState() ConnectionState {
1303 c.handshakeMutex.Lock()
1304 defer c.handshakeMutex.Unlock()
1305
1306 var state ConnectionState
1307 state.HandshakeComplete = c.handshakeComplete
1308 if c.handshakeComplete {
1309 state.Version = c.vers
1310 state.NegotiatedProtocol = c.clientProtocol
1311 state.DidResume = c.didResume
1312 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001313 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001314 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001315 state.PeerCertificates = c.peerCertificates
1316 state.VerifiedChains = c.verifiedChains
1317 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001318 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001319 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001320 state.TLSUnique = c.firstFinished[:]
Adam Langley95c29f32014-06-20 12:00:00 -07001321 }
1322
1323 return state
1324}
1325
1326// OCSPResponse returns the stapled OCSP response from the TLS server, if
1327// any. (Only valid for client connections.)
1328func (c *Conn) OCSPResponse() []byte {
1329 c.handshakeMutex.Lock()
1330 defer c.handshakeMutex.Unlock()
1331
1332 return c.ocspResponse
1333}
1334
1335// VerifyHostname checks that the peer certificate chain is valid for
1336// connecting to host. If so, it returns nil; if not, it returns an error
1337// describing the problem.
1338func (c *Conn) VerifyHostname(host string) error {
1339 c.handshakeMutex.Lock()
1340 defer c.handshakeMutex.Unlock()
1341 if !c.isClient {
1342 return errors.New("tls: VerifyHostname called on TLS server connection")
1343 }
1344 if !c.handshakeComplete {
1345 return errors.New("tls: handshake has not yet been performed")
1346 }
1347 return c.peerCertificates[0].VerifyHostname(host)
1348}
David Benjaminc565ebb2015-04-03 04:06:36 -04001349
1350// ExportKeyingMaterial exports keying material from the current connection
1351// state, as per RFC 5705.
1352func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1353 c.handshakeMutex.Lock()
1354 defer c.handshakeMutex.Unlock()
1355 if !c.handshakeComplete {
1356 return nil, errors.New("tls: handshake has not yet been performed")
1357 }
1358
1359 seedLen := len(c.clientRandom) + len(c.serverRandom)
1360 if useContext {
1361 seedLen += 2 + len(context)
1362 }
1363 seed := make([]byte, 0, seedLen)
1364 seed = append(seed, c.clientRandom[:]...)
1365 seed = append(seed, c.serverRandom[:]...)
1366 if useContext {
1367 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1368 seed = append(seed, context...)
1369 }
1370 result := make([]byte, length)
1371 prfForVersion(c.vers, c.cipherSuite)(result, c.masterSecret[:], label, seed)
1372 return result, nil
1373}