blob: 3913995b8e299447cdf55d125fb30327be5d5168 [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()
David Benjaminf2b83632016-03-01 22:57:46 -0500192
193 if config.Bugs.NullAllCiphers {
194 hc.cipher = nil
195 hc.mac = nil
196 }
Adam Langley95c29f32014-06-20 12:00:00 -0700197 return nil
198}
199
200// incSeq increments the sequence number.
David Benjamin5e961c12014-11-07 01:48:35 -0500201func (hc *halfConn) incSeq(isOutgoing bool) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400202 limit := 0
David Benjamin5e961c12014-11-07 01:48:35 -0500203 increment := uint64(1)
David Benjamin83c0bc92014-08-04 01:23:53 -0400204 if hc.isDTLS {
205 // Increment up to the epoch in DTLS.
206 limit = 2
207 }
208 for i := 7; i >= limit; i-- {
David Benjamin5e961c12014-11-07 01:48:35 -0500209 increment += uint64(hc.seq[i])
210 hc.seq[i] = byte(increment)
211 increment >>= 8
Adam Langley95c29f32014-06-20 12:00:00 -0700212 }
213
214 // Not allowed to let sequence number wrap.
215 // Instead, must renegotiate before it does.
216 // Not likely enough to bother.
David Benjamin5e961c12014-11-07 01:48:35 -0500217 if increment != 0 {
218 panic("TLS: sequence number wraparound")
219 }
David Benjamin8e6db492015-07-25 18:29:23 -0400220
221 hc.updateOutSeq()
Adam Langley95c29f32014-06-20 12:00:00 -0700222}
223
David Benjamin83f90402015-01-27 01:09:43 -0500224// incNextSeq increments the starting sequence number for the next epoch.
225func (hc *halfConn) incNextSeq() {
226 for i := len(hc.nextSeq) - 1; i >= 0; i-- {
227 hc.nextSeq[i]++
228 if hc.nextSeq[i] != 0 {
229 return
230 }
231 }
232 panic("TLS: sequence number wraparound")
233}
234
235// incEpoch resets the sequence number. In DTLS, it also increments the epoch
236// half of the sequence number.
David Benjamin83c0bc92014-08-04 01:23:53 -0400237func (hc *halfConn) incEpoch() {
David Benjamin83c0bc92014-08-04 01:23:53 -0400238 if hc.isDTLS {
239 for i := 1; i >= 0; i-- {
240 hc.seq[i]++
241 if hc.seq[i] != 0 {
242 break
243 }
244 if i == 0 {
245 panic("TLS: epoch number wraparound")
246 }
247 }
David Benjamin83f90402015-01-27 01:09:43 -0500248 copy(hc.seq[2:], hc.nextSeq[:])
249 for i := range hc.nextSeq {
250 hc.nextSeq[i] = 0
251 }
252 } else {
253 for i := range hc.seq {
254 hc.seq[i] = 0
255 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400256 }
David Benjamin8e6db492015-07-25 18:29:23 -0400257
258 hc.updateOutSeq()
259}
260
261func (hc *halfConn) updateOutSeq() {
262 if hc.config.Bugs.SequenceNumberMapping != nil {
263 seqU64 := binary.BigEndian.Uint64(hc.seq[:])
264 seqU64 = hc.config.Bugs.SequenceNumberMapping(seqU64)
265 binary.BigEndian.PutUint64(hc.outSeq[:], seqU64)
266
267 // The DTLS epoch cannot be changed.
268 copy(hc.outSeq[:2], hc.seq[:2])
269 return
270 }
271
272 copy(hc.outSeq[:], hc.seq[:])
David Benjamin83c0bc92014-08-04 01:23:53 -0400273}
274
275func (hc *halfConn) recordHeaderLen() int {
276 if hc.isDTLS {
277 return dtlsRecordHeaderLen
278 }
279 return tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700280}
281
282// removePadding returns an unpadded slice, in constant time, which is a prefix
283// of the input. It also returns a byte which is equal to 255 if the padding
284// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
285func removePadding(payload []byte) ([]byte, byte) {
286 if len(payload) < 1 {
287 return payload, 0
288 }
289
290 paddingLen := payload[len(payload)-1]
291 t := uint(len(payload)-1) - uint(paddingLen)
292 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
293 good := byte(int32(^t) >> 31)
294
295 toCheck := 255 // the maximum possible padding length
296 // The length of the padded data is public, so we can use an if here
297 if toCheck+1 > len(payload) {
298 toCheck = len(payload) - 1
299 }
300
301 for i := 0; i < toCheck; i++ {
302 t := uint(paddingLen) - uint(i)
303 // if i <= paddingLen then the MSB of t is zero
304 mask := byte(int32(^t) >> 31)
305 b := payload[len(payload)-1-i]
306 good &^= mask&paddingLen ^ mask&b
307 }
308
309 // We AND together the bits of good and replicate the result across
310 // all the bits.
311 good &= good << 4
312 good &= good << 2
313 good &= good << 1
314 good = uint8(int8(good) >> 7)
315
316 toRemove := good&paddingLen + 1
317 return payload[:len(payload)-int(toRemove)], good
318}
319
320// removePaddingSSL30 is a replacement for removePadding in the case that the
321// protocol version is SSLv3. In this version, the contents of the padding
322// are random and cannot be checked.
323func removePaddingSSL30(payload []byte) ([]byte, byte) {
324 if len(payload) < 1 {
325 return payload, 0
326 }
327
328 paddingLen := int(payload[len(payload)-1]) + 1
329 if paddingLen > len(payload) {
330 return payload, 0
331 }
332
333 return payload[:len(payload)-paddingLen], 255
334}
335
336func roundUp(a, b int) int {
337 return a + (b-a%b)%b
338}
339
340// cbcMode is an interface for block ciphers using cipher block chaining.
341type cbcMode interface {
342 cipher.BlockMode
343 SetIV([]byte)
344}
345
346// decrypt checks and strips the mac and decrypts the data in b. Returns a
347// success boolean, the number of bytes to skip from the start of the record in
348// order to get the application payload, and an optional alert value.
349func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, alertValue alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400350 recordHeaderLen := hc.recordHeaderLen()
351
Adam Langley95c29f32014-06-20 12:00:00 -0700352 // pull out payload
353 payload := b.data[recordHeaderLen:]
354
355 macSize := 0
356 if hc.mac != nil {
357 macSize = hc.mac.Size()
358 }
359
360 paddingGood := byte(255)
361 explicitIVLen := 0
362
David Benjamin83c0bc92014-08-04 01:23:53 -0400363 seq := hc.seq[:]
364 if hc.isDTLS {
365 // DTLS sequence numbers are explicit.
366 seq = b.data[3:11]
367 }
368
Adam Langley95c29f32014-06-20 12:00:00 -0700369 // decrypt
370 if hc.cipher != nil {
371 switch c := hc.cipher.(type) {
372 case cipher.Stream:
373 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400374 case *tlsAead:
375 nonce := seq
376 if c.explicitNonce {
377 explicitIVLen = 8
378 if len(payload) < explicitIVLen {
379 return false, 0, alertBadRecordMAC
380 }
381 nonce = payload[:8]
382 payload = payload[8:]
Adam Langley95c29f32014-06-20 12:00:00 -0700383 }
Adam Langley95c29f32014-06-20 12:00:00 -0700384
385 var additionalData [13]byte
David Benjamin83c0bc92014-08-04 01:23:53 -0400386 copy(additionalData[:], seq)
Adam Langley95c29f32014-06-20 12:00:00 -0700387 copy(additionalData[8:], b.data[:3])
388 n := len(payload) - c.Overhead()
389 additionalData[11] = byte(n >> 8)
390 additionalData[12] = byte(n)
391 var err error
392 payload, err = c.Open(payload[:0], nonce, payload, additionalData[:])
393 if err != nil {
394 return false, 0, alertBadRecordMAC
395 }
396 b.resize(recordHeaderLen + explicitIVLen + len(payload))
397 case cbcMode:
398 blockSize := c.BlockSize()
David Benjamin83c0bc92014-08-04 01:23:53 -0400399 if hc.version >= VersionTLS11 || hc.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700400 explicitIVLen = blockSize
401 }
402
403 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
404 return false, 0, alertBadRecordMAC
405 }
406
407 if explicitIVLen > 0 {
408 c.SetIV(payload[:explicitIVLen])
409 payload = payload[explicitIVLen:]
410 }
411 c.CryptBlocks(payload, payload)
412 if hc.version == VersionSSL30 {
413 payload, paddingGood = removePaddingSSL30(payload)
414 } else {
415 payload, paddingGood = removePadding(payload)
416 }
417 b.resize(recordHeaderLen + explicitIVLen + len(payload))
418
419 // note that we still have a timing side-channel in the
420 // MAC check, below. An attacker can align the record
421 // so that a correct padding will cause one less hash
422 // block to be calculated. Then they can iteratively
423 // decrypt a record by breaking each byte. See
424 // "Password Interception in a SSL/TLS Channel", Brice
425 // Canvel et al.
426 //
427 // However, our behavior matches OpenSSL, so we leak
428 // only as much as they do.
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700429 case nullCipher:
430 break
Adam Langley95c29f32014-06-20 12:00:00 -0700431 default:
432 panic("unknown cipher type")
433 }
434 }
435
436 // check, strip mac
437 if hc.mac != nil {
438 if len(payload) < macSize {
439 return false, 0, alertBadRecordMAC
440 }
441
442 // strip mac off payload, b.data
443 n := len(payload) - macSize
David Benjamin83c0bc92014-08-04 01:23:53 -0400444 b.data[recordHeaderLen-2] = byte(n >> 8)
445 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700446 b.resize(recordHeaderLen + explicitIVLen + n)
447 remoteMAC := payload[n:]
David Benjamin83c0bc92014-08-04 01:23:53 -0400448 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
Adam Langley95c29f32014-06-20 12:00:00 -0700449
450 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
451 return false, 0, alertBadRecordMAC
452 }
453 hc.inDigestBuf = localMAC
454 }
David Benjamin5e961c12014-11-07 01:48:35 -0500455 hc.incSeq(false)
Adam Langley95c29f32014-06-20 12:00:00 -0700456
457 return true, recordHeaderLen + explicitIVLen, 0
458}
459
460// padToBlockSize calculates the needed padding block, if any, for a payload.
461// On exit, prefix aliases payload and extends to the end of the last full
462// block of payload. finalBlock is a fresh slice which contains the contents of
463// any suffix of payload as well as the needed padding to make finalBlock a
464// full block.
Adam Langley80842bd2014-06-20 12:00:00 -0700465func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
Adam Langley95c29f32014-06-20 12:00:00 -0700466 overrun := len(payload) % blockSize
Adam Langley95c29f32014-06-20 12:00:00 -0700467 prefix = payload[:len(payload)-overrun]
Adam Langley80842bd2014-06-20 12:00:00 -0700468
469 paddingLen := blockSize - overrun
470 finalSize := blockSize
471 if config.Bugs.MaxPadding {
472 for paddingLen+blockSize <= 256 {
473 paddingLen += blockSize
474 }
475 finalSize = 256
476 }
477 finalBlock = make([]byte, finalSize)
478 for i := range finalBlock {
Adam Langley95c29f32014-06-20 12:00:00 -0700479 finalBlock[i] = byte(paddingLen - 1)
480 }
Adam Langley80842bd2014-06-20 12:00:00 -0700481 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
482 finalBlock[overrun] ^= 0xff
483 }
484 copy(finalBlock, payload[len(payload)-overrun:])
Adam Langley95c29f32014-06-20 12:00:00 -0700485 return
486}
487
488// encrypt encrypts and macs the data in b.
489func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400490 recordHeaderLen := hc.recordHeaderLen()
491
Adam Langley95c29f32014-06-20 12:00:00 -0700492 // mac
493 if hc.mac != nil {
David Benjamin8e6db492015-07-25 18:29:23 -0400494 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 -0700495
496 n := len(b.data)
497 b.resize(n + len(mac))
498 copy(b.data[n:], mac)
499 hc.outDigestBuf = mac
500 }
501
502 payload := b.data[recordHeaderLen:]
503
504 // encrypt
505 if hc.cipher != nil {
506 switch c := hc.cipher.(type) {
507 case cipher.Stream:
508 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400509 case *tlsAead:
Adam Langley95c29f32014-06-20 12:00:00 -0700510 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
511 b.resize(len(b.data) + c.Overhead())
David Benjamin8e6db492015-07-25 18:29:23 -0400512 nonce := hc.outSeq[:]
David Benjamine9a80ff2015-04-07 00:46:46 -0400513 if c.explicitNonce {
514 nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
515 }
Adam Langley95c29f32014-06-20 12:00:00 -0700516 payload := b.data[recordHeaderLen+explicitIVLen:]
517 payload = payload[:payloadLen]
518
519 var additionalData [13]byte
David Benjamin8e6db492015-07-25 18:29:23 -0400520 copy(additionalData[:], hc.outSeq[:])
Adam Langley95c29f32014-06-20 12:00:00 -0700521 copy(additionalData[8:], b.data[:3])
522 additionalData[11] = byte(payloadLen >> 8)
523 additionalData[12] = byte(payloadLen)
524
525 c.Seal(payload[:0], nonce, payload, additionalData[:])
526 case cbcMode:
527 blockSize := c.BlockSize()
528 if explicitIVLen > 0 {
529 c.SetIV(payload[:explicitIVLen])
530 payload = payload[explicitIVLen:]
531 }
Adam Langley80842bd2014-06-20 12:00:00 -0700532 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700533 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
534 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
535 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700536 case nullCipher:
537 break
Adam Langley95c29f32014-06-20 12:00:00 -0700538 default:
539 panic("unknown cipher type")
540 }
541 }
542
543 // update length to include MAC and any block padding needed.
544 n := len(b.data) - recordHeaderLen
David Benjamin83c0bc92014-08-04 01:23:53 -0400545 b.data[recordHeaderLen-2] = byte(n >> 8)
546 b.data[recordHeaderLen-1] = byte(n)
David Benjamin5e961c12014-11-07 01:48:35 -0500547 hc.incSeq(true)
Adam Langley95c29f32014-06-20 12:00:00 -0700548
549 return true, 0
550}
551
552// A block is a simple data buffer.
553type block struct {
554 data []byte
555 off int // index for Read
556 link *block
557}
558
559// resize resizes block to be n bytes, growing if necessary.
560func (b *block) resize(n int) {
561 if n > cap(b.data) {
562 b.reserve(n)
563 }
564 b.data = b.data[0:n]
565}
566
567// reserve makes sure that block contains a capacity of at least n bytes.
568func (b *block) reserve(n int) {
569 if cap(b.data) >= n {
570 return
571 }
572 m := cap(b.data)
573 if m == 0 {
574 m = 1024
575 }
576 for m < n {
577 m *= 2
578 }
579 data := make([]byte, len(b.data), m)
580 copy(data, b.data)
581 b.data = data
582}
583
584// readFromUntil reads from r into b until b contains at least n bytes
585// or else returns an error.
586func (b *block) readFromUntil(r io.Reader, n int) error {
587 // quick case
588 if len(b.data) >= n {
589 return nil
590 }
591
592 // read until have enough.
593 b.reserve(n)
594 for {
595 m, err := r.Read(b.data[len(b.data):cap(b.data)])
596 b.data = b.data[0 : len(b.data)+m]
597 if len(b.data) >= n {
598 // TODO(bradfitz,agl): slightly suspicious
599 // that we're throwing away r.Read's err here.
600 break
601 }
602 if err != nil {
603 return err
604 }
605 }
606 return nil
607}
608
609func (b *block) Read(p []byte) (n int, err error) {
610 n = copy(p, b.data[b.off:])
611 b.off += n
612 return
613}
614
615// newBlock allocates a new block, from hc's free list if possible.
616func (hc *halfConn) newBlock() *block {
617 b := hc.bfree
618 if b == nil {
619 return new(block)
620 }
621 hc.bfree = b.link
622 b.link = nil
623 b.resize(0)
624 return b
625}
626
627// freeBlock returns a block to hc's free list.
628// The protocol is such that each side only has a block or two on
629// its free list at a time, so there's no need to worry about
630// trimming the list, etc.
631func (hc *halfConn) freeBlock(b *block) {
632 b.link = hc.bfree
633 hc.bfree = b
634}
635
636// splitBlock splits a block after the first n bytes,
637// returning a block with those n bytes and a
638// block with the remainder. the latter may be nil.
639func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
640 if len(b.data) <= n {
641 return b, nil
642 }
643 bb := hc.newBlock()
644 bb.resize(len(b.data) - n)
645 copy(bb.data, b.data[n:])
646 b.data = b.data[0:n]
647 return b, bb
648}
649
David Benjamin83c0bc92014-08-04 01:23:53 -0400650func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
651 if c.isDTLS {
652 return c.dtlsDoReadRecord(want)
653 }
654
655 recordHeaderLen := tlsRecordHeaderLen
656
657 if c.rawInput == nil {
658 c.rawInput = c.in.newBlock()
659 }
660 b := c.rawInput
661
662 // Read header, payload.
663 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
664 // RFC suggests that EOF without an alertCloseNotify is
665 // an error, but popular web sites seem to do this,
David Benjamin30789da2015-08-29 22:56:45 -0400666 // so we can't make it an error, outside of tests.
667 if err == io.EOF && c.config.Bugs.ExpectCloseNotify {
668 err = io.ErrUnexpectedEOF
669 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400670 if e, ok := err.(net.Error); !ok || !e.Temporary() {
671 c.in.setErrorLocked(err)
672 }
673 return 0, nil, err
674 }
675 typ := recordType(b.data[0])
676
677 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
678 // start with a uint16 length where the MSB is set and the first record
679 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
680 // an SSLv2 client.
681 if want == recordTypeHandshake && typ == 0x80 {
682 c.sendAlert(alertProtocolVersion)
683 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
684 }
685
686 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
687 n := int(b.data[3])<<8 | int(b.data[4])
David Benjamin1e29a6b2014-12-10 02:27:24 -0500688 if c.haveVers {
689 if vers != c.vers {
690 c.sendAlert(alertProtocolVersion)
691 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers))
692 }
693 } else {
694 if expect := c.config.Bugs.ExpectInitialRecordVersion; expect != 0 && vers != expect {
695 c.sendAlert(alertProtocolVersion)
696 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
697 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400698 }
699 if n > maxCiphertext {
700 c.sendAlert(alertRecordOverflow)
701 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
702 }
703 if !c.haveVers {
704 // First message, be extra suspicious:
705 // this might not be a TLS client.
706 // Bail out before reading a full 'body', if possible.
707 // The current max version is 3.1.
708 // If the version is >= 16.0, it's probably not real.
709 // Similarly, a clientHello message encodes in
710 // well under a kilobyte. If the length is >= 12 kB,
711 // it's probably not real.
712 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
713 c.sendAlert(alertUnexpectedMessage)
714 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
715 }
716 }
717 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
718 if err == io.EOF {
719 err = io.ErrUnexpectedEOF
720 }
721 if e, ok := err.(net.Error); !ok || !e.Temporary() {
722 c.in.setErrorLocked(err)
723 }
724 return 0, nil, err
725 }
726
727 // Process message.
728 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
729 ok, off, err := c.in.decrypt(b)
730 if !ok {
731 c.in.setErrorLocked(c.sendAlert(err))
732 }
733 b.off = off
734 return typ, b, nil
735}
736
Adam Langley95c29f32014-06-20 12:00:00 -0700737// readRecord reads the next TLS record from the connection
738// and updates the record layer state.
739// c.in.Mutex <= L; c.input == nil.
740func (c *Conn) readRecord(want recordType) error {
741 // Caller must be in sync with connection:
742 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700743 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700744 switch want {
745 default:
746 c.sendAlert(alertInternalError)
747 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
748 case recordTypeHandshake, recordTypeChangeCipherSpec:
749 if c.handshakeComplete {
750 c.sendAlert(alertInternalError)
751 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
752 }
753 case recordTypeApplicationData:
David Benjamine58c4f52014-08-24 03:47:07 -0400754 if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart {
Adam Langley95c29f32014-06-20 12:00:00 -0700755 c.sendAlert(alertInternalError)
756 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
757 }
David Benjamin30789da2015-08-29 22:56:45 -0400758 case recordTypeAlert:
759 // Looking for a close_notify. Note: unlike a real
760 // implementation, this is not tolerant of additional records.
761 // See the documentation for ExpectCloseNotify.
Adam Langley95c29f32014-06-20 12:00:00 -0700762 }
763
764Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400765 typ, b, err := c.doReadRecord(want)
766 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700767 return err
768 }
Adam Langley95c29f32014-06-20 12:00:00 -0700769 data := b.data[b.off:]
770 if len(data) > maxPlaintext {
771 err := c.sendAlert(alertRecordOverflow)
772 c.in.freeBlock(b)
773 return c.in.setErrorLocked(err)
774 }
775
776 switch typ {
777 default:
778 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
779
780 case recordTypeAlert:
781 if len(data) != 2 {
782 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
783 break
784 }
785 if alert(data[1]) == alertCloseNotify {
786 c.in.setErrorLocked(io.EOF)
787 break
788 }
789 switch data[0] {
790 case alertLevelWarning:
791 // drop on the floor
792 c.in.freeBlock(b)
793 goto Again
794 case alertLevelError:
795 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
796 default:
797 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
798 }
799
800 case recordTypeChangeCipherSpec:
801 if typ != want || len(data) != 1 || data[0] != 1 {
802 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
803 break
804 }
Adam Langley80842bd2014-06-20 12:00:00 -0700805 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700806 if err != nil {
807 c.in.setErrorLocked(c.sendAlert(err.(alert)))
808 }
809
810 case recordTypeApplicationData:
811 if typ != want {
812 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
813 break
814 }
815 c.input = b
816 b = nil
817
818 case recordTypeHandshake:
819 // TODO(rsc): Should at least pick off connection close.
820 if typ != want {
Adam Langley2ae77d22014-10-28 17:29:33 -0700821 // A client might need to process a HelloRequest from
822 // the server, thus receiving a handshake message when
David Benjamind9b091b2015-01-27 01:10:54 -0500823 // application data is expected is ok.
David Benjamin30789da2015-08-29 22:56:45 -0400824 if !c.isClient || want != recordTypeApplicationData {
Adam Langley2ae77d22014-10-28 17:29:33 -0700825 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
826 }
Adam Langley95c29f32014-06-20 12:00:00 -0700827 }
828 c.hand.Write(data)
829 }
830
831 if b != nil {
832 c.in.freeBlock(b)
833 }
834 return c.in.err
835}
836
837// sendAlert sends a TLS alert message.
838// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400839func (c *Conn) sendAlertLocked(level byte, err alert) error {
840 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700841 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400842 if c.config.Bugs.FragmentAlert {
843 c.writeRecord(recordTypeAlert, c.tmp[0:1])
844 c.writeRecord(recordTypeAlert, c.tmp[1:2])
David Benjamin0d3a8c62016-03-11 22:25:18 -0500845 } else if c.config.Bugs.DoubleAlert {
846 copy(c.tmp[2:4], c.tmp[0:2])
847 c.writeRecord(recordTypeAlert, c.tmp[0:4])
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400848 } else {
849 c.writeRecord(recordTypeAlert, c.tmp[0:2])
850 }
David Benjamin24f346d2015-06-06 03:28:08 -0400851 // Error alerts are fatal to the connection.
852 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700853 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
854 }
855 return nil
856}
857
858// sendAlert sends a TLS alert message.
859// L < c.out.Mutex.
860func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400861 level := byte(alertLevelError)
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500862 if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertficate {
David Benjamin24f346d2015-06-06 03:28:08 -0400863 level = alertLevelWarning
864 }
865 return c.SendAlert(level, err)
866}
867
868func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700869 c.out.Lock()
870 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -0400871 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -0700872}
873
David Benjamind86c7672014-08-02 04:07:12 -0400874// writeV2Record writes a record for a V2ClientHello.
875func (c *Conn) writeV2Record(data []byte) (n int, err error) {
876 record := make([]byte, 2+len(data))
877 record[0] = uint8(len(data)>>8) | 0x80
878 record[1] = uint8(len(data))
879 copy(record[2:], data)
880 return c.conn.Write(record)
881}
882
Adam Langley95c29f32014-06-20 12:00:00 -0700883// writeRecord writes a TLS record with the given type and payload
884// to the connection and updates the record layer state.
885// c.out.Mutex <= L.
886func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400887 if c.isDTLS {
888 return c.dtlsWriteRecord(typ, data)
889 }
890
891 recordHeaderLen := tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700892 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -0400893 first := true
894 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -0400895 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -0700896 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -0400897 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -0700898 m = maxPlaintext
899 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400900 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
901 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -0400902 // By default, do not fragment the client_version or
903 // server_version, which are located in the first 6
904 // bytes.
905 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
906 m = 6
907 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400908 }
Adam Langley95c29f32014-06-20 12:00:00 -0700909 explicitIVLen := 0
910 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -0400911 first = false
Adam Langley95c29f32014-06-20 12:00:00 -0700912
913 var cbc cbcMode
914 if c.out.version >= VersionTLS11 {
915 var ok bool
916 if cbc, ok = c.out.cipher.(cbcMode); ok {
917 explicitIVLen = cbc.BlockSize()
918 }
919 }
920 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -0400921 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -0700922 explicitIVLen = 8
923 // The AES-GCM construction in TLS has an
924 // explicit nonce so that the nonce can be
925 // random. However, the nonce is only 8 bytes
926 // which is too small for a secure, random
927 // nonce. Therefore we use the sequence number
928 // as the nonce.
929 explicitIVIsSeq = true
930 }
931 }
932 b.resize(recordHeaderLen + explicitIVLen + m)
933 b.data[0] = byte(typ)
934 vers := c.vers
935 if vers == 0 {
936 // Some TLS servers fail if the record version is
937 // greater than TLS 1.0 for the initial ClientHello.
938 vers = VersionTLS10
939 }
940 b.data[1] = byte(vers >> 8)
941 b.data[2] = byte(vers)
942 b.data[3] = byte(m >> 8)
943 b.data[4] = byte(m)
944 if explicitIVLen > 0 {
945 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
946 if explicitIVIsSeq {
947 copy(explicitIV, c.out.seq[:])
948 } else {
949 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
950 break
951 }
952 }
953 }
954 copy(b.data[recordHeaderLen+explicitIVLen:], data)
955 c.out.encrypt(b, explicitIVLen)
956 _, err = c.conn.Write(b.data)
957 if err != nil {
958 break
959 }
960 n += m
961 data = data[m:]
962 }
963 c.out.freeBlock(b)
964
965 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -0700966 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700967 if err != nil {
968 // Cannot call sendAlert directly,
969 // because we already hold c.out.Mutex.
970 c.tmp[0] = alertLevelError
971 c.tmp[1] = byte(err.(alert))
972 c.writeRecord(recordTypeAlert, c.tmp[0:2])
973 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
974 }
975 }
976 return
977}
978
David Benjamin83c0bc92014-08-04 01:23:53 -0400979func (c *Conn) doReadHandshake() ([]byte, error) {
980 if c.isDTLS {
981 return c.dtlsDoReadHandshake()
982 }
983
Adam Langley95c29f32014-06-20 12:00:00 -0700984 for c.hand.Len() < 4 {
985 if err := c.in.err; err != nil {
986 return nil, err
987 }
988 if err := c.readRecord(recordTypeHandshake); err != nil {
989 return nil, err
990 }
991 }
992
993 data := c.hand.Bytes()
994 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
995 if n > maxHandshake {
996 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
997 }
998 for c.hand.Len() < 4+n {
999 if err := c.in.err; err != nil {
1000 return nil, err
1001 }
1002 if err := c.readRecord(recordTypeHandshake); err != nil {
1003 return nil, err
1004 }
1005 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001006 return c.hand.Next(4 + n), nil
1007}
1008
1009// readHandshake reads the next handshake message from
1010// the record layer.
1011// c.in.Mutex < L; c.out.Mutex < L.
1012func (c *Conn) readHandshake() (interface{}, error) {
1013 data, err := c.doReadHandshake()
1014 if err != nil {
1015 return nil, err
1016 }
1017
Adam Langley95c29f32014-06-20 12:00:00 -07001018 var m handshakeMessage
1019 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001020 case typeHelloRequest:
1021 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001022 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001023 m = &clientHelloMsg{
1024 isDTLS: c.isDTLS,
1025 }
Adam Langley95c29f32014-06-20 12:00:00 -07001026 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001027 m = &serverHelloMsg{
1028 isDTLS: c.isDTLS,
1029 }
Adam Langley95c29f32014-06-20 12:00:00 -07001030 case typeNewSessionTicket:
1031 m = new(newSessionTicketMsg)
1032 case typeCertificate:
1033 m = new(certificateMsg)
1034 case typeCertificateRequest:
1035 m = &certificateRequestMsg{
1036 hasSignatureAndHash: c.vers >= VersionTLS12,
1037 }
1038 case typeCertificateStatus:
1039 m = new(certificateStatusMsg)
1040 case typeServerKeyExchange:
1041 m = new(serverKeyExchangeMsg)
1042 case typeServerHelloDone:
1043 m = new(serverHelloDoneMsg)
1044 case typeClientKeyExchange:
1045 m = new(clientKeyExchangeMsg)
1046 case typeCertificateVerify:
1047 m = &certificateVerifyMsg{
1048 hasSignatureAndHash: c.vers >= VersionTLS12,
1049 }
1050 case typeNextProtocol:
1051 m = new(nextProtoMsg)
1052 case typeFinished:
1053 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001054 case typeHelloVerifyRequest:
1055 m = new(helloVerifyRequestMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001056 case typeEncryptedExtensions:
1057 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001058 default:
1059 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1060 }
1061
1062 // The handshake message unmarshallers
1063 // expect to be able to keep references to data,
1064 // so pass in a fresh copy that won't be overwritten.
1065 data = append([]byte(nil), data...)
1066
1067 if !m.unmarshal(data) {
1068 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1069 }
1070 return m, nil
1071}
1072
David Benjamin83f90402015-01-27 01:09:43 -05001073// skipPacket processes all the DTLS records in packet. It updates
1074// sequence number expectations but otherwise ignores them.
1075func (c *Conn) skipPacket(packet []byte) error {
1076 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001077 if len(packet) < 13 {
1078 return errors.New("tls: bad packet")
1079 }
David Benjamin83f90402015-01-27 01:09:43 -05001080 // Dropped packets are completely ignored save to update
1081 // expected sequence numbers for this and the next epoch. (We
1082 // don't assert on the contents of the packets both for
1083 // simplicity and because a previous test with one shorter
1084 // timeout schedule would have done so.)
1085 epoch := packet[3:5]
1086 seq := packet[5:11]
1087 length := uint16(packet[11])<<8 | uint16(packet[12])
1088 if bytes.Equal(c.in.seq[:2], epoch) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001089 if bytes.Compare(seq, c.in.seq[2:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001090 return errors.New("tls: sequence mismatch")
1091 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001092 copy(c.in.seq[2:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001093 c.in.incSeq(false)
1094 } else {
David Benjamin13e81fc2015-11-02 17:16:13 -05001095 if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001096 return errors.New("tls: sequence mismatch")
1097 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001098 copy(c.in.nextSeq[:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001099 c.in.incNextSeq()
1100 }
David Benjamin6ca93552015-08-28 16:16:25 -04001101 if len(packet) < 13+int(length) {
1102 return errors.New("tls: bad packet")
1103 }
David Benjamin83f90402015-01-27 01:09:43 -05001104 packet = packet[13+length:]
1105 }
1106 return nil
1107}
1108
1109// simulatePacketLoss simulates the loss of a handshake leg from the
1110// peer based on the schedule in c.config.Bugs. If resendFunc is
1111// non-nil, it is called after each simulated timeout to retransmit
1112// handshake messages from the local end. This is used in cases where
1113// the peer retransmits on a stale Finished rather than a timeout.
1114func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1115 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1116 return nil
1117 }
1118 if !c.isDTLS {
1119 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1120 }
1121 if c.config.Bugs.PacketAdaptor == nil {
1122 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1123 }
1124 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1125 // Simulate a timeout.
1126 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1127 if err != nil {
1128 return err
1129 }
1130 for _, packet := range packets {
1131 if err := c.skipPacket(packet); err != nil {
1132 return err
1133 }
1134 }
1135 if resendFunc != nil {
1136 resendFunc()
1137 }
1138 }
1139 return nil
1140}
1141
Adam Langley95c29f32014-06-20 12:00:00 -07001142// Write writes data to the connection.
1143func (c *Conn) Write(b []byte) (int, error) {
1144 if err := c.Handshake(); err != nil {
1145 return 0, err
1146 }
1147
1148 c.out.Lock()
1149 defer c.out.Unlock()
1150
1151 if err := c.out.err; err != nil {
1152 return 0, err
1153 }
1154
1155 if !c.handshakeComplete {
1156 return 0, alertInternalError
1157 }
1158
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001159 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001160 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001161 }
1162
Adam Langley27a0d082015-11-03 13:34:10 -08001163 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1164 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
1165 }
1166
Adam Langley95c29f32014-06-20 12:00:00 -07001167 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1168 // attack when using block mode ciphers due to predictable IVs.
1169 // This can be prevented by splitting each Application Data
1170 // record into two records, effectively randomizing the IV.
1171 //
1172 // http://www.openssl.org/~bodo/tls-cbc.txt
1173 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1174 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1175
1176 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001177 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001178 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1179 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1180 if err != nil {
1181 return n, c.out.setErrorLocked(err)
1182 }
1183 m, b = 1, b[1:]
1184 }
1185 }
1186
1187 n, err := c.writeRecord(recordTypeApplicationData, b)
1188 return n + m, c.out.setErrorLocked(err)
1189}
1190
Adam Langley2ae77d22014-10-28 17:29:33 -07001191func (c *Conn) handleRenegotiation() error {
1192 c.handshakeComplete = false
1193 if !c.isClient {
1194 panic("renegotiation should only happen for a client")
1195 }
1196
1197 msg, err := c.readHandshake()
1198 if err != nil {
1199 return err
1200 }
1201 _, ok := msg.(*helloRequestMsg)
1202 if !ok {
1203 c.sendAlert(alertUnexpectedMessage)
1204 return alertUnexpectedMessage
1205 }
1206
1207 return c.Handshake()
1208}
1209
Adam Langleycf2d4f42014-10-28 19:06:14 -07001210func (c *Conn) Renegotiate() error {
1211 if !c.isClient {
David Benjaminef5dfd22015-12-06 13:17:07 -05001212 helloReq := new(helloRequestMsg).marshal()
1213 if c.config.Bugs.BadHelloRequest != nil {
1214 helloReq = c.config.Bugs.BadHelloRequest
1215 }
1216 c.writeRecord(recordTypeHandshake, helloReq)
Adam Langleycf2d4f42014-10-28 19:06:14 -07001217 }
1218
1219 c.handshakeComplete = false
1220 return c.Handshake()
1221}
1222
Adam Langley95c29f32014-06-20 12:00:00 -07001223// Read can be made to time out and return a net.Error with Timeout() == true
1224// after a fixed time limit; see SetDeadline and SetReadDeadline.
1225func (c *Conn) Read(b []byte) (n int, err error) {
1226 if err = c.Handshake(); err != nil {
1227 return
1228 }
1229
1230 c.in.Lock()
1231 defer c.in.Unlock()
1232
1233 // Some OpenSSL servers send empty records in order to randomize the
1234 // CBC IV. So this loop ignores a limited number of empty records.
1235 const maxConsecutiveEmptyRecords = 100
1236 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1237 for c.input == nil && c.in.err == nil {
1238 if err := c.readRecord(recordTypeApplicationData); err != nil {
1239 // Soft error, like EAGAIN
1240 return 0, err
1241 }
David Benjamind9b091b2015-01-27 01:10:54 -05001242 if c.hand.Len() > 0 {
Adam Langley2ae77d22014-10-28 17:29:33 -07001243 // We received handshake bytes, indicating the
David Benjamind9b091b2015-01-27 01:10:54 -05001244 // start of a renegotiation.
Adam Langley2ae77d22014-10-28 17:29:33 -07001245 if err := c.handleRenegotiation(); err != nil {
1246 return 0, err
1247 }
1248 continue
1249 }
Adam Langley95c29f32014-06-20 12:00:00 -07001250 }
1251 if err := c.in.err; err != nil {
1252 return 0, err
1253 }
1254
1255 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001256 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001257 c.in.freeBlock(c.input)
1258 c.input = nil
1259 }
1260
1261 // If a close-notify alert is waiting, read it so that
1262 // we can return (n, EOF) instead of (n, nil), to signal
1263 // to the HTTP response reading goroutine that the
1264 // connection is now closed. This eliminates a race
1265 // where the HTTP response reading goroutine would
1266 // otherwise not observe the EOF until its next read,
1267 // by which time a client goroutine might have already
1268 // tried to reuse the HTTP connection for a new
1269 // request.
1270 // See https://codereview.appspot.com/76400046
1271 // and http://golang.org/issue/3514
1272 if ri := c.rawInput; ri != nil &&
1273 n != 0 && err == nil &&
1274 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1275 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1276 err = recErr // will be io.EOF on closeNotify
1277 }
1278 }
1279
1280 if n != 0 || err != nil {
1281 return n, err
1282 }
1283 }
1284
1285 return 0, io.ErrNoProgress
1286}
1287
1288// Close closes the connection.
1289func (c *Conn) Close() error {
1290 var alertErr error
1291
1292 c.handshakeMutex.Lock()
1293 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001294 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
David Benjaminfa214e42016-05-10 17:03:10 -04001295 alert := alertCloseNotify
1296 if c.config.Bugs.SendAlertOnShutdown != 0 {
1297 alert = c.config.Bugs.SendAlertOnShutdown
1298 }
1299 alertErr = c.sendAlert(alert)
David Benjamin4d559612016-05-18 14:31:51 -04001300 // Clear local alerts when sending alerts so we continue to wait
1301 // for the peer rather than closing the socket early.
1302 if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1303 alertErr = nil
1304 }
Adam Langley95c29f32014-06-20 12:00:00 -07001305 }
1306
David Benjamin30789da2015-08-29 22:56:45 -04001307 // Consume a close_notify from the peer if one hasn't been received
1308 // already. This avoids the peer from failing |SSL_shutdown| due to a
1309 // write failing.
1310 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1311 for c.in.error() == nil {
1312 c.readRecord(recordTypeAlert)
1313 }
1314 if c.in.error() != io.EOF {
1315 alertErr = c.in.error()
1316 }
1317 }
1318
Adam Langley95c29f32014-06-20 12:00:00 -07001319 if err := c.conn.Close(); err != nil {
1320 return err
1321 }
1322 return alertErr
1323}
1324
1325// Handshake runs the client or server handshake
1326// protocol if it has not yet been run.
1327// Most uses of this package need not call Handshake
1328// explicitly: the first Read or Write will call it automatically.
1329func (c *Conn) Handshake() error {
1330 c.handshakeMutex.Lock()
1331 defer c.handshakeMutex.Unlock()
1332 if err := c.handshakeErr; err != nil {
1333 return err
1334 }
1335 if c.handshakeComplete {
1336 return nil
1337 }
1338
David Benjamin9a41d1b2015-05-16 01:30:09 -04001339 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1340 c.conn.Write([]byte{
1341 byte(recordTypeAlert), // type
1342 0xfe, 0xff, // version
1343 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1344 0x0, 0x2, // length
1345 })
1346 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1347 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001348 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1349 c.writeRecord(recordTypeApplicationData, data)
1350 }
Adam Langley95c29f32014-06-20 12:00:00 -07001351 if c.isClient {
1352 c.handshakeErr = c.clientHandshake()
1353 } else {
1354 c.handshakeErr = c.serverHandshake()
1355 }
David Benjaminddb9f152015-02-03 15:44:39 -05001356 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1357 c.writeRecord(recordType(42), []byte("invalid record"))
1358 }
Adam Langley95c29f32014-06-20 12:00:00 -07001359 return c.handshakeErr
1360}
1361
1362// ConnectionState returns basic TLS details about the connection.
1363func (c *Conn) ConnectionState() ConnectionState {
1364 c.handshakeMutex.Lock()
1365 defer c.handshakeMutex.Unlock()
1366
1367 var state ConnectionState
1368 state.HandshakeComplete = c.handshakeComplete
1369 if c.handshakeComplete {
1370 state.Version = c.vers
1371 state.NegotiatedProtocol = c.clientProtocol
1372 state.DidResume = c.didResume
1373 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001374 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001375 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001376 state.PeerCertificates = c.peerCertificates
1377 state.VerifiedChains = c.verifiedChains
1378 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001379 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001380 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001381 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001382 state.SCTList = c.sctList
Steven Valdez0d62f262015-09-04 12:41:04 -04001383 state.ClientCertSignatureHash = c.clientCertSignatureHash
Adam Langley95c29f32014-06-20 12:00:00 -07001384 }
1385
1386 return state
1387}
1388
1389// OCSPResponse returns the stapled OCSP response from the TLS server, if
1390// any. (Only valid for client connections.)
1391func (c *Conn) OCSPResponse() []byte {
1392 c.handshakeMutex.Lock()
1393 defer c.handshakeMutex.Unlock()
1394
1395 return c.ocspResponse
1396}
1397
1398// VerifyHostname checks that the peer certificate chain is valid for
1399// connecting to host. If so, it returns nil; if not, it returns an error
1400// describing the problem.
1401func (c *Conn) VerifyHostname(host string) error {
1402 c.handshakeMutex.Lock()
1403 defer c.handshakeMutex.Unlock()
1404 if !c.isClient {
1405 return errors.New("tls: VerifyHostname called on TLS server connection")
1406 }
1407 if !c.handshakeComplete {
1408 return errors.New("tls: handshake has not yet been performed")
1409 }
1410 return c.peerCertificates[0].VerifyHostname(host)
1411}
David Benjaminc565ebb2015-04-03 04:06:36 -04001412
1413// ExportKeyingMaterial exports keying material from the current connection
1414// state, as per RFC 5705.
1415func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1416 c.handshakeMutex.Lock()
1417 defer c.handshakeMutex.Unlock()
1418 if !c.handshakeComplete {
1419 return nil, errors.New("tls: handshake has not yet been performed")
1420 }
1421
1422 seedLen := len(c.clientRandom) + len(c.serverRandom)
1423 if useContext {
1424 seedLen += 2 + len(context)
1425 }
1426 seed := make([]byte, 0, seedLen)
1427 seed = append(seed, c.clientRandom[:]...)
1428 seed = append(seed, c.serverRandom[:]...)
1429 if useContext {
1430 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1431 seed = append(seed, context...)
1432 }
1433 result := make([]byte, length)
1434 prfForVersion(c.vers, c.cipherSuite)(result, c.masterSecret[:], label, seed)
1435 return result, nil
1436}
David Benjamin3e052de2015-11-25 20:10:31 -05001437
1438// noRenegotiationInfo returns true if the renegotiation info extension
1439// should be supported in the current handshake.
1440func (c *Conn) noRenegotiationInfo() bool {
1441 if c.config.Bugs.NoRenegotiationInfo {
1442 return true
1443 }
1444 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1445 return true
1446 }
1447 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1448 return true
1449 }
1450 return false
1451}