blob: 7178d2081f0bba64ab68fcb451fc1a3ba38e61eb [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
Adam Langleydc7e9c42015-09-29 15:21:04 -07007package runner
Adam Langley95c29f32014-06-20 12:00:00 -07008
9import (
10 "bytes"
11 "crypto/cipher"
David Benjamind30a9902014-08-24 01:44:23 -040012 "crypto/ecdsa"
Adam Langley95c29f32014-06-20 12:00:00 -070013 "crypto/subtle"
14 "crypto/x509"
David Benjamin8e6db492015-07-25 18:29:23 -040015 "encoding/binary"
Adam Langley95c29f32014-06-20 12:00:00 -070016 "errors"
17 "fmt"
18 "io"
19 "net"
20 "sync"
21 "time"
22)
23
24// A Conn represents a secured connection.
25// It implements the net.Conn interface.
26type Conn struct {
27 // constant
28 conn net.Conn
David Benjamin83c0bc92014-08-04 01:23:53 -040029 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -070030 isClient bool
31
32 // constant after handshake; protected by handshakeMutex
Adam Langley75712922014-10-10 16:23:43 -070033 handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
34 handshakeErr error // error resulting from handshake
35 vers uint16 // TLS version
36 haveVers bool // version has been negotiated
37 config *Config // configuration passed to constructor
38 handshakeComplete bool
39 didResume bool // whether this connection was a session resumption
40 extendedMasterSecret bool // whether this session used an extended master secret
David Benjaminc565ebb2015-04-03 04:06:36 -040041 cipherSuite *cipherSuite
Adam Langley75712922014-10-10 16:23:43 -070042 ocspResponse []byte // stapled OCSP response
Paul Lietar4fac72e2015-09-09 13:44:55 +010043 sctList []byte // signed certificate timestamp list
Adam Langley75712922014-10-10 16:23:43 -070044 peerCertificates []*x509.Certificate
Adam Langley95c29f32014-06-20 12:00:00 -070045 // verifiedChains contains the certificate chains that we built, as
46 // opposed to the ones presented by the server.
47 verifiedChains [][]*x509.Certificate
48 // serverName contains the server name indicated by the client, if any.
Adam Langleyaf0e32c2015-06-03 09:57:23 -070049 serverName string
50 // firstFinished contains the first Finished hash sent during the
51 // handshake. This is the "tls-unique" channel binding value.
52 firstFinished [12]byte
Steven Valdez0d62f262015-09-04 12:41:04 -040053 // clientCertSignatureHash contains the TLS hash id for the hash that
54 // was used by the client to sign the handshake with a client
55 // certificate. This is only set by a server and is zero if no client
56 // certificates were used.
57 clientCertSignatureHash uint8
Adam Langleyaf0e32c2015-06-03 09:57:23 -070058
David Benjaminc565ebb2015-04-03 04:06:36 -040059 clientRandom, serverRandom [32]byte
60 masterSecret [48]byte
Adam Langley95c29f32014-06-20 12:00:00 -070061
62 clientProtocol string
63 clientProtocolFallback bool
David Benjaminfc7b0862014-09-06 13:21:53 -040064 usedALPN bool
Adam Langley95c29f32014-06-20 12:00:00 -070065
Adam Langley2ae77d22014-10-28 17:29:33 -070066 // verify_data values for the renegotiation extension.
67 clientVerify []byte
68 serverVerify []byte
69
David Benjamind30a9902014-08-24 01:44:23 -040070 channelID *ecdsa.PublicKey
71
David Benjaminca6c8262014-11-15 19:06:08 -050072 srtpProtectionProfile uint16
73
David Benjaminc44b1df2014-11-23 12:11:01 -050074 clientVersion uint16
75
Adam Langley95c29f32014-06-20 12:00:00 -070076 // input/output
77 in, out halfConn // in.Mutex < out.Mutex
78 rawInput *block // raw input, right off the wire
David Benjamin83c0bc92014-08-04 01:23:53 -040079 input *block // application record waiting to be read
80 hand bytes.Buffer // handshake record waiting to be read
81
82 // DTLS state
83 sendHandshakeSeq uint16
84 recvHandshakeSeq uint16
David Benjaminb3774b92015-01-31 17:16:01 -050085 handMsg []byte // pending assembled handshake message
86 handMsgLen int // handshake message length, not including the header
87 pendingFragments [][]byte // pending outgoing handshake fragments.
Adam Langley95c29f32014-06-20 12:00:00 -070088
89 tmp [16]byte
90}
91
David Benjamin5e961c12014-11-07 01:48:35 -050092func (c *Conn) init() {
93 c.in.isDTLS = c.isDTLS
94 c.out.isDTLS = c.isDTLS
95 c.in.config = c.config
96 c.out.config = c.config
David Benjamin8e6db492015-07-25 18:29:23 -040097
98 c.out.updateOutSeq()
David Benjamin5e961c12014-11-07 01:48:35 -050099}
100
Adam Langley95c29f32014-06-20 12:00:00 -0700101// Access to net.Conn methods.
102// Cannot just embed net.Conn because that would
103// export the struct field too.
104
105// LocalAddr returns the local network address.
106func (c *Conn) LocalAddr() net.Addr {
107 return c.conn.LocalAddr()
108}
109
110// RemoteAddr returns the remote network address.
111func (c *Conn) RemoteAddr() net.Addr {
112 return c.conn.RemoteAddr()
113}
114
115// SetDeadline sets the read and write deadlines associated with the connection.
116// A zero value for t means Read and Write will not time out.
117// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
118func (c *Conn) SetDeadline(t time.Time) error {
119 return c.conn.SetDeadline(t)
120}
121
122// SetReadDeadline sets the read deadline on the underlying connection.
123// A zero value for t means Read will not time out.
124func (c *Conn) SetReadDeadline(t time.Time) error {
125 return c.conn.SetReadDeadline(t)
126}
127
128// SetWriteDeadline sets the write deadline on the underlying conneciton.
129// A zero value for t means Write will not time out.
130// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
131func (c *Conn) SetWriteDeadline(t time.Time) error {
132 return c.conn.SetWriteDeadline(t)
133}
134
135// A halfConn represents one direction of the record layer
136// connection, either sending or receiving.
137type halfConn struct {
138 sync.Mutex
139
David Benjamin83c0bc92014-08-04 01:23:53 -0400140 err error // first permanent error
141 version uint16 // protocol version
142 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -0700143 cipher interface{} // cipher algorithm
144 mac macFunction
145 seq [8]byte // 64-bit sequence number
David Benjamin8e6db492015-07-25 18:29:23 -0400146 outSeq [8]byte // Mapped sequence number
Adam Langley95c29f32014-06-20 12:00:00 -0700147 bfree *block // list of free blocks
148
149 nextCipher interface{} // next encryption state
150 nextMac macFunction // next MAC algorithm
David Benjamin83f90402015-01-27 01:09:43 -0500151 nextSeq [6]byte // next epoch's starting sequence number in DTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700152
153 // used to save allocating a new buffer for each MAC.
154 inDigestBuf, outDigestBuf []byte
Adam Langley80842bd2014-06-20 12:00:00 -0700155
156 config *Config
Adam Langley95c29f32014-06-20 12:00:00 -0700157}
158
159func (hc *halfConn) setErrorLocked(err error) error {
160 hc.err = err
161 return err
162}
163
164func (hc *halfConn) error() error {
Adam Langley2ae77d22014-10-28 17:29:33 -0700165 // This should be locked, but I've removed it for the renegotiation
166 // tests since we don't concurrently read and write the same tls.Conn
167 // in any case during testing.
Adam Langley95c29f32014-06-20 12:00:00 -0700168 err := hc.err
Adam Langley95c29f32014-06-20 12:00:00 -0700169 return err
170}
171
172// prepareCipherSpec sets the encryption and MAC states
173// that a subsequent changeCipherSpec will use.
174func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
175 hc.version = version
176 hc.nextCipher = cipher
177 hc.nextMac = mac
178}
179
180// changeCipherSpec changes the encryption and MAC states
181// to the ones previously passed to prepareCipherSpec.
Adam Langley80842bd2014-06-20 12:00:00 -0700182func (hc *halfConn) changeCipherSpec(config *Config) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700183 if hc.nextCipher == nil {
184 return alertInternalError
185 }
186 hc.cipher = hc.nextCipher
187 hc.mac = hc.nextMac
188 hc.nextCipher = nil
189 hc.nextMac = nil
Adam Langley80842bd2014-06-20 12:00:00 -0700190 hc.config = config
David Benjamin83c0bc92014-08-04 01:23:53 -0400191 hc.incEpoch()
Adam Langley95c29f32014-06-20 12:00:00 -0700192 return nil
193}
194
195// incSeq increments the sequence number.
David Benjamin5e961c12014-11-07 01:48:35 -0500196func (hc *halfConn) incSeq(isOutgoing bool) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400197 limit := 0
David Benjamin5e961c12014-11-07 01:48:35 -0500198 increment := uint64(1)
David Benjamin83c0bc92014-08-04 01:23:53 -0400199 if hc.isDTLS {
200 // Increment up to the epoch in DTLS.
201 limit = 2
202 }
203 for i := 7; i >= limit; i-- {
David Benjamin5e961c12014-11-07 01:48:35 -0500204 increment += uint64(hc.seq[i])
205 hc.seq[i] = byte(increment)
206 increment >>= 8
Adam Langley95c29f32014-06-20 12:00:00 -0700207 }
208
209 // Not allowed to let sequence number wrap.
210 // Instead, must renegotiate before it does.
211 // Not likely enough to bother.
David Benjamin5e961c12014-11-07 01:48:35 -0500212 if increment != 0 {
213 panic("TLS: sequence number wraparound")
214 }
David Benjamin8e6db492015-07-25 18:29:23 -0400215
216 hc.updateOutSeq()
Adam Langley95c29f32014-06-20 12:00:00 -0700217}
218
David Benjamin83f90402015-01-27 01:09:43 -0500219// incNextSeq increments the starting sequence number for the next epoch.
220func (hc *halfConn) incNextSeq() {
221 for i := len(hc.nextSeq) - 1; i >= 0; i-- {
222 hc.nextSeq[i]++
223 if hc.nextSeq[i] != 0 {
224 return
225 }
226 }
227 panic("TLS: sequence number wraparound")
228}
229
230// incEpoch resets the sequence number. In DTLS, it also increments the epoch
231// half of the sequence number.
David Benjamin83c0bc92014-08-04 01:23:53 -0400232func (hc *halfConn) incEpoch() {
David Benjamin83c0bc92014-08-04 01:23:53 -0400233 if hc.isDTLS {
234 for i := 1; i >= 0; i-- {
235 hc.seq[i]++
236 if hc.seq[i] != 0 {
237 break
238 }
239 if i == 0 {
240 panic("TLS: epoch number wraparound")
241 }
242 }
David Benjamin83f90402015-01-27 01:09:43 -0500243 copy(hc.seq[2:], hc.nextSeq[:])
244 for i := range hc.nextSeq {
245 hc.nextSeq[i] = 0
246 }
247 } else {
248 for i := range hc.seq {
249 hc.seq[i] = 0
250 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400251 }
David Benjamin8e6db492015-07-25 18:29:23 -0400252
253 hc.updateOutSeq()
254}
255
256func (hc *halfConn) updateOutSeq() {
257 if hc.config.Bugs.SequenceNumberMapping != nil {
258 seqU64 := binary.BigEndian.Uint64(hc.seq[:])
259 seqU64 = hc.config.Bugs.SequenceNumberMapping(seqU64)
260 binary.BigEndian.PutUint64(hc.outSeq[:], seqU64)
261
262 // The DTLS epoch cannot be changed.
263 copy(hc.outSeq[:2], hc.seq[:2])
264 return
265 }
266
267 copy(hc.outSeq[:], hc.seq[:])
David Benjamin83c0bc92014-08-04 01:23:53 -0400268}
269
270func (hc *halfConn) recordHeaderLen() int {
271 if hc.isDTLS {
272 return dtlsRecordHeaderLen
273 }
274 return tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700275}
276
277// removePadding returns an unpadded slice, in constant time, which is a prefix
278// of the input. It also returns a byte which is equal to 255 if the padding
279// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
280func removePadding(payload []byte) ([]byte, byte) {
281 if len(payload) < 1 {
282 return payload, 0
283 }
284
285 paddingLen := payload[len(payload)-1]
286 t := uint(len(payload)-1) - uint(paddingLen)
287 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
288 good := byte(int32(^t) >> 31)
289
290 toCheck := 255 // the maximum possible padding length
291 // The length of the padded data is public, so we can use an if here
292 if toCheck+1 > len(payload) {
293 toCheck = len(payload) - 1
294 }
295
296 for i := 0; i < toCheck; i++ {
297 t := uint(paddingLen) - uint(i)
298 // if i <= paddingLen then the MSB of t is zero
299 mask := byte(int32(^t) >> 31)
300 b := payload[len(payload)-1-i]
301 good &^= mask&paddingLen ^ mask&b
302 }
303
304 // We AND together the bits of good and replicate the result across
305 // all the bits.
306 good &= good << 4
307 good &= good << 2
308 good &= good << 1
309 good = uint8(int8(good) >> 7)
310
311 toRemove := good&paddingLen + 1
312 return payload[:len(payload)-int(toRemove)], good
313}
314
315// removePaddingSSL30 is a replacement for removePadding in the case that the
316// protocol version is SSLv3. In this version, the contents of the padding
317// are random and cannot be checked.
318func removePaddingSSL30(payload []byte) ([]byte, byte) {
319 if len(payload) < 1 {
320 return payload, 0
321 }
322
323 paddingLen := int(payload[len(payload)-1]) + 1
324 if paddingLen > len(payload) {
325 return payload, 0
326 }
327
328 return payload[:len(payload)-paddingLen], 255
329}
330
331func roundUp(a, b int) int {
332 return a + (b-a%b)%b
333}
334
335// cbcMode is an interface for block ciphers using cipher block chaining.
336type cbcMode interface {
337 cipher.BlockMode
338 SetIV([]byte)
339}
340
341// decrypt checks and strips the mac and decrypts the data in b. Returns a
342// success boolean, the number of bytes to skip from the start of the record in
343// order to get the application payload, and an optional alert value.
344func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, alertValue alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400345 recordHeaderLen := hc.recordHeaderLen()
346
Adam Langley95c29f32014-06-20 12:00:00 -0700347 // pull out payload
348 payload := b.data[recordHeaderLen:]
349
350 macSize := 0
351 if hc.mac != nil {
352 macSize = hc.mac.Size()
353 }
354
355 paddingGood := byte(255)
356 explicitIVLen := 0
357
David Benjamin83c0bc92014-08-04 01:23:53 -0400358 seq := hc.seq[:]
359 if hc.isDTLS {
360 // DTLS sequence numbers are explicit.
361 seq = b.data[3:11]
362 }
363
Adam Langley95c29f32014-06-20 12:00:00 -0700364 // decrypt
365 if hc.cipher != nil {
366 switch c := hc.cipher.(type) {
367 case cipher.Stream:
368 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400369 case *tlsAead:
370 nonce := seq
371 if c.explicitNonce {
372 explicitIVLen = 8
373 if len(payload) < explicitIVLen {
374 return false, 0, alertBadRecordMAC
375 }
376 nonce = payload[:8]
377 payload = payload[8:]
Adam Langley95c29f32014-06-20 12:00:00 -0700378 }
Adam Langley95c29f32014-06-20 12:00:00 -0700379
380 var additionalData [13]byte
David Benjamin83c0bc92014-08-04 01:23:53 -0400381 copy(additionalData[:], seq)
Adam Langley95c29f32014-06-20 12:00:00 -0700382 copy(additionalData[8:], b.data[:3])
383 n := len(payload) - c.Overhead()
384 additionalData[11] = byte(n >> 8)
385 additionalData[12] = byte(n)
386 var err error
387 payload, err = c.Open(payload[:0], nonce, payload, additionalData[:])
388 if err != nil {
389 return false, 0, alertBadRecordMAC
390 }
391 b.resize(recordHeaderLen + explicitIVLen + len(payload))
392 case cbcMode:
393 blockSize := c.BlockSize()
David Benjamin83c0bc92014-08-04 01:23:53 -0400394 if hc.version >= VersionTLS11 || hc.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700395 explicitIVLen = blockSize
396 }
397
398 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
399 return false, 0, alertBadRecordMAC
400 }
401
402 if explicitIVLen > 0 {
403 c.SetIV(payload[:explicitIVLen])
404 payload = payload[explicitIVLen:]
405 }
406 c.CryptBlocks(payload, payload)
407 if hc.version == VersionSSL30 {
408 payload, paddingGood = removePaddingSSL30(payload)
409 } else {
410 payload, paddingGood = removePadding(payload)
411 }
412 b.resize(recordHeaderLen + explicitIVLen + len(payload))
413
414 // note that we still have a timing side-channel in the
415 // MAC check, below. An attacker can align the record
416 // so that a correct padding will cause one less hash
417 // block to be calculated. Then they can iteratively
418 // decrypt a record by breaking each byte. See
419 // "Password Interception in a SSL/TLS Channel", Brice
420 // Canvel et al.
421 //
422 // However, our behavior matches OpenSSL, so we leak
423 // only as much as they do.
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700424 case nullCipher:
425 break
Adam Langley95c29f32014-06-20 12:00:00 -0700426 default:
427 panic("unknown cipher type")
428 }
429 }
430
431 // check, strip mac
432 if hc.mac != nil {
433 if len(payload) < macSize {
434 return false, 0, alertBadRecordMAC
435 }
436
437 // strip mac off payload, b.data
438 n := len(payload) - macSize
David Benjamin83c0bc92014-08-04 01:23:53 -0400439 b.data[recordHeaderLen-2] = byte(n >> 8)
440 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700441 b.resize(recordHeaderLen + explicitIVLen + n)
442 remoteMAC := payload[n:]
David Benjamin83c0bc92014-08-04 01:23:53 -0400443 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
Adam Langley95c29f32014-06-20 12:00:00 -0700444
445 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
446 return false, 0, alertBadRecordMAC
447 }
448 hc.inDigestBuf = localMAC
449 }
David Benjamin5e961c12014-11-07 01:48:35 -0500450 hc.incSeq(false)
Adam Langley95c29f32014-06-20 12:00:00 -0700451
452 return true, recordHeaderLen + explicitIVLen, 0
453}
454
455// padToBlockSize calculates the needed padding block, if any, for a payload.
456// On exit, prefix aliases payload and extends to the end of the last full
457// block of payload. finalBlock is a fresh slice which contains the contents of
458// any suffix of payload as well as the needed padding to make finalBlock a
459// full block.
Adam Langley80842bd2014-06-20 12:00:00 -0700460func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
Adam Langley95c29f32014-06-20 12:00:00 -0700461 overrun := len(payload) % blockSize
Adam Langley95c29f32014-06-20 12:00:00 -0700462 prefix = payload[:len(payload)-overrun]
Adam Langley80842bd2014-06-20 12:00:00 -0700463
464 paddingLen := blockSize - overrun
465 finalSize := blockSize
466 if config.Bugs.MaxPadding {
467 for paddingLen+blockSize <= 256 {
468 paddingLen += blockSize
469 }
470 finalSize = 256
471 }
472 finalBlock = make([]byte, finalSize)
473 for i := range finalBlock {
Adam Langley95c29f32014-06-20 12:00:00 -0700474 finalBlock[i] = byte(paddingLen - 1)
475 }
Adam Langley80842bd2014-06-20 12:00:00 -0700476 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
477 finalBlock[overrun] ^= 0xff
478 }
479 copy(finalBlock, payload[len(payload)-overrun:])
Adam Langley95c29f32014-06-20 12:00:00 -0700480 return
481}
482
483// encrypt encrypts and macs the data in b.
484func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400485 recordHeaderLen := hc.recordHeaderLen()
486
Adam Langley95c29f32014-06-20 12:00:00 -0700487 // mac
488 if hc.mac != nil {
David Benjamin8e6db492015-07-25 18:29:23 -0400489 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 -0700490
491 n := len(b.data)
492 b.resize(n + len(mac))
493 copy(b.data[n:], mac)
494 hc.outDigestBuf = mac
495 }
496
497 payload := b.data[recordHeaderLen:]
498
499 // encrypt
500 if hc.cipher != nil {
501 switch c := hc.cipher.(type) {
502 case cipher.Stream:
503 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400504 case *tlsAead:
Adam Langley95c29f32014-06-20 12:00:00 -0700505 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
506 b.resize(len(b.data) + c.Overhead())
David Benjamin8e6db492015-07-25 18:29:23 -0400507 nonce := hc.outSeq[:]
David Benjamine9a80ff2015-04-07 00:46:46 -0400508 if c.explicitNonce {
509 nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
510 }
Adam Langley95c29f32014-06-20 12:00:00 -0700511 payload := b.data[recordHeaderLen+explicitIVLen:]
512 payload = payload[:payloadLen]
513
514 var additionalData [13]byte
David Benjamin8e6db492015-07-25 18:29:23 -0400515 copy(additionalData[:], hc.outSeq[:])
Adam Langley95c29f32014-06-20 12:00:00 -0700516 copy(additionalData[8:], b.data[:3])
517 additionalData[11] = byte(payloadLen >> 8)
518 additionalData[12] = byte(payloadLen)
519
520 c.Seal(payload[:0], nonce, payload, additionalData[:])
521 case cbcMode:
522 blockSize := c.BlockSize()
523 if explicitIVLen > 0 {
524 c.SetIV(payload[:explicitIVLen])
525 payload = payload[explicitIVLen:]
526 }
Adam Langley80842bd2014-06-20 12:00:00 -0700527 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700528 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
529 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
530 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700531 case nullCipher:
532 break
Adam Langley95c29f32014-06-20 12:00:00 -0700533 default:
534 panic("unknown cipher type")
535 }
536 }
537
538 // update length to include MAC and any block padding needed.
539 n := len(b.data) - recordHeaderLen
David Benjamin83c0bc92014-08-04 01:23:53 -0400540 b.data[recordHeaderLen-2] = byte(n >> 8)
541 b.data[recordHeaderLen-1] = byte(n)
David Benjamin5e961c12014-11-07 01:48:35 -0500542 hc.incSeq(true)
Adam Langley95c29f32014-06-20 12:00:00 -0700543
544 return true, 0
545}
546
547// A block is a simple data buffer.
548type block struct {
549 data []byte
550 off int // index for Read
551 link *block
552}
553
554// resize resizes block to be n bytes, growing if necessary.
555func (b *block) resize(n int) {
556 if n > cap(b.data) {
557 b.reserve(n)
558 }
559 b.data = b.data[0:n]
560}
561
562// reserve makes sure that block contains a capacity of at least n bytes.
563func (b *block) reserve(n int) {
564 if cap(b.data) >= n {
565 return
566 }
567 m := cap(b.data)
568 if m == 0 {
569 m = 1024
570 }
571 for m < n {
572 m *= 2
573 }
574 data := make([]byte, len(b.data), m)
575 copy(data, b.data)
576 b.data = data
577}
578
579// readFromUntil reads from r into b until b contains at least n bytes
580// or else returns an error.
581func (b *block) readFromUntil(r io.Reader, n int) error {
582 // quick case
583 if len(b.data) >= n {
584 return nil
585 }
586
587 // read until have enough.
588 b.reserve(n)
589 for {
590 m, err := r.Read(b.data[len(b.data):cap(b.data)])
591 b.data = b.data[0 : len(b.data)+m]
592 if len(b.data) >= n {
593 // TODO(bradfitz,agl): slightly suspicious
594 // that we're throwing away r.Read's err here.
595 break
596 }
597 if err != nil {
598 return err
599 }
600 }
601 return nil
602}
603
604func (b *block) Read(p []byte) (n int, err error) {
605 n = copy(p, b.data[b.off:])
606 b.off += n
607 return
608}
609
610// newBlock allocates a new block, from hc's free list if possible.
611func (hc *halfConn) newBlock() *block {
612 b := hc.bfree
613 if b == nil {
614 return new(block)
615 }
616 hc.bfree = b.link
617 b.link = nil
618 b.resize(0)
619 return b
620}
621
622// freeBlock returns a block to hc's free list.
623// The protocol is such that each side only has a block or two on
624// its free list at a time, so there's no need to worry about
625// trimming the list, etc.
626func (hc *halfConn) freeBlock(b *block) {
627 b.link = hc.bfree
628 hc.bfree = b
629}
630
631// splitBlock splits a block after the first n bytes,
632// returning a block with those n bytes and a
633// block with the remainder. the latter may be nil.
634func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
635 if len(b.data) <= n {
636 return b, nil
637 }
638 bb := hc.newBlock()
639 bb.resize(len(b.data) - n)
640 copy(bb.data, b.data[n:])
641 b.data = b.data[0:n]
642 return b, bb
643}
644
David Benjamin83c0bc92014-08-04 01:23:53 -0400645func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
646 if c.isDTLS {
647 return c.dtlsDoReadRecord(want)
648 }
649
650 recordHeaderLen := tlsRecordHeaderLen
651
652 if c.rawInput == nil {
653 c.rawInput = c.in.newBlock()
654 }
655 b := c.rawInput
656
657 // Read header, payload.
658 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
659 // RFC suggests that EOF without an alertCloseNotify is
660 // an error, but popular web sites seem to do this,
David Benjamin30789da2015-08-29 22:56:45 -0400661 // so we can't make it an error, outside of tests.
662 if err == io.EOF && c.config.Bugs.ExpectCloseNotify {
663 err = io.ErrUnexpectedEOF
664 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400665 if e, ok := err.(net.Error); !ok || !e.Temporary() {
666 c.in.setErrorLocked(err)
667 }
668 return 0, nil, err
669 }
670 typ := recordType(b.data[0])
671
672 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
673 // start with a uint16 length where the MSB is set and the first record
674 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
675 // an SSLv2 client.
676 if want == recordTypeHandshake && typ == 0x80 {
677 c.sendAlert(alertProtocolVersion)
678 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
679 }
680
681 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
682 n := int(b.data[3])<<8 | int(b.data[4])
David Benjamin1e29a6b2014-12-10 02:27:24 -0500683 if c.haveVers {
684 if vers != c.vers {
685 c.sendAlert(alertProtocolVersion)
686 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers))
687 }
688 } else {
689 if expect := c.config.Bugs.ExpectInitialRecordVersion; expect != 0 && vers != expect {
690 c.sendAlert(alertProtocolVersion)
691 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
692 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400693 }
694 if n > maxCiphertext {
695 c.sendAlert(alertRecordOverflow)
696 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
697 }
698 if !c.haveVers {
699 // First message, be extra suspicious:
700 // this might not be a TLS client.
701 // Bail out before reading a full 'body', if possible.
702 // The current max version is 3.1.
703 // If the version is >= 16.0, it's probably not real.
704 // Similarly, a clientHello message encodes in
705 // well under a kilobyte. If the length is >= 12 kB,
706 // it's probably not real.
707 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
708 c.sendAlert(alertUnexpectedMessage)
709 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
710 }
711 }
712 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
713 if err == io.EOF {
714 err = io.ErrUnexpectedEOF
715 }
716 if e, ok := err.(net.Error); !ok || !e.Temporary() {
717 c.in.setErrorLocked(err)
718 }
719 return 0, nil, err
720 }
721
722 // Process message.
723 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
724 ok, off, err := c.in.decrypt(b)
725 if !ok {
726 c.in.setErrorLocked(c.sendAlert(err))
727 }
728 b.off = off
729 return typ, b, nil
730}
731
Adam Langley95c29f32014-06-20 12:00:00 -0700732// readRecord reads the next TLS record from the connection
733// and updates the record layer state.
734// c.in.Mutex <= L; c.input == nil.
735func (c *Conn) readRecord(want recordType) error {
736 // Caller must be in sync with connection:
737 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700738 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700739 switch want {
740 default:
741 c.sendAlert(alertInternalError)
742 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
743 case recordTypeHandshake, recordTypeChangeCipherSpec:
744 if c.handshakeComplete {
745 c.sendAlert(alertInternalError)
746 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
747 }
748 case recordTypeApplicationData:
David Benjamine58c4f52014-08-24 03:47:07 -0400749 if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart {
Adam Langley95c29f32014-06-20 12:00:00 -0700750 c.sendAlert(alertInternalError)
751 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
752 }
David Benjamin30789da2015-08-29 22:56:45 -0400753 case recordTypeAlert:
754 // Looking for a close_notify. Note: unlike a real
755 // implementation, this is not tolerant of additional records.
756 // See the documentation for ExpectCloseNotify.
Adam Langley95c29f32014-06-20 12:00:00 -0700757 }
758
759Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400760 typ, b, err := c.doReadRecord(want)
761 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700762 return err
763 }
Adam Langley95c29f32014-06-20 12:00:00 -0700764 data := b.data[b.off:]
765 if len(data) > maxPlaintext {
766 err := c.sendAlert(alertRecordOverflow)
767 c.in.freeBlock(b)
768 return c.in.setErrorLocked(err)
769 }
770
771 switch typ {
772 default:
773 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
774
775 case recordTypeAlert:
776 if len(data) != 2 {
777 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
778 break
779 }
780 if alert(data[1]) == alertCloseNotify {
781 c.in.setErrorLocked(io.EOF)
782 break
783 }
784 switch data[0] {
785 case alertLevelWarning:
786 // drop on the floor
787 c.in.freeBlock(b)
788 goto Again
789 case alertLevelError:
790 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
791 default:
792 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
793 }
794
795 case recordTypeChangeCipherSpec:
796 if typ != want || len(data) != 1 || data[0] != 1 {
797 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
798 break
799 }
Adam Langley80842bd2014-06-20 12:00:00 -0700800 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700801 if err != nil {
802 c.in.setErrorLocked(c.sendAlert(err.(alert)))
803 }
804
805 case recordTypeApplicationData:
806 if typ != want {
807 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
808 break
809 }
810 c.input = b
811 b = nil
812
813 case recordTypeHandshake:
814 // TODO(rsc): Should at least pick off connection close.
815 if typ != want {
Adam Langley2ae77d22014-10-28 17:29:33 -0700816 // A client might need to process a HelloRequest from
817 // the server, thus receiving a handshake message when
David Benjamind9b091b2015-01-27 01:10:54 -0500818 // application data is expected is ok.
David Benjamin30789da2015-08-29 22:56:45 -0400819 if !c.isClient || want != recordTypeApplicationData {
Adam Langley2ae77d22014-10-28 17:29:33 -0700820 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
821 }
Adam Langley95c29f32014-06-20 12:00:00 -0700822 }
823 c.hand.Write(data)
824 }
825
826 if b != nil {
827 c.in.freeBlock(b)
828 }
829 return c.in.err
830}
831
832// sendAlert sends a TLS alert message.
833// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400834func (c *Conn) sendAlertLocked(level byte, err alert) error {
835 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700836 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400837 if c.config.Bugs.FragmentAlert {
838 c.writeRecord(recordTypeAlert, c.tmp[0:1])
839 c.writeRecord(recordTypeAlert, c.tmp[1:2])
840 } else {
841 c.writeRecord(recordTypeAlert, c.tmp[0:2])
842 }
David Benjamin24f346d2015-06-06 03:28:08 -0400843 // Error alerts are fatal to the connection.
844 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700845 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
846 }
847 return nil
848}
849
850// sendAlert sends a TLS alert message.
851// L < c.out.Mutex.
852func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400853 level := byte(alertLevelError)
854 if err == alertNoRenegotiation || err == alertCloseNotify {
855 level = alertLevelWarning
856 }
857 return c.SendAlert(level, err)
858}
859
860func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700861 c.out.Lock()
862 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -0400863 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -0700864}
865
David Benjamind86c7672014-08-02 04:07:12 -0400866// writeV2Record writes a record for a V2ClientHello.
867func (c *Conn) writeV2Record(data []byte) (n int, err error) {
868 record := make([]byte, 2+len(data))
869 record[0] = uint8(len(data)>>8) | 0x80
870 record[1] = uint8(len(data))
871 copy(record[2:], data)
872 return c.conn.Write(record)
873}
874
Adam Langley95c29f32014-06-20 12:00:00 -0700875// writeRecord writes a TLS record with the given type and payload
876// to the connection and updates the record layer state.
877// c.out.Mutex <= L.
878func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400879 if c.isDTLS {
880 return c.dtlsWriteRecord(typ, data)
881 }
882
883 recordHeaderLen := tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700884 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -0400885 first := true
886 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -0400887 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -0700888 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -0400889 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -0700890 m = maxPlaintext
891 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400892 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
893 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -0400894 // By default, do not fragment the client_version or
895 // server_version, which are located in the first 6
896 // bytes.
897 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
898 m = 6
899 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400900 }
Adam Langley95c29f32014-06-20 12:00:00 -0700901 explicitIVLen := 0
902 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -0400903 first = false
Adam Langley95c29f32014-06-20 12:00:00 -0700904
905 var cbc cbcMode
906 if c.out.version >= VersionTLS11 {
907 var ok bool
908 if cbc, ok = c.out.cipher.(cbcMode); ok {
909 explicitIVLen = cbc.BlockSize()
910 }
911 }
912 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -0400913 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -0700914 explicitIVLen = 8
915 // The AES-GCM construction in TLS has an
916 // explicit nonce so that the nonce can be
917 // random. However, the nonce is only 8 bytes
918 // which is too small for a secure, random
919 // nonce. Therefore we use the sequence number
920 // as the nonce.
921 explicitIVIsSeq = true
922 }
923 }
924 b.resize(recordHeaderLen + explicitIVLen + m)
925 b.data[0] = byte(typ)
926 vers := c.vers
927 if vers == 0 {
928 // Some TLS servers fail if the record version is
929 // greater than TLS 1.0 for the initial ClientHello.
930 vers = VersionTLS10
931 }
932 b.data[1] = byte(vers >> 8)
933 b.data[2] = byte(vers)
934 b.data[3] = byte(m >> 8)
935 b.data[4] = byte(m)
936 if explicitIVLen > 0 {
937 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
938 if explicitIVIsSeq {
939 copy(explicitIV, c.out.seq[:])
940 } else {
941 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
942 break
943 }
944 }
945 }
946 copy(b.data[recordHeaderLen+explicitIVLen:], data)
947 c.out.encrypt(b, explicitIVLen)
948 _, err = c.conn.Write(b.data)
949 if err != nil {
950 break
951 }
952 n += m
953 data = data[m:]
954 }
955 c.out.freeBlock(b)
956
957 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -0700958 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700959 if err != nil {
960 // Cannot call sendAlert directly,
961 // because we already hold c.out.Mutex.
962 c.tmp[0] = alertLevelError
963 c.tmp[1] = byte(err.(alert))
964 c.writeRecord(recordTypeAlert, c.tmp[0:2])
965 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
966 }
967 }
968 return
969}
970
David Benjamin83c0bc92014-08-04 01:23:53 -0400971func (c *Conn) doReadHandshake() ([]byte, error) {
972 if c.isDTLS {
973 return c.dtlsDoReadHandshake()
974 }
975
Adam Langley95c29f32014-06-20 12:00:00 -0700976 for c.hand.Len() < 4 {
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 }
984
985 data := c.hand.Bytes()
986 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
987 if n > maxHandshake {
988 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
989 }
990 for c.hand.Len() < 4+n {
991 if err := c.in.err; err != nil {
992 return nil, err
993 }
994 if err := c.readRecord(recordTypeHandshake); err != nil {
995 return nil, err
996 }
997 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400998 return c.hand.Next(4 + n), nil
999}
1000
1001// readHandshake reads the next handshake message from
1002// the record layer.
1003// c.in.Mutex < L; c.out.Mutex < L.
1004func (c *Conn) readHandshake() (interface{}, error) {
1005 data, err := c.doReadHandshake()
1006 if err != nil {
1007 return nil, err
1008 }
1009
Adam Langley95c29f32014-06-20 12:00:00 -07001010 var m handshakeMessage
1011 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001012 case typeHelloRequest:
1013 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001014 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001015 m = &clientHelloMsg{
1016 isDTLS: c.isDTLS,
1017 }
Adam Langley95c29f32014-06-20 12:00:00 -07001018 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001019 m = &serverHelloMsg{
1020 isDTLS: c.isDTLS,
1021 }
Adam Langley95c29f32014-06-20 12:00:00 -07001022 case typeNewSessionTicket:
1023 m = new(newSessionTicketMsg)
1024 case typeCertificate:
1025 m = new(certificateMsg)
1026 case typeCertificateRequest:
1027 m = &certificateRequestMsg{
1028 hasSignatureAndHash: c.vers >= VersionTLS12,
1029 }
1030 case typeCertificateStatus:
1031 m = new(certificateStatusMsg)
1032 case typeServerKeyExchange:
1033 m = new(serverKeyExchangeMsg)
1034 case typeServerHelloDone:
1035 m = new(serverHelloDoneMsg)
1036 case typeClientKeyExchange:
1037 m = new(clientKeyExchangeMsg)
1038 case typeCertificateVerify:
1039 m = &certificateVerifyMsg{
1040 hasSignatureAndHash: c.vers >= VersionTLS12,
1041 }
1042 case typeNextProtocol:
1043 m = new(nextProtoMsg)
1044 case typeFinished:
1045 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001046 case typeHelloVerifyRequest:
1047 m = new(helloVerifyRequestMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001048 case typeEncryptedExtensions:
1049 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001050 default:
1051 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1052 }
1053
1054 // The handshake message unmarshallers
1055 // expect to be able to keep references to data,
1056 // so pass in a fresh copy that won't be overwritten.
1057 data = append([]byte(nil), data...)
1058
1059 if !m.unmarshal(data) {
1060 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1061 }
1062 return m, nil
1063}
1064
David Benjamin83f90402015-01-27 01:09:43 -05001065// skipPacket processes all the DTLS records in packet. It updates
1066// sequence number expectations but otherwise ignores them.
1067func (c *Conn) skipPacket(packet []byte) error {
1068 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001069 if len(packet) < 13 {
1070 return errors.New("tls: bad packet")
1071 }
David Benjamin83f90402015-01-27 01:09:43 -05001072 // Dropped packets are completely ignored save to update
1073 // expected sequence numbers for this and the next epoch. (We
1074 // don't assert on the contents of the packets both for
1075 // simplicity and because a previous test with one shorter
1076 // timeout schedule would have done so.)
1077 epoch := packet[3:5]
1078 seq := packet[5:11]
1079 length := uint16(packet[11])<<8 | uint16(packet[12])
1080 if bytes.Equal(c.in.seq[:2], epoch) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001081 if bytes.Compare(seq, c.in.seq[2:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001082 return errors.New("tls: sequence mismatch")
1083 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001084 copy(c.in.seq[2:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001085 c.in.incSeq(false)
1086 } else {
David Benjamin13e81fc2015-11-02 17:16:13 -05001087 if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001088 return errors.New("tls: sequence mismatch")
1089 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001090 copy(c.in.nextSeq[:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001091 c.in.incNextSeq()
1092 }
David Benjamin6ca93552015-08-28 16:16:25 -04001093 if len(packet) < 13+int(length) {
1094 return errors.New("tls: bad packet")
1095 }
David Benjamin83f90402015-01-27 01:09:43 -05001096 packet = packet[13+length:]
1097 }
1098 return nil
1099}
1100
1101// simulatePacketLoss simulates the loss of a handshake leg from the
1102// peer based on the schedule in c.config.Bugs. If resendFunc is
1103// non-nil, it is called after each simulated timeout to retransmit
1104// handshake messages from the local end. This is used in cases where
1105// the peer retransmits on a stale Finished rather than a timeout.
1106func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1107 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1108 return nil
1109 }
1110 if !c.isDTLS {
1111 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1112 }
1113 if c.config.Bugs.PacketAdaptor == nil {
1114 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1115 }
1116 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1117 // Simulate a timeout.
1118 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1119 if err != nil {
1120 return err
1121 }
1122 for _, packet := range packets {
1123 if err := c.skipPacket(packet); err != nil {
1124 return err
1125 }
1126 }
1127 if resendFunc != nil {
1128 resendFunc()
1129 }
1130 }
1131 return nil
1132}
1133
Adam Langley95c29f32014-06-20 12:00:00 -07001134// Write writes data to the connection.
1135func (c *Conn) Write(b []byte) (int, error) {
1136 if err := c.Handshake(); err != nil {
1137 return 0, err
1138 }
1139
1140 c.out.Lock()
1141 defer c.out.Unlock()
1142
1143 if err := c.out.err; err != nil {
1144 return 0, err
1145 }
1146
1147 if !c.handshakeComplete {
1148 return 0, alertInternalError
1149 }
1150
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001151 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001152 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001153 }
1154
Adam Langley27a0d082015-11-03 13:34:10 -08001155 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1156 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
1157 }
1158
Adam Langley95c29f32014-06-20 12:00:00 -07001159 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1160 // attack when using block mode ciphers due to predictable IVs.
1161 // This can be prevented by splitting each Application Data
1162 // record into two records, effectively randomizing the IV.
1163 //
1164 // http://www.openssl.org/~bodo/tls-cbc.txt
1165 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1166 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1167
1168 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001169 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001170 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1171 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1172 if err != nil {
1173 return n, c.out.setErrorLocked(err)
1174 }
1175 m, b = 1, b[1:]
1176 }
1177 }
1178
1179 n, err := c.writeRecord(recordTypeApplicationData, b)
1180 return n + m, c.out.setErrorLocked(err)
1181}
1182
Adam Langley2ae77d22014-10-28 17:29:33 -07001183func (c *Conn) handleRenegotiation() error {
1184 c.handshakeComplete = false
1185 if !c.isClient {
1186 panic("renegotiation should only happen for a client")
1187 }
1188
1189 msg, err := c.readHandshake()
1190 if err != nil {
1191 return err
1192 }
1193 _, ok := msg.(*helloRequestMsg)
1194 if !ok {
1195 c.sendAlert(alertUnexpectedMessage)
1196 return alertUnexpectedMessage
1197 }
1198
1199 return c.Handshake()
1200}
1201
Adam Langleycf2d4f42014-10-28 19:06:14 -07001202func (c *Conn) Renegotiate() error {
1203 if !c.isClient {
1204 helloReq := new(helloRequestMsg)
1205 c.writeRecord(recordTypeHandshake, helloReq.marshal())
1206 }
1207
1208 c.handshakeComplete = false
1209 return c.Handshake()
1210}
1211
Adam Langley95c29f32014-06-20 12:00:00 -07001212// Read can be made to time out and return a net.Error with Timeout() == true
1213// after a fixed time limit; see SetDeadline and SetReadDeadline.
1214func (c *Conn) Read(b []byte) (n int, err error) {
1215 if err = c.Handshake(); err != nil {
1216 return
1217 }
1218
1219 c.in.Lock()
1220 defer c.in.Unlock()
1221
1222 // Some OpenSSL servers send empty records in order to randomize the
1223 // CBC IV. So this loop ignores a limited number of empty records.
1224 const maxConsecutiveEmptyRecords = 100
1225 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1226 for c.input == nil && c.in.err == nil {
1227 if err := c.readRecord(recordTypeApplicationData); err != nil {
1228 // Soft error, like EAGAIN
1229 return 0, err
1230 }
David Benjamind9b091b2015-01-27 01:10:54 -05001231 if c.hand.Len() > 0 {
Adam Langley2ae77d22014-10-28 17:29:33 -07001232 // We received handshake bytes, indicating the
David Benjamind9b091b2015-01-27 01:10:54 -05001233 // start of a renegotiation.
Adam Langley2ae77d22014-10-28 17:29:33 -07001234 if err := c.handleRenegotiation(); err != nil {
1235 return 0, err
1236 }
1237 continue
1238 }
Adam Langley95c29f32014-06-20 12:00:00 -07001239 }
1240 if err := c.in.err; err != nil {
1241 return 0, err
1242 }
1243
1244 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001245 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001246 c.in.freeBlock(c.input)
1247 c.input = nil
1248 }
1249
1250 // If a close-notify alert is waiting, read it so that
1251 // we can return (n, EOF) instead of (n, nil), to signal
1252 // to the HTTP response reading goroutine that the
1253 // connection is now closed. This eliminates a race
1254 // where the HTTP response reading goroutine would
1255 // otherwise not observe the EOF until its next read,
1256 // by which time a client goroutine might have already
1257 // tried to reuse the HTTP connection for a new
1258 // request.
1259 // See https://codereview.appspot.com/76400046
1260 // and http://golang.org/issue/3514
1261 if ri := c.rawInput; ri != nil &&
1262 n != 0 && err == nil &&
1263 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1264 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1265 err = recErr // will be io.EOF on closeNotify
1266 }
1267 }
1268
1269 if n != 0 || err != nil {
1270 return n, err
1271 }
1272 }
1273
1274 return 0, io.ErrNoProgress
1275}
1276
1277// Close closes the connection.
1278func (c *Conn) Close() error {
1279 var alertErr error
1280
1281 c.handshakeMutex.Lock()
1282 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001283 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
Adam Langley95c29f32014-06-20 12:00:00 -07001284 alertErr = c.sendAlert(alertCloseNotify)
1285 }
1286
David Benjamin30789da2015-08-29 22:56:45 -04001287 // Consume a close_notify from the peer if one hasn't been received
1288 // already. This avoids the peer from failing |SSL_shutdown| due to a
1289 // write failing.
1290 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1291 for c.in.error() == nil {
1292 c.readRecord(recordTypeAlert)
1293 }
1294 if c.in.error() != io.EOF {
1295 alertErr = c.in.error()
1296 }
1297 }
1298
Adam Langley95c29f32014-06-20 12:00:00 -07001299 if err := c.conn.Close(); err != nil {
1300 return err
1301 }
1302 return alertErr
1303}
1304
1305// Handshake runs the client or server handshake
1306// protocol if it has not yet been run.
1307// Most uses of this package need not call Handshake
1308// explicitly: the first Read or Write will call it automatically.
1309func (c *Conn) Handshake() error {
1310 c.handshakeMutex.Lock()
1311 defer c.handshakeMutex.Unlock()
1312 if err := c.handshakeErr; err != nil {
1313 return err
1314 }
1315 if c.handshakeComplete {
1316 return nil
1317 }
1318
David Benjamin9a41d1b2015-05-16 01:30:09 -04001319 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1320 c.conn.Write([]byte{
1321 byte(recordTypeAlert), // type
1322 0xfe, 0xff, // version
1323 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1324 0x0, 0x2, // length
1325 })
1326 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1327 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001328 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1329 c.writeRecord(recordTypeApplicationData, data)
1330 }
Adam Langley95c29f32014-06-20 12:00:00 -07001331 if c.isClient {
1332 c.handshakeErr = c.clientHandshake()
1333 } else {
1334 c.handshakeErr = c.serverHandshake()
1335 }
David Benjaminddb9f152015-02-03 15:44:39 -05001336 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1337 c.writeRecord(recordType(42), []byte("invalid record"))
1338 }
Adam Langley95c29f32014-06-20 12:00:00 -07001339 return c.handshakeErr
1340}
1341
1342// ConnectionState returns basic TLS details about the connection.
1343func (c *Conn) ConnectionState() ConnectionState {
1344 c.handshakeMutex.Lock()
1345 defer c.handshakeMutex.Unlock()
1346
1347 var state ConnectionState
1348 state.HandshakeComplete = c.handshakeComplete
1349 if c.handshakeComplete {
1350 state.Version = c.vers
1351 state.NegotiatedProtocol = c.clientProtocol
1352 state.DidResume = c.didResume
1353 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001354 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001355 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001356 state.PeerCertificates = c.peerCertificates
1357 state.VerifiedChains = c.verifiedChains
1358 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001359 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001360 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001361 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001362 state.SCTList = c.sctList
Steven Valdez0d62f262015-09-04 12:41:04 -04001363 state.ClientCertSignatureHash = c.clientCertSignatureHash
Adam Langley95c29f32014-06-20 12:00:00 -07001364 }
1365
1366 return state
1367}
1368
1369// OCSPResponse returns the stapled OCSP response from the TLS server, if
1370// any. (Only valid for client connections.)
1371func (c *Conn) OCSPResponse() []byte {
1372 c.handshakeMutex.Lock()
1373 defer c.handshakeMutex.Unlock()
1374
1375 return c.ocspResponse
1376}
1377
1378// VerifyHostname checks that the peer certificate chain is valid for
1379// connecting to host. If so, it returns nil; if not, it returns an error
1380// describing the problem.
1381func (c *Conn) VerifyHostname(host string) error {
1382 c.handshakeMutex.Lock()
1383 defer c.handshakeMutex.Unlock()
1384 if !c.isClient {
1385 return errors.New("tls: VerifyHostname called on TLS server connection")
1386 }
1387 if !c.handshakeComplete {
1388 return errors.New("tls: handshake has not yet been performed")
1389 }
1390 return c.peerCertificates[0].VerifyHostname(host)
1391}
David Benjaminc565ebb2015-04-03 04:06:36 -04001392
1393// ExportKeyingMaterial exports keying material from the current connection
1394// state, as per RFC 5705.
1395func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1396 c.handshakeMutex.Lock()
1397 defer c.handshakeMutex.Unlock()
1398 if !c.handshakeComplete {
1399 return nil, errors.New("tls: handshake has not yet been performed")
1400 }
1401
1402 seedLen := len(c.clientRandom) + len(c.serverRandom)
1403 if useContext {
1404 seedLen += 2 + len(context)
1405 }
1406 seed := make([]byte, 0, seedLen)
1407 seed = append(seed, c.clientRandom[:]...)
1408 seed = append(seed, c.serverRandom[:]...)
1409 if useContext {
1410 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1411 seed = append(seed, context...)
1412 }
1413 result := make([]byte, length)
1414 prfForVersion(c.vers, c.cipherSuite)(result, c.masterSecret[:], label, seed)
1415 return result, nil
1416}
David Benjamin3e052de2015-11-25 20:10:31 -05001417
1418// noRenegotiationInfo returns true if the renegotiation info extension
1419// should be supported in the current handshake.
1420func (c *Conn) noRenegotiationInfo() bool {
1421 if c.config.Bugs.NoRenegotiationInfo {
1422 return true
1423 }
1424 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1425 return true
1426 }
1427 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1428 return true
1429 }
1430 return false
1431}