blob: 3b4d0b7040c797ef32bb9443b8a7010533b4195e [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 Benjaminbde00392016-06-21 12:19:28 -0400717 // Alerts sent near version negotiation do not have a well-defined
718 // record-layer version prior to TLS 1.3. (In TLS 1.3, the record-layer
719 // version is irrelevant.)
720 if typ != recordTypeAlert {
721 if c.haveVers {
722 if vers != c.vers && c.vers < VersionTLS13 {
723 c.sendAlert(alertProtocolVersion)
724 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers))
725 }
726 } else {
727 if expect := c.config.Bugs.ExpectInitialRecordVersion; expect != 0 && vers != expect {
728 c.sendAlert(alertProtocolVersion)
729 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
730 }
David Benjamin1e29a6b2014-12-10 02:27:24 -0500731 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400732 }
733 if n > maxCiphertext {
734 c.sendAlert(alertRecordOverflow)
735 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
736 }
737 if !c.haveVers {
738 // First message, be extra suspicious:
739 // this might not be a TLS client.
740 // Bail out before reading a full 'body', if possible.
741 // The current max version is 3.1.
742 // If the version is >= 16.0, it's probably not real.
743 // Similarly, a clientHello message encodes in
744 // well under a kilobyte. If the length is >= 12 kB,
745 // it's probably not real.
746 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
747 c.sendAlert(alertUnexpectedMessage)
748 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
749 }
750 }
751 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
752 if err == io.EOF {
753 err = io.ErrUnexpectedEOF
754 }
755 if e, ok := err.(net.Error); !ok || !e.Temporary() {
756 c.in.setErrorLocked(err)
757 }
758 return 0, nil, err
759 }
760
761 // Process message.
762 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
Nick Harper1fd39d82016-06-14 18:14:35 -0700763 ok, off, encTyp, err := c.in.decrypt(b)
764 if c.vers >= VersionTLS13 && c.in.cipher != nil {
765 // TODO(nharper): Check that outer type (typ) is
766 // application data.
767 typ = encTyp
768 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400769 if !ok {
770 c.in.setErrorLocked(c.sendAlert(err))
771 }
772 b.off = off
773 return typ, b, nil
774}
775
Adam Langley95c29f32014-06-20 12:00:00 -0700776// readRecord reads the next TLS record from the connection
777// and updates the record layer state.
778// c.in.Mutex <= L; c.input == nil.
779func (c *Conn) readRecord(want recordType) error {
780 // Caller must be in sync with connection:
781 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700782 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700783 switch want {
784 default:
785 c.sendAlert(alertInternalError)
786 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
787 case recordTypeHandshake, recordTypeChangeCipherSpec:
788 if c.handshakeComplete {
789 c.sendAlert(alertInternalError)
790 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
791 }
792 case recordTypeApplicationData:
David Benjamine58c4f52014-08-24 03:47:07 -0400793 if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart {
Adam Langley95c29f32014-06-20 12:00:00 -0700794 c.sendAlert(alertInternalError)
795 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
796 }
David Benjamin30789da2015-08-29 22:56:45 -0400797 case recordTypeAlert:
798 // Looking for a close_notify. Note: unlike a real
799 // implementation, this is not tolerant of additional records.
800 // See the documentation for ExpectCloseNotify.
Adam Langley95c29f32014-06-20 12:00:00 -0700801 }
802
803Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400804 typ, b, err := c.doReadRecord(want)
805 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700806 return err
807 }
Adam Langley95c29f32014-06-20 12:00:00 -0700808 data := b.data[b.off:]
809 if len(data) > maxPlaintext {
810 err := c.sendAlert(alertRecordOverflow)
811 c.in.freeBlock(b)
812 return c.in.setErrorLocked(err)
813 }
814
815 switch typ {
816 default:
817 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
818
819 case recordTypeAlert:
820 if len(data) != 2 {
821 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
822 break
823 }
824 if alert(data[1]) == alertCloseNotify {
825 c.in.setErrorLocked(io.EOF)
826 break
827 }
828 switch data[0] {
829 case alertLevelWarning:
830 // drop on the floor
831 c.in.freeBlock(b)
832 goto Again
833 case alertLevelError:
834 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
835 default:
836 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
837 }
838
839 case recordTypeChangeCipherSpec:
840 if typ != want || len(data) != 1 || data[0] != 1 {
841 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
842 break
843 }
Adam Langley80842bd2014-06-20 12:00:00 -0700844 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700845 if err != nil {
846 c.in.setErrorLocked(c.sendAlert(err.(alert)))
847 }
848
849 case recordTypeApplicationData:
850 if typ != want {
851 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
852 break
853 }
854 c.input = b
855 b = nil
856
857 case recordTypeHandshake:
858 // TODO(rsc): Should at least pick off connection close.
859 if typ != want {
Adam Langley2ae77d22014-10-28 17:29:33 -0700860 // A client might need to process a HelloRequest from
861 // the server, thus receiving a handshake message when
David Benjamind9b091b2015-01-27 01:10:54 -0500862 // application data is expected is ok.
David Benjamin30789da2015-08-29 22:56:45 -0400863 if !c.isClient || want != recordTypeApplicationData {
Adam Langley2ae77d22014-10-28 17:29:33 -0700864 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
865 }
Adam Langley95c29f32014-06-20 12:00:00 -0700866 }
867 c.hand.Write(data)
868 }
869
870 if b != nil {
871 c.in.freeBlock(b)
872 }
873 return c.in.err
874}
875
876// sendAlert sends a TLS alert message.
877// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400878func (c *Conn) sendAlertLocked(level byte, err alert) error {
879 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700880 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400881 if c.config.Bugs.FragmentAlert {
882 c.writeRecord(recordTypeAlert, c.tmp[0:1])
883 c.writeRecord(recordTypeAlert, c.tmp[1:2])
David Benjamin0d3a8c62016-03-11 22:25:18 -0500884 } else if c.config.Bugs.DoubleAlert {
885 copy(c.tmp[2:4], c.tmp[0:2])
886 c.writeRecord(recordTypeAlert, c.tmp[0:4])
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400887 } else {
888 c.writeRecord(recordTypeAlert, c.tmp[0:2])
889 }
David Benjamin24f346d2015-06-06 03:28:08 -0400890 // Error alerts are fatal to the connection.
891 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700892 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
893 }
894 return nil
895}
896
897// sendAlert sends a TLS alert message.
898// L < c.out.Mutex.
899func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400900 level := byte(alertLevelError)
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500901 if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertficate {
David Benjamin24f346d2015-06-06 03:28:08 -0400902 level = alertLevelWarning
903 }
904 return c.SendAlert(level, err)
905}
906
907func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700908 c.out.Lock()
909 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -0400910 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -0700911}
912
David Benjamind86c7672014-08-02 04:07:12 -0400913// writeV2Record writes a record for a V2ClientHello.
914func (c *Conn) writeV2Record(data []byte) (n int, err error) {
915 record := make([]byte, 2+len(data))
916 record[0] = uint8(len(data)>>8) | 0x80
917 record[1] = uint8(len(data))
918 copy(record[2:], data)
919 return c.conn.Write(record)
920}
921
Adam Langley95c29f32014-06-20 12:00:00 -0700922// writeRecord writes a TLS record with the given type and payload
923// to the connection and updates the record layer state.
924// c.out.Mutex <= L.
925func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400926 if c.isDTLS {
927 return c.dtlsWriteRecord(typ, data)
928 }
929
930 recordHeaderLen := tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700931 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -0400932 first := true
933 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -0400934 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -0700935 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -0400936 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -0700937 m = maxPlaintext
938 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400939 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
940 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -0400941 // By default, do not fragment the client_version or
942 // server_version, which are located in the first 6
943 // bytes.
944 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
945 m = 6
946 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400947 }
Adam Langley95c29f32014-06-20 12:00:00 -0700948 explicitIVLen := 0
949 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -0400950 first = false
Adam Langley95c29f32014-06-20 12:00:00 -0700951
952 var cbc cbcMode
953 if c.out.version >= VersionTLS11 {
954 var ok bool
955 if cbc, ok = c.out.cipher.(cbcMode); ok {
956 explicitIVLen = cbc.BlockSize()
957 }
958 }
959 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -0400960 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -0700961 explicitIVLen = 8
962 // The AES-GCM construction in TLS has an
963 // explicit nonce so that the nonce can be
964 // random. However, the nonce is only 8 bytes
965 // which is too small for a secure, random
966 // nonce. Therefore we use the sequence number
967 // as the nonce.
968 explicitIVIsSeq = true
969 }
970 }
971 b.resize(recordHeaderLen + explicitIVLen + m)
972 b.data[0] = byte(typ)
Nick Harper1fd39d82016-06-14 18:14:35 -0700973 if c.vers >= VersionTLS13 && c.out.cipher != nil {
974 // TODO(nharper): Add a ProtocolBugs to skip this.
975 b.data[0] = byte(recordTypeApplicationData)
976 }
Adam Langley95c29f32014-06-20 12:00:00 -0700977 vers := c.vers
Nick Harper1fd39d82016-06-14 18:14:35 -0700978 if vers == 0 || vers >= VersionTLS13 {
Adam Langley95c29f32014-06-20 12:00:00 -0700979 // Some TLS servers fail if the record version is
980 // greater than TLS 1.0 for the initial ClientHello.
Nick Harper1fd39d82016-06-14 18:14:35 -0700981 //
982 // TLS 1.3 fixes the version number in the record
983 // layer to {3, 1}.
Adam Langley95c29f32014-06-20 12:00:00 -0700984 vers = VersionTLS10
985 }
986 b.data[1] = byte(vers >> 8)
987 b.data[2] = byte(vers)
988 b.data[3] = byte(m >> 8)
989 b.data[4] = byte(m)
990 if explicitIVLen > 0 {
991 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
992 if explicitIVIsSeq {
993 copy(explicitIV, c.out.seq[:])
994 } else {
995 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
996 break
997 }
998 }
999 }
1000 copy(b.data[recordHeaderLen+explicitIVLen:], data)
Nick Harper1fd39d82016-06-14 18:14:35 -07001001 c.out.encrypt(b, explicitIVLen, typ)
Adam Langley95c29f32014-06-20 12:00:00 -07001002 _, err = c.conn.Write(b.data)
1003 if err != nil {
1004 break
1005 }
1006 n += m
1007 data = data[m:]
1008 }
1009 c.out.freeBlock(b)
1010
1011 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -07001012 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -07001013 if err != nil {
1014 // Cannot call sendAlert directly,
1015 // because we already hold c.out.Mutex.
1016 c.tmp[0] = alertLevelError
1017 c.tmp[1] = byte(err.(alert))
1018 c.writeRecord(recordTypeAlert, c.tmp[0:2])
1019 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
1020 }
1021 }
1022 return
1023}
1024
David Benjamin83c0bc92014-08-04 01:23:53 -04001025func (c *Conn) doReadHandshake() ([]byte, error) {
1026 if c.isDTLS {
1027 return c.dtlsDoReadHandshake()
1028 }
1029
Adam Langley95c29f32014-06-20 12:00:00 -07001030 for c.hand.Len() < 4 {
1031 if err := c.in.err; err != nil {
1032 return nil, err
1033 }
1034 if err := c.readRecord(recordTypeHandshake); err != nil {
1035 return nil, err
1036 }
1037 }
1038
1039 data := c.hand.Bytes()
1040 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1041 if n > maxHandshake {
1042 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
1043 }
1044 for c.hand.Len() < 4+n {
1045 if err := c.in.err; err != nil {
1046 return nil, err
1047 }
1048 if err := c.readRecord(recordTypeHandshake); err != nil {
1049 return nil, err
1050 }
1051 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001052 return c.hand.Next(4 + n), nil
1053}
1054
1055// readHandshake reads the next handshake message from
1056// the record layer.
1057// c.in.Mutex < L; c.out.Mutex < L.
1058func (c *Conn) readHandshake() (interface{}, error) {
1059 data, err := c.doReadHandshake()
1060 if err != nil {
1061 return nil, err
1062 }
1063
Adam Langley95c29f32014-06-20 12:00:00 -07001064 var m handshakeMessage
1065 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001066 case typeHelloRequest:
1067 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001068 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001069 m = &clientHelloMsg{
1070 isDTLS: c.isDTLS,
1071 }
Adam Langley95c29f32014-06-20 12:00:00 -07001072 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001073 m = &serverHelloMsg{
1074 isDTLS: c.isDTLS,
1075 }
Adam Langley95c29f32014-06-20 12:00:00 -07001076 case typeNewSessionTicket:
1077 m = new(newSessionTicketMsg)
1078 case typeCertificate:
1079 m = new(certificateMsg)
1080 case typeCertificateRequest:
1081 m = &certificateRequestMsg{
1082 hasSignatureAndHash: c.vers >= VersionTLS12,
1083 }
1084 case typeCertificateStatus:
1085 m = new(certificateStatusMsg)
1086 case typeServerKeyExchange:
1087 m = new(serverKeyExchangeMsg)
1088 case typeServerHelloDone:
1089 m = new(serverHelloDoneMsg)
1090 case typeClientKeyExchange:
1091 m = new(clientKeyExchangeMsg)
1092 case typeCertificateVerify:
1093 m = &certificateVerifyMsg{
1094 hasSignatureAndHash: c.vers >= VersionTLS12,
1095 }
1096 case typeNextProtocol:
1097 m = new(nextProtoMsg)
1098 case typeFinished:
1099 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001100 case typeHelloVerifyRequest:
1101 m = new(helloVerifyRequestMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001102 case typeEncryptedExtensions:
1103 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001104 default:
1105 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1106 }
1107
1108 // The handshake message unmarshallers
1109 // expect to be able to keep references to data,
1110 // so pass in a fresh copy that won't be overwritten.
1111 data = append([]byte(nil), data...)
1112
1113 if !m.unmarshal(data) {
1114 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1115 }
1116 return m, nil
1117}
1118
David Benjamin83f90402015-01-27 01:09:43 -05001119// skipPacket processes all the DTLS records in packet. It updates
1120// sequence number expectations but otherwise ignores them.
1121func (c *Conn) skipPacket(packet []byte) error {
1122 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001123 if len(packet) < 13 {
1124 return errors.New("tls: bad packet")
1125 }
David Benjamin83f90402015-01-27 01:09:43 -05001126 // Dropped packets are completely ignored save to update
1127 // expected sequence numbers for this and the next epoch. (We
1128 // don't assert on the contents of the packets both for
1129 // simplicity and because a previous test with one shorter
1130 // timeout schedule would have done so.)
1131 epoch := packet[3:5]
1132 seq := packet[5:11]
1133 length := uint16(packet[11])<<8 | uint16(packet[12])
1134 if bytes.Equal(c.in.seq[:2], epoch) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001135 if bytes.Compare(seq, c.in.seq[2:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001136 return errors.New("tls: sequence mismatch")
1137 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001138 copy(c.in.seq[2:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001139 c.in.incSeq(false)
1140 } else {
David Benjamin13e81fc2015-11-02 17:16:13 -05001141 if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001142 return errors.New("tls: sequence mismatch")
1143 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001144 copy(c.in.nextSeq[:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001145 c.in.incNextSeq()
1146 }
David Benjamin6ca93552015-08-28 16:16:25 -04001147 if len(packet) < 13+int(length) {
1148 return errors.New("tls: bad packet")
1149 }
David Benjamin83f90402015-01-27 01:09:43 -05001150 packet = packet[13+length:]
1151 }
1152 return nil
1153}
1154
1155// simulatePacketLoss simulates the loss of a handshake leg from the
1156// peer based on the schedule in c.config.Bugs. If resendFunc is
1157// non-nil, it is called after each simulated timeout to retransmit
1158// handshake messages from the local end. This is used in cases where
1159// the peer retransmits on a stale Finished rather than a timeout.
1160func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1161 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1162 return nil
1163 }
1164 if !c.isDTLS {
1165 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1166 }
1167 if c.config.Bugs.PacketAdaptor == nil {
1168 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1169 }
1170 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1171 // Simulate a timeout.
1172 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1173 if err != nil {
1174 return err
1175 }
1176 for _, packet := range packets {
1177 if err := c.skipPacket(packet); err != nil {
1178 return err
1179 }
1180 }
1181 if resendFunc != nil {
1182 resendFunc()
1183 }
1184 }
1185 return nil
1186}
1187
Adam Langley95c29f32014-06-20 12:00:00 -07001188// Write writes data to the connection.
1189func (c *Conn) Write(b []byte) (int, error) {
1190 if err := c.Handshake(); err != nil {
1191 return 0, err
1192 }
1193
1194 c.out.Lock()
1195 defer c.out.Unlock()
1196
1197 if err := c.out.err; err != nil {
1198 return 0, err
1199 }
1200
1201 if !c.handshakeComplete {
1202 return 0, alertInternalError
1203 }
1204
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001205 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001206 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001207 }
1208
Adam Langley27a0d082015-11-03 13:34:10 -08001209 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1210 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
1211 }
1212
Adam Langley95c29f32014-06-20 12:00:00 -07001213 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1214 // attack when using block mode ciphers due to predictable IVs.
1215 // This can be prevented by splitting each Application Data
1216 // record into two records, effectively randomizing the IV.
1217 //
1218 // http://www.openssl.org/~bodo/tls-cbc.txt
1219 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1220 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1221
1222 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001223 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001224 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1225 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1226 if err != nil {
1227 return n, c.out.setErrorLocked(err)
1228 }
1229 m, b = 1, b[1:]
1230 }
1231 }
1232
1233 n, err := c.writeRecord(recordTypeApplicationData, b)
1234 return n + m, c.out.setErrorLocked(err)
1235}
1236
Adam Langley2ae77d22014-10-28 17:29:33 -07001237func (c *Conn) handleRenegotiation() error {
1238 c.handshakeComplete = false
1239 if !c.isClient {
1240 panic("renegotiation should only happen for a client")
1241 }
1242
1243 msg, err := c.readHandshake()
1244 if err != nil {
1245 return err
1246 }
1247 _, ok := msg.(*helloRequestMsg)
1248 if !ok {
1249 c.sendAlert(alertUnexpectedMessage)
1250 return alertUnexpectedMessage
1251 }
1252
1253 return c.Handshake()
1254}
1255
Adam Langleycf2d4f42014-10-28 19:06:14 -07001256func (c *Conn) Renegotiate() error {
1257 if !c.isClient {
David Benjaminef5dfd22015-12-06 13:17:07 -05001258 helloReq := new(helloRequestMsg).marshal()
1259 if c.config.Bugs.BadHelloRequest != nil {
1260 helloReq = c.config.Bugs.BadHelloRequest
1261 }
1262 c.writeRecord(recordTypeHandshake, helloReq)
Adam Langleycf2d4f42014-10-28 19:06:14 -07001263 }
1264
1265 c.handshakeComplete = false
1266 return c.Handshake()
1267}
1268
Adam Langley95c29f32014-06-20 12:00:00 -07001269// Read can be made to time out and return a net.Error with Timeout() == true
1270// after a fixed time limit; see SetDeadline and SetReadDeadline.
1271func (c *Conn) Read(b []byte) (n int, err error) {
1272 if err = c.Handshake(); err != nil {
1273 return
1274 }
1275
1276 c.in.Lock()
1277 defer c.in.Unlock()
1278
1279 // Some OpenSSL servers send empty records in order to randomize the
1280 // CBC IV. So this loop ignores a limited number of empty records.
1281 const maxConsecutiveEmptyRecords = 100
1282 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1283 for c.input == nil && c.in.err == nil {
1284 if err := c.readRecord(recordTypeApplicationData); err != nil {
1285 // Soft error, like EAGAIN
1286 return 0, err
1287 }
David Benjamind9b091b2015-01-27 01:10:54 -05001288 if c.hand.Len() > 0 {
Adam Langley2ae77d22014-10-28 17:29:33 -07001289 // We received handshake bytes, indicating the
David Benjamind9b091b2015-01-27 01:10:54 -05001290 // start of a renegotiation.
Adam Langley2ae77d22014-10-28 17:29:33 -07001291 if err := c.handleRenegotiation(); err != nil {
1292 return 0, err
1293 }
1294 continue
1295 }
Adam Langley95c29f32014-06-20 12:00:00 -07001296 }
1297 if err := c.in.err; err != nil {
1298 return 0, err
1299 }
1300
1301 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001302 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001303 c.in.freeBlock(c.input)
1304 c.input = nil
1305 }
1306
1307 // If a close-notify alert is waiting, read it so that
1308 // we can return (n, EOF) instead of (n, nil), to signal
1309 // to the HTTP response reading goroutine that the
1310 // connection is now closed. This eliminates a race
1311 // where the HTTP response reading goroutine would
1312 // otherwise not observe the EOF until its next read,
1313 // by which time a client goroutine might have already
1314 // tried to reuse the HTTP connection for a new
1315 // request.
1316 // See https://codereview.appspot.com/76400046
1317 // and http://golang.org/issue/3514
1318 if ri := c.rawInput; ri != nil &&
1319 n != 0 && err == nil &&
1320 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1321 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1322 err = recErr // will be io.EOF on closeNotify
1323 }
1324 }
1325
1326 if n != 0 || err != nil {
1327 return n, err
1328 }
1329 }
1330
1331 return 0, io.ErrNoProgress
1332}
1333
1334// Close closes the connection.
1335func (c *Conn) Close() error {
1336 var alertErr error
1337
1338 c.handshakeMutex.Lock()
1339 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001340 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
David Benjaminfa214e42016-05-10 17:03:10 -04001341 alert := alertCloseNotify
1342 if c.config.Bugs.SendAlertOnShutdown != 0 {
1343 alert = c.config.Bugs.SendAlertOnShutdown
1344 }
1345 alertErr = c.sendAlert(alert)
David Benjamin4d559612016-05-18 14:31:51 -04001346 // Clear local alerts when sending alerts so we continue to wait
1347 // for the peer rather than closing the socket early.
1348 if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1349 alertErr = nil
1350 }
Adam Langley95c29f32014-06-20 12:00:00 -07001351 }
1352
David Benjamin30789da2015-08-29 22:56:45 -04001353 // Consume a close_notify from the peer if one hasn't been received
1354 // already. This avoids the peer from failing |SSL_shutdown| due to a
1355 // write failing.
1356 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1357 for c.in.error() == nil {
1358 c.readRecord(recordTypeAlert)
1359 }
1360 if c.in.error() != io.EOF {
1361 alertErr = c.in.error()
1362 }
1363 }
1364
Adam Langley95c29f32014-06-20 12:00:00 -07001365 if err := c.conn.Close(); err != nil {
1366 return err
1367 }
1368 return alertErr
1369}
1370
1371// Handshake runs the client or server handshake
1372// protocol if it has not yet been run.
1373// Most uses of this package need not call Handshake
1374// explicitly: the first Read or Write will call it automatically.
1375func (c *Conn) Handshake() error {
1376 c.handshakeMutex.Lock()
1377 defer c.handshakeMutex.Unlock()
1378 if err := c.handshakeErr; err != nil {
1379 return err
1380 }
1381 if c.handshakeComplete {
1382 return nil
1383 }
1384
David Benjamin9a41d1b2015-05-16 01:30:09 -04001385 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1386 c.conn.Write([]byte{
1387 byte(recordTypeAlert), // type
1388 0xfe, 0xff, // version
1389 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1390 0x0, 0x2, // length
1391 })
1392 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1393 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001394 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1395 c.writeRecord(recordTypeApplicationData, data)
1396 }
Adam Langley95c29f32014-06-20 12:00:00 -07001397 if c.isClient {
1398 c.handshakeErr = c.clientHandshake()
1399 } else {
1400 c.handshakeErr = c.serverHandshake()
1401 }
David Benjaminddb9f152015-02-03 15:44:39 -05001402 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1403 c.writeRecord(recordType(42), []byte("invalid record"))
1404 }
Adam Langley95c29f32014-06-20 12:00:00 -07001405 return c.handshakeErr
1406}
1407
1408// ConnectionState returns basic TLS details about the connection.
1409func (c *Conn) ConnectionState() ConnectionState {
1410 c.handshakeMutex.Lock()
1411 defer c.handshakeMutex.Unlock()
1412
1413 var state ConnectionState
1414 state.HandshakeComplete = c.handshakeComplete
1415 if c.handshakeComplete {
1416 state.Version = c.vers
1417 state.NegotiatedProtocol = c.clientProtocol
1418 state.DidResume = c.didResume
1419 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001420 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001421 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001422 state.PeerCertificates = c.peerCertificates
1423 state.VerifiedChains = c.verifiedChains
1424 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001425 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001426 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001427 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001428 state.SCTList = c.sctList
Steven Valdez0d62f262015-09-04 12:41:04 -04001429 state.ClientCertSignatureHash = c.clientCertSignatureHash
Adam Langley95c29f32014-06-20 12:00:00 -07001430 }
1431
1432 return state
1433}
1434
1435// OCSPResponse returns the stapled OCSP response from the TLS server, if
1436// any. (Only valid for client connections.)
1437func (c *Conn) OCSPResponse() []byte {
1438 c.handshakeMutex.Lock()
1439 defer c.handshakeMutex.Unlock()
1440
1441 return c.ocspResponse
1442}
1443
1444// VerifyHostname checks that the peer certificate chain is valid for
1445// connecting to host. If so, it returns nil; if not, it returns an error
1446// describing the problem.
1447func (c *Conn) VerifyHostname(host string) error {
1448 c.handshakeMutex.Lock()
1449 defer c.handshakeMutex.Unlock()
1450 if !c.isClient {
1451 return errors.New("tls: VerifyHostname called on TLS server connection")
1452 }
1453 if !c.handshakeComplete {
1454 return errors.New("tls: handshake has not yet been performed")
1455 }
1456 return c.peerCertificates[0].VerifyHostname(host)
1457}
David Benjaminc565ebb2015-04-03 04:06:36 -04001458
1459// ExportKeyingMaterial exports keying material from the current connection
1460// state, as per RFC 5705.
1461func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1462 c.handshakeMutex.Lock()
1463 defer c.handshakeMutex.Unlock()
1464 if !c.handshakeComplete {
1465 return nil, errors.New("tls: handshake has not yet been performed")
1466 }
1467
1468 seedLen := len(c.clientRandom) + len(c.serverRandom)
1469 if useContext {
1470 seedLen += 2 + len(context)
1471 }
1472 seed := make([]byte, 0, seedLen)
1473 seed = append(seed, c.clientRandom[:]...)
1474 seed = append(seed, c.serverRandom[:]...)
1475 if useContext {
1476 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1477 seed = append(seed, context...)
1478 }
1479 result := make([]byte, length)
1480 prfForVersion(c.vers, c.cipherSuite)(result, c.masterSecret[:], label, seed)
1481 return result, nil
1482}
David Benjamin3e052de2015-11-25 20:10:31 -05001483
1484// noRenegotiationInfo returns true if the renegotiation info extension
1485// should be supported in the current handshake.
1486func (c *Conn) noRenegotiationInfo() bool {
1487 if c.config.Bugs.NoRenegotiationInfo {
1488 return true
1489 }
1490 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1491 return true
1492 }
1493 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1494 return true
1495 }
1496 return false
1497}