blob: 39bdfda5cfd5a105a69487bec8ccbe3158eb9f35 [file] [log] [blame]
Adam Langley95c29f32014-06-20 12:00:00 -07001// Copyright 2010 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5// TLS low level connection and record layer
6
7package main
8
9import (
10 "bytes"
11 "crypto/cipher"
David Benjamind30a9902014-08-24 01:44:23 -040012 "crypto/ecdsa"
Adam Langley95c29f32014-06-20 12:00:00 -070013 "crypto/subtle"
14 "crypto/x509"
David Benjamin8e6db492015-07-25 18:29:23 -040015 "encoding/binary"
Adam Langley95c29f32014-06-20 12:00:00 -070016 "errors"
17 "fmt"
18 "io"
19 "net"
20 "sync"
21 "time"
22)
23
24// A Conn represents a secured connection.
25// It implements the net.Conn interface.
26type Conn struct {
27 // constant
28 conn net.Conn
David Benjamin83c0bc92014-08-04 01:23:53 -040029 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -070030 isClient bool
31
32 // constant after handshake; protected by handshakeMutex
Adam Langley75712922014-10-10 16:23:43 -070033 handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
34 handshakeErr error // error resulting from handshake
35 vers uint16 // TLS version
36 haveVers bool // version has been negotiated
37 config *Config // configuration passed to constructor
38 handshakeComplete bool
39 didResume bool // whether this connection was a session resumption
40 extendedMasterSecret bool // whether this session used an extended master secret
David Benjaminc565ebb2015-04-03 04:06:36 -040041 cipherSuite *cipherSuite
Adam Langley75712922014-10-10 16:23:43 -070042 ocspResponse []byte // stapled OCSP response
Paul Lietar4fac72e2015-09-09 13:44:55 +010043 sctList []byte // signed certificate timestamp list
Adam Langley75712922014-10-10 16:23:43 -070044 peerCertificates []*x509.Certificate
Adam Langley95c29f32014-06-20 12:00:00 -070045 // verifiedChains contains the certificate chains that we built, as
46 // opposed to the ones presented by the server.
47 verifiedChains [][]*x509.Certificate
48 // serverName contains the server name indicated by the client, if any.
Adam Langleyaf0e32c2015-06-03 09:57:23 -070049 serverName string
50 // firstFinished contains the first Finished hash sent during the
51 // handshake. This is the "tls-unique" channel binding value.
52 firstFinished [12]byte
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) {
1081 if !bytes.Equal(c.in.seq[2:], seq) {
1082 return errors.New("tls: sequence mismatch")
1083 }
1084 c.in.incSeq(false)
1085 } else {
1086 if !bytes.Equal(c.in.nextSeq[:], seq) {
1087 return errors.New("tls: sequence mismatch")
1088 }
1089 c.in.incNextSeq()
1090 }
David Benjamin6ca93552015-08-28 16:16:25 -04001091 if len(packet) < 13+int(length) {
1092 return errors.New("tls: bad packet")
1093 }
David Benjamin83f90402015-01-27 01:09:43 -05001094 packet = packet[13+length:]
1095 }
1096 return nil
1097}
1098
1099// simulatePacketLoss simulates the loss of a handshake leg from the
1100// peer based on the schedule in c.config.Bugs. If resendFunc is
1101// non-nil, it is called after each simulated timeout to retransmit
1102// handshake messages from the local end. This is used in cases where
1103// the peer retransmits on a stale Finished rather than a timeout.
1104func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1105 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1106 return nil
1107 }
1108 if !c.isDTLS {
1109 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1110 }
1111 if c.config.Bugs.PacketAdaptor == nil {
1112 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1113 }
1114 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1115 // Simulate a timeout.
1116 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1117 if err != nil {
1118 return err
1119 }
1120 for _, packet := range packets {
1121 if err := c.skipPacket(packet); err != nil {
1122 return err
1123 }
1124 }
1125 if resendFunc != nil {
1126 resendFunc()
1127 }
1128 }
1129 return nil
1130}
1131
Adam Langley95c29f32014-06-20 12:00:00 -07001132// Write writes data to the connection.
1133func (c *Conn) Write(b []byte) (int, error) {
1134 if err := c.Handshake(); err != nil {
1135 return 0, err
1136 }
1137
1138 c.out.Lock()
1139 defer c.out.Unlock()
1140
1141 if err := c.out.err; err != nil {
1142 return 0, err
1143 }
1144
1145 if !c.handshakeComplete {
1146 return 0, alertInternalError
1147 }
1148
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001149 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001150 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001151 }
1152
Adam Langley95c29f32014-06-20 12:00:00 -07001153 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1154 // attack when using block mode ciphers due to predictable IVs.
1155 // This can be prevented by splitting each Application Data
1156 // record into two records, effectively randomizing the IV.
1157 //
1158 // http://www.openssl.org/~bodo/tls-cbc.txt
1159 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1160 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1161
1162 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001163 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001164 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1165 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1166 if err != nil {
1167 return n, c.out.setErrorLocked(err)
1168 }
1169 m, b = 1, b[1:]
1170 }
1171 }
1172
1173 n, err := c.writeRecord(recordTypeApplicationData, b)
1174 return n + m, c.out.setErrorLocked(err)
1175}
1176
Adam Langley2ae77d22014-10-28 17:29:33 -07001177func (c *Conn) handleRenegotiation() error {
1178 c.handshakeComplete = false
1179 if !c.isClient {
1180 panic("renegotiation should only happen for a client")
1181 }
1182
1183 msg, err := c.readHandshake()
1184 if err != nil {
1185 return err
1186 }
1187 _, ok := msg.(*helloRequestMsg)
1188 if !ok {
1189 c.sendAlert(alertUnexpectedMessage)
1190 return alertUnexpectedMessage
1191 }
1192
1193 return c.Handshake()
1194}
1195
Adam Langleycf2d4f42014-10-28 19:06:14 -07001196func (c *Conn) Renegotiate() error {
1197 if !c.isClient {
1198 helloReq := new(helloRequestMsg)
1199 c.writeRecord(recordTypeHandshake, helloReq.marshal())
1200 }
1201
1202 c.handshakeComplete = false
1203 return c.Handshake()
1204}
1205
Adam Langley95c29f32014-06-20 12:00:00 -07001206// Read can be made to time out and return a net.Error with Timeout() == true
1207// after a fixed time limit; see SetDeadline and SetReadDeadline.
1208func (c *Conn) Read(b []byte) (n int, err error) {
1209 if err = c.Handshake(); err != nil {
1210 return
1211 }
1212
1213 c.in.Lock()
1214 defer c.in.Unlock()
1215
1216 // Some OpenSSL servers send empty records in order to randomize the
1217 // CBC IV. So this loop ignores a limited number of empty records.
1218 const maxConsecutiveEmptyRecords = 100
1219 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1220 for c.input == nil && c.in.err == nil {
1221 if err := c.readRecord(recordTypeApplicationData); err != nil {
1222 // Soft error, like EAGAIN
1223 return 0, err
1224 }
David Benjamind9b091b2015-01-27 01:10:54 -05001225 if c.hand.Len() > 0 {
Adam Langley2ae77d22014-10-28 17:29:33 -07001226 // We received handshake bytes, indicating the
David Benjamind9b091b2015-01-27 01:10:54 -05001227 // start of a renegotiation.
Adam Langley2ae77d22014-10-28 17:29:33 -07001228 if err := c.handleRenegotiation(); err != nil {
1229 return 0, err
1230 }
1231 continue
1232 }
Adam Langley95c29f32014-06-20 12:00:00 -07001233 }
1234 if err := c.in.err; err != nil {
1235 return 0, err
1236 }
1237
1238 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001239 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001240 c.in.freeBlock(c.input)
1241 c.input = nil
1242 }
1243
1244 // If a close-notify alert is waiting, read it so that
1245 // we can return (n, EOF) instead of (n, nil), to signal
1246 // to the HTTP response reading goroutine that the
1247 // connection is now closed. This eliminates a race
1248 // where the HTTP response reading goroutine would
1249 // otherwise not observe the EOF until its next read,
1250 // by which time a client goroutine might have already
1251 // tried to reuse the HTTP connection for a new
1252 // request.
1253 // See https://codereview.appspot.com/76400046
1254 // and http://golang.org/issue/3514
1255 if ri := c.rawInput; ri != nil &&
1256 n != 0 && err == nil &&
1257 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1258 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1259 err = recErr // will be io.EOF on closeNotify
1260 }
1261 }
1262
1263 if n != 0 || err != nil {
1264 return n, err
1265 }
1266 }
1267
1268 return 0, io.ErrNoProgress
1269}
1270
1271// Close closes the connection.
1272func (c *Conn) Close() error {
1273 var alertErr error
1274
1275 c.handshakeMutex.Lock()
1276 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001277 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
Adam Langley95c29f32014-06-20 12:00:00 -07001278 alertErr = c.sendAlert(alertCloseNotify)
1279 }
1280
David Benjamin30789da2015-08-29 22:56:45 -04001281 // Consume a close_notify from the peer if one hasn't been received
1282 // already. This avoids the peer from failing |SSL_shutdown| due to a
1283 // write failing.
1284 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1285 for c.in.error() == nil {
1286 c.readRecord(recordTypeAlert)
1287 }
1288 if c.in.error() != io.EOF {
1289 alertErr = c.in.error()
1290 }
1291 }
1292
Adam Langley95c29f32014-06-20 12:00:00 -07001293 if err := c.conn.Close(); err != nil {
1294 return err
1295 }
1296 return alertErr
1297}
1298
1299// Handshake runs the client or server handshake
1300// protocol if it has not yet been run.
1301// Most uses of this package need not call Handshake
1302// explicitly: the first Read or Write will call it automatically.
1303func (c *Conn) Handshake() error {
1304 c.handshakeMutex.Lock()
1305 defer c.handshakeMutex.Unlock()
1306 if err := c.handshakeErr; err != nil {
1307 return err
1308 }
1309 if c.handshakeComplete {
1310 return nil
1311 }
1312
David Benjamin9a41d1b2015-05-16 01:30:09 -04001313 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1314 c.conn.Write([]byte{
1315 byte(recordTypeAlert), // type
1316 0xfe, 0xff, // version
1317 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1318 0x0, 0x2, // length
1319 })
1320 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1321 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001322 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1323 c.writeRecord(recordTypeApplicationData, data)
1324 }
Adam Langley95c29f32014-06-20 12:00:00 -07001325 if c.isClient {
1326 c.handshakeErr = c.clientHandshake()
1327 } else {
1328 c.handshakeErr = c.serverHandshake()
1329 }
David Benjaminddb9f152015-02-03 15:44:39 -05001330 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1331 c.writeRecord(recordType(42), []byte("invalid record"))
1332 }
Adam Langley95c29f32014-06-20 12:00:00 -07001333 return c.handshakeErr
1334}
1335
1336// ConnectionState returns basic TLS details about the connection.
1337func (c *Conn) ConnectionState() ConnectionState {
1338 c.handshakeMutex.Lock()
1339 defer c.handshakeMutex.Unlock()
1340
1341 var state ConnectionState
1342 state.HandshakeComplete = c.handshakeComplete
1343 if c.handshakeComplete {
1344 state.Version = c.vers
1345 state.NegotiatedProtocol = c.clientProtocol
1346 state.DidResume = c.didResume
1347 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001348 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001349 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001350 state.PeerCertificates = c.peerCertificates
1351 state.VerifiedChains = c.verifiedChains
1352 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001353 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001354 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001355 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001356 state.SCTList = c.sctList
Steven Valdez0d62f262015-09-04 12:41:04 -04001357 state.ClientCertSignatureHash = c.clientCertSignatureHash
Adam Langley95c29f32014-06-20 12:00:00 -07001358 }
1359
1360 return state
1361}
1362
1363// OCSPResponse returns the stapled OCSP response from the TLS server, if
1364// any. (Only valid for client connections.)
1365func (c *Conn) OCSPResponse() []byte {
1366 c.handshakeMutex.Lock()
1367 defer c.handshakeMutex.Unlock()
1368
1369 return c.ocspResponse
1370}
1371
1372// VerifyHostname checks that the peer certificate chain is valid for
1373// connecting to host. If so, it returns nil; if not, it returns an error
1374// describing the problem.
1375func (c *Conn) VerifyHostname(host string) error {
1376 c.handshakeMutex.Lock()
1377 defer c.handshakeMutex.Unlock()
1378 if !c.isClient {
1379 return errors.New("tls: VerifyHostname called on TLS server connection")
1380 }
1381 if !c.handshakeComplete {
1382 return errors.New("tls: handshake has not yet been performed")
1383 }
1384 return c.peerCertificates[0].VerifyHostname(host)
1385}
David Benjaminc565ebb2015-04-03 04:06:36 -04001386
1387// ExportKeyingMaterial exports keying material from the current connection
1388// state, as per RFC 5705.
1389func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1390 c.handshakeMutex.Lock()
1391 defer c.handshakeMutex.Unlock()
1392 if !c.handshakeComplete {
1393 return nil, errors.New("tls: handshake has not yet been performed")
1394 }
1395
1396 seedLen := len(c.clientRandom) + len(c.serverRandom)
1397 if useContext {
1398 seedLen += 2 + len(context)
1399 }
1400 seed := make([]byte, 0, seedLen)
1401 seed = append(seed, c.clientRandom[:]...)
1402 seed = append(seed, c.serverRandom[:]...)
1403 if useContext {
1404 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1405 seed = append(seed, context...)
1406 }
1407 result := make([]byte, length)
1408 prfForVersion(c.vers, c.cipherSuite)(result, c.masterSecret[:], label, seed)
1409 return result, nil
1410}