blob: e8f68575292378869aa482c4bbae38e0ab0570cf [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
Nick Harper1fd39d82016-06-14 18:14:35 -0700348// order to get the application payload, the encrypted record type (or 0
349// if there is none), and an optional alert value.
350func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, contentType recordType, alertValue alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400351 recordHeaderLen := hc.recordHeaderLen()
352
Adam Langley95c29f32014-06-20 12:00:00 -0700353 // pull out payload
354 payload := b.data[recordHeaderLen:]
355
356 macSize := 0
357 if hc.mac != nil {
358 macSize = hc.mac.Size()
359 }
360
361 paddingGood := byte(255)
362 explicitIVLen := 0
363
David Benjamin83c0bc92014-08-04 01:23:53 -0400364 seq := hc.seq[:]
365 if hc.isDTLS {
366 // DTLS sequence numbers are explicit.
367 seq = b.data[3:11]
368 }
369
Adam Langley95c29f32014-06-20 12:00:00 -0700370 // decrypt
371 if hc.cipher != nil {
372 switch c := hc.cipher.(type) {
373 case cipher.Stream:
374 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400375 case *tlsAead:
376 nonce := seq
377 if c.explicitNonce {
378 explicitIVLen = 8
379 if len(payload) < explicitIVLen {
Nick Harper1fd39d82016-06-14 18:14:35 -0700380 return false, 0, 0, alertBadRecordMAC
David Benjamine9a80ff2015-04-07 00:46:46 -0400381 }
382 nonce = payload[:8]
383 payload = payload[8:]
Adam Langley95c29f32014-06-20 12:00:00 -0700384 }
Adam Langley95c29f32014-06-20 12:00:00 -0700385
Nick Harper1fd39d82016-06-14 18:14:35 -0700386 var additionalData []byte
387 if hc.version < VersionTLS13 {
388 additionalData = make([]byte, 13)
389 copy(additionalData, seq)
390 copy(additionalData[8:], b.data[:3])
391 n := len(payload) - c.Overhead()
392 additionalData[11] = byte(n >> 8)
393 additionalData[12] = byte(n)
394 }
Adam Langley95c29f32014-06-20 12:00:00 -0700395 var err error
Nick Harper1fd39d82016-06-14 18:14:35 -0700396 payload, err = c.Open(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700397 if err != nil {
Nick Harper1fd39d82016-06-14 18:14:35 -0700398 return false, 0, 0, alertBadRecordMAC
399 }
400 if hc.version >= VersionTLS13 {
401 i := len(payload)
402 for i > 0 && payload[i-1] == 0 {
403 i--
404 }
405 payload = payload[:i]
406 if len(payload) == 0 {
407 return false, 0, 0, alertUnexpectedMessage
408 }
409 contentType = recordType(payload[len(payload)-1])
410 payload = payload[:len(payload)-1]
Adam Langley95c29f32014-06-20 12:00:00 -0700411 }
412 b.resize(recordHeaderLen + explicitIVLen + len(payload))
413 case cbcMode:
414 blockSize := c.BlockSize()
David Benjamin83c0bc92014-08-04 01:23:53 -0400415 if hc.version >= VersionTLS11 || hc.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700416 explicitIVLen = blockSize
417 }
418
419 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
Nick Harper1fd39d82016-06-14 18:14:35 -0700420 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700421 }
422
423 if explicitIVLen > 0 {
424 c.SetIV(payload[:explicitIVLen])
425 payload = payload[explicitIVLen:]
426 }
427 c.CryptBlocks(payload, payload)
428 if hc.version == VersionSSL30 {
429 payload, paddingGood = removePaddingSSL30(payload)
430 } else {
431 payload, paddingGood = removePadding(payload)
432 }
433 b.resize(recordHeaderLen + explicitIVLen + len(payload))
434
435 // note that we still have a timing side-channel in the
436 // MAC check, below. An attacker can align the record
437 // so that a correct padding will cause one less hash
438 // block to be calculated. Then they can iteratively
439 // decrypt a record by breaking each byte. See
440 // "Password Interception in a SSL/TLS Channel", Brice
441 // Canvel et al.
442 //
443 // However, our behavior matches OpenSSL, so we leak
444 // only as much as they do.
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700445 case nullCipher:
446 break
Adam Langley95c29f32014-06-20 12:00:00 -0700447 default:
448 panic("unknown cipher type")
449 }
450 }
451
452 // check, strip mac
453 if hc.mac != nil {
454 if len(payload) < macSize {
Nick Harper1fd39d82016-06-14 18:14:35 -0700455 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700456 }
457
458 // strip mac off payload, b.data
459 n := len(payload) - macSize
David Benjamin83c0bc92014-08-04 01:23:53 -0400460 b.data[recordHeaderLen-2] = byte(n >> 8)
461 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700462 b.resize(recordHeaderLen + explicitIVLen + n)
463 remoteMAC := payload[n:]
David Benjamin83c0bc92014-08-04 01:23:53 -0400464 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
Adam Langley95c29f32014-06-20 12:00:00 -0700465
466 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
Nick Harper1fd39d82016-06-14 18:14:35 -0700467 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700468 }
469 hc.inDigestBuf = localMAC
470 }
David Benjamin5e961c12014-11-07 01:48:35 -0500471 hc.incSeq(false)
Adam Langley95c29f32014-06-20 12:00:00 -0700472
Nick Harper1fd39d82016-06-14 18:14:35 -0700473 return true, recordHeaderLen + explicitIVLen, contentType, 0
Adam Langley95c29f32014-06-20 12:00:00 -0700474}
475
476// padToBlockSize calculates the needed padding block, if any, for a payload.
477// On exit, prefix aliases payload and extends to the end of the last full
478// block of payload. finalBlock is a fresh slice which contains the contents of
479// any suffix of payload as well as the needed padding to make finalBlock a
480// full block.
Adam Langley80842bd2014-06-20 12:00:00 -0700481func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
Adam Langley95c29f32014-06-20 12:00:00 -0700482 overrun := len(payload) % blockSize
Adam Langley95c29f32014-06-20 12:00:00 -0700483 prefix = payload[:len(payload)-overrun]
Adam Langley80842bd2014-06-20 12:00:00 -0700484
485 paddingLen := blockSize - overrun
486 finalSize := blockSize
487 if config.Bugs.MaxPadding {
488 for paddingLen+blockSize <= 256 {
489 paddingLen += blockSize
490 }
491 finalSize = 256
492 }
493 finalBlock = make([]byte, finalSize)
494 for i := range finalBlock {
Adam Langley95c29f32014-06-20 12:00:00 -0700495 finalBlock[i] = byte(paddingLen - 1)
496 }
Adam Langley80842bd2014-06-20 12:00:00 -0700497 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
498 finalBlock[overrun] ^= 0xff
499 }
500 copy(finalBlock, payload[len(payload)-overrun:])
Adam Langley95c29f32014-06-20 12:00:00 -0700501 return
502}
503
504// encrypt encrypts and macs the data in b.
Nick Harper1fd39d82016-06-14 18:14:35 -0700505func (hc *halfConn) encrypt(b *block, explicitIVLen int, typ recordType) (bool, alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400506 recordHeaderLen := hc.recordHeaderLen()
507
Adam Langley95c29f32014-06-20 12:00:00 -0700508 // mac
509 if hc.mac != nil {
David Benjamin8e6db492015-07-25 18:29:23 -0400510 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 -0700511
512 n := len(b.data)
513 b.resize(n + len(mac))
514 copy(b.data[n:], mac)
515 hc.outDigestBuf = mac
516 }
517
518 payload := b.data[recordHeaderLen:]
519
520 // encrypt
521 if hc.cipher != nil {
522 switch c := hc.cipher.(type) {
523 case cipher.Stream:
524 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400525 case *tlsAead:
Adam Langley95c29f32014-06-20 12:00:00 -0700526 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
David Benjaminc9ae27c2016-06-24 22:56:37 -0400527 paddingLen := 0
Nick Harper1fd39d82016-06-14 18:14:35 -0700528 if hc.version >= VersionTLS13 {
David Benjaminc9ae27c2016-06-24 22:56:37 -0400529 payloadLen++
530 paddingLen = hc.config.Bugs.RecordPadding
531 }
532 if hc.config.Bugs.OmitRecordContents {
533 payloadLen = 0
534 }
535 b.resize(recordHeaderLen + explicitIVLen + payloadLen + paddingLen + c.Overhead())
536 if hc.version >= VersionTLS13 {
537 if !hc.config.Bugs.OmitRecordContents {
538 b.data[payloadLen+recordHeaderLen-1] = byte(typ)
539 }
540 for i := 0; i < hc.config.Bugs.RecordPadding; i++ {
541 b.data[payloadLen+recordHeaderLen+i] = 0
542 }
543 payloadLen += paddingLen
Nick Harper1fd39d82016-06-14 18:14:35 -0700544 }
David Benjamin8e6db492015-07-25 18:29:23 -0400545 nonce := hc.outSeq[:]
David Benjamine9a80ff2015-04-07 00:46:46 -0400546 if c.explicitNonce {
547 nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
548 }
Adam Langley95c29f32014-06-20 12:00:00 -0700549 payload := b.data[recordHeaderLen+explicitIVLen:]
550 payload = payload[:payloadLen]
551
Nick Harper1fd39d82016-06-14 18:14:35 -0700552 var additionalData []byte
553 if hc.version < VersionTLS13 {
554 additionalData = make([]byte, 13)
555 copy(additionalData, hc.outSeq[:])
556 copy(additionalData[8:], b.data[:3])
557 additionalData[11] = byte(payloadLen >> 8)
558 additionalData[12] = byte(payloadLen)
559 }
Adam Langley95c29f32014-06-20 12:00:00 -0700560
Nick Harper1fd39d82016-06-14 18:14:35 -0700561 c.Seal(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700562 case cbcMode:
563 blockSize := c.BlockSize()
564 if explicitIVLen > 0 {
565 c.SetIV(payload[:explicitIVLen])
566 payload = payload[explicitIVLen:]
567 }
Adam Langley80842bd2014-06-20 12:00:00 -0700568 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700569 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
570 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
571 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700572 case nullCipher:
573 break
Adam Langley95c29f32014-06-20 12:00:00 -0700574 default:
575 panic("unknown cipher type")
576 }
577 }
578
579 // update length to include MAC and any block padding needed.
580 n := len(b.data) - recordHeaderLen
David Benjamin83c0bc92014-08-04 01:23:53 -0400581 b.data[recordHeaderLen-2] = byte(n >> 8)
582 b.data[recordHeaderLen-1] = byte(n)
David Benjamin5e961c12014-11-07 01:48:35 -0500583 hc.incSeq(true)
Adam Langley95c29f32014-06-20 12:00:00 -0700584
585 return true, 0
586}
587
588// A block is a simple data buffer.
589type block struct {
590 data []byte
591 off int // index for Read
592 link *block
593}
594
595// resize resizes block to be n bytes, growing if necessary.
596func (b *block) resize(n int) {
597 if n > cap(b.data) {
598 b.reserve(n)
599 }
600 b.data = b.data[0:n]
601}
602
603// reserve makes sure that block contains a capacity of at least n bytes.
604func (b *block) reserve(n int) {
605 if cap(b.data) >= n {
606 return
607 }
608 m := cap(b.data)
609 if m == 0 {
610 m = 1024
611 }
612 for m < n {
613 m *= 2
614 }
615 data := make([]byte, len(b.data), m)
616 copy(data, b.data)
617 b.data = data
618}
619
620// readFromUntil reads from r into b until b contains at least n bytes
621// or else returns an error.
622func (b *block) readFromUntil(r io.Reader, n int) error {
623 // quick case
624 if len(b.data) >= n {
625 return nil
626 }
627
628 // read until have enough.
629 b.reserve(n)
630 for {
631 m, err := r.Read(b.data[len(b.data):cap(b.data)])
632 b.data = b.data[0 : len(b.data)+m]
633 if len(b.data) >= n {
634 // TODO(bradfitz,agl): slightly suspicious
635 // that we're throwing away r.Read's err here.
636 break
637 }
638 if err != nil {
639 return err
640 }
641 }
642 return nil
643}
644
645func (b *block) Read(p []byte) (n int, err error) {
646 n = copy(p, b.data[b.off:])
647 b.off += n
648 return
649}
650
651// newBlock allocates a new block, from hc's free list if possible.
652func (hc *halfConn) newBlock() *block {
653 b := hc.bfree
654 if b == nil {
655 return new(block)
656 }
657 hc.bfree = b.link
658 b.link = nil
659 b.resize(0)
660 return b
661}
662
663// freeBlock returns a block to hc's free list.
664// The protocol is such that each side only has a block or two on
665// its free list at a time, so there's no need to worry about
666// trimming the list, etc.
667func (hc *halfConn) freeBlock(b *block) {
668 b.link = hc.bfree
669 hc.bfree = b
670}
671
672// splitBlock splits a block after the first n bytes,
673// returning a block with those n bytes and a
674// block with the remainder. the latter may be nil.
675func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
676 if len(b.data) <= n {
677 return b, nil
678 }
679 bb := hc.newBlock()
680 bb.resize(len(b.data) - n)
681 copy(bb.data, b.data[n:])
682 b.data = b.data[0:n]
683 return b, bb
684}
685
David Benjamin83c0bc92014-08-04 01:23:53 -0400686func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
687 if c.isDTLS {
688 return c.dtlsDoReadRecord(want)
689 }
690
691 recordHeaderLen := tlsRecordHeaderLen
692
693 if c.rawInput == nil {
694 c.rawInput = c.in.newBlock()
695 }
696 b := c.rawInput
697
698 // Read header, payload.
699 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
700 // RFC suggests that EOF without an alertCloseNotify is
701 // an error, but popular web sites seem to do this,
David Benjamin30789da2015-08-29 22:56:45 -0400702 // so we can't make it an error, outside of tests.
703 if err == io.EOF && c.config.Bugs.ExpectCloseNotify {
704 err = io.ErrUnexpectedEOF
705 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400706 if e, ok := err.(net.Error); !ok || !e.Temporary() {
707 c.in.setErrorLocked(err)
708 }
709 return 0, nil, err
710 }
711 typ := recordType(b.data[0])
712
713 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
714 // start with a uint16 length where the MSB is set and the first record
715 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
716 // an SSLv2 client.
717 if want == recordTypeHandshake && typ == 0x80 {
718 c.sendAlert(alertProtocolVersion)
719 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
720 }
721
722 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
723 n := int(b.data[3])<<8 | int(b.data[4])
David Benjaminbde00392016-06-21 12:19:28 -0400724 // Alerts sent near version negotiation do not have a well-defined
725 // record-layer version prior to TLS 1.3. (In TLS 1.3, the record-layer
726 // version is irrelevant.)
727 if typ != recordTypeAlert {
728 if c.haveVers {
729 if vers != c.vers && c.vers < VersionTLS13 {
730 c.sendAlert(alertProtocolVersion)
731 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers))
732 }
733 } else {
734 if expect := c.config.Bugs.ExpectInitialRecordVersion; expect != 0 && vers != expect {
735 c.sendAlert(alertProtocolVersion)
736 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
737 }
David Benjamin1e29a6b2014-12-10 02:27:24 -0500738 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400739 }
740 if n > maxCiphertext {
741 c.sendAlert(alertRecordOverflow)
742 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
743 }
744 if !c.haveVers {
745 // First message, be extra suspicious:
746 // this might not be a TLS client.
747 // Bail out before reading a full 'body', if possible.
748 // The current max version is 3.1.
749 // If the version is >= 16.0, it's probably not real.
750 // Similarly, a clientHello message encodes in
751 // well under a kilobyte. If the length is >= 12 kB,
752 // it's probably not real.
753 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
754 c.sendAlert(alertUnexpectedMessage)
755 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
756 }
757 }
758 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
759 if err == io.EOF {
760 err = io.ErrUnexpectedEOF
761 }
762 if e, ok := err.(net.Error); !ok || !e.Temporary() {
763 c.in.setErrorLocked(err)
764 }
765 return 0, nil, err
766 }
767
768 // Process message.
769 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
Nick Harper1fd39d82016-06-14 18:14:35 -0700770 ok, off, encTyp, err := c.in.decrypt(b)
771 if c.vers >= VersionTLS13 && c.in.cipher != nil {
David Benjaminc9ae27c2016-06-24 22:56:37 -0400772 if typ != recordTypeApplicationData {
773 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: outer record type is not application data"))
774 }
Nick Harper1fd39d82016-06-14 18:14:35 -0700775 typ = encTyp
776 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400777 if !ok {
778 c.in.setErrorLocked(c.sendAlert(err))
779 }
780 b.off = off
781 return typ, b, nil
782}
783
Adam Langley95c29f32014-06-20 12:00:00 -0700784// readRecord reads the next TLS record from the connection
785// and updates the record layer state.
786// c.in.Mutex <= L; c.input == nil.
787func (c *Conn) readRecord(want recordType) error {
788 // Caller must be in sync with connection:
789 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700790 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700791 switch want {
792 default:
793 c.sendAlert(alertInternalError)
794 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
795 case recordTypeHandshake, recordTypeChangeCipherSpec:
796 if c.handshakeComplete {
797 c.sendAlert(alertInternalError)
798 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
799 }
800 case recordTypeApplicationData:
David Benjamine58c4f52014-08-24 03:47:07 -0400801 if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart {
Adam Langley95c29f32014-06-20 12:00:00 -0700802 c.sendAlert(alertInternalError)
803 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
804 }
David Benjamin30789da2015-08-29 22:56:45 -0400805 case recordTypeAlert:
806 // Looking for a close_notify. Note: unlike a real
807 // implementation, this is not tolerant of additional records.
808 // See the documentation for ExpectCloseNotify.
Adam Langley95c29f32014-06-20 12:00:00 -0700809 }
810
811Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400812 typ, b, err := c.doReadRecord(want)
813 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700814 return err
815 }
Adam Langley95c29f32014-06-20 12:00:00 -0700816 data := b.data[b.off:]
817 if len(data) > maxPlaintext {
818 err := c.sendAlert(alertRecordOverflow)
819 c.in.freeBlock(b)
820 return c.in.setErrorLocked(err)
821 }
822
823 switch typ {
824 default:
825 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
826
827 case recordTypeAlert:
828 if len(data) != 2 {
829 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
830 break
831 }
832 if alert(data[1]) == alertCloseNotify {
833 c.in.setErrorLocked(io.EOF)
834 break
835 }
836 switch data[0] {
837 case alertLevelWarning:
838 // drop on the floor
839 c.in.freeBlock(b)
840 goto Again
841 case alertLevelError:
842 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
843 default:
844 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
845 }
846
847 case recordTypeChangeCipherSpec:
848 if typ != want || len(data) != 1 || data[0] != 1 {
849 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
850 break
851 }
Adam Langley80842bd2014-06-20 12:00:00 -0700852 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700853 if err != nil {
854 c.in.setErrorLocked(c.sendAlert(err.(alert)))
855 }
856
857 case recordTypeApplicationData:
858 if typ != want {
859 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
860 break
861 }
862 c.input = b
863 b = nil
864
865 case recordTypeHandshake:
866 // TODO(rsc): Should at least pick off connection close.
867 if typ != want {
Adam Langley2ae77d22014-10-28 17:29:33 -0700868 // A client might need to process a HelloRequest from
869 // the server, thus receiving a handshake message when
David Benjamind9b091b2015-01-27 01:10:54 -0500870 // application data is expected is ok.
David Benjamin30789da2015-08-29 22:56:45 -0400871 if !c.isClient || want != recordTypeApplicationData {
Adam Langley2ae77d22014-10-28 17:29:33 -0700872 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
873 }
Adam Langley95c29f32014-06-20 12:00:00 -0700874 }
875 c.hand.Write(data)
876 }
877
878 if b != nil {
879 c.in.freeBlock(b)
880 }
881 return c.in.err
882}
883
884// sendAlert sends a TLS alert message.
885// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400886func (c *Conn) sendAlertLocked(level byte, err alert) error {
887 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700888 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400889 if c.config.Bugs.FragmentAlert {
890 c.writeRecord(recordTypeAlert, c.tmp[0:1])
891 c.writeRecord(recordTypeAlert, c.tmp[1:2])
David Benjamin0d3a8c62016-03-11 22:25:18 -0500892 } else if c.config.Bugs.DoubleAlert {
893 copy(c.tmp[2:4], c.tmp[0:2])
894 c.writeRecord(recordTypeAlert, c.tmp[0:4])
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400895 } else {
896 c.writeRecord(recordTypeAlert, c.tmp[0:2])
897 }
David Benjamin24f346d2015-06-06 03:28:08 -0400898 // Error alerts are fatal to the connection.
899 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700900 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
901 }
902 return nil
903}
904
905// sendAlert sends a TLS alert message.
906// L < c.out.Mutex.
907func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400908 level := byte(alertLevelError)
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500909 if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertficate {
David Benjamin24f346d2015-06-06 03:28:08 -0400910 level = alertLevelWarning
911 }
912 return c.SendAlert(level, err)
913}
914
915func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700916 c.out.Lock()
917 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -0400918 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -0700919}
920
David Benjamind86c7672014-08-02 04:07:12 -0400921// writeV2Record writes a record for a V2ClientHello.
922func (c *Conn) writeV2Record(data []byte) (n int, err error) {
923 record := make([]byte, 2+len(data))
924 record[0] = uint8(len(data)>>8) | 0x80
925 record[1] = uint8(len(data))
926 copy(record[2:], data)
927 return c.conn.Write(record)
928}
929
Adam Langley95c29f32014-06-20 12:00:00 -0700930// writeRecord writes a TLS record with the given type and payload
931// to the connection and updates the record layer state.
932// c.out.Mutex <= L.
933func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400934 if c.isDTLS {
935 return c.dtlsWriteRecord(typ, data)
936 }
937
938 recordHeaderLen := tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700939 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -0400940 first := true
941 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -0400942 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -0700943 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -0400944 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -0700945 m = maxPlaintext
946 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400947 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
948 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -0400949 // By default, do not fragment the client_version or
950 // server_version, which are located in the first 6
951 // bytes.
952 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
953 m = 6
954 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400955 }
Adam Langley95c29f32014-06-20 12:00:00 -0700956 explicitIVLen := 0
957 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -0400958 first = false
Adam Langley95c29f32014-06-20 12:00:00 -0700959
960 var cbc cbcMode
961 if c.out.version >= VersionTLS11 {
962 var ok bool
963 if cbc, ok = c.out.cipher.(cbcMode); ok {
964 explicitIVLen = cbc.BlockSize()
965 }
966 }
967 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -0400968 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -0700969 explicitIVLen = 8
970 // The AES-GCM construction in TLS has an
971 // explicit nonce so that the nonce can be
972 // random. However, the nonce is only 8 bytes
973 // which is too small for a secure, random
974 // nonce. Therefore we use the sequence number
975 // as the nonce.
976 explicitIVIsSeq = true
977 }
978 }
979 b.resize(recordHeaderLen + explicitIVLen + m)
980 b.data[0] = byte(typ)
Nick Harper1fd39d82016-06-14 18:14:35 -0700981 if c.vers >= VersionTLS13 && c.out.cipher != nil {
Nick Harper1fd39d82016-06-14 18:14:35 -0700982 b.data[0] = byte(recordTypeApplicationData)
David Benjaminc9ae27c2016-06-24 22:56:37 -0400983 if outerType := c.config.Bugs.OuterRecordType; outerType != 0 {
984 b.data[0] = byte(outerType)
985 }
Nick Harper1fd39d82016-06-14 18:14:35 -0700986 }
Adam Langley95c29f32014-06-20 12:00:00 -0700987 vers := c.vers
Nick Harper1fd39d82016-06-14 18:14:35 -0700988 if vers == 0 || vers >= VersionTLS13 {
Adam Langley95c29f32014-06-20 12:00:00 -0700989 // Some TLS servers fail if the record version is
990 // greater than TLS 1.0 for the initial ClientHello.
Nick Harper1fd39d82016-06-14 18:14:35 -0700991 //
992 // TLS 1.3 fixes the version number in the record
993 // layer to {3, 1}.
Adam Langley95c29f32014-06-20 12:00:00 -0700994 vers = VersionTLS10
995 }
996 b.data[1] = byte(vers >> 8)
997 b.data[2] = byte(vers)
998 b.data[3] = byte(m >> 8)
999 b.data[4] = byte(m)
1000 if explicitIVLen > 0 {
1001 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
1002 if explicitIVIsSeq {
1003 copy(explicitIV, c.out.seq[:])
1004 } else {
1005 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
1006 break
1007 }
1008 }
1009 }
1010 copy(b.data[recordHeaderLen+explicitIVLen:], data)
Nick Harper1fd39d82016-06-14 18:14:35 -07001011 c.out.encrypt(b, explicitIVLen, typ)
Adam Langley95c29f32014-06-20 12:00:00 -07001012 _, err = c.conn.Write(b.data)
1013 if err != nil {
1014 break
1015 }
1016 n += m
1017 data = data[m:]
1018 }
1019 c.out.freeBlock(b)
1020
1021 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -07001022 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -07001023 if err != nil {
1024 // Cannot call sendAlert directly,
1025 // because we already hold c.out.Mutex.
1026 c.tmp[0] = alertLevelError
1027 c.tmp[1] = byte(err.(alert))
1028 c.writeRecord(recordTypeAlert, c.tmp[0:2])
1029 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
1030 }
1031 }
1032 return
1033}
1034
David Benjamin83c0bc92014-08-04 01:23:53 -04001035func (c *Conn) doReadHandshake() ([]byte, error) {
1036 if c.isDTLS {
1037 return c.dtlsDoReadHandshake()
1038 }
1039
Adam Langley95c29f32014-06-20 12:00:00 -07001040 for c.hand.Len() < 4 {
1041 if err := c.in.err; err != nil {
1042 return nil, err
1043 }
1044 if err := c.readRecord(recordTypeHandshake); err != nil {
1045 return nil, err
1046 }
1047 }
1048
1049 data := c.hand.Bytes()
1050 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1051 if n > maxHandshake {
1052 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
1053 }
1054 for c.hand.Len() < 4+n {
1055 if err := c.in.err; err != nil {
1056 return nil, err
1057 }
1058 if err := c.readRecord(recordTypeHandshake); err != nil {
1059 return nil, err
1060 }
1061 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001062 return c.hand.Next(4 + n), nil
1063}
1064
1065// readHandshake reads the next handshake message from
1066// the record layer.
1067// c.in.Mutex < L; c.out.Mutex < L.
1068func (c *Conn) readHandshake() (interface{}, error) {
1069 data, err := c.doReadHandshake()
1070 if err != nil {
1071 return nil, err
1072 }
1073
Adam Langley95c29f32014-06-20 12:00:00 -07001074 var m handshakeMessage
1075 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001076 case typeHelloRequest:
1077 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001078 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001079 m = &clientHelloMsg{
1080 isDTLS: c.isDTLS,
1081 }
Adam Langley95c29f32014-06-20 12:00:00 -07001082 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001083 m = &serverHelloMsg{
1084 isDTLS: c.isDTLS,
1085 }
Adam Langley95c29f32014-06-20 12:00:00 -07001086 case typeNewSessionTicket:
1087 m = new(newSessionTicketMsg)
1088 case typeCertificate:
1089 m = new(certificateMsg)
1090 case typeCertificateRequest:
1091 m = &certificateRequestMsg{
1092 hasSignatureAndHash: c.vers >= VersionTLS12,
1093 }
1094 case typeCertificateStatus:
1095 m = new(certificateStatusMsg)
1096 case typeServerKeyExchange:
1097 m = new(serverKeyExchangeMsg)
1098 case typeServerHelloDone:
1099 m = new(serverHelloDoneMsg)
1100 case typeClientKeyExchange:
1101 m = new(clientKeyExchangeMsg)
1102 case typeCertificateVerify:
1103 m = &certificateVerifyMsg{
1104 hasSignatureAndHash: c.vers >= VersionTLS12,
1105 }
1106 case typeNextProtocol:
1107 m = new(nextProtoMsg)
1108 case typeFinished:
1109 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001110 case typeHelloVerifyRequest:
1111 m = new(helloVerifyRequestMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001112 case typeEncryptedExtensions:
1113 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001114 default:
1115 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1116 }
1117
1118 // The handshake message unmarshallers
1119 // expect to be able to keep references to data,
1120 // so pass in a fresh copy that won't be overwritten.
1121 data = append([]byte(nil), data...)
1122
1123 if !m.unmarshal(data) {
1124 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1125 }
1126 return m, nil
1127}
1128
David Benjamin83f90402015-01-27 01:09:43 -05001129// skipPacket processes all the DTLS records in packet. It updates
1130// sequence number expectations but otherwise ignores them.
1131func (c *Conn) skipPacket(packet []byte) error {
1132 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001133 if len(packet) < 13 {
1134 return errors.New("tls: bad packet")
1135 }
David Benjamin83f90402015-01-27 01:09:43 -05001136 // Dropped packets are completely ignored save to update
1137 // expected sequence numbers for this and the next epoch. (We
1138 // don't assert on the contents of the packets both for
1139 // simplicity and because a previous test with one shorter
1140 // timeout schedule would have done so.)
1141 epoch := packet[3:5]
1142 seq := packet[5:11]
1143 length := uint16(packet[11])<<8 | uint16(packet[12])
1144 if bytes.Equal(c.in.seq[:2], epoch) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001145 if bytes.Compare(seq, c.in.seq[2:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001146 return errors.New("tls: sequence mismatch")
1147 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001148 copy(c.in.seq[2:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001149 c.in.incSeq(false)
1150 } else {
David Benjamin13e81fc2015-11-02 17:16:13 -05001151 if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001152 return errors.New("tls: sequence mismatch")
1153 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001154 copy(c.in.nextSeq[:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001155 c.in.incNextSeq()
1156 }
David Benjamin6ca93552015-08-28 16:16:25 -04001157 if len(packet) < 13+int(length) {
1158 return errors.New("tls: bad packet")
1159 }
David Benjamin83f90402015-01-27 01:09:43 -05001160 packet = packet[13+length:]
1161 }
1162 return nil
1163}
1164
1165// simulatePacketLoss simulates the loss of a handshake leg from the
1166// peer based on the schedule in c.config.Bugs. If resendFunc is
1167// non-nil, it is called after each simulated timeout to retransmit
1168// handshake messages from the local end. This is used in cases where
1169// the peer retransmits on a stale Finished rather than a timeout.
1170func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1171 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1172 return nil
1173 }
1174 if !c.isDTLS {
1175 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1176 }
1177 if c.config.Bugs.PacketAdaptor == nil {
1178 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1179 }
1180 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1181 // Simulate a timeout.
1182 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1183 if err != nil {
1184 return err
1185 }
1186 for _, packet := range packets {
1187 if err := c.skipPacket(packet); err != nil {
1188 return err
1189 }
1190 }
1191 if resendFunc != nil {
1192 resendFunc()
1193 }
1194 }
1195 return nil
1196}
1197
Adam Langley95c29f32014-06-20 12:00:00 -07001198// Write writes data to the connection.
1199func (c *Conn) Write(b []byte) (int, error) {
1200 if err := c.Handshake(); err != nil {
1201 return 0, err
1202 }
1203
1204 c.out.Lock()
1205 defer c.out.Unlock()
1206
1207 if err := c.out.err; err != nil {
1208 return 0, err
1209 }
1210
1211 if !c.handshakeComplete {
1212 return 0, alertInternalError
1213 }
1214
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001215 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001216 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001217 }
1218
Adam Langley27a0d082015-11-03 13:34:10 -08001219 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1220 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
1221 }
1222
Adam Langley95c29f32014-06-20 12:00:00 -07001223 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1224 // attack when using block mode ciphers due to predictable IVs.
1225 // This can be prevented by splitting each Application Data
1226 // record into two records, effectively randomizing the IV.
1227 //
1228 // http://www.openssl.org/~bodo/tls-cbc.txt
1229 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1230 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1231
1232 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001233 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001234 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1235 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1236 if err != nil {
1237 return n, c.out.setErrorLocked(err)
1238 }
1239 m, b = 1, b[1:]
1240 }
1241 }
1242
1243 n, err := c.writeRecord(recordTypeApplicationData, b)
1244 return n + m, c.out.setErrorLocked(err)
1245}
1246
Adam Langley2ae77d22014-10-28 17:29:33 -07001247func (c *Conn) handleRenegotiation() error {
1248 c.handshakeComplete = false
1249 if !c.isClient {
1250 panic("renegotiation should only happen for a client")
1251 }
1252
1253 msg, err := c.readHandshake()
1254 if err != nil {
1255 return err
1256 }
1257 _, ok := msg.(*helloRequestMsg)
1258 if !ok {
1259 c.sendAlert(alertUnexpectedMessage)
1260 return alertUnexpectedMessage
1261 }
1262
1263 return c.Handshake()
1264}
1265
Adam Langleycf2d4f42014-10-28 19:06:14 -07001266func (c *Conn) Renegotiate() error {
1267 if !c.isClient {
David Benjaminef5dfd22015-12-06 13:17:07 -05001268 helloReq := new(helloRequestMsg).marshal()
1269 if c.config.Bugs.BadHelloRequest != nil {
1270 helloReq = c.config.Bugs.BadHelloRequest
1271 }
1272 c.writeRecord(recordTypeHandshake, helloReq)
Adam Langleycf2d4f42014-10-28 19:06:14 -07001273 }
1274
1275 c.handshakeComplete = false
1276 return c.Handshake()
1277}
1278
Adam Langley95c29f32014-06-20 12:00:00 -07001279// Read can be made to time out and return a net.Error with Timeout() == true
1280// after a fixed time limit; see SetDeadline and SetReadDeadline.
1281func (c *Conn) Read(b []byte) (n int, err error) {
1282 if err = c.Handshake(); err != nil {
1283 return
1284 }
1285
1286 c.in.Lock()
1287 defer c.in.Unlock()
1288
1289 // Some OpenSSL servers send empty records in order to randomize the
1290 // CBC IV. So this loop ignores a limited number of empty records.
1291 const maxConsecutiveEmptyRecords = 100
1292 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1293 for c.input == nil && c.in.err == nil {
1294 if err := c.readRecord(recordTypeApplicationData); err != nil {
1295 // Soft error, like EAGAIN
1296 return 0, err
1297 }
David Benjamind9b091b2015-01-27 01:10:54 -05001298 if c.hand.Len() > 0 {
Adam Langley2ae77d22014-10-28 17:29:33 -07001299 // We received handshake bytes, indicating the
David Benjamind9b091b2015-01-27 01:10:54 -05001300 // start of a renegotiation.
Adam Langley2ae77d22014-10-28 17:29:33 -07001301 if err := c.handleRenegotiation(); err != nil {
1302 return 0, err
1303 }
1304 continue
1305 }
Adam Langley95c29f32014-06-20 12:00:00 -07001306 }
1307 if err := c.in.err; err != nil {
1308 return 0, err
1309 }
1310
1311 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001312 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001313 c.in.freeBlock(c.input)
1314 c.input = nil
1315 }
1316
1317 // If a close-notify alert is waiting, read it so that
1318 // we can return (n, EOF) instead of (n, nil), to signal
1319 // to the HTTP response reading goroutine that the
1320 // connection is now closed. This eliminates a race
1321 // where the HTTP response reading goroutine would
1322 // otherwise not observe the EOF until its next read,
1323 // by which time a client goroutine might have already
1324 // tried to reuse the HTTP connection for a new
1325 // request.
1326 // See https://codereview.appspot.com/76400046
1327 // and http://golang.org/issue/3514
1328 if ri := c.rawInput; ri != nil &&
1329 n != 0 && err == nil &&
1330 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1331 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1332 err = recErr // will be io.EOF on closeNotify
1333 }
1334 }
1335
1336 if n != 0 || err != nil {
1337 return n, err
1338 }
1339 }
1340
1341 return 0, io.ErrNoProgress
1342}
1343
1344// Close closes the connection.
1345func (c *Conn) Close() error {
1346 var alertErr error
1347
1348 c.handshakeMutex.Lock()
1349 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001350 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
David Benjaminfa214e42016-05-10 17:03:10 -04001351 alert := alertCloseNotify
1352 if c.config.Bugs.SendAlertOnShutdown != 0 {
1353 alert = c.config.Bugs.SendAlertOnShutdown
1354 }
1355 alertErr = c.sendAlert(alert)
David Benjamin4d559612016-05-18 14:31:51 -04001356 // Clear local alerts when sending alerts so we continue to wait
1357 // for the peer rather than closing the socket early.
1358 if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1359 alertErr = nil
1360 }
Adam Langley95c29f32014-06-20 12:00:00 -07001361 }
1362
David Benjamin30789da2015-08-29 22:56:45 -04001363 // Consume a close_notify from the peer if one hasn't been received
1364 // already. This avoids the peer from failing |SSL_shutdown| due to a
1365 // write failing.
1366 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1367 for c.in.error() == nil {
1368 c.readRecord(recordTypeAlert)
1369 }
1370 if c.in.error() != io.EOF {
1371 alertErr = c.in.error()
1372 }
1373 }
1374
Adam Langley95c29f32014-06-20 12:00:00 -07001375 if err := c.conn.Close(); err != nil {
1376 return err
1377 }
1378 return alertErr
1379}
1380
1381// Handshake runs the client or server handshake
1382// protocol if it has not yet been run.
1383// Most uses of this package need not call Handshake
1384// explicitly: the first Read or Write will call it automatically.
1385func (c *Conn) Handshake() error {
1386 c.handshakeMutex.Lock()
1387 defer c.handshakeMutex.Unlock()
1388 if err := c.handshakeErr; err != nil {
1389 return err
1390 }
1391 if c.handshakeComplete {
1392 return nil
1393 }
1394
David Benjamin9a41d1b2015-05-16 01:30:09 -04001395 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1396 c.conn.Write([]byte{
1397 byte(recordTypeAlert), // type
1398 0xfe, 0xff, // version
1399 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1400 0x0, 0x2, // length
1401 })
1402 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1403 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001404 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1405 c.writeRecord(recordTypeApplicationData, data)
1406 }
Adam Langley95c29f32014-06-20 12:00:00 -07001407 if c.isClient {
1408 c.handshakeErr = c.clientHandshake()
1409 } else {
1410 c.handshakeErr = c.serverHandshake()
1411 }
David Benjaminddb9f152015-02-03 15:44:39 -05001412 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1413 c.writeRecord(recordType(42), []byte("invalid record"))
1414 }
Adam Langley95c29f32014-06-20 12:00:00 -07001415 return c.handshakeErr
1416}
1417
1418// ConnectionState returns basic TLS details about the connection.
1419func (c *Conn) ConnectionState() ConnectionState {
1420 c.handshakeMutex.Lock()
1421 defer c.handshakeMutex.Unlock()
1422
1423 var state ConnectionState
1424 state.HandshakeComplete = c.handshakeComplete
1425 if c.handshakeComplete {
1426 state.Version = c.vers
1427 state.NegotiatedProtocol = c.clientProtocol
1428 state.DidResume = c.didResume
1429 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001430 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001431 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001432 state.PeerCertificates = c.peerCertificates
1433 state.VerifiedChains = c.verifiedChains
1434 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001435 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001436 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001437 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001438 state.SCTList = c.sctList
Steven Valdez0d62f262015-09-04 12:41:04 -04001439 state.ClientCertSignatureHash = c.clientCertSignatureHash
Adam Langley95c29f32014-06-20 12:00:00 -07001440 }
1441
1442 return state
1443}
1444
1445// OCSPResponse returns the stapled OCSP response from the TLS server, if
1446// any. (Only valid for client connections.)
1447func (c *Conn) OCSPResponse() []byte {
1448 c.handshakeMutex.Lock()
1449 defer c.handshakeMutex.Unlock()
1450
1451 return c.ocspResponse
1452}
1453
1454// VerifyHostname checks that the peer certificate chain is valid for
1455// connecting to host. If so, it returns nil; if not, it returns an error
1456// describing the problem.
1457func (c *Conn) VerifyHostname(host string) error {
1458 c.handshakeMutex.Lock()
1459 defer c.handshakeMutex.Unlock()
1460 if !c.isClient {
1461 return errors.New("tls: VerifyHostname called on TLS server connection")
1462 }
1463 if !c.handshakeComplete {
1464 return errors.New("tls: handshake has not yet been performed")
1465 }
1466 return c.peerCertificates[0].VerifyHostname(host)
1467}
David Benjaminc565ebb2015-04-03 04:06:36 -04001468
1469// ExportKeyingMaterial exports keying material from the current connection
1470// state, as per RFC 5705.
1471func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1472 c.handshakeMutex.Lock()
1473 defer c.handshakeMutex.Unlock()
1474 if !c.handshakeComplete {
1475 return nil, errors.New("tls: handshake has not yet been performed")
1476 }
1477
1478 seedLen := len(c.clientRandom) + len(c.serverRandom)
1479 if useContext {
1480 seedLen += 2 + len(context)
1481 }
1482 seed := make([]byte, 0, seedLen)
1483 seed = append(seed, c.clientRandom[:]...)
1484 seed = append(seed, c.serverRandom[:]...)
1485 if useContext {
1486 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1487 seed = append(seed, context...)
1488 }
1489 result := make([]byte, length)
1490 prfForVersion(c.vers, c.cipherSuite)(result, c.masterSecret[:], label, seed)
1491 return result, nil
1492}
David Benjamin3e052de2015-11-25 20:10:31 -05001493
1494// noRenegotiationInfo returns true if the renegotiation info extension
1495// should be supported in the current handshake.
1496func (c *Conn) noRenegotiationInfo() bool {
1497 if c.config.Bugs.NoRenegotiationInfo {
1498 return true
1499 }
1500 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1501 return true
1502 }
1503 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1504 return true
1505 }
1506 return false
1507}