blob: 3f406bba9f391be1b0fe2ec5b62998f37d8b926b [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:
Nick Harper1fd39d82016-06-14 18:14:35 -0700526 contentTypeLen := 0
527 if hc.version >= VersionTLS13 {
528 contentTypeLen = 1
529 }
Adam Langley95c29f32014-06-20 12:00:00 -0700530 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
Nick Harper1fd39d82016-06-14 18:14:35 -0700531 b.resize(len(b.data) + contentTypeLen + c.Overhead())
532 if hc.version >= VersionTLS13 {
533 b.data[payloadLen+recordHeaderLen] = byte(typ)
534 payloadLen += 1
535 // TODO(nharper): Add ProtocolBugs to add
536 // padding.
537 }
David Benjamin8e6db492015-07-25 18:29:23 -0400538 nonce := hc.outSeq[:]
David Benjamine9a80ff2015-04-07 00:46:46 -0400539 if c.explicitNonce {
540 nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
541 }
Adam Langley95c29f32014-06-20 12:00:00 -0700542 payload := b.data[recordHeaderLen+explicitIVLen:]
543 payload = payload[:payloadLen]
544
Nick Harper1fd39d82016-06-14 18:14:35 -0700545 var additionalData []byte
546 if hc.version < VersionTLS13 {
547 additionalData = make([]byte, 13)
548 copy(additionalData, hc.outSeq[:])
549 copy(additionalData[8:], b.data[:3])
550 additionalData[11] = byte(payloadLen >> 8)
551 additionalData[12] = byte(payloadLen)
552 }
Adam Langley95c29f32014-06-20 12:00:00 -0700553
Nick Harper1fd39d82016-06-14 18:14:35 -0700554 c.Seal(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700555 case cbcMode:
556 blockSize := c.BlockSize()
557 if explicitIVLen > 0 {
558 c.SetIV(payload[:explicitIVLen])
559 payload = payload[explicitIVLen:]
560 }
Adam Langley80842bd2014-06-20 12:00:00 -0700561 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700562 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
563 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
564 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700565 case nullCipher:
566 break
Adam Langley95c29f32014-06-20 12:00:00 -0700567 default:
568 panic("unknown cipher type")
569 }
570 }
571
572 // update length to include MAC and any block padding needed.
573 n := len(b.data) - recordHeaderLen
David Benjamin83c0bc92014-08-04 01:23:53 -0400574 b.data[recordHeaderLen-2] = byte(n >> 8)
575 b.data[recordHeaderLen-1] = byte(n)
David Benjamin5e961c12014-11-07 01:48:35 -0500576 hc.incSeq(true)
Adam Langley95c29f32014-06-20 12:00:00 -0700577
578 return true, 0
579}
580
581// A block is a simple data buffer.
582type block struct {
583 data []byte
584 off int // index for Read
585 link *block
586}
587
588// resize resizes block to be n bytes, growing if necessary.
589func (b *block) resize(n int) {
590 if n > cap(b.data) {
591 b.reserve(n)
592 }
593 b.data = b.data[0:n]
594}
595
596// reserve makes sure that block contains a capacity of at least n bytes.
597func (b *block) reserve(n int) {
598 if cap(b.data) >= n {
599 return
600 }
601 m := cap(b.data)
602 if m == 0 {
603 m = 1024
604 }
605 for m < n {
606 m *= 2
607 }
608 data := make([]byte, len(b.data), m)
609 copy(data, b.data)
610 b.data = data
611}
612
613// readFromUntil reads from r into b until b contains at least n bytes
614// or else returns an error.
615func (b *block) readFromUntil(r io.Reader, n int) error {
616 // quick case
617 if len(b.data) >= n {
618 return nil
619 }
620
621 // read until have enough.
622 b.reserve(n)
623 for {
624 m, err := r.Read(b.data[len(b.data):cap(b.data)])
625 b.data = b.data[0 : len(b.data)+m]
626 if len(b.data) >= n {
627 // TODO(bradfitz,agl): slightly suspicious
628 // that we're throwing away r.Read's err here.
629 break
630 }
631 if err != nil {
632 return err
633 }
634 }
635 return nil
636}
637
638func (b *block) Read(p []byte) (n int, err error) {
639 n = copy(p, b.data[b.off:])
640 b.off += n
641 return
642}
643
644// newBlock allocates a new block, from hc's free list if possible.
645func (hc *halfConn) newBlock() *block {
646 b := hc.bfree
647 if b == nil {
648 return new(block)
649 }
650 hc.bfree = b.link
651 b.link = nil
652 b.resize(0)
653 return b
654}
655
656// freeBlock returns a block to hc's free list.
657// The protocol is such that each side only has a block or two on
658// its free list at a time, so there's no need to worry about
659// trimming the list, etc.
660func (hc *halfConn) freeBlock(b *block) {
661 b.link = hc.bfree
662 hc.bfree = b
663}
664
665// splitBlock splits a block after the first n bytes,
666// returning a block with those n bytes and a
667// block with the remainder. the latter may be nil.
668func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
669 if len(b.data) <= n {
670 return b, nil
671 }
672 bb := hc.newBlock()
673 bb.resize(len(b.data) - n)
674 copy(bb.data, b.data[n:])
675 b.data = b.data[0:n]
676 return b, bb
677}
678
David Benjamin83c0bc92014-08-04 01:23:53 -0400679func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
680 if c.isDTLS {
681 return c.dtlsDoReadRecord(want)
682 }
683
684 recordHeaderLen := tlsRecordHeaderLen
685
686 if c.rawInput == nil {
687 c.rawInput = c.in.newBlock()
688 }
689 b := c.rawInput
690
691 // Read header, payload.
692 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
693 // RFC suggests that EOF without an alertCloseNotify is
694 // an error, but popular web sites seem to do this,
David Benjamin30789da2015-08-29 22:56:45 -0400695 // so we can't make it an error, outside of tests.
696 if err == io.EOF && c.config.Bugs.ExpectCloseNotify {
697 err = io.ErrUnexpectedEOF
698 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400699 if e, ok := err.(net.Error); !ok || !e.Temporary() {
700 c.in.setErrorLocked(err)
701 }
702 return 0, nil, err
703 }
704 typ := recordType(b.data[0])
705
706 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
707 // start with a uint16 length where the MSB is set and the first record
708 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
709 // an SSLv2 client.
710 if want == recordTypeHandshake && typ == 0x80 {
711 c.sendAlert(alertProtocolVersion)
712 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
713 }
714
715 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
716 n := int(b.data[3])<<8 | int(b.data[4])
David Benjamin1e29a6b2014-12-10 02:27:24 -0500717 if c.haveVers {
Nick Harper1fd39d82016-06-14 18:14:35 -0700718 if vers != c.vers && c.vers < VersionTLS13 {
David Benjamin1e29a6b2014-12-10 02:27:24 -0500719 c.sendAlert(alertProtocolVersion)
720 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers))
721 }
722 } else {
723 if expect := c.config.Bugs.ExpectInitialRecordVersion; expect != 0 && vers != expect {
724 c.sendAlert(alertProtocolVersion)
725 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
726 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400727 }
728 if n > maxCiphertext {
729 c.sendAlert(alertRecordOverflow)
730 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
731 }
732 if !c.haveVers {
733 // First message, be extra suspicious:
734 // this might not be a TLS client.
735 // Bail out before reading a full 'body', if possible.
736 // The current max version is 3.1.
737 // If the version is >= 16.0, it's probably not real.
738 // Similarly, a clientHello message encodes in
739 // well under a kilobyte. If the length is >= 12 kB,
740 // it's probably not real.
741 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
742 c.sendAlert(alertUnexpectedMessage)
743 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
744 }
745 }
746 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
747 if err == io.EOF {
748 err = io.ErrUnexpectedEOF
749 }
750 if e, ok := err.(net.Error); !ok || !e.Temporary() {
751 c.in.setErrorLocked(err)
752 }
753 return 0, nil, err
754 }
755
756 // Process message.
757 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
Nick Harper1fd39d82016-06-14 18:14:35 -0700758 ok, off, encTyp, err := c.in.decrypt(b)
759 if c.vers >= VersionTLS13 && c.in.cipher != nil {
760 // TODO(nharper): Check that outer type (typ) is
761 // application data.
762 typ = encTyp
763 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400764 if !ok {
765 c.in.setErrorLocked(c.sendAlert(err))
766 }
767 b.off = off
768 return typ, b, nil
769}
770
Adam Langley95c29f32014-06-20 12:00:00 -0700771// readRecord reads the next TLS record from the connection
772// and updates the record layer state.
773// c.in.Mutex <= L; c.input == nil.
774func (c *Conn) readRecord(want recordType) error {
775 // Caller must be in sync with connection:
776 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700777 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700778 switch want {
779 default:
780 c.sendAlert(alertInternalError)
781 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
782 case recordTypeHandshake, recordTypeChangeCipherSpec:
783 if c.handshakeComplete {
784 c.sendAlert(alertInternalError)
785 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
786 }
787 case recordTypeApplicationData:
David Benjamine58c4f52014-08-24 03:47:07 -0400788 if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart {
Adam Langley95c29f32014-06-20 12:00:00 -0700789 c.sendAlert(alertInternalError)
790 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
791 }
David Benjamin30789da2015-08-29 22:56:45 -0400792 case recordTypeAlert:
793 // Looking for a close_notify. Note: unlike a real
794 // implementation, this is not tolerant of additional records.
795 // See the documentation for ExpectCloseNotify.
Adam Langley95c29f32014-06-20 12:00:00 -0700796 }
797
798Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400799 typ, b, err := c.doReadRecord(want)
800 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700801 return err
802 }
Adam Langley95c29f32014-06-20 12:00:00 -0700803 data := b.data[b.off:]
804 if len(data) > maxPlaintext {
805 err := c.sendAlert(alertRecordOverflow)
806 c.in.freeBlock(b)
807 return c.in.setErrorLocked(err)
808 }
809
810 switch typ {
811 default:
812 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
813
814 case recordTypeAlert:
815 if len(data) != 2 {
816 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
817 break
818 }
819 if alert(data[1]) == alertCloseNotify {
820 c.in.setErrorLocked(io.EOF)
821 break
822 }
823 switch data[0] {
824 case alertLevelWarning:
825 // drop on the floor
826 c.in.freeBlock(b)
827 goto Again
828 case alertLevelError:
829 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
830 default:
831 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
832 }
833
834 case recordTypeChangeCipherSpec:
835 if typ != want || len(data) != 1 || data[0] != 1 {
836 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
837 break
838 }
Adam Langley80842bd2014-06-20 12:00:00 -0700839 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700840 if err != nil {
841 c.in.setErrorLocked(c.sendAlert(err.(alert)))
842 }
843
844 case recordTypeApplicationData:
845 if typ != want {
846 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
847 break
848 }
849 c.input = b
850 b = nil
851
852 case recordTypeHandshake:
853 // TODO(rsc): Should at least pick off connection close.
854 if typ != want {
Adam Langley2ae77d22014-10-28 17:29:33 -0700855 // A client might need to process a HelloRequest from
856 // the server, thus receiving a handshake message when
David Benjamind9b091b2015-01-27 01:10:54 -0500857 // application data is expected is ok.
David Benjamin30789da2015-08-29 22:56:45 -0400858 if !c.isClient || want != recordTypeApplicationData {
Adam Langley2ae77d22014-10-28 17:29:33 -0700859 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
860 }
Adam Langley95c29f32014-06-20 12:00:00 -0700861 }
862 c.hand.Write(data)
863 }
864
865 if b != nil {
866 c.in.freeBlock(b)
867 }
868 return c.in.err
869}
870
871// sendAlert sends a TLS alert message.
872// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400873func (c *Conn) sendAlertLocked(level byte, err alert) error {
874 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700875 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400876 if c.config.Bugs.FragmentAlert {
877 c.writeRecord(recordTypeAlert, c.tmp[0:1])
878 c.writeRecord(recordTypeAlert, c.tmp[1:2])
David Benjamin0d3a8c62016-03-11 22:25:18 -0500879 } else if c.config.Bugs.DoubleAlert {
880 copy(c.tmp[2:4], c.tmp[0:2])
881 c.writeRecord(recordTypeAlert, c.tmp[0:4])
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400882 } else {
883 c.writeRecord(recordTypeAlert, c.tmp[0:2])
884 }
David Benjamin24f346d2015-06-06 03:28:08 -0400885 // Error alerts are fatal to the connection.
886 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700887 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
888 }
889 return nil
890}
891
892// sendAlert sends a TLS alert message.
893// L < c.out.Mutex.
894func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400895 level := byte(alertLevelError)
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500896 if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertficate {
David Benjamin24f346d2015-06-06 03:28:08 -0400897 level = alertLevelWarning
898 }
899 return c.SendAlert(level, err)
900}
901
902func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700903 c.out.Lock()
904 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -0400905 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -0700906}
907
David Benjamind86c7672014-08-02 04:07:12 -0400908// writeV2Record writes a record for a V2ClientHello.
909func (c *Conn) writeV2Record(data []byte) (n int, err error) {
910 record := make([]byte, 2+len(data))
911 record[0] = uint8(len(data)>>8) | 0x80
912 record[1] = uint8(len(data))
913 copy(record[2:], data)
914 return c.conn.Write(record)
915}
916
Adam Langley95c29f32014-06-20 12:00:00 -0700917// writeRecord writes a TLS record with the given type and payload
918// to the connection and updates the record layer state.
919// c.out.Mutex <= L.
920func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400921 if c.isDTLS {
922 return c.dtlsWriteRecord(typ, data)
923 }
924
925 recordHeaderLen := tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700926 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -0400927 first := true
928 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -0400929 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -0700930 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -0400931 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -0700932 m = maxPlaintext
933 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400934 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
935 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -0400936 // By default, do not fragment the client_version or
937 // server_version, which are located in the first 6
938 // bytes.
939 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
940 m = 6
941 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400942 }
Adam Langley95c29f32014-06-20 12:00:00 -0700943 explicitIVLen := 0
944 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -0400945 first = false
Adam Langley95c29f32014-06-20 12:00:00 -0700946
947 var cbc cbcMode
948 if c.out.version >= VersionTLS11 {
949 var ok bool
950 if cbc, ok = c.out.cipher.(cbcMode); ok {
951 explicitIVLen = cbc.BlockSize()
952 }
953 }
954 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -0400955 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -0700956 explicitIVLen = 8
957 // The AES-GCM construction in TLS has an
958 // explicit nonce so that the nonce can be
959 // random. However, the nonce is only 8 bytes
960 // which is too small for a secure, random
961 // nonce. Therefore we use the sequence number
962 // as the nonce.
963 explicitIVIsSeq = true
964 }
965 }
966 b.resize(recordHeaderLen + explicitIVLen + m)
967 b.data[0] = byte(typ)
Nick Harper1fd39d82016-06-14 18:14:35 -0700968 if c.vers >= VersionTLS13 && c.out.cipher != nil {
969 // TODO(nharper): Add a ProtocolBugs to skip this.
970 b.data[0] = byte(recordTypeApplicationData)
971 }
Adam Langley95c29f32014-06-20 12:00:00 -0700972 vers := c.vers
Nick Harper1fd39d82016-06-14 18:14:35 -0700973 if vers == 0 || vers >= VersionTLS13 {
Adam Langley95c29f32014-06-20 12:00:00 -0700974 // Some TLS servers fail if the record version is
975 // greater than TLS 1.0 for the initial ClientHello.
Nick Harper1fd39d82016-06-14 18:14:35 -0700976 //
977 // TLS 1.3 fixes the version number in the record
978 // layer to {3, 1}.
Adam Langley95c29f32014-06-20 12:00:00 -0700979 vers = VersionTLS10
980 }
981 b.data[1] = byte(vers >> 8)
982 b.data[2] = byte(vers)
983 b.data[3] = byte(m >> 8)
984 b.data[4] = byte(m)
985 if explicitIVLen > 0 {
986 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
987 if explicitIVIsSeq {
988 copy(explicitIV, c.out.seq[:])
989 } else {
990 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
991 break
992 }
993 }
994 }
995 copy(b.data[recordHeaderLen+explicitIVLen:], data)
Nick Harper1fd39d82016-06-14 18:14:35 -0700996 c.out.encrypt(b, explicitIVLen, typ)
Adam Langley95c29f32014-06-20 12:00:00 -0700997 _, err = c.conn.Write(b.data)
998 if err != nil {
999 break
1000 }
1001 n += m
1002 data = data[m:]
1003 }
1004 c.out.freeBlock(b)
1005
1006 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -07001007 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -07001008 if err != nil {
1009 // Cannot call sendAlert directly,
1010 // because we already hold c.out.Mutex.
1011 c.tmp[0] = alertLevelError
1012 c.tmp[1] = byte(err.(alert))
1013 c.writeRecord(recordTypeAlert, c.tmp[0:2])
1014 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
1015 }
1016 }
1017 return
1018}
1019
David Benjamin83c0bc92014-08-04 01:23:53 -04001020func (c *Conn) doReadHandshake() ([]byte, error) {
1021 if c.isDTLS {
1022 return c.dtlsDoReadHandshake()
1023 }
1024
Adam Langley95c29f32014-06-20 12:00:00 -07001025 for c.hand.Len() < 4 {
1026 if err := c.in.err; err != nil {
1027 return nil, err
1028 }
1029 if err := c.readRecord(recordTypeHandshake); err != nil {
1030 return nil, err
1031 }
1032 }
1033
1034 data := c.hand.Bytes()
1035 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1036 if n > maxHandshake {
1037 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
1038 }
1039 for c.hand.Len() < 4+n {
1040 if err := c.in.err; err != nil {
1041 return nil, err
1042 }
1043 if err := c.readRecord(recordTypeHandshake); err != nil {
1044 return nil, err
1045 }
1046 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001047 return c.hand.Next(4 + n), nil
1048}
1049
1050// readHandshake reads the next handshake message from
1051// the record layer.
1052// c.in.Mutex < L; c.out.Mutex < L.
1053func (c *Conn) readHandshake() (interface{}, error) {
1054 data, err := c.doReadHandshake()
1055 if err != nil {
1056 return nil, err
1057 }
1058
Adam Langley95c29f32014-06-20 12:00:00 -07001059 var m handshakeMessage
1060 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001061 case typeHelloRequest:
1062 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001063 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001064 m = &clientHelloMsg{
1065 isDTLS: c.isDTLS,
1066 }
Adam Langley95c29f32014-06-20 12:00:00 -07001067 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001068 m = &serverHelloMsg{
1069 isDTLS: c.isDTLS,
1070 }
Adam Langley95c29f32014-06-20 12:00:00 -07001071 case typeNewSessionTicket:
1072 m = new(newSessionTicketMsg)
1073 case typeCertificate:
1074 m = new(certificateMsg)
1075 case typeCertificateRequest:
1076 m = &certificateRequestMsg{
1077 hasSignatureAndHash: c.vers >= VersionTLS12,
1078 }
1079 case typeCertificateStatus:
1080 m = new(certificateStatusMsg)
1081 case typeServerKeyExchange:
1082 m = new(serverKeyExchangeMsg)
1083 case typeServerHelloDone:
1084 m = new(serverHelloDoneMsg)
1085 case typeClientKeyExchange:
1086 m = new(clientKeyExchangeMsg)
1087 case typeCertificateVerify:
1088 m = &certificateVerifyMsg{
1089 hasSignatureAndHash: c.vers >= VersionTLS12,
1090 }
1091 case typeNextProtocol:
1092 m = new(nextProtoMsg)
1093 case typeFinished:
1094 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001095 case typeHelloVerifyRequest:
1096 m = new(helloVerifyRequestMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001097 case typeEncryptedExtensions:
1098 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001099 default:
1100 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1101 }
1102
1103 // The handshake message unmarshallers
1104 // expect to be able to keep references to data,
1105 // so pass in a fresh copy that won't be overwritten.
1106 data = append([]byte(nil), data...)
1107
1108 if !m.unmarshal(data) {
1109 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1110 }
1111 return m, nil
1112}
1113
David Benjamin83f90402015-01-27 01:09:43 -05001114// skipPacket processes all the DTLS records in packet. It updates
1115// sequence number expectations but otherwise ignores them.
1116func (c *Conn) skipPacket(packet []byte) error {
1117 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001118 if len(packet) < 13 {
1119 return errors.New("tls: bad packet")
1120 }
David Benjamin83f90402015-01-27 01:09:43 -05001121 // Dropped packets are completely ignored save to update
1122 // expected sequence numbers for this and the next epoch. (We
1123 // don't assert on the contents of the packets both for
1124 // simplicity and because a previous test with one shorter
1125 // timeout schedule would have done so.)
1126 epoch := packet[3:5]
1127 seq := packet[5:11]
1128 length := uint16(packet[11])<<8 | uint16(packet[12])
1129 if bytes.Equal(c.in.seq[:2], epoch) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001130 if bytes.Compare(seq, c.in.seq[2:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001131 return errors.New("tls: sequence mismatch")
1132 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001133 copy(c.in.seq[2:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001134 c.in.incSeq(false)
1135 } else {
David Benjamin13e81fc2015-11-02 17:16:13 -05001136 if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001137 return errors.New("tls: sequence mismatch")
1138 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001139 copy(c.in.nextSeq[:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001140 c.in.incNextSeq()
1141 }
David Benjamin6ca93552015-08-28 16:16:25 -04001142 if len(packet) < 13+int(length) {
1143 return errors.New("tls: bad packet")
1144 }
David Benjamin83f90402015-01-27 01:09:43 -05001145 packet = packet[13+length:]
1146 }
1147 return nil
1148}
1149
1150// simulatePacketLoss simulates the loss of a handshake leg from the
1151// peer based on the schedule in c.config.Bugs. If resendFunc is
1152// non-nil, it is called after each simulated timeout to retransmit
1153// handshake messages from the local end. This is used in cases where
1154// the peer retransmits on a stale Finished rather than a timeout.
1155func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1156 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1157 return nil
1158 }
1159 if !c.isDTLS {
1160 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1161 }
1162 if c.config.Bugs.PacketAdaptor == nil {
1163 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1164 }
1165 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1166 // Simulate a timeout.
1167 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1168 if err != nil {
1169 return err
1170 }
1171 for _, packet := range packets {
1172 if err := c.skipPacket(packet); err != nil {
1173 return err
1174 }
1175 }
1176 if resendFunc != nil {
1177 resendFunc()
1178 }
1179 }
1180 return nil
1181}
1182
Adam Langley95c29f32014-06-20 12:00:00 -07001183// Write writes data to the connection.
1184func (c *Conn) Write(b []byte) (int, error) {
1185 if err := c.Handshake(); err != nil {
1186 return 0, err
1187 }
1188
1189 c.out.Lock()
1190 defer c.out.Unlock()
1191
1192 if err := c.out.err; err != nil {
1193 return 0, err
1194 }
1195
1196 if !c.handshakeComplete {
1197 return 0, alertInternalError
1198 }
1199
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001200 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001201 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001202 }
1203
Adam Langley27a0d082015-11-03 13:34:10 -08001204 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1205 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
1206 }
1207
Adam Langley95c29f32014-06-20 12:00:00 -07001208 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1209 // attack when using block mode ciphers due to predictable IVs.
1210 // This can be prevented by splitting each Application Data
1211 // record into two records, effectively randomizing the IV.
1212 //
1213 // http://www.openssl.org/~bodo/tls-cbc.txt
1214 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1215 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1216
1217 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001218 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001219 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1220 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1221 if err != nil {
1222 return n, c.out.setErrorLocked(err)
1223 }
1224 m, b = 1, b[1:]
1225 }
1226 }
1227
1228 n, err := c.writeRecord(recordTypeApplicationData, b)
1229 return n + m, c.out.setErrorLocked(err)
1230}
1231
Adam Langley2ae77d22014-10-28 17:29:33 -07001232func (c *Conn) handleRenegotiation() error {
1233 c.handshakeComplete = false
1234 if !c.isClient {
1235 panic("renegotiation should only happen for a client")
1236 }
1237
1238 msg, err := c.readHandshake()
1239 if err != nil {
1240 return err
1241 }
1242 _, ok := msg.(*helloRequestMsg)
1243 if !ok {
1244 c.sendAlert(alertUnexpectedMessage)
1245 return alertUnexpectedMessage
1246 }
1247
1248 return c.Handshake()
1249}
1250
Adam Langleycf2d4f42014-10-28 19:06:14 -07001251func (c *Conn) Renegotiate() error {
1252 if !c.isClient {
David Benjaminef5dfd22015-12-06 13:17:07 -05001253 helloReq := new(helloRequestMsg).marshal()
1254 if c.config.Bugs.BadHelloRequest != nil {
1255 helloReq = c.config.Bugs.BadHelloRequest
1256 }
1257 c.writeRecord(recordTypeHandshake, helloReq)
Adam Langleycf2d4f42014-10-28 19:06:14 -07001258 }
1259
1260 c.handshakeComplete = false
1261 return c.Handshake()
1262}
1263
Adam Langley95c29f32014-06-20 12:00:00 -07001264// Read can be made to time out and return a net.Error with Timeout() == true
1265// after a fixed time limit; see SetDeadline and SetReadDeadline.
1266func (c *Conn) Read(b []byte) (n int, err error) {
1267 if err = c.Handshake(); err != nil {
1268 return
1269 }
1270
1271 c.in.Lock()
1272 defer c.in.Unlock()
1273
1274 // Some OpenSSL servers send empty records in order to randomize the
1275 // CBC IV. So this loop ignores a limited number of empty records.
1276 const maxConsecutiveEmptyRecords = 100
1277 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1278 for c.input == nil && c.in.err == nil {
1279 if err := c.readRecord(recordTypeApplicationData); err != nil {
1280 // Soft error, like EAGAIN
1281 return 0, err
1282 }
David Benjamind9b091b2015-01-27 01:10:54 -05001283 if c.hand.Len() > 0 {
Adam Langley2ae77d22014-10-28 17:29:33 -07001284 // We received handshake bytes, indicating the
David Benjamind9b091b2015-01-27 01:10:54 -05001285 // start of a renegotiation.
Adam Langley2ae77d22014-10-28 17:29:33 -07001286 if err := c.handleRenegotiation(); err != nil {
1287 return 0, err
1288 }
1289 continue
1290 }
Adam Langley95c29f32014-06-20 12:00:00 -07001291 }
1292 if err := c.in.err; err != nil {
1293 return 0, err
1294 }
1295
1296 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001297 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001298 c.in.freeBlock(c.input)
1299 c.input = nil
1300 }
1301
1302 // If a close-notify alert is waiting, read it so that
1303 // we can return (n, EOF) instead of (n, nil), to signal
1304 // to the HTTP response reading goroutine that the
1305 // connection is now closed. This eliminates a race
1306 // where the HTTP response reading goroutine would
1307 // otherwise not observe the EOF until its next read,
1308 // by which time a client goroutine might have already
1309 // tried to reuse the HTTP connection for a new
1310 // request.
1311 // See https://codereview.appspot.com/76400046
1312 // and http://golang.org/issue/3514
1313 if ri := c.rawInput; ri != nil &&
1314 n != 0 && err == nil &&
1315 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1316 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1317 err = recErr // will be io.EOF on closeNotify
1318 }
1319 }
1320
1321 if n != 0 || err != nil {
1322 return n, err
1323 }
1324 }
1325
1326 return 0, io.ErrNoProgress
1327}
1328
1329// Close closes the connection.
1330func (c *Conn) Close() error {
1331 var alertErr error
1332
1333 c.handshakeMutex.Lock()
1334 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001335 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
David Benjaminfa214e42016-05-10 17:03:10 -04001336 alert := alertCloseNotify
1337 if c.config.Bugs.SendAlertOnShutdown != 0 {
1338 alert = c.config.Bugs.SendAlertOnShutdown
1339 }
1340 alertErr = c.sendAlert(alert)
David Benjamin4d559612016-05-18 14:31:51 -04001341 // Clear local alerts when sending alerts so we continue to wait
1342 // for the peer rather than closing the socket early.
1343 if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1344 alertErr = nil
1345 }
Adam Langley95c29f32014-06-20 12:00:00 -07001346 }
1347
David Benjamin30789da2015-08-29 22:56:45 -04001348 // Consume a close_notify from the peer if one hasn't been received
1349 // already. This avoids the peer from failing |SSL_shutdown| due to a
1350 // write failing.
1351 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1352 for c.in.error() == nil {
1353 c.readRecord(recordTypeAlert)
1354 }
1355 if c.in.error() != io.EOF {
1356 alertErr = c.in.error()
1357 }
1358 }
1359
Adam Langley95c29f32014-06-20 12:00:00 -07001360 if err := c.conn.Close(); err != nil {
1361 return err
1362 }
1363 return alertErr
1364}
1365
1366// Handshake runs the client or server handshake
1367// protocol if it has not yet been run.
1368// Most uses of this package need not call Handshake
1369// explicitly: the first Read or Write will call it automatically.
1370func (c *Conn) Handshake() error {
1371 c.handshakeMutex.Lock()
1372 defer c.handshakeMutex.Unlock()
1373 if err := c.handshakeErr; err != nil {
1374 return err
1375 }
1376 if c.handshakeComplete {
1377 return nil
1378 }
1379
David Benjamin9a41d1b2015-05-16 01:30:09 -04001380 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1381 c.conn.Write([]byte{
1382 byte(recordTypeAlert), // type
1383 0xfe, 0xff, // version
1384 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1385 0x0, 0x2, // length
1386 })
1387 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1388 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001389 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1390 c.writeRecord(recordTypeApplicationData, data)
1391 }
Adam Langley95c29f32014-06-20 12:00:00 -07001392 if c.isClient {
1393 c.handshakeErr = c.clientHandshake()
1394 } else {
1395 c.handshakeErr = c.serverHandshake()
1396 }
David Benjaminddb9f152015-02-03 15:44:39 -05001397 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1398 c.writeRecord(recordType(42), []byte("invalid record"))
1399 }
Adam Langley95c29f32014-06-20 12:00:00 -07001400 return c.handshakeErr
1401}
1402
1403// ConnectionState returns basic TLS details about the connection.
1404func (c *Conn) ConnectionState() ConnectionState {
1405 c.handshakeMutex.Lock()
1406 defer c.handshakeMutex.Unlock()
1407
1408 var state ConnectionState
1409 state.HandshakeComplete = c.handshakeComplete
1410 if c.handshakeComplete {
1411 state.Version = c.vers
1412 state.NegotiatedProtocol = c.clientProtocol
1413 state.DidResume = c.didResume
1414 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001415 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001416 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001417 state.PeerCertificates = c.peerCertificates
1418 state.VerifiedChains = c.verifiedChains
1419 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001420 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001421 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001422 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001423 state.SCTList = c.sctList
Steven Valdez0d62f262015-09-04 12:41:04 -04001424 state.ClientCertSignatureHash = c.clientCertSignatureHash
Adam Langley95c29f32014-06-20 12:00:00 -07001425 }
1426
1427 return state
1428}
1429
1430// OCSPResponse returns the stapled OCSP response from the TLS server, if
1431// any. (Only valid for client connections.)
1432func (c *Conn) OCSPResponse() []byte {
1433 c.handshakeMutex.Lock()
1434 defer c.handshakeMutex.Unlock()
1435
1436 return c.ocspResponse
1437}
1438
1439// VerifyHostname checks that the peer certificate chain is valid for
1440// connecting to host. If so, it returns nil; if not, it returns an error
1441// describing the problem.
1442func (c *Conn) VerifyHostname(host string) error {
1443 c.handshakeMutex.Lock()
1444 defer c.handshakeMutex.Unlock()
1445 if !c.isClient {
1446 return errors.New("tls: VerifyHostname called on TLS server connection")
1447 }
1448 if !c.handshakeComplete {
1449 return errors.New("tls: handshake has not yet been performed")
1450 }
1451 return c.peerCertificates[0].VerifyHostname(host)
1452}
David Benjaminc565ebb2015-04-03 04:06:36 -04001453
1454// ExportKeyingMaterial exports keying material from the current connection
1455// state, as per RFC 5705.
1456func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1457 c.handshakeMutex.Lock()
1458 defer c.handshakeMutex.Unlock()
1459 if !c.handshakeComplete {
1460 return nil, errors.New("tls: handshake has not yet been performed")
1461 }
1462
1463 seedLen := len(c.clientRandom) + len(c.serverRandom)
1464 if useContext {
1465 seedLen += 2 + len(context)
1466 }
1467 seed := make([]byte, 0, seedLen)
1468 seed = append(seed, c.clientRandom[:]...)
1469 seed = append(seed, c.serverRandom[:]...)
1470 if useContext {
1471 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1472 seed = append(seed, context...)
1473 }
1474 result := make([]byte, length)
1475 prfForVersion(c.vers, c.cipherSuite)(result, c.masterSecret[:], label, seed)
1476 return result, nil
1477}
David Benjamin3e052de2015-11-25 20:10:31 -05001478
1479// noRenegotiationInfo returns true if the renegotiation info extension
1480// should be supported in the current handshake.
1481func (c *Conn) noRenegotiationInfo() bool {
1482 if c.config.Bugs.NoRenegotiationInfo {
1483 return true
1484 }
1485 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1486 return true
1487 }
1488 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1489 return true
1490 }
1491 return false
1492}