blob: 8244a4c1c2952f8f113a28c602a02ced41723b18 [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
Nick Harper60edffd2016-06-21 15:19:24 -070053 // peerSignatureAlgorithm contains the signature algorithm that was used
54 // by the peer in the handshake, or zero if not applicable.
55 peerSignatureAlgorithm signatureAlgorithm
Adam Langleyaf0e32c2015-06-03 09:57:23 -070056
David Benjaminc565ebb2015-04-03 04:06:36 -040057 clientRandom, serverRandom [32]byte
58 masterSecret [48]byte
Adam Langley95c29f32014-06-20 12:00:00 -070059
60 clientProtocol string
61 clientProtocolFallback bool
David Benjaminfc7b0862014-09-06 13:21:53 -040062 usedALPN bool
Adam Langley95c29f32014-06-20 12:00:00 -070063
Adam Langley2ae77d22014-10-28 17:29:33 -070064 // verify_data values for the renegotiation extension.
65 clientVerify []byte
66 serverVerify []byte
67
David Benjamind30a9902014-08-24 01:44:23 -040068 channelID *ecdsa.PublicKey
69
David Benjaminca6c8262014-11-15 19:06:08 -050070 srtpProtectionProfile uint16
71
David Benjaminc44b1df2014-11-23 12:11:01 -050072 clientVersion uint16
73
Adam Langley95c29f32014-06-20 12:00:00 -070074 // input/output
75 in, out halfConn // in.Mutex < out.Mutex
76 rawInput *block // raw input, right off the wire
David Benjamin83c0bc92014-08-04 01:23:53 -040077 input *block // application record waiting to be read
78 hand bytes.Buffer // handshake record waiting to be read
79
80 // DTLS state
81 sendHandshakeSeq uint16
82 recvHandshakeSeq uint16
David Benjaminb3774b92015-01-31 17:16:01 -050083 handMsg []byte // pending assembled handshake message
84 handMsgLen int // handshake message length, not including the header
85 pendingFragments [][]byte // pending outgoing handshake fragments.
Adam Langley95c29f32014-06-20 12:00:00 -070086
87 tmp [16]byte
88}
89
David Benjamin5e961c12014-11-07 01:48:35 -050090func (c *Conn) init() {
91 c.in.isDTLS = c.isDTLS
92 c.out.isDTLS = c.isDTLS
93 c.in.config = c.config
94 c.out.config = c.config
David Benjamin8e6db492015-07-25 18:29:23 -040095
96 c.out.updateOutSeq()
David Benjamin5e961c12014-11-07 01:48:35 -050097}
98
Adam Langley95c29f32014-06-20 12:00:00 -070099// Access to net.Conn methods.
100// Cannot just embed net.Conn because that would
101// export the struct field too.
102
103// LocalAddr returns the local network address.
104func (c *Conn) LocalAddr() net.Addr {
105 return c.conn.LocalAddr()
106}
107
108// RemoteAddr returns the remote network address.
109func (c *Conn) RemoteAddr() net.Addr {
110 return c.conn.RemoteAddr()
111}
112
113// SetDeadline sets the read and write deadlines associated with the connection.
114// A zero value for t means Read and Write will not time out.
115// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
116func (c *Conn) SetDeadline(t time.Time) error {
117 return c.conn.SetDeadline(t)
118}
119
120// SetReadDeadline sets the read deadline on the underlying connection.
121// A zero value for t means Read will not time out.
122func (c *Conn) SetReadDeadline(t time.Time) error {
123 return c.conn.SetReadDeadline(t)
124}
125
126// SetWriteDeadline sets the write deadline on the underlying conneciton.
127// A zero value for t means Write will not time out.
128// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
129func (c *Conn) SetWriteDeadline(t time.Time) error {
130 return c.conn.SetWriteDeadline(t)
131}
132
133// A halfConn represents one direction of the record layer
134// connection, either sending or receiving.
135type halfConn struct {
136 sync.Mutex
137
David Benjamin83c0bc92014-08-04 01:23:53 -0400138 err error // first permanent error
139 version uint16 // protocol version
140 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -0700141 cipher interface{} // cipher algorithm
142 mac macFunction
143 seq [8]byte // 64-bit sequence number
David Benjamin8e6db492015-07-25 18:29:23 -0400144 outSeq [8]byte // Mapped sequence number
Adam Langley95c29f32014-06-20 12:00:00 -0700145 bfree *block // list of free blocks
146
147 nextCipher interface{} // next encryption state
148 nextMac macFunction // next MAC algorithm
David Benjamin83f90402015-01-27 01:09:43 -0500149 nextSeq [6]byte // next epoch's starting sequence number in DTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700150
151 // used to save allocating a new buffer for each MAC.
152 inDigestBuf, outDigestBuf []byte
Adam Langley80842bd2014-06-20 12:00:00 -0700153
154 config *Config
Adam Langley95c29f32014-06-20 12:00:00 -0700155}
156
157func (hc *halfConn) setErrorLocked(err error) error {
158 hc.err = err
159 return err
160}
161
162func (hc *halfConn) error() error {
Adam Langley2ae77d22014-10-28 17:29:33 -0700163 // This should be locked, but I've removed it for the renegotiation
164 // tests since we don't concurrently read and write the same tls.Conn
165 // in any case during testing.
Adam Langley95c29f32014-06-20 12:00:00 -0700166 err := hc.err
Adam Langley95c29f32014-06-20 12:00:00 -0700167 return err
168}
169
170// prepareCipherSpec sets the encryption and MAC states
171// that a subsequent changeCipherSpec will use.
172func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
173 hc.version = version
174 hc.nextCipher = cipher
175 hc.nextMac = mac
176}
177
178// changeCipherSpec changes the encryption and MAC states
179// to the ones previously passed to prepareCipherSpec.
Adam Langley80842bd2014-06-20 12:00:00 -0700180func (hc *halfConn) changeCipherSpec(config *Config) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700181 if hc.nextCipher == nil {
182 return alertInternalError
183 }
184 hc.cipher = hc.nextCipher
185 hc.mac = hc.nextMac
186 hc.nextCipher = nil
187 hc.nextMac = nil
Adam Langley80842bd2014-06-20 12:00:00 -0700188 hc.config = config
David Benjamin83c0bc92014-08-04 01:23:53 -0400189 hc.incEpoch()
David Benjaminf2b83632016-03-01 22:57:46 -0500190
191 if config.Bugs.NullAllCiphers {
192 hc.cipher = nil
193 hc.mac = nil
194 }
Adam Langley95c29f32014-06-20 12:00:00 -0700195 return nil
196}
197
198// incSeq increments the sequence number.
David Benjamin5e961c12014-11-07 01:48:35 -0500199func (hc *halfConn) incSeq(isOutgoing bool) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400200 limit := 0
David Benjamin5e961c12014-11-07 01:48:35 -0500201 increment := uint64(1)
David Benjamin83c0bc92014-08-04 01:23:53 -0400202 if hc.isDTLS {
203 // Increment up to the epoch in DTLS.
204 limit = 2
205 }
206 for i := 7; i >= limit; i-- {
David Benjamin5e961c12014-11-07 01:48:35 -0500207 increment += uint64(hc.seq[i])
208 hc.seq[i] = byte(increment)
209 increment >>= 8
Adam Langley95c29f32014-06-20 12:00:00 -0700210 }
211
212 // Not allowed to let sequence number wrap.
213 // Instead, must renegotiate before it does.
214 // Not likely enough to bother.
David Benjamin5e961c12014-11-07 01:48:35 -0500215 if increment != 0 {
216 panic("TLS: sequence number wraparound")
217 }
David Benjamin8e6db492015-07-25 18:29:23 -0400218
219 hc.updateOutSeq()
Adam Langley95c29f32014-06-20 12:00:00 -0700220}
221
David Benjamin83f90402015-01-27 01:09:43 -0500222// incNextSeq increments the starting sequence number for the next epoch.
223func (hc *halfConn) incNextSeq() {
224 for i := len(hc.nextSeq) - 1; i >= 0; i-- {
225 hc.nextSeq[i]++
226 if hc.nextSeq[i] != 0 {
227 return
228 }
229 }
230 panic("TLS: sequence number wraparound")
231}
232
233// incEpoch resets the sequence number. In DTLS, it also increments the epoch
234// half of the sequence number.
David Benjamin83c0bc92014-08-04 01:23:53 -0400235func (hc *halfConn) incEpoch() {
David Benjamin83c0bc92014-08-04 01:23:53 -0400236 if hc.isDTLS {
237 for i := 1; i >= 0; i-- {
238 hc.seq[i]++
239 if hc.seq[i] != 0 {
240 break
241 }
242 if i == 0 {
243 panic("TLS: epoch number wraparound")
244 }
245 }
David Benjamin83f90402015-01-27 01:09:43 -0500246 copy(hc.seq[2:], hc.nextSeq[:])
247 for i := range hc.nextSeq {
248 hc.nextSeq[i] = 0
249 }
250 } else {
251 for i := range hc.seq {
252 hc.seq[i] = 0
253 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400254 }
David Benjamin8e6db492015-07-25 18:29:23 -0400255
256 hc.updateOutSeq()
257}
258
259func (hc *halfConn) updateOutSeq() {
260 if hc.config.Bugs.SequenceNumberMapping != nil {
261 seqU64 := binary.BigEndian.Uint64(hc.seq[:])
262 seqU64 = hc.config.Bugs.SequenceNumberMapping(seqU64)
263 binary.BigEndian.PutUint64(hc.outSeq[:], seqU64)
264
265 // The DTLS epoch cannot be changed.
266 copy(hc.outSeq[:2], hc.seq[:2])
267 return
268 }
269
270 copy(hc.outSeq[:], hc.seq[:])
David Benjamin83c0bc92014-08-04 01:23:53 -0400271}
272
273func (hc *halfConn) recordHeaderLen() int {
274 if hc.isDTLS {
275 return dtlsRecordHeaderLen
276 }
277 return tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700278}
279
280// removePadding returns an unpadded slice, in constant time, which is a prefix
281// of the input. It also returns a byte which is equal to 255 if the padding
282// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
283func removePadding(payload []byte) ([]byte, byte) {
284 if len(payload) < 1 {
285 return payload, 0
286 }
287
288 paddingLen := payload[len(payload)-1]
289 t := uint(len(payload)-1) - uint(paddingLen)
290 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
291 good := byte(int32(^t) >> 31)
292
293 toCheck := 255 // the maximum possible padding length
294 // The length of the padded data is public, so we can use an if here
295 if toCheck+1 > len(payload) {
296 toCheck = len(payload) - 1
297 }
298
299 for i := 0; i < toCheck; i++ {
300 t := uint(paddingLen) - uint(i)
301 // if i <= paddingLen then the MSB of t is zero
302 mask := byte(int32(^t) >> 31)
303 b := payload[len(payload)-1-i]
304 good &^= mask&paddingLen ^ mask&b
305 }
306
307 // We AND together the bits of good and replicate the result across
308 // all the bits.
309 good &= good << 4
310 good &= good << 2
311 good &= good << 1
312 good = uint8(int8(good) >> 7)
313
314 toRemove := good&paddingLen + 1
315 return payload[:len(payload)-int(toRemove)], good
316}
317
318// removePaddingSSL30 is a replacement for removePadding in the case that the
319// protocol version is SSLv3. In this version, the contents of the padding
320// are random and cannot be checked.
321func removePaddingSSL30(payload []byte) ([]byte, byte) {
322 if len(payload) < 1 {
323 return payload, 0
324 }
325
326 paddingLen := int(payload[len(payload)-1]) + 1
327 if paddingLen > len(payload) {
328 return payload, 0
329 }
330
331 return payload[:len(payload)-paddingLen], 255
332}
333
334func roundUp(a, b int) int {
335 return a + (b-a%b)%b
336}
337
338// cbcMode is an interface for block ciphers using cipher block chaining.
339type cbcMode interface {
340 cipher.BlockMode
341 SetIV([]byte)
342}
343
344// decrypt checks and strips the mac and decrypts the data in b. Returns a
345// success boolean, the number of bytes to skip from the start of the record in
Nick Harper1fd39d82016-06-14 18:14:35 -0700346// order to get the application payload, the encrypted record type (or 0
347// if there is none), and an optional alert value.
348func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, contentType recordType, alertValue alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400349 recordHeaderLen := hc.recordHeaderLen()
350
Adam Langley95c29f32014-06-20 12:00:00 -0700351 // pull out payload
352 payload := b.data[recordHeaderLen:]
353
354 macSize := 0
355 if hc.mac != nil {
356 macSize = hc.mac.Size()
357 }
358
359 paddingGood := byte(255)
360 explicitIVLen := 0
361
David Benjamin83c0bc92014-08-04 01:23:53 -0400362 seq := hc.seq[:]
363 if hc.isDTLS {
364 // DTLS sequence numbers are explicit.
365 seq = b.data[3:11]
366 }
367
Adam Langley95c29f32014-06-20 12:00:00 -0700368 // decrypt
369 if hc.cipher != nil {
370 switch c := hc.cipher.(type) {
371 case cipher.Stream:
372 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400373 case *tlsAead:
374 nonce := seq
375 if c.explicitNonce {
376 explicitIVLen = 8
377 if len(payload) < explicitIVLen {
Nick Harper1fd39d82016-06-14 18:14:35 -0700378 return false, 0, 0, alertBadRecordMAC
David Benjamine9a80ff2015-04-07 00:46:46 -0400379 }
380 nonce = payload[:8]
381 payload = payload[8:]
Adam Langley95c29f32014-06-20 12:00:00 -0700382 }
Adam Langley95c29f32014-06-20 12:00:00 -0700383
Nick Harper1fd39d82016-06-14 18:14:35 -0700384 var additionalData []byte
385 if hc.version < VersionTLS13 {
386 additionalData = make([]byte, 13)
387 copy(additionalData, seq)
388 copy(additionalData[8:], b.data[:3])
389 n := len(payload) - c.Overhead()
390 additionalData[11] = byte(n >> 8)
391 additionalData[12] = byte(n)
392 }
Adam Langley95c29f32014-06-20 12:00:00 -0700393 var err error
Nick Harper1fd39d82016-06-14 18:14:35 -0700394 payload, err = c.Open(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700395 if err != nil {
Nick Harper1fd39d82016-06-14 18:14:35 -0700396 return false, 0, 0, alertBadRecordMAC
397 }
398 if hc.version >= VersionTLS13 {
399 i := len(payload)
400 for i > 0 && payload[i-1] == 0 {
401 i--
402 }
403 payload = payload[:i]
404 if len(payload) == 0 {
405 return false, 0, 0, alertUnexpectedMessage
406 }
407 contentType = recordType(payload[len(payload)-1])
408 payload = payload[:len(payload)-1]
Adam Langley95c29f32014-06-20 12:00:00 -0700409 }
410 b.resize(recordHeaderLen + explicitIVLen + len(payload))
411 case cbcMode:
412 blockSize := c.BlockSize()
David Benjamin83c0bc92014-08-04 01:23:53 -0400413 if hc.version >= VersionTLS11 || hc.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700414 explicitIVLen = blockSize
415 }
416
417 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
Nick Harper1fd39d82016-06-14 18:14:35 -0700418 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700419 }
420
421 if explicitIVLen > 0 {
422 c.SetIV(payload[:explicitIVLen])
423 payload = payload[explicitIVLen:]
424 }
425 c.CryptBlocks(payload, payload)
426 if hc.version == VersionSSL30 {
427 payload, paddingGood = removePaddingSSL30(payload)
428 } else {
429 payload, paddingGood = removePadding(payload)
430 }
431 b.resize(recordHeaderLen + explicitIVLen + len(payload))
432
433 // note that we still have a timing side-channel in the
434 // MAC check, below. An attacker can align the record
435 // so that a correct padding will cause one less hash
436 // block to be calculated. Then they can iteratively
437 // decrypt a record by breaking each byte. See
438 // "Password Interception in a SSL/TLS Channel", Brice
439 // Canvel et al.
440 //
441 // However, our behavior matches OpenSSL, so we leak
442 // only as much as they do.
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700443 case nullCipher:
444 break
Adam Langley95c29f32014-06-20 12:00:00 -0700445 default:
446 panic("unknown cipher type")
447 }
448 }
449
450 // check, strip mac
451 if hc.mac != nil {
452 if len(payload) < macSize {
Nick Harper1fd39d82016-06-14 18:14:35 -0700453 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700454 }
455
456 // strip mac off payload, b.data
457 n := len(payload) - macSize
David Benjamin83c0bc92014-08-04 01:23:53 -0400458 b.data[recordHeaderLen-2] = byte(n >> 8)
459 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700460 b.resize(recordHeaderLen + explicitIVLen + n)
461 remoteMAC := payload[n:]
David Benjamin83c0bc92014-08-04 01:23:53 -0400462 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
Adam Langley95c29f32014-06-20 12:00:00 -0700463
464 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
Nick Harper1fd39d82016-06-14 18:14:35 -0700465 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700466 }
467 hc.inDigestBuf = localMAC
468 }
David Benjamin5e961c12014-11-07 01:48:35 -0500469 hc.incSeq(false)
Adam Langley95c29f32014-06-20 12:00:00 -0700470
Nick Harper1fd39d82016-06-14 18:14:35 -0700471 return true, recordHeaderLen + explicitIVLen, contentType, 0
Adam Langley95c29f32014-06-20 12:00:00 -0700472}
473
474// padToBlockSize calculates the needed padding block, if any, for a payload.
475// On exit, prefix aliases payload and extends to the end of the last full
476// block of payload. finalBlock is a fresh slice which contains the contents of
477// any suffix of payload as well as the needed padding to make finalBlock a
478// full block.
Adam Langley80842bd2014-06-20 12:00:00 -0700479func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
Adam Langley95c29f32014-06-20 12:00:00 -0700480 overrun := len(payload) % blockSize
Adam Langley95c29f32014-06-20 12:00:00 -0700481 prefix = payload[:len(payload)-overrun]
Adam Langley80842bd2014-06-20 12:00:00 -0700482
483 paddingLen := blockSize - overrun
484 finalSize := blockSize
485 if config.Bugs.MaxPadding {
486 for paddingLen+blockSize <= 256 {
487 paddingLen += blockSize
488 }
489 finalSize = 256
490 }
491 finalBlock = make([]byte, finalSize)
492 for i := range finalBlock {
Adam Langley95c29f32014-06-20 12:00:00 -0700493 finalBlock[i] = byte(paddingLen - 1)
494 }
Adam Langley80842bd2014-06-20 12:00:00 -0700495 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
496 finalBlock[overrun] ^= 0xff
497 }
498 copy(finalBlock, payload[len(payload)-overrun:])
Adam Langley95c29f32014-06-20 12:00:00 -0700499 return
500}
501
502// encrypt encrypts and macs the data in b.
Nick Harper1fd39d82016-06-14 18:14:35 -0700503func (hc *halfConn) encrypt(b *block, explicitIVLen int, typ recordType) (bool, alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400504 recordHeaderLen := hc.recordHeaderLen()
505
Adam Langley95c29f32014-06-20 12:00:00 -0700506 // mac
507 if hc.mac != nil {
David Benjamin8e6db492015-07-25 18:29:23 -0400508 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 -0700509
510 n := len(b.data)
511 b.resize(n + len(mac))
512 copy(b.data[n:], mac)
513 hc.outDigestBuf = mac
514 }
515
516 payload := b.data[recordHeaderLen:]
517
518 // encrypt
519 if hc.cipher != nil {
520 switch c := hc.cipher.(type) {
521 case cipher.Stream:
522 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400523 case *tlsAead:
Adam Langley95c29f32014-06-20 12:00:00 -0700524 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
David Benjaminc9ae27c2016-06-24 22:56:37 -0400525 paddingLen := 0
Nick Harper1fd39d82016-06-14 18:14:35 -0700526 if hc.version >= VersionTLS13 {
David Benjaminc9ae27c2016-06-24 22:56:37 -0400527 payloadLen++
528 paddingLen = hc.config.Bugs.RecordPadding
529 }
530 if hc.config.Bugs.OmitRecordContents {
531 payloadLen = 0
532 }
533 b.resize(recordHeaderLen + explicitIVLen + payloadLen + paddingLen + c.Overhead())
534 if hc.version >= VersionTLS13 {
535 if !hc.config.Bugs.OmitRecordContents {
536 b.data[payloadLen+recordHeaderLen-1] = byte(typ)
537 }
538 for i := 0; i < hc.config.Bugs.RecordPadding; i++ {
539 b.data[payloadLen+recordHeaderLen+i] = 0
540 }
541 payloadLen += paddingLen
Nick Harper1fd39d82016-06-14 18:14:35 -0700542 }
David Benjamin8e6db492015-07-25 18:29:23 -0400543 nonce := hc.outSeq[:]
David Benjamine9a80ff2015-04-07 00:46:46 -0400544 if c.explicitNonce {
545 nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
546 }
Adam Langley95c29f32014-06-20 12:00:00 -0700547 payload := b.data[recordHeaderLen+explicitIVLen:]
548 payload = payload[:payloadLen]
549
Nick Harper1fd39d82016-06-14 18:14:35 -0700550 var additionalData []byte
551 if hc.version < VersionTLS13 {
552 additionalData = make([]byte, 13)
553 copy(additionalData, hc.outSeq[:])
554 copy(additionalData[8:], b.data[:3])
555 additionalData[11] = byte(payloadLen >> 8)
556 additionalData[12] = byte(payloadLen)
557 }
Adam Langley95c29f32014-06-20 12:00:00 -0700558
Nick Harper1fd39d82016-06-14 18:14:35 -0700559 c.Seal(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700560 case cbcMode:
561 blockSize := c.BlockSize()
562 if explicitIVLen > 0 {
563 c.SetIV(payload[:explicitIVLen])
564 payload = payload[explicitIVLen:]
565 }
Adam Langley80842bd2014-06-20 12:00:00 -0700566 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700567 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
568 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
569 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700570 case nullCipher:
571 break
Adam Langley95c29f32014-06-20 12:00:00 -0700572 default:
573 panic("unknown cipher type")
574 }
575 }
576
577 // update length to include MAC and any block padding needed.
578 n := len(b.data) - recordHeaderLen
David Benjamin83c0bc92014-08-04 01:23:53 -0400579 b.data[recordHeaderLen-2] = byte(n >> 8)
580 b.data[recordHeaderLen-1] = byte(n)
David Benjamin5e961c12014-11-07 01:48:35 -0500581 hc.incSeq(true)
Adam Langley95c29f32014-06-20 12:00:00 -0700582
583 return true, 0
584}
585
586// A block is a simple data buffer.
587type block struct {
588 data []byte
589 off int // index for Read
590 link *block
591}
592
593// resize resizes block to be n bytes, growing if necessary.
594func (b *block) resize(n int) {
595 if n > cap(b.data) {
596 b.reserve(n)
597 }
598 b.data = b.data[0:n]
599}
600
601// reserve makes sure that block contains a capacity of at least n bytes.
602func (b *block) reserve(n int) {
603 if cap(b.data) >= n {
604 return
605 }
606 m := cap(b.data)
607 if m == 0 {
608 m = 1024
609 }
610 for m < n {
611 m *= 2
612 }
613 data := make([]byte, len(b.data), m)
614 copy(data, b.data)
615 b.data = data
616}
617
618// readFromUntil reads from r into b until b contains at least n bytes
619// or else returns an error.
620func (b *block) readFromUntil(r io.Reader, n int) error {
621 // quick case
622 if len(b.data) >= n {
623 return nil
624 }
625
626 // read until have enough.
627 b.reserve(n)
628 for {
629 m, err := r.Read(b.data[len(b.data):cap(b.data)])
630 b.data = b.data[0 : len(b.data)+m]
631 if len(b.data) >= n {
632 // TODO(bradfitz,agl): slightly suspicious
633 // that we're throwing away r.Read's err here.
634 break
635 }
636 if err != nil {
637 return err
638 }
639 }
640 return nil
641}
642
643func (b *block) Read(p []byte) (n int, err error) {
644 n = copy(p, b.data[b.off:])
645 b.off += n
646 return
647}
648
649// newBlock allocates a new block, from hc's free list if possible.
650func (hc *halfConn) newBlock() *block {
651 b := hc.bfree
652 if b == nil {
653 return new(block)
654 }
655 hc.bfree = b.link
656 b.link = nil
657 b.resize(0)
658 return b
659}
660
661// freeBlock returns a block to hc's free list.
662// The protocol is such that each side only has a block or two on
663// its free list at a time, so there's no need to worry about
664// trimming the list, etc.
665func (hc *halfConn) freeBlock(b *block) {
666 b.link = hc.bfree
667 hc.bfree = b
668}
669
670// splitBlock splits a block after the first n bytes,
671// returning a block with those n bytes and a
672// block with the remainder. the latter may be nil.
673func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
674 if len(b.data) <= n {
675 return b, nil
676 }
677 bb := hc.newBlock()
678 bb.resize(len(b.data) - n)
679 copy(bb.data, b.data[n:])
680 b.data = b.data[0:n]
681 return b, bb
682}
683
David Benjamin83c0bc92014-08-04 01:23:53 -0400684func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
685 if c.isDTLS {
686 return c.dtlsDoReadRecord(want)
687 }
688
689 recordHeaderLen := tlsRecordHeaderLen
690
691 if c.rawInput == nil {
692 c.rawInput = c.in.newBlock()
693 }
694 b := c.rawInput
695
696 // Read header, payload.
697 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
698 // RFC suggests that EOF without an alertCloseNotify is
699 // an error, but popular web sites seem to do this,
David Benjamin30789da2015-08-29 22:56:45 -0400700 // so we can't make it an error, outside of tests.
701 if err == io.EOF && c.config.Bugs.ExpectCloseNotify {
702 err = io.ErrUnexpectedEOF
703 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400704 if e, ok := err.(net.Error); !ok || !e.Temporary() {
705 c.in.setErrorLocked(err)
706 }
707 return 0, nil, err
708 }
709 typ := recordType(b.data[0])
710
711 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
712 // start with a uint16 length where the MSB is set and the first record
713 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
714 // an SSLv2 client.
715 if want == recordTypeHandshake && typ == 0x80 {
716 c.sendAlert(alertProtocolVersion)
717 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
718 }
719
720 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
721 n := int(b.data[3])<<8 | int(b.data[4])
David Benjaminbde00392016-06-21 12:19:28 -0400722 // Alerts sent near version negotiation do not have a well-defined
723 // record-layer version prior to TLS 1.3. (In TLS 1.3, the record-layer
724 // version is irrelevant.)
725 if typ != recordTypeAlert {
726 if c.haveVers {
727 if vers != c.vers && c.vers < VersionTLS13 {
728 c.sendAlert(alertProtocolVersion)
729 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers))
730 }
731 } else {
732 if expect := c.config.Bugs.ExpectInitialRecordVersion; expect != 0 && vers != expect {
733 c.sendAlert(alertProtocolVersion)
734 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
735 }
David Benjamin1e29a6b2014-12-10 02:27:24 -0500736 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400737 }
738 if n > maxCiphertext {
739 c.sendAlert(alertRecordOverflow)
740 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
741 }
742 if !c.haveVers {
743 // First message, be extra suspicious:
744 // this might not be a TLS client.
745 // Bail out before reading a full 'body', if possible.
746 // The current max version is 3.1.
747 // If the version is >= 16.0, it's probably not real.
748 // Similarly, a clientHello message encodes in
749 // well under a kilobyte. If the length is >= 12 kB,
750 // it's probably not real.
751 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
752 c.sendAlert(alertUnexpectedMessage)
753 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
754 }
755 }
756 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
757 if err == io.EOF {
758 err = io.ErrUnexpectedEOF
759 }
760 if e, ok := err.(net.Error); !ok || !e.Temporary() {
761 c.in.setErrorLocked(err)
762 }
763 return 0, nil, err
764 }
765
766 // Process message.
767 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
Nick Harper1fd39d82016-06-14 18:14:35 -0700768 ok, off, encTyp, err := c.in.decrypt(b)
769 if c.vers >= VersionTLS13 && c.in.cipher != nil {
David Benjaminc9ae27c2016-06-24 22:56:37 -0400770 if typ != recordTypeApplicationData {
771 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: outer record type is not application data"))
772 }
Nick Harper1fd39d82016-06-14 18:14:35 -0700773 typ = encTyp
774 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400775 if !ok {
776 c.in.setErrorLocked(c.sendAlert(err))
777 }
778 b.off = off
779 return typ, b, nil
780}
781
Adam Langley95c29f32014-06-20 12:00:00 -0700782// readRecord reads the next TLS record from the connection
783// and updates the record layer state.
784// c.in.Mutex <= L; c.input == nil.
785func (c *Conn) readRecord(want recordType) error {
786 // Caller must be in sync with connection:
787 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700788 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700789 switch want {
790 default:
791 c.sendAlert(alertInternalError)
792 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
793 case recordTypeHandshake, recordTypeChangeCipherSpec:
794 if c.handshakeComplete {
795 c.sendAlert(alertInternalError)
796 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
797 }
798 case recordTypeApplicationData:
David Benjamine58c4f52014-08-24 03:47:07 -0400799 if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart {
Adam Langley95c29f32014-06-20 12:00:00 -0700800 c.sendAlert(alertInternalError)
801 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
802 }
David Benjamin30789da2015-08-29 22:56:45 -0400803 case recordTypeAlert:
804 // Looking for a close_notify. Note: unlike a real
805 // implementation, this is not tolerant of additional records.
806 // See the documentation for ExpectCloseNotify.
Adam Langley95c29f32014-06-20 12:00:00 -0700807 }
808
809Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400810 typ, b, err := c.doReadRecord(want)
811 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700812 return err
813 }
Adam Langley95c29f32014-06-20 12:00:00 -0700814 data := b.data[b.off:]
815 if len(data) > maxPlaintext {
816 err := c.sendAlert(alertRecordOverflow)
817 c.in.freeBlock(b)
818 return c.in.setErrorLocked(err)
819 }
820
821 switch typ {
822 default:
823 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
824
825 case recordTypeAlert:
826 if len(data) != 2 {
827 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
828 break
829 }
830 if alert(data[1]) == alertCloseNotify {
831 c.in.setErrorLocked(io.EOF)
832 break
833 }
834 switch data[0] {
835 case alertLevelWarning:
836 // drop on the floor
837 c.in.freeBlock(b)
838 goto Again
839 case alertLevelError:
840 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
841 default:
842 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
843 }
844
845 case recordTypeChangeCipherSpec:
846 if typ != want || len(data) != 1 || data[0] != 1 {
847 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
848 break
849 }
Adam Langley80842bd2014-06-20 12:00:00 -0700850 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700851 if err != nil {
852 c.in.setErrorLocked(c.sendAlert(err.(alert)))
853 }
854
855 case recordTypeApplicationData:
856 if typ != want {
857 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
858 break
859 }
860 c.input = b
861 b = nil
862
863 case recordTypeHandshake:
864 // TODO(rsc): Should at least pick off connection close.
865 if typ != want {
Adam Langley2ae77d22014-10-28 17:29:33 -0700866 // A client might need to process a HelloRequest from
867 // the server, thus receiving a handshake message when
David Benjamind9b091b2015-01-27 01:10:54 -0500868 // application data is expected is ok.
David Benjamin30789da2015-08-29 22:56:45 -0400869 if !c.isClient || want != recordTypeApplicationData {
Adam Langley2ae77d22014-10-28 17:29:33 -0700870 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
871 }
Adam Langley95c29f32014-06-20 12:00:00 -0700872 }
873 c.hand.Write(data)
874 }
875
876 if b != nil {
877 c.in.freeBlock(b)
878 }
879 return c.in.err
880}
881
882// sendAlert sends a TLS alert message.
883// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400884func (c *Conn) sendAlertLocked(level byte, err alert) error {
885 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700886 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400887 if c.config.Bugs.FragmentAlert {
888 c.writeRecord(recordTypeAlert, c.tmp[0:1])
889 c.writeRecord(recordTypeAlert, c.tmp[1:2])
David Benjamin0d3a8c62016-03-11 22:25:18 -0500890 } else if c.config.Bugs.DoubleAlert {
891 copy(c.tmp[2:4], c.tmp[0:2])
892 c.writeRecord(recordTypeAlert, c.tmp[0:4])
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400893 } else {
894 c.writeRecord(recordTypeAlert, c.tmp[0:2])
895 }
David Benjamin24f346d2015-06-06 03:28:08 -0400896 // Error alerts are fatal to the connection.
897 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700898 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
899 }
900 return nil
901}
902
903// sendAlert sends a TLS alert message.
904// L < c.out.Mutex.
905func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400906 level := byte(alertLevelError)
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500907 if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertficate {
David Benjamin24f346d2015-06-06 03:28:08 -0400908 level = alertLevelWarning
909 }
910 return c.SendAlert(level, err)
911}
912
913func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700914 c.out.Lock()
915 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -0400916 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -0700917}
918
David Benjamind86c7672014-08-02 04:07:12 -0400919// writeV2Record writes a record for a V2ClientHello.
920func (c *Conn) writeV2Record(data []byte) (n int, err error) {
921 record := make([]byte, 2+len(data))
922 record[0] = uint8(len(data)>>8) | 0x80
923 record[1] = uint8(len(data))
924 copy(record[2:], data)
925 return c.conn.Write(record)
926}
927
Adam Langley95c29f32014-06-20 12:00:00 -0700928// writeRecord writes a TLS record with the given type and payload
929// to the connection and updates the record layer state.
930// c.out.Mutex <= L.
931func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400932 if c.isDTLS {
933 return c.dtlsWriteRecord(typ, data)
934 }
935
936 recordHeaderLen := tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700937 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -0400938 first := true
939 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -0400940 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -0700941 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -0400942 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -0700943 m = maxPlaintext
944 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400945 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
946 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -0400947 // By default, do not fragment the client_version or
948 // server_version, which are located in the first 6
949 // bytes.
950 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
951 m = 6
952 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400953 }
Adam Langley95c29f32014-06-20 12:00:00 -0700954 explicitIVLen := 0
955 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -0400956 first = false
Adam Langley95c29f32014-06-20 12:00:00 -0700957
958 var cbc cbcMode
959 if c.out.version >= VersionTLS11 {
960 var ok bool
961 if cbc, ok = c.out.cipher.(cbcMode); ok {
962 explicitIVLen = cbc.BlockSize()
963 }
964 }
965 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -0400966 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -0700967 explicitIVLen = 8
968 // The AES-GCM construction in TLS has an
969 // explicit nonce so that the nonce can be
970 // random. However, the nonce is only 8 bytes
971 // which is too small for a secure, random
972 // nonce. Therefore we use the sequence number
973 // as the nonce.
974 explicitIVIsSeq = true
975 }
976 }
977 b.resize(recordHeaderLen + explicitIVLen + m)
978 b.data[0] = byte(typ)
Nick Harper1fd39d82016-06-14 18:14:35 -0700979 if c.vers >= VersionTLS13 && c.out.cipher != nil {
Nick Harper1fd39d82016-06-14 18:14:35 -0700980 b.data[0] = byte(recordTypeApplicationData)
David Benjaminc9ae27c2016-06-24 22:56:37 -0400981 if outerType := c.config.Bugs.OuterRecordType; outerType != 0 {
982 b.data[0] = byte(outerType)
983 }
Nick Harper1fd39d82016-06-14 18:14:35 -0700984 }
Adam Langley95c29f32014-06-20 12:00:00 -0700985 vers := c.vers
Nick Harper1fd39d82016-06-14 18:14:35 -0700986 if vers == 0 || vers >= VersionTLS13 {
Adam Langley95c29f32014-06-20 12:00:00 -0700987 // Some TLS servers fail if the record version is
988 // greater than TLS 1.0 for the initial ClientHello.
Nick Harper1fd39d82016-06-14 18:14:35 -0700989 //
990 // TLS 1.3 fixes the version number in the record
991 // layer to {3, 1}.
Adam Langley95c29f32014-06-20 12:00:00 -0700992 vers = VersionTLS10
993 }
994 b.data[1] = byte(vers >> 8)
995 b.data[2] = byte(vers)
996 b.data[3] = byte(m >> 8)
997 b.data[4] = byte(m)
998 if explicitIVLen > 0 {
999 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
1000 if explicitIVIsSeq {
1001 copy(explicitIV, c.out.seq[:])
1002 } else {
1003 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
1004 break
1005 }
1006 }
1007 }
1008 copy(b.data[recordHeaderLen+explicitIVLen:], data)
Nick Harper1fd39d82016-06-14 18:14:35 -07001009 c.out.encrypt(b, explicitIVLen, typ)
Adam Langley95c29f32014-06-20 12:00:00 -07001010 _, err = c.conn.Write(b.data)
1011 if err != nil {
1012 break
1013 }
1014 n += m
1015 data = data[m:]
1016 }
1017 c.out.freeBlock(b)
1018
1019 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -07001020 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -07001021 if err != nil {
1022 // Cannot call sendAlert directly,
1023 // because we already hold c.out.Mutex.
1024 c.tmp[0] = alertLevelError
1025 c.tmp[1] = byte(err.(alert))
1026 c.writeRecord(recordTypeAlert, c.tmp[0:2])
1027 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
1028 }
1029 }
1030 return
1031}
1032
David Benjamin83c0bc92014-08-04 01:23:53 -04001033func (c *Conn) doReadHandshake() ([]byte, error) {
1034 if c.isDTLS {
1035 return c.dtlsDoReadHandshake()
1036 }
1037
Adam Langley95c29f32014-06-20 12:00:00 -07001038 for c.hand.Len() < 4 {
1039 if err := c.in.err; err != nil {
1040 return nil, err
1041 }
1042 if err := c.readRecord(recordTypeHandshake); err != nil {
1043 return nil, err
1044 }
1045 }
1046
1047 data := c.hand.Bytes()
1048 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1049 if n > maxHandshake {
1050 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
1051 }
1052 for c.hand.Len() < 4+n {
1053 if err := c.in.err; err != nil {
1054 return nil, err
1055 }
1056 if err := c.readRecord(recordTypeHandshake); err != nil {
1057 return nil, err
1058 }
1059 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001060 return c.hand.Next(4 + n), nil
1061}
1062
1063// readHandshake reads the next handshake message from
1064// the record layer.
1065// c.in.Mutex < L; c.out.Mutex < L.
1066func (c *Conn) readHandshake() (interface{}, error) {
1067 data, err := c.doReadHandshake()
1068 if err != nil {
1069 return nil, err
1070 }
1071
Adam Langley95c29f32014-06-20 12:00:00 -07001072 var m handshakeMessage
1073 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001074 case typeHelloRequest:
1075 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001076 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001077 m = &clientHelloMsg{
1078 isDTLS: c.isDTLS,
1079 }
Adam Langley95c29f32014-06-20 12:00:00 -07001080 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001081 m = &serverHelloMsg{
1082 isDTLS: c.isDTLS,
1083 }
Adam Langley95c29f32014-06-20 12:00:00 -07001084 case typeNewSessionTicket:
1085 m = new(newSessionTicketMsg)
1086 case typeCertificate:
1087 m = new(certificateMsg)
1088 case typeCertificateRequest:
1089 m = &certificateRequestMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001090 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001091 }
1092 case typeCertificateStatus:
1093 m = new(certificateStatusMsg)
1094 case typeServerKeyExchange:
1095 m = new(serverKeyExchangeMsg)
1096 case typeServerHelloDone:
1097 m = new(serverHelloDoneMsg)
1098 case typeClientKeyExchange:
1099 m = new(clientKeyExchangeMsg)
1100 case typeCertificateVerify:
1101 m = &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001102 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001103 }
1104 case typeNextProtocol:
1105 m = new(nextProtoMsg)
1106 case typeFinished:
1107 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001108 case typeHelloVerifyRequest:
1109 m = new(helloVerifyRequestMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001110 case typeEncryptedExtensions:
1111 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001112 default:
1113 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1114 }
1115
1116 // The handshake message unmarshallers
1117 // expect to be able to keep references to data,
1118 // so pass in a fresh copy that won't be overwritten.
1119 data = append([]byte(nil), data...)
1120
1121 if !m.unmarshal(data) {
1122 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1123 }
1124 return m, nil
1125}
1126
David Benjamin83f90402015-01-27 01:09:43 -05001127// skipPacket processes all the DTLS records in packet. It updates
1128// sequence number expectations but otherwise ignores them.
1129func (c *Conn) skipPacket(packet []byte) error {
1130 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001131 if len(packet) < 13 {
1132 return errors.New("tls: bad packet")
1133 }
David Benjamin83f90402015-01-27 01:09:43 -05001134 // Dropped packets are completely ignored save to update
1135 // expected sequence numbers for this and the next epoch. (We
1136 // don't assert on the contents of the packets both for
1137 // simplicity and because a previous test with one shorter
1138 // timeout schedule would have done so.)
1139 epoch := packet[3:5]
1140 seq := packet[5:11]
1141 length := uint16(packet[11])<<8 | uint16(packet[12])
1142 if bytes.Equal(c.in.seq[:2], epoch) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001143 if bytes.Compare(seq, c.in.seq[2:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001144 return errors.New("tls: sequence mismatch")
1145 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001146 copy(c.in.seq[2:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001147 c.in.incSeq(false)
1148 } else {
David Benjamin13e81fc2015-11-02 17:16:13 -05001149 if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001150 return errors.New("tls: sequence mismatch")
1151 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001152 copy(c.in.nextSeq[:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001153 c.in.incNextSeq()
1154 }
David Benjamin6ca93552015-08-28 16:16:25 -04001155 if len(packet) < 13+int(length) {
1156 return errors.New("tls: bad packet")
1157 }
David Benjamin83f90402015-01-27 01:09:43 -05001158 packet = packet[13+length:]
1159 }
1160 return nil
1161}
1162
1163// simulatePacketLoss simulates the loss of a handshake leg from the
1164// peer based on the schedule in c.config.Bugs. If resendFunc is
1165// non-nil, it is called after each simulated timeout to retransmit
1166// handshake messages from the local end. This is used in cases where
1167// the peer retransmits on a stale Finished rather than a timeout.
1168func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1169 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1170 return nil
1171 }
1172 if !c.isDTLS {
1173 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1174 }
1175 if c.config.Bugs.PacketAdaptor == nil {
1176 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1177 }
1178 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1179 // Simulate a timeout.
1180 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1181 if err != nil {
1182 return err
1183 }
1184 for _, packet := range packets {
1185 if err := c.skipPacket(packet); err != nil {
1186 return err
1187 }
1188 }
1189 if resendFunc != nil {
1190 resendFunc()
1191 }
1192 }
1193 return nil
1194}
1195
Adam Langley95c29f32014-06-20 12:00:00 -07001196// Write writes data to the connection.
1197func (c *Conn) Write(b []byte) (int, error) {
1198 if err := c.Handshake(); err != nil {
1199 return 0, err
1200 }
1201
1202 c.out.Lock()
1203 defer c.out.Unlock()
1204
1205 if err := c.out.err; err != nil {
1206 return 0, err
1207 }
1208
1209 if !c.handshakeComplete {
1210 return 0, alertInternalError
1211 }
1212
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001213 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001214 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001215 }
1216
Adam Langley27a0d082015-11-03 13:34:10 -08001217 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1218 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
1219 }
1220
Adam Langley95c29f32014-06-20 12:00:00 -07001221 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1222 // attack when using block mode ciphers due to predictable IVs.
1223 // This can be prevented by splitting each Application Data
1224 // record into two records, effectively randomizing the IV.
1225 //
1226 // http://www.openssl.org/~bodo/tls-cbc.txt
1227 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1228 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1229
1230 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001231 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001232 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1233 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1234 if err != nil {
1235 return n, c.out.setErrorLocked(err)
1236 }
1237 m, b = 1, b[1:]
1238 }
1239 }
1240
1241 n, err := c.writeRecord(recordTypeApplicationData, b)
1242 return n + m, c.out.setErrorLocked(err)
1243}
1244
Adam Langley2ae77d22014-10-28 17:29:33 -07001245func (c *Conn) handleRenegotiation() error {
1246 c.handshakeComplete = false
1247 if !c.isClient {
1248 panic("renegotiation should only happen for a client")
1249 }
1250
1251 msg, err := c.readHandshake()
1252 if err != nil {
1253 return err
1254 }
1255 _, ok := msg.(*helloRequestMsg)
1256 if !ok {
1257 c.sendAlert(alertUnexpectedMessage)
1258 return alertUnexpectedMessage
1259 }
1260
1261 return c.Handshake()
1262}
1263
Adam Langleycf2d4f42014-10-28 19:06:14 -07001264func (c *Conn) Renegotiate() error {
1265 if !c.isClient {
David Benjaminef5dfd22015-12-06 13:17:07 -05001266 helloReq := new(helloRequestMsg).marshal()
1267 if c.config.Bugs.BadHelloRequest != nil {
1268 helloReq = c.config.Bugs.BadHelloRequest
1269 }
1270 c.writeRecord(recordTypeHandshake, helloReq)
Adam Langleycf2d4f42014-10-28 19:06:14 -07001271 }
1272
1273 c.handshakeComplete = false
1274 return c.Handshake()
1275}
1276
Adam Langley95c29f32014-06-20 12:00:00 -07001277// Read can be made to time out and return a net.Error with Timeout() == true
1278// after a fixed time limit; see SetDeadline and SetReadDeadline.
1279func (c *Conn) Read(b []byte) (n int, err error) {
1280 if err = c.Handshake(); err != nil {
1281 return
1282 }
1283
1284 c.in.Lock()
1285 defer c.in.Unlock()
1286
1287 // Some OpenSSL servers send empty records in order to randomize the
1288 // CBC IV. So this loop ignores a limited number of empty records.
1289 const maxConsecutiveEmptyRecords = 100
1290 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1291 for c.input == nil && c.in.err == nil {
1292 if err := c.readRecord(recordTypeApplicationData); err != nil {
1293 // Soft error, like EAGAIN
1294 return 0, err
1295 }
David Benjamind9b091b2015-01-27 01:10:54 -05001296 if c.hand.Len() > 0 {
Adam Langley2ae77d22014-10-28 17:29:33 -07001297 // We received handshake bytes, indicating the
David Benjamind9b091b2015-01-27 01:10:54 -05001298 // start of a renegotiation.
Adam Langley2ae77d22014-10-28 17:29:33 -07001299 if err := c.handleRenegotiation(); err != nil {
1300 return 0, err
1301 }
1302 continue
1303 }
Adam Langley95c29f32014-06-20 12:00:00 -07001304 }
1305 if err := c.in.err; err != nil {
1306 return 0, err
1307 }
1308
1309 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001310 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001311 c.in.freeBlock(c.input)
1312 c.input = nil
1313 }
1314
1315 // If a close-notify alert is waiting, read it so that
1316 // we can return (n, EOF) instead of (n, nil), to signal
1317 // to the HTTP response reading goroutine that the
1318 // connection is now closed. This eliminates a race
1319 // where the HTTP response reading goroutine would
1320 // otherwise not observe the EOF until its next read,
1321 // by which time a client goroutine might have already
1322 // tried to reuse the HTTP connection for a new
1323 // request.
1324 // See https://codereview.appspot.com/76400046
1325 // and http://golang.org/issue/3514
1326 if ri := c.rawInput; ri != nil &&
1327 n != 0 && err == nil &&
1328 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1329 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1330 err = recErr // will be io.EOF on closeNotify
1331 }
1332 }
1333
1334 if n != 0 || err != nil {
1335 return n, err
1336 }
1337 }
1338
1339 return 0, io.ErrNoProgress
1340}
1341
1342// Close closes the connection.
1343func (c *Conn) Close() error {
1344 var alertErr error
1345
1346 c.handshakeMutex.Lock()
1347 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001348 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
David Benjaminfa214e42016-05-10 17:03:10 -04001349 alert := alertCloseNotify
1350 if c.config.Bugs.SendAlertOnShutdown != 0 {
1351 alert = c.config.Bugs.SendAlertOnShutdown
1352 }
1353 alertErr = c.sendAlert(alert)
David Benjamin4d559612016-05-18 14:31:51 -04001354 // Clear local alerts when sending alerts so we continue to wait
1355 // for the peer rather than closing the socket early.
1356 if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1357 alertErr = nil
1358 }
Adam Langley95c29f32014-06-20 12:00:00 -07001359 }
1360
David Benjamin30789da2015-08-29 22:56:45 -04001361 // Consume a close_notify from the peer if one hasn't been received
1362 // already. This avoids the peer from failing |SSL_shutdown| due to a
1363 // write failing.
1364 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1365 for c.in.error() == nil {
1366 c.readRecord(recordTypeAlert)
1367 }
1368 if c.in.error() != io.EOF {
1369 alertErr = c.in.error()
1370 }
1371 }
1372
Adam Langley95c29f32014-06-20 12:00:00 -07001373 if err := c.conn.Close(); err != nil {
1374 return err
1375 }
1376 return alertErr
1377}
1378
1379// Handshake runs the client or server handshake
1380// protocol if it has not yet been run.
1381// Most uses of this package need not call Handshake
1382// explicitly: the first Read or Write will call it automatically.
1383func (c *Conn) Handshake() error {
1384 c.handshakeMutex.Lock()
1385 defer c.handshakeMutex.Unlock()
1386 if err := c.handshakeErr; err != nil {
1387 return err
1388 }
1389 if c.handshakeComplete {
1390 return nil
1391 }
1392
David Benjamin9a41d1b2015-05-16 01:30:09 -04001393 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1394 c.conn.Write([]byte{
1395 byte(recordTypeAlert), // type
1396 0xfe, 0xff, // version
1397 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1398 0x0, 0x2, // length
1399 })
1400 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1401 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001402 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1403 c.writeRecord(recordTypeApplicationData, data)
1404 }
Adam Langley95c29f32014-06-20 12:00:00 -07001405 if c.isClient {
1406 c.handshakeErr = c.clientHandshake()
1407 } else {
1408 c.handshakeErr = c.serverHandshake()
1409 }
David Benjaminddb9f152015-02-03 15:44:39 -05001410 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1411 c.writeRecord(recordType(42), []byte("invalid record"))
1412 }
Adam Langley95c29f32014-06-20 12:00:00 -07001413 return c.handshakeErr
1414}
1415
1416// ConnectionState returns basic TLS details about the connection.
1417func (c *Conn) ConnectionState() ConnectionState {
1418 c.handshakeMutex.Lock()
1419 defer c.handshakeMutex.Unlock()
1420
1421 var state ConnectionState
1422 state.HandshakeComplete = c.handshakeComplete
1423 if c.handshakeComplete {
1424 state.Version = c.vers
1425 state.NegotiatedProtocol = c.clientProtocol
1426 state.DidResume = c.didResume
1427 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001428 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001429 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001430 state.PeerCertificates = c.peerCertificates
1431 state.VerifiedChains = c.verifiedChains
1432 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001433 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001434 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001435 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001436 state.SCTList = c.sctList
Nick Harper60edffd2016-06-21 15:19:24 -07001437 state.PeerSignatureAlgorithm = c.peerSignatureAlgorithm
Adam Langley95c29f32014-06-20 12:00:00 -07001438 }
1439
1440 return state
1441}
1442
1443// OCSPResponse returns the stapled OCSP response from the TLS server, if
1444// any. (Only valid for client connections.)
1445func (c *Conn) OCSPResponse() []byte {
1446 c.handshakeMutex.Lock()
1447 defer c.handshakeMutex.Unlock()
1448
1449 return c.ocspResponse
1450}
1451
1452// VerifyHostname checks that the peer certificate chain is valid for
1453// connecting to host. If so, it returns nil; if not, it returns an error
1454// describing the problem.
1455func (c *Conn) VerifyHostname(host string) error {
1456 c.handshakeMutex.Lock()
1457 defer c.handshakeMutex.Unlock()
1458 if !c.isClient {
1459 return errors.New("tls: VerifyHostname called on TLS server connection")
1460 }
1461 if !c.handshakeComplete {
1462 return errors.New("tls: handshake has not yet been performed")
1463 }
1464 return c.peerCertificates[0].VerifyHostname(host)
1465}
David Benjaminc565ebb2015-04-03 04:06:36 -04001466
1467// ExportKeyingMaterial exports keying material from the current connection
1468// state, as per RFC 5705.
1469func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1470 c.handshakeMutex.Lock()
1471 defer c.handshakeMutex.Unlock()
1472 if !c.handshakeComplete {
1473 return nil, errors.New("tls: handshake has not yet been performed")
1474 }
1475
1476 seedLen := len(c.clientRandom) + len(c.serverRandom)
1477 if useContext {
1478 seedLen += 2 + len(context)
1479 }
1480 seed := make([]byte, 0, seedLen)
1481 seed = append(seed, c.clientRandom[:]...)
1482 seed = append(seed, c.serverRandom[:]...)
1483 if useContext {
1484 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1485 seed = append(seed, context...)
1486 }
1487 result := make([]byte, length)
1488 prfForVersion(c.vers, c.cipherSuite)(result, c.masterSecret[:], label, seed)
1489 return result, nil
1490}
David Benjamin3e052de2015-11-25 20:10:31 -05001491
1492// noRenegotiationInfo returns true if the renegotiation info extension
1493// should be supported in the current handshake.
1494func (c *Conn) noRenegotiationInfo() bool {
1495 if c.config.Bugs.NoRenegotiationInfo {
1496 return true
1497 }
1498 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1499 return true
1500 }
1501 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1502 return true
1503 }
1504 return false
1505}