blob: 9969f8b5bec72ace5c5e4106adbeffce19afc5e9 [file] [log] [blame]
Adam Langley95c29f32014-06-20 12:00:00 -07001// Copyright 2010 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5// TLS low level connection and record layer
6
Adam Langleydc7e9c42015-09-29 15:21:04 -07007package runner
Adam Langley95c29f32014-06-20 12:00:00 -07008
9import (
10 "bytes"
11 "crypto/cipher"
David Benjamind30a9902014-08-24 01:44:23 -040012 "crypto/ecdsa"
Adam Langley95c29f32014-06-20 12:00:00 -070013 "crypto/subtle"
14 "crypto/x509"
David Benjamin8e6db492015-07-25 18:29:23 -040015 "encoding/binary"
Adam Langley95c29f32014-06-20 12:00:00 -070016 "errors"
17 "fmt"
18 "io"
19 "net"
20 "sync"
21 "time"
22)
23
24// A Conn represents a secured connection.
25// It implements the net.Conn interface.
26type Conn struct {
27 // constant
28 conn net.Conn
David Benjamin83c0bc92014-08-04 01:23:53 -040029 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -070030 isClient bool
31
32 // constant after handshake; protected by handshakeMutex
Adam Langley75712922014-10-10 16:23:43 -070033 handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
34 handshakeErr error // error resulting from handshake
35 vers uint16 // TLS version
36 haveVers bool // version has been negotiated
37 config *Config // configuration passed to constructor
38 handshakeComplete bool
39 didResume bool // whether this connection was a session resumption
40 extendedMasterSecret bool // whether this session used an extended master secret
David Benjaminc565ebb2015-04-03 04:06:36 -040041 cipherSuite *cipherSuite
Adam Langley75712922014-10-10 16:23:43 -070042 ocspResponse []byte // stapled OCSP response
Paul Lietar4fac72e2015-09-09 13:44:55 +010043 sctList []byte // signed certificate timestamp list
Adam Langley75712922014-10-10 16:23:43 -070044 peerCertificates []*x509.Certificate
Adam Langley95c29f32014-06-20 12:00:00 -070045 // verifiedChains contains the certificate chains that we built, as
46 // opposed to the ones presented by the server.
47 verifiedChains [][]*x509.Certificate
48 // serverName contains the server name indicated by the client, if any.
Adam Langleyaf0e32c2015-06-03 09:57:23 -070049 serverName string
50 // firstFinished contains the first Finished hash sent during the
51 // handshake. This is the "tls-unique" channel binding value.
52 firstFinished [12]byte
Nick Harper60edffd2016-06-21 15:19:24 -070053 // peerSignatureAlgorithm contains the signature algorithm that was used
54 // by the peer in the handshake, or zero if not applicable.
55 peerSignatureAlgorithm signatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -040056 // curveID contains the curve that was used in the handshake, or zero if
57 // not applicable.
58 curveID CurveID
Adam Langleyaf0e32c2015-06-03 09:57:23 -070059
David Benjaminc565ebb2015-04-03 04:06:36 -040060 clientRandom, serverRandom [32]byte
David Benjamin97a0a082016-07-13 17:57:35 -040061 exporterSecret []byte
David Benjamin58104882016-07-18 01:25:41 +020062 resumptionSecret []byte
Adam Langley95c29f32014-06-20 12:00:00 -070063
64 clientProtocol string
65 clientProtocolFallback bool
David Benjaminfc7b0862014-09-06 13:21:53 -040066 usedALPN bool
Adam Langley95c29f32014-06-20 12:00:00 -070067
Adam Langley2ae77d22014-10-28 17:29:33 -070068 // verify_data values for the renegotiation extension.
69 clientVerify []byte
70 serverVerify []byte
71
David Benjamind30a9902014-08-24 01:44:23 -040072 channelID *ecdsa.PublicKey
73
David Benjaminca6c8262014-11-15 19:06:08 -050074 srtpProtectionProfile uint16
75
David Benjaminc44b1df2014-11-23 12:11:01 -050076 clientVersion uint16
77
Adam Langley95c29f32014-06-20 12:00:00 -070078 // input/output
79 in, out halfConn // in.Mutex < out.Mutex
80 rawInput *block // raw input, right off the wire
David Benjamin83c0bc92014-08-04 01:23:53 -040081 input *block // application record waiting to be read
82 hand bytes.Buffer // handshake record waiting to be read
83
David Benjamin582ba042016-07-07 12:33:25 -070084 // pendingFlight, if PackHandshakeFlight is enabled, is the buffer of
85 // handshake data to be split into records at the end of the flight.
86 pendingFlight bytes.Buffer
87
David Benjamin83c0bc92014-08-04 01:23:53 -040088 // DTLS state
89 sendHandshakeSeq uint16
90 recvHandshakeSeq uint16
David Benjaminb3774b92015-01-31 17:16:01 -050091 handMsg []byte // pending assembled handshake message
92 handMsgLen int // handshake message length, not including the header
93 pendingFragments [][]byte // pending outgoing handshake fragments.
Adam Langley95c29f32014-06-20 12:00:00 -070094
95 tmp [16]byte
96}
97
David Benjamin5e961c12014-11-07 01:48:35 -050098func (c *Conn) init() {
99 c.in.isDTLS = c.isDTLS
100 c.out.isDTLS = c.isDTLS
101 c.in.config = c.config
102 c.out.config = c.config
David Benjamin8e6db492015-07-25 18:29:23 -0400103
104 c.out.updateOutSeq()
David Benjamin5e961c12014-11-07 01:48:35 -0500105}
106
Adam Langley95c29f32014-06-20 12:00:00 -0700107// Access to net.Conn methods.
108// Cannot just embed net.Conn because that would
109// export the struct field too.
110
111// LocalAddr returns the local network address.
112func (c *Conn) LocalAddr() net.Addr {
113 return c.conn.LocalAddr()
114}
115
116// RemoteAddr returns the remote network address.
117func (c *Conn) RemoteAddr() net.Addr {
118 return c.conn.RemoteAddr()
119}
120
121// SetDeadline sets the read and write deadlines associated with the connection.
122// A zero value for t means Read and Write will not time out.
123// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
124func (c *Conn) SetDeadline(t time.Time) error {
125 return c.conn.SetDeadline(t)
126}
127
128// SetReadDeadline sets the read deadline on the underlying connection.
129// A zero value for t means Read will not time out.
130func (c *Conn) SetReadDeadline(t time.Time) error {
131 return c.conn.SetReadDeadline(t)
132}
133
134// SetWriteDeadline sets the write deadline on the underlying conneciton.
135// A zero value for t means Write will not time out.
136// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
137func (c *Conn) SetWriteDeadline(t time.Time) error {
138 return c.conn.SetWriteDeadline(t)
139}
140
141// A halfConn represents one direction of the record layer
142// connection, either sending or receiving.
143type halfConn struct {
144 sync.Mutex
145
David Benjamin83c0bc92014-08-04 01:23:53 -0400146 err error // first permanent error
147 version uint16 // protocol version
148 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -0700149 cipher interface{} // cipher algorithm
150 mac macFunction
151 seq [8]byte // 64-bit sequence number
David Benjamin8e6db492015-07-25 18:29:23 -0400152 outSeq [8]byte // Mapped sequence number
Adam Langley95c29f32014-06-20 12:00:00 -0700153 bfree *block // list of free blocks
154
155 nextCipher interface{} // next encryption state
156 nextMac macFunction // next MAC algorithm
David Benjamin83f90402015-01-27 01:09:43 -0500157 nextSeq [6]byte // next epoch's starting sequence number in DTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700158
159 // used to save allocating a new buffer for each MAC.
160 inDigestBuf, outDigestBuf []byte
Adam Langley80842bd2014-06-20 12:00:00 -0700161
David Benjamin21c00282016-07-18 21:56:23 +0200162 trafficSecret []byte
163 keyUpdateGeneration int
164
Adam Langley80842bd2014-06-20 12:00:00 -0700165 config *Config
Adam Langley95c29f32014-06-20 12:00:00 -0700166}
167
168func (hc *halfConn) setErrorLocked(err error) error {
169 hc.err = err
170 return err
171}
172
173func (hc *halfConn) error() error {
Adam Langley2ae77d22014-10-28 17:29:33 -0700174 // This should be locked, but I've removed it for the renegotiation
175 // tests since we don't concurrently read and write the same tls.Conn
176 // in any case during testing.
Adam Langley95c29f32014-06-20 12:00:00 -0700177 err := hc.err
Adam Langley95c29f32014-06-20 12:00:00 -0700178 return err
179}
180
181// prepareCipherSpec sets the encryption and MAC states
182// that a subsequent changeCipherSpec will use.
183func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
184 hc.version = version
185 hc.nextCipher = cipher
186 hc.nextMac = mac
187}
188
189// changeCipherSpec changes the encryption and MAC states
190// to the ones previously passed to prepareCipherSpec.
Adam Langley80842bd2014-06-20 12:00:00 -0700191func (hc *halfConn) changeCipherSpec(config *Config) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700192 if hc.nextCipher == nil {
193 return alertInternalError
194 }
195 hc.cipher = hc.nextCipher
196 hc.mac = hc.nextMac
197 hc.nextCipher = nil
198 hc.nextMac = nil
Adam Langley80842bd2014-06-20 12:00:00 -0700199 hc.config = config
David Benjamin83c0bc92014-08-04 01:23:53 -0400200 hc.incEpoch()
David Benjaminf2b83632016-03-01 22:57:46 -0500201
202 if config.Bugs.NullAllCiphers {
203 hc.cipher = nil
204 hc.mac = nil
205 }
Adam Langley95c29f32014-06-20 12:00:00 -0700206 return nil
207}
208
David Benjamin21c00282016-07-18 21:56:23 +0200209// useTrafficSecret sets the current cipher state for TLS 1.3.
210func (hc *halfConn) useTrafficSecret(version uint16, suite *cipherSuite, secret, phase []byte, side trafficDirection) {
Nick Harperb41d2e42016-07-01 17:50:32 -0400211 hc.version = version
David Benjamin21c00282016-07-18 21:56:23 +0200212 hc.cipher = deriveTrafficAEAD(version, suite, secret, phase, side)
213 hc.trafficSecret = secret
Nick Harperb41d2e42016-07-01 17:50:32 -0400214 hc.incEpoch()
215}
216
David Benjamin21c00282016-07-18 21:56:23 +0200217func (hc *halfConn) doKeyUpdate(c *Conn, isOutgoing bool) {
218 side := serverWrite
219 if c.isClient == isOutgoing {
220 side = clientWrite
221 }
222 hc.useTrafficSecret(hc.version, c.cipherSuite, updateTrafficSecret(c.cipherSuite.hash(), hc.trafficSecret), applicationPhase, side)
223 hc.keyUpdateGeneration++
224}
225
Adam Langley95c29f32014-06-20 12:00:00 -0700226// incSeq increments the sequence number.
David Benjamin5e961c12014-11-07 01:48:35 -0500227func (hc *halfConn) incSeq(isOutgoing bool) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400228 limit := 0
David Benjamin5e961c12014-11-07 01:48:35 -0500229 increment := uint64(1)
David Benjamin83c0bc92014-08-04 01:23:53 -0400230 if hc.isDTLS {
231 // Increment up to the epoch in DTLS.
232 limit = 2
233 }
234 for i := 7; i >= limit; i-- {
David Benjamin5e961c12014-11-07 01:48:35 -0500235 increment += uint64(hc.seq[i])
236 hc.seq[i] = byte(increment)
237 increment >>= 8
Adam Langley95c29f32014-06-20 12:00:00 -0700238 }
239
240 // Not allowed to let sequence number wrap.
241 // Instead, must renegotiate before it does.
242 // Not likely enough to bother.
David Benjamin5e961c12014-11-07 01:48:35 -0500243 if increment != 0 {
244 panic("TLS: sequence number wraparound")
245 }
David Benjamin8e6db492015-07-25 18:29:23 -0400246
247 hc.updateOutSeq()
Adam Langley95c29f32014-06-20 12:00:00 -0700248}
249
David Benjamin83f90402015-01-27 01:09:43 -0500250// incNextSeq increments the starting sequence number for the next epoch.
251func (hc *halfConn) incNextSeq() {
252 for i := len(hc.nextSeq) - 1; i >= 0; i-- {
253 hc.nextSeq[i]++
254 if hc.nextSeq[i] != 0 {
255 return
256 }
257 }
258 panic("TLS: sequence number wraparound")
259}
260
261// incEpoch resets the sequence number. In DTLS, it also increments the epoch
262// half of the sequence number.
David Benjamin83c0bc92014-08-04 01:23:53 -0400263func (hc *halfConn) incEpoch() {
David Benjamin83c0bc92014-08-04 01:23:53 -0400264 if hc.isDTLS {
265 for i := 1; i >= 0; i-- {
266 hc.seq[i]++
267 if hc.seq[i] != 0 {
268 break
269 }
270 if i == 0 {
271 panic("TLS: epoch number wraparound")
272 }
273 }
David Benjamin83f90402015-01-27 01:09:43 -0500274 copy(hc.seq[2:], hc.nextSeq[:])
275 for i := range hc.nextSeq {
276 hc.nextSeq[i] = 0
277 }
278 } else {
279 for i := range hc.seq {
280 hc.seq[i] = 0
281 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400282 }
David Benjamin8e6db492015-07-25 18:29:23 -0400283
284 hc.updateOutSeq()
285}
286
287func (hc *halfConn) updateOutSeq() {
288 if hc.config.Bugs.SequenceNumberMapping != nil {
289 seqU64 := binary.BigEndian.Uint64(hc.seq[:])
290 seqU64 = hc.config.Bugs.SequenceNumberMapping(seqU64)
291 binary.BigEndian.PutUint64(hc.outSeq[:], seqU64)
292
293 // The DTLS epoch cannot be changed.
294 copy(hc.outSeq[:2], hc.seq[:2])
295 return
296 }
297
298 copy(hc.outSeq[:], hc.seq[:])
David Benjamin83c0bc92014-08-04 01:23:53 -0400299}
300
301func (hc *halfConn) recordHeaderLen() int {
302 if hc.isDTLS {
303 return dtlsRecordHeaderLen
304 }
305 return tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700306}
307
308// removePadding returns an unpadded slice, in constant time, which is a prefix
309// of the input. It also returns a byte which is equal to 255 if the padding
310// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
311func removePadding(payload []byte) ([]byte, byte) {
312 if len(payload) < 1 {
313 return payload, 0
314 }
315
316 paddingLen := payload[len(payload)-1]
317 t := uint(len(payload)-1) - uint(paddingLen)
318 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
319 good := byte(int32(^t) >> 31)
320
321 toCheck := 255 // the maximum possible padding length
322 // The length of the padded data is public, so we can use an if here
323 if toCheck+1 > len(payload) {
324 toCheck = len(payload) - 1
325 }
326
327 for i := 0; i < toCheck; i++ {
328 t := uint(paddingLen) - uint(i)
329 // if i <= paddingLen then the MSB of t is zero
330 mask := byte(int32(^t) >> 31)
331 b := payload[len(payload)-1-i]
332 good &^= mask&paddingLen ^ mask&b
333 }
334
335 // We AND together the bits of good and replicate the result across
336 // all the bits.
337 good &= good << 4
338 good &= good << 2
339 good &= good << 1
340 good = uint8(int8(good) >> 7)
341
342 toRemove := good&paddingLen + 1
343 return payload[:len(payload)-int(toRemove)], good
344}
345
346// removePaddingSSL30 is a replacement for removePadding in the case that the
347// protocol version is SSLv3. In this version, the contents of the padding
348// are random and cannot be checked.
349func removePaddingSSL30(payload []byte) ([]byte, byte) {
350 if len(payload) < 1 {
351 return payload, 0
352 }
353
354 paddingLen := int(payload[len(payload)-1]) + 1
355 if paddingLen > len(payload) {
356 return payload, 0
357 }
358
359 return payload[:len(payload)-paddingLen], 255
360}
361
362func roundUp(a, b int) int {
363 return a + (b-a%b)%b
364}
365
366// cbcMode is an interface for block ciphers using cipher block chaining.
367type cbcMode interface {
368 cipher.BlockMode
369 SetIV([]byte)
370}
371
372// decrypt checks and strips the mac and decrypts the data in b. Returns a
373// success boolean, the number of bytes to skip from the start of the record in
Nick Harper1fd39d82016-06-14 18:14:35 -0700374// order to get the application payload, the encrypted record type (or 0
375// if there is none), and an optional alert value.
376func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, contentType recordType, alertValue alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400377 recordHeaderLen := hc.recordHeaderLen()
378
Adam Langley95c29f32014-06-20 12:00:00 -0700379 // pull out payload
380 payload := b.data[recordHeaderLen:]
381
382 macSize := 0
383 if hc.mac != nil {
384 macSize = hc.mac.Size()
385 }
386
387 paddingGood := byte(255)
388 explicitIVLen := 0
389
David Benjamin83c0bc92014-08-04 01:23:53 -0400390 seq := hc.seq[:]
391 if hc.isDTLS {
392 // DTLS sequence numbers are explicit.
393 seq = b.data[3:11]
394 }
395
Adam Langley95c29f32014-06-20 12:00:00 -0700396 // decrypt
397 if hc.cipher != nil {
398 switch c := hc.cipher.(type) {
399 case cipher.Stream:
400 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400401 case *tlsAead:
402 nonce := seq
403 if c.explicitNonce {
404 explicitIVLen = 8
405 if len(payload) < explicitIVLen {
Nick Harper1fd39d82016-06-14 18:14:35 -0700406 return false, 0, 0, alertBadRecordMAC
David Benjamine9a80ff2015-04-07 00:46:46 -0400407 }
408 nonce = payload[:8]
409 payload = payload[8:]
Adam Langley95c29f32014-06-20 12:00:00 -0700410 }
Adam Langley95c29f32014-06-20 12:00:00 -0700411
Nick Harper1fd39d82016-06-14 18:14:35 -0700412 var additionalData []byte
413 if hc.version < VersionTLS13 {
414 additionalData = make([]byte, 13)
415 copy(additionalData, seq)
416 copy(additionalData[8:], b.data[:3])
417 n := len(payload) - c.Overhead()
418 additionalData[11] = byte(n >> 8)
419 additionalData[12] = byte(n)
420 }
Adam Langley95c29f32014-06-20 12:00:00 -0700421 var err error
Nick Harper1fd39d82016-06-14 18:14:35 -0700422 payload, err = c.Open(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700423 if err != nil {
Nick Harper1fd39d82016-06-14 18:14:35 -0700424 return false, 0, 0, alertBadRecordMAC
425 }
426 if hc.version >= VersionTLS13 {
427 i := len(payload)
428 for i > 0 && payload[i-1] == 0 {
429 i--
430 }
431 payload = payload[:i]
432 if len(payload) == 0 {
433 return false, 0, 0, alertUnexpectedMessage
434 }
435 contentType = recordType(payload[len(payload)-1])
436 payload = payload[:len(payload)-1]
Adam Langley95c29f32014-06-20 12:00:00 -0700437 }
438 b.resize(recordHeaderLen + explicitIVLen + len(payload))
439 case cbcMode:
440 blockSize := c.BlockSize()
David Benjamin83c0bc92014-08-04 01:23:53 -0400441 if hc.version >= VersionTLS11 || hc.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700442 explicitIVLen = blockSize
443 }
444
445 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
Nick Harper1fd39d82016-06-14 18:14:35 -0700446 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700447 }
448
449 if explicitIVLen > 0 {
450 c.SetIV(payload[:explicitIVLen])
451 payload = payload[explicitIVLen:]
452 }
453 c.CryptBlocks(payload, payload)
454 if hc.version == VersionSSL30 {
455 payload, paddingGood = removePaddingSSL30(payload)
456 } else {
457 payload, paddingGood = removePadding(payload)
458 }
459 b.resize(recordHeaderLen + explicitIVLen + len(payload))
460
461 // note that we still have a timing side-channel in the
462 // MAC check, below. An attacker can align the record
463 // so that a correct padding will cause one less hash
464 // block to be calculated. Then they can iteratively
465 // decrypt a record by breaking each byte. See
466 // "Password Interception in a SSL/TLS Channel", Brice
467 // Canvel et al.
468 //
469 // However, our behavior matches OpenSSL, so we leak
470 // only as much as they do.
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700471 case nullCipher:
472 break
Adam Langley95c29f32014-06-20 12:00:00 -0700473 default:
474 panic("unknown cipher type")
475 }
476 }
477
478 // check, strip mac
479 if hc.mac != nil {
480 if len(payload) < macSize {
Nick Harper1fd39d82016-06-14 18:14:35 -0700481 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700482 }
483
484 // strip mac off payload, b.data
485 n := len(payload) - macSize
David Benjamin83c0bc92014-08-04 01:23:53 -0400486 b.data[recordHeaderLen-2] = byte(n >> 8)
487 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700488 b.resize(recordHeaderLen + explicitIVLen + n)
489 remoteMAC := payload[n:]
David Benjamin83c0bc92014-08-04 01:23:53 -0400490 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
Adam Langley95c29f32014-06-20 12:00:00 -0700491
492 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
Nick Harper1fd39d82016-06-14 18:14:35 -0700493 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700494 }
495 hc.inDigestBuf = localMAC
496 }
David Benjamin5e961c12014-11-07 01:48:35 -0500497 hc.incSeq(false)
Adam Langley95c29f32014-06-20 12:00:00 -0700498
Nick Harper1fd39d82016-06-14 18:14:35 -0700499 return true, recordHeaderLen + explicitIVLen, contentType, 0
Adam Langley95c29f32014-06-20 12:00:00 -0700500}
501
502// padToBlockSize calculates the needed padding block, if any, for a payload.
503// On exit, prefix aliases payload and extends to the end of the last full
504// block of payload. finalBlock is a fresh slice which contains the contents of
505// any suffix of payload as well as the needed padding to make finalBlock a
506// full block.
Adam Langley80842bd2014-06-20 12:00:00 -0700507func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
Adam Langley95c29f32014-06-20 12:00:00 -0700508 overrun := len(payload) % blockSize
Adam Langley95c29f32014-06-20 12:00:00 -0700509 prefix = payload[:len(payload)-overrun]
Adam Langley80842bd2014-06-20 12:00:00 -0700510
511 paddingLen := blockSize - overrun
512 finalSize := blockSize
513 if config.Bugs.MaxPadding {
514 for paddingLen+blockSize <= 256 {
515 paddingLen += blockSize
516 }
517 finalSize = 256
518 }
519 finalBlock = make([]byte, finalSize)
520 for i := range finalBlock {
Adam Langley95c29f32014-06-20 12:00:00 -0700521 finalBlock[i] = byte(paddingLen - 1)
522 }
Adam Langley80842bd2014-06-20 12:00:00 -0700523 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
524 finalBlock[overrun] ^= 0xff
525 }
526 copy(finalBlock, payload[len(payload)-overrun:])
Adam Langley95c29f32014-06-20 12:00:00 -0700527 return
528}
529
530// encrypt encrypts and macs the data in b.
Nick Harper1fd39d82016-06-14 18:14:35 -0700531func (hc *halfConn) encrypt(b *block, explicitIVLen int, typ recordType) (bool, alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400532 recordHeaderLen := hc.recordHeaderLen()
533
Adam Langley95c29f32014-06-20 12:00:00 -0700534 // mac
535 if hc.mac != nil {
David Benjamin8e6db492015-07-25 18:29:23 -0400536 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 -0700537
538 n := len(b.data)
539 b.resize(n + len(mac))
540 copy(b.data[n:], mac)
541 hc.outDigestBuf = mac
542 }
543
544 payload := b.data[recordHeaderLen:]
545
546 // encrypt
547 if hc.cipher != nil {
548 switch c := hc.cipher.(type) {
549 case cipher.Stream:
550 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400551 case *tlsAead:
Adam Langley95c29f32014-06-20 12:00:00 -0700552 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
David Benjaminc9ae27c2016-06-24 22:56:37 -0400553 paddingLen := 0
Nick Harper1fd39d82016-06-14 18:14:35 -0700554 if hc.version >= VersionTLS13 {
David Benjaminc9ae27c2016-06-24 22:56:37 -0400555 payloadLen++
556 paddingLen = hc.config.Bugs.RecordPadding
557 }
558 if hc.config.Bugs.OmitRecordContents {
559 payloadLen = 0
560 }
561 b.resize(recordHeaderLen + explicitIVLen + payloadLen + paddingLen + c.Overhead())
562 if hc.version >= VersionTLS13 {
563 if !hc.config.Bugs.OmitRecordContents {
564 b.data[payloadLen+recordHeaderLen-1] = byte(typ)
565 }
566 for i := 0; i < hc.config.Bugs.RecordPadding; i++ {
567 b.data[payloadLen+recordHeaderLen+i] = 0
568 }
569 payloadLen += paddingLen
Nick Harper1fd39d82016-06-14 18:14:35 -0700570 }
David Benjamin8e6db492015-07-25 18:29:23 -0400571 nonce := hc.outSeq[:]
David Benjamine9a80ff2015-04-07 00:46:46 -0400572 if c.explicitNonce {
573 nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
574 }
Adam Langley95c29f32014-06-20 12:00:00 -0700575 payload := b.data[recordHeaderLen+explicitIVLen:]
576 payload = payload[:payloadLen]
577
Nick Harper1fd39d82016-06-14 18:14:35 -0700578 var additionalData []byte
579 if hc.version < VersionTLS13 {
580 additionalData = make([]byte, 13)
581 copy(additionalData, hc.outSeq[:])
582 copy(additionalData[8:], b.data[:3])
583 additionalData[11] = byte(payloadLen >> 8)
584 additionalData[12] = byte(payloadLen)
585 }
Adam Langley95c29f32014-06-20 12:00:00 -0700586
Nick Harper1fd39d82016-06-14 18:14:35 -0700587 c.Seal(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700588 case cbcMode:
589 blockSize := c.BlockSize()
590 if explicitIVLen > 0 {
591 c.SetIV(payload[:explicitIVLen])
592 payload = payload[explicitIVLen:]
593 }
Adam Langley80842bd2014-06-20 12:00:00 -0700594 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700595 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
596 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
597 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700598 case nullCipher:
599 break
Adam Langley95c29f32014-06-20 12:00:00 -0700600 default:
601 panic("unknown cipher type")
602 }
603 }
604
605 // update length to include MAC and any block padding needed.
606 n := len(b.data) - recordHeaderLen
David Benjamin83c0bc92014-08-04 01:23:53 -0400607 b.data[recordHeaderLen-2] = byte(n >> 8)
608 b.data[recordHeaderLen-1] = byte(n)
David Benjamin5e961c12014-11-07 01:48:35 -0500609 hc.incSeq(true)
Adam Langley95c29f32014-06-20 12:00:00 -0700610
611 return true, 0
612}
613
614// A block is a simple data buffer.
615type block struct {
616 data []byte
617 off int // index for Read
618 link *block
619}
620
621// resize resizes block to be n bytes, growing if necessary.
622func (b *block) resize(n int) {
623 if n > cap(b.data) {
624 b.reserve(n)
625 }
626 b.data = b.data[0:n]
627}
628
629// reserve makes sure that block contains a capacity of at least n bytes.
630func (b *block) reserve(n int) {
631 if cap(b.data) >= n {
632 return
633 }
634 m := cap(b.data)
635 if m == 0 {
636 m = 1024
637 }
638 for m < n {
639 m *= 2
640 }
641 data := make([]byte, len(b.data), m)
642 copy(data, b.data)
643 b.data = data
644}
645
646// readFromUntil reads from r into b until b contains at least n bytes
647// or else returns an error.
648func (b *block) readFromUntil(r io.Reader, n int) error {
649 // quick case
650 if len(b.data) >= n {
651 return nil
652 }
653
654 // read until have enough.
655 b.reserve(n)
656 for {
657 m, err := r.Read(b.data[len(b.data):cap(b.data)])
658 b.data = b.data[0 : len(b.data)+m]
659 if len(b.data) >= n {
660 // TODO(bradfitz,agl): slightly suspicious
661 // that we're throwing away r.Read's err here.
662 break
663 }
664 if err != nil {
665 return err
666 }
667 }
668 return nil
669}
670
671func (b *block) Read(p []byte) (n int, err error) {
672 n = copy(p, b.data[b.off:])
673 b.off += n
674 return
675}
676
677// newBlock allocates a new block, from hc's free list if possible.
678func (hc *halfConn) newBlock() *block {
679 b := hc.bfree
680 if b == nil {
681 return new(block)
682 }
683 hc.bfree = b.link
684 b.link = nil
685 b.resize(0)
686 return b
687}
688
689// freeBlock returns a block to hc's free list.
690// The protocol is such that each side only has a block or two on
691// its free list at a time, so there's no need to worry about
692// trimming the list, etc.
693func (hc *halfConn) freeBlock(b *block) {
694 b.link = hc.bfree
695 hc.bfree = b
696}
697
698// splitBlock splits a block after the first n bytes,
699// returning a block with those n bytes and a
700// block with the remainder. the latter may be nil.
701func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
702 if len(b.data) <= n {
703 return b, nil
704 }
705 bb := hc.newBlock()
706 bb.resize(len(b.data) - n)
707 copy(bb.data, b.data[n:])
708 b.data = b.data[0:n]
709 return b, bb
710}
711
David Benjamin83c0bc92014-08-04 01:23:53 -0400712func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
713 if c.isDTLS {
714 return c.dtlsDoReadRecord(want)
715 }
716
717 recordHeaderLen := tlsRecordHeaderLen
718
719 if c.rawInput == nil {
720 c.rawInput = c.in.newBlock()
721 }
722 b := c.rawInput
723
724 // Read header, payload.
725 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
726 // RFC suggests that EOF without an alertCloseNotify is
727 // an error, but popular web sites seem to do this,
David Benjamin30789da2015-08-29 22:56:45 -0400728 // so we can't make it an error, outside of tests.
729 if err == io.EOF && c.config.Bugs.ExpectCloseNotify {
730 err = io.ErrUnexpectedEOF
731 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400732 if e, ok := err.(net.Error); !ok || !e.Temporary() {
733 c.in.setErrorLocked(err)
734 }
735 return 0, nil, err
736 }
737 typ := recordType(b.data[0])
738
739 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
740 // start with a uint16 length where the MSB is set and the first record
741 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
742 // an SSLv2 client.
743 if want == recordTypeHandshake && typ == 0x80 {
744 c.sendAlert(alertProtocolVersion)
745 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
746 }
747
748 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
749 n := int(b.data[3])<<8 | int(b.data[4])
David Benjaminbde00392016-06-21 12:19:28 -0400750 // Alerts sent near version negotiation do not have a well-defined
751 // record-layer version prior to TLS 1.3. (In TLS 1.3, the record-layer
752 // version is irrelevant.)
753 if typ != recordTypeAlert {
754 if c.haveVers {
755 if vers != c.vers && c.vers < VersionTLS13 {
756 c.sendAlert(alertProtocolVersion)
757 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers))
758 }
759 } else {
760 if expect := c.config.Bugs.ExpectInitialRecordVersion; expect != 0 && vers != expect {
761 c.sendAlert(alertProtocolVersion)
762 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
763 }
David Benjamin1e29a6b2014-12-10 02:27:24 -0500764 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400765 }
766 if n > maxCiphertext {
767 c.sendAlert(alertRecordOverflow)
768 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
769 }
770 if !c.haveVers {
771 // First message, be extra suspicious:
772 // this might not be a TLS client.
773 // Bail out before reading a full 'body', if possible.
774 // The current max version is 3.1.
775 // If the version is >= 16.0, it's probably not real.
776 // Similarly, a clientHello message encodes in
777 // well under a kilobyte. If the length is >= 12 kB,
778 // it's probably not real.
779 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
780 c.sendAlert(alertUnexpectedMessage)
781 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
782 }
783 }
784 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
785 if err == io.EOF {
786 err = io.ErrUnexpectedEOF
787 }
788 if e, ok := err.(net.Error); !ok || !e.Temporary() {
789 c.in.setErrorLocked(err)
790 }
791 return 0, nil, err
792 }
793
794 // Process message.
795 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
David Benjaminff26f092016-07-01 16:13:42 -0400796 ok, off, encTyp, alertValue := c.in.decrypt(b)
797 if !ok {
798 return 0, nil, c.in.setErrorLocked(c.sendAlert(alertValue))
799 }
800 b.off = off
801
Nick Harper1fd39d82016-06-14 18:14:35 -0700802 if c.vers >= VersionTLS13 && c.in.cipher != nil {
David Benjaminc9ae27c2016-06-24 22:56:37 -0400803 if typ != recordTypeApplicationData {
804 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: outer record type is not application data"))
805 }
Nick Harper1fd39d82016-06-14 18:14:35 -0700806 typ = encTyp
807 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400808 return typ, b, nil
809}
810
Adam Langley95c29f32014-06-20 12:00:00 -0700811// readRecord reads the next TLS record from the connection
812// and updates the record layer state.
813// c.in.Mutex <= L; c.input == nil.
814func (c *Conn) readRecord(want recordType) error {
815 // Caller must be in sync with connection:
816 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700817 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700818 switch want {
819 default:
820 c.sendAlert(alertInternalError)
821 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
822 case recordTypeHandshake, recordTypeChangeCipherSpec:
823 if c.handshakeComplete {
824 c.sendAlert(alertInternalError)
825 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
826 }
827 case recordTypeApplicationData:
David Benjamine58c4f52014-08-24 03:47:07 -0400828 if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart {
Adam Langley95c29f32014-06-20 12:00:00 -0700829 c.sendAlert(alertInternalError)
830 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
831 }
David Benjamin30789da2015-08-29 22:56:45 -0400832 case recordTypeAlert:
833 // Looking for a close_notify. Note: unlike a real
834 // implementation, this is not tolerant of additional records.
835 // See the documentation for ExpectCloseNotify.
Adam Langley95c29f32014-06-20 12:00:00 -0700836 }
837
838Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400839 typ, b, err := c.doReadRecord(want)
840 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700841 return err
842 }
Adam Langley95c29f32014-06-20 12:00:00 -0700843 data := b.data[b.off:]
844 if len(data) > maxPlaintext {
845 err := c.sendAlert(alertRecordOverflow)
846 c.in.freeBlock(b)
847 return c.in.setErrorLocked(err)
848 }
849
850 switch typ {
851 default:
852 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
853
854 case recordTypeAlert:
855 if len(data) != 2 {
856 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
857 break
858 }
859 if alert(data[1]) == alertCloseNotify {
860 c.in.setErrorLocked(io.EOF)
861 break
862 }
863 switch data[0] {
864 case alertLevelWarning:
865 // drop on the floor
866 c.in.freeBlock(b)
867 goto Again
868 case alertLevelError:
869 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
870 default:
871 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
872 }
873
874 case recordTypeChangeCipherSpec:
875 if typ != want || len(data) != 1 || data[0] != 1 {
876 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
877 break
878 }
Adam Langley80842bd2014-06-20 12:00:00 -0700879 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700880 if err != nil {
881 c.in.setErrorLocked(c.sendAlert(err.(alert)))
882 }
883
884 case recordTypeApplicationData:
885 if typ != want {
886 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
887 break
888 }
889 c.input = b
890 b = nil
891
892 case recordTypeHandshake:
David Benjamind5a4ecb2016-07-18 01:17:13 +0200893 // Allow handshake data while reading application data to
894 // trigger post-handshake messages.
Adam Langley95c29f32014-06-20 12:00:00 -0700895 // TODO(rsc): Should at least pick off connection close.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200896 if typ != want && want != recordTypeApplicationData {
897 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
Adam Langley95c29f32014-06-20 12:00:00 -0700898 }
899 c.hand.Write(data)
900 }
901
902 if b != nil {
903 c.in.freeBlock(b)
904 }
905 return c.in.err
906}
907
908// sendAlert sends a TLS alert message.
909// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400910func (c *Conn) sendAlertLocked(level byte, err alert) error {
911 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700912 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400913 if c.config.Bugs.FragmentAlert {
914 c.writeRecord(recordTypeAlert, c.tmp[0:1])
915 c.writeRecord(recordTypeAlert, c.tmp[1:2])
David Benjamin0d3a8c62016-03-11 22:25:18 -0500916 } else if c.config.Bugs.DoubleAlert {
917 copy(c.tmp[2:4], c.tmp[0:2])
918 c.writeRecord(recordTypeAlert, c.tmp[0:4])
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400919 } else {
920 c.writeRecord(recordTypeAlert, c.tmp[0:2])
921 }
David Benjamin24f346d2015-06-06 03:28:08 -0400922 // Error alerts are fatal to the connection.
923 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700924 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
925 }
926 return nil
927}
928
929// sendAlert sends a TLS alert message.
930// L < c.out.Mutex.
931func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400932 level := byte(alertLevelError)
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500933 if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertficate {
David Benjamin24f346d2015-06-06 03:28:08 -0400934 level = alertLevelWarning
935 }
936 return c.SendAlert(level, err)
937}
938
939func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700940 c.out.Lock()
941 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -0400942 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -0700943}
944
David Benjamind86c7672014-08-02 04:07:12 -0400945// writeV2Record writes a record for a V2ClientHello.
946func (c *Conn) writeV2Record(data []byte) (n int, err error) {
947 record := make([]byte, 2+len(data))
948 record[0] = uint8(len(data)>>8) | 0x80
949 record[1] = uint8(len(data))
950 copy(record[2:], data)
951 return c.conn.Write(record)
952}
953
Adam Langley95c29f32014-06-20 12:00:00 -0700954// writeRecord writes a TLS record with the given type and payload
955// to the connection and updates the record layer state.
956// c.out.Mutex <= L.
957func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin639846e2016-09-09 11:41:18 -0400958 if msgType := c.config.Bugs.SendWrongMessageType; msgType != 0 {
959 if typ == recordTypeHandshake && data[0] == msgType {
David Benjamin0b8d5da2016-07-15 00:39:56 -0400960 newData := make([]byte, len(data))
961 copy(newData, data)
962 newData[0] += 42
963 data = newData
964 }
965 }
966
David Benjamin639846e2016-09-09 11:41:18 -0400967 if msgType := c.config.Bugs.SendTrailingMessageData; msgType != 0 {
968 if typ == recordTypeHandshake && data[0] == msgType {
969 newData := make([]byte, len(data))
970 copy(newData, data)
971
972 // Add a 0 to the body.
973 newData = append(newData, 0)
974 // Fix the header.
975 newLen := len(newData) - 4
976 newData[1] = byte(newLen >> 16)
977 newData[2] = byte(newLen >> 8)
978 newData[3] = byte(newLen)
979
980 data = newData
981 }
982 }
983
David Benjamin83c0bc92014-08-04 01:23:53 -0400984 if c.isDTLS {
985 return c.dtlsWriteRecord(typ, data)
986 }
987
David Benjamin71dd6662016-07-08 14:10:48 -0700988 if typ == recordTypeHandshake {
989 if c.config.Bugs.SendHelloRequestBeforeEveryHandshakeMessage {
990 newData := make([]byte, 0, 4+len(data))
991 newData = append(newData, typeHelloRequest, 0, 0, 0)
992 newData = append(newData, data...)
993 data = newData
994 }
995
996 if c.config.Bugs.PackHandshakeFlight {
997 c.pendingFlight.Write(data)
998 return len(data), nil
999 }
David Benjamin582ba042016-07-07 12:33:25 -07001000 }
1001
1002 return c.doWriteRecord(typ, data)
1003}
1004
1005func (c *Conn) doWriteRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin83c0bc92014-08-04 01:23:53 -04001006 recordHeaderLen := tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -07001007 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -04001008 first := true
1009 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -04001010 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -07001011 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -04001012 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -07001013 m = maxPlaintext
1014 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001015 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
1016 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -04001017 // By default, do not fragment the client_version or
1018 // server_version, which are located in the first 6
1019 // bytes.
1020 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
1021 m = 6
1022 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001023 }
Adam Langley95c29f32014-06-20 12:00:00 -07001024 explicitIVLen := 0
1025 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -04001026 first = false
Adam Langley95c29f32014-06-20 12:00:00 -07001027
1028 var cbc cbcMode
1029 if c.out.version >= VersionTLS11 {
1030 var ok bool
1031 if cbc, ok = c.out.cipher.(cbcMode); ok {
1032 explicitIVLen = cbc.BlockSize()
1033 }
1034 }
1035 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -04001036 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -07001037 explicitIVLen = 8
1038 // The AES-GCM construction in TLS has an
1039 // explicit nonce so that the nonce can be
1040 // random. However, the nonce is only 8 bytes
1041 // which is too small for a secure, random
1042 // nonce. Therefore we use the sequence number
1043 // as the nonce.
1044 explicitIVIsSeq = true
1045 }
1046 }
1047 b.resize(recordHeaderLen + explicitIVLen + m)
1048 b.data[0] = byte(typ)
Nick Harper1fd39d82016-06-14 18:14:35 -07001049 if c.vers >= VersionTLS13 && c.out.cipher != nil {
Nick Harper1fd39d82016-06-14 18:14:35 -07001050 b.data[0] = byte(recordTypeApplicationData)
David Benjaminc9ae27c2016-06-24 22:56:37 -04001051 if outerType := c.config.Bugs.OuterRecordType; outerType != 0 {
1052 b.data[0] = byte(outerType)
1053 }
Nick Harper1fd39d82016-06-14 18:14:35 -07001054 }
Adam Langley95c29f32014-06-20 12:00:00 -07001055 vers := c.vers
Nick Harper1fd39d82016-06-14 18:14:35 -07001056 if vers == 0 || vers >= VersionTLS13 {
Adam Langley95c29f32014-06-20 12:00:00 -07001057 // Some TLS servers fail if the record version is
1058 // greater than TLS 1.0 for the initial ClientHello.
Nick Harper1fd39d82016-06-14 18:14:35 -07001059 //
1060 // TLS 1.3 fixes the version number in the record
1061 // layer to {3, 1}.
Adam Langley95c29f32014-06-20 12:00:00 -07001062 vers = VersionTLS10
1063 }
1064 b.data[1] = byte(vers >> 8)
1065 b.data[2] = byte(vers)
1066 b.data[3] = byte(m >> 8)
1067 b.data[4] = byte(m)
1068 if explicitIVLen > 0 {
1069 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
1070 if explicitIVIsSeq {
1071 copy(explicitIV, c.out.seq[:])
1072 } else {
1073 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
1074 break
1075 }
1076 }
1077 }
1078 copy(b.data[recordHeaderLen+explicitIVLen:], data)
Nick Harper1fd39d82016-06-14 18:14:35 -07001079 c.out.encrypt(b, explicitIVLen, typ)
Adam Langley95c29f32014-06-20 12:00:00 -07001080 _, err = c.conn.Write(b.data)
1081 if err != nil {
1082 break
1083 }
1084 n += m
1085 data = data[m:]
1086 }
1087 c.out.freeBlock(b)
1088
1089 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -07001090 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -07001091 if err != nil {
1092 // Cannot call sendAlert directly,
1093 // because we already hold c.out.Mutex.
1094 c.tmp[0] = alertLevelError
1095 c.tmp[1] = byte(err.(alert))
1096 c.writeRecord(recordTypeAlert, c.tmp[0:2])
1097 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
1098 }
1099 }
1100 return
1101}
1102
David Benjamin582ba042016-07-07 12:33:25 -07001103func (c *Conn) flushHandshake() error {
1104 if c.isDTLS {
1105 return c.dtlsFlushHandshake()
1106 }
1107
1108 for c.pendingFlight.Len() > 0 {
1109 var buf [maxPlaintext]byte
1110 n, _ := c.pendingFlight.Read(buf[:])
1111 if _, err := c.doWriteRecord(recordTypeHandshake, buf[:n]); err != nil {
1112 return err
1113 }
1114 }
1115
1116 c.pendingFlight.Reset()
1117 return nil
1118}
1119
David Benjamin83c0bc92014-08-04 01:23:53 -04001120func (c *Conn) doReadHandshake() ([]byte, error) {
1121 if c.isDTLS {
1122 return c.dtlsDoReadHandshake()
1123 }
1124
Adam Langley95c29f32014-06-20 12:00:00 -07001125 for c.hand.Len() < 4 {
1126 if err := c.in.err; err != nil {
1127 return nil, err
1128 }
1129 if err := c.readRecord(recordTypeHandshake); err != nil {
1130 return nil, err
1131 }
1132 }
1133
1134 data := c.hand.Bytes()
1135 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1136 if n > maxHandshake {
1137 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
1138 }
1139 for c.hand.Len() < 4+n {
1140 if err := c.in.err; err != nil {
1141 return nil, err
1142 }
1143 if err := c.readRecord(recordTypeHandshake); err != nil {
1144 return nil, err
1145 }
1146 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001147 return c.hand.Next(4 + n), nil
1148}
1149
1150// readHandshake reads the next handshake message from
1151// the record layer.
1152// c.in.Mutex < L; c.out.Mutex < L.
1153func (c *Conn) readHandshake() (interface{}, error) {
1154 data, err := c.doReadHandshake()
1155 if err != nil {
1156 return nil, err
1157 }
1158
Adam Langley95c29f32014-06-20 12:00:00 -07001159 var m handshakeMessage
1160 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001161 case typeHelloRequest:
1162 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001163 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001164 m = &clientHelloMsg{
1165 isDTLS: c.isDTLS,
1166 }
Adam Langley95c29f32014-06-20 12:00:00 -07001167 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001168 m = &serverHelloMsg{
1169 isDTLS: c.isDTLS,
1170 }
Nick Harperdcfbc672016-07-16 17:47:31 +02001171 case typeHelloRetryRequest:
1172 m = new(helloRetryRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001173 case typeNewSessionTicket:
David Benjamin58104882016-07-18 01:25:41 +02001174 m = &newSessionTicketMsg{
1175 version: c.vers,
1176 }
Nick Harperb41d2e42016-07-01 17:50:32 -04001177 case typeEncryptedExtensions:
1178 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001179 case typeCertificate:
Nick Harperb41d2e42016-07-01 17:50:32 -04001180 m = &certificateMsg{
David Benjamin8d315d72016-07-18 01:03:18 +02001181 hasRequestContext: c.vers >= VersionTLS13,
Nick Harperb41d2e42016-07-01 17:50:32 -04001182 }
Adam Langley95c29f32014-06-20 12:00:00 -07001183 case typeCertificateRequest:
1184 m = &certificateRequestMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001185 hasSignatureAlgorithm: c.vers >= VersionTLS12,
David Benjamin8d315d72016-07-18 01:03:18 +02001186 hasRequestContext: c.vers >= VersionTLS13,
Adam Langley95c29f32014-06-20 12:00:00 -07001187 }
1188 case typeCertificateStatus:
1189 m = new(certificateStatusMsg)
1190 case typeServerKeyExchange:
1191 m = new(serverKeyExchangeMsg)
1192 case typeServerHelloDone:
1193 m = new(serverHelloDoneMsg)
1194 case typeClientKeyExchange:
1195 m = new(clientKeyExchangeMsg)
1196 case typeCertificateVerify:
1197 m = &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001198 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001199 }
1200 case typeNextProtocol:
1201 m = new(nextProtoMsg)
1202 case typeFinished:
1203 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001204 case typeHelloVerifyRequest:
1205 m = new(helloVerifyRequestMsg)
David Benjamin24599a82016-06-30 18:56:53 -04001206 case typeChannelID:
1207 m = new(channelIDMsg)
David Benjamin21c00282016-07-18 21:56:23 +02001208 case typeKeyUpdate:
1209 m = new(keyUpdateMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001210 default:
1211 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1212 }
1213
1214 // The handshake message unmarshallers
1215 // expect to be able to keep references to data,
1216 // so pass in a fresh copy that won't be overwritten.
1217 data = append([]byte(nil), data...)
1218
1219 if !m.unmarshal(data) {
1220 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1221 }
1222 return m, nil
1223}
1224
David Benjamin83f90402015-01-27 01:09:43 -05001225// skipPacket processes all the DTLS records in packet. It updates
1226// sequence number expectations but otherwise ignores them.
1227func (c *Conn) skipPacket(packet []byte) error {
1228 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001229 if len(packet) < 13 {
1230 return errors.New("tls: bad packet")
1231 }
David Benjamin83f90402015-01-27 01:09:43 -05001232 // Dropped packets are completely ignored save to update
1233 // expected sequence numbers for this and the next epoch. (We
1234 // don't assert on the contents of the packets both for
1235 // simplicity and because a previous test with one shorter
1236 // timeout schedule would have done so.)
1237 epoch := packet[3:5]
1238 seq := packet[5:11]
1239 length := uint16(packet[11])<<8 | uint16(packet[12])
1240 if bytes.Equal(c.in.seq[:2], epoch) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001241 if bytes.Compare(seq, c.in.seq[2:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001242 return errors.New("tls: sequence mismatch")
1243 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001244 copy(c.in.seq[2:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001245 c.in.incSeq(false)
1246 } else {
David Benjamin13e81fc2015-11-02 17:16:13 -05001247 if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001248 return errors.New("tls: sequence mismatch")
1249 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001250 copy(c.in.nextSeq[:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001251 c.in.incNextSeq()
1252 }
David Benjamin6ca93552015-08-28 16:16:25 -04001253 if len(packet) < 13+int(length) {
1254 return errors.New("tls: bad packet")
1255 }
David Benjamin83f90402015-01-27 01:09:43 -05001256 packet = packet[13+length:]
1257 }
1258 return nil
1259}
1260
1261// simulatePacketLoss simulates the loss of a handshake leg from the
1262// peer based on the schedule in c.config.Bugs. If resendFunc is
1263// non-nil, it is called after each simulated timeout to retransmit
1264// handshake messages from the local end. This is used in cases where
1265// the peer retransmits on a stale Finished rather than a timeout.
1266func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1267 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1268 return nil
1269 }
1270 if !c.isDTLS {
1271 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1272 }
1273 if c.config.Bugs.PacketAdaptor == nil {
1274 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1275 }
1276 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1277 // Simulate a timeout.
1278 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1279 if err != nil {
1280 return err
1281 }
1282 for _, packet := range packets {
1283 if err := c.skipPacket(packet); err != nil {
1284 return err
1285 }
1286 }
1287 if resendFunc != nil {
1288 resendFunc()
1289 }
1290 }
1291 return nil
1292}
1293
David Benjamin47921102016-07-28 11:29:18 -04001294func (c *Conn) SendHalfHelloRequest() error {
1295 if err := c.Handshake(); err != nil {
1296 return err
1297 }
1298
1299 c.out.Lock()
1300 defer c.out.Unlock()
1301
1302 if _, err := c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0}); err != nil {
1303 return err
1304 }
1305 return c.flushHandshake()
1306}
1307
Adam Langley95c29f32014-06-20 12:00:00 -07001308// Write writes data to the connection.
1309func (c *Conn) Write(b []byte) (int, error) {
1310 if err := c.Handshake(); err != nil {
1311 return 0, err
1312 }
1313
1314 c.out.Lock()
1315 defer c.out.Unlock()
1316
David Benjamin12d2c482016-07-24 10:56:51 -04001317 // Flush any pending handshake data. PackHelloRequestWithFinished may
1318 // have been set and the handshake not followed by Renegotiate.
1319 c.flushHandshake()
1320
Adam Langley95c29f32014-06-20 12:00:00 -07001321 if err := c.out.err; err != nil {
1322 return 0, err
1323 }
1324
1325 if !c.handshakeComplete {
1326 return 0, alertInternalError
1327 }
1328
David Benjamin21c00282016-07-18 21:56:23 +02001329 // Catch up with KeyUpdates from the peer.
1330 for c.out.keyUpdateGeneration < c.in.keyUpdateGeneration {
1331 if err := c.sendKeyUpdateLocked(); err != nil {
1332 return 0, err
1333 }
1334 }
1335
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001336 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001337 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001338 }
1339
Adam Langley27a0d082015-11-03 13:34:10 -08001340 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1341 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
David Benjamin582ba042016-07-07 12:33:25 -07001342 c.flushHandshake()
Adam Langley27a0d082015-11-03 13:34:10 -08001343 }
1344
Steven Valdez1dc53d22016-07-26 12:27:38 -04001345 if c.config.Bugs.SendKeyUpdateBeforeEveryAppDataRecord {
1346 c.sendKeyUpdateLocked()
1347 }
1348
Adam Langley95c29f32014-06-20 12:00:00 -07001349 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1350 // attack when using block mode ciphers due to predictable IVs.
1351 // This can be prevented by splitting each Application Data
1352 // record into two records, effectively randomizing the IV.
1353 //
1354 // http://www.openssl.org/~bodo/tls-cbc.txt
1355 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1356 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1357
1358 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001359 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001360 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1361 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1362 if err != nil {
1363 return n, c.out.setErrorLocked(err)
1364 }
1365 m, b = 1, b[1:]
1366 }
1367 }
1368
1369 n, err := c.writeRecord(recordTypeApplicationData, b)
1370 return n + m, c.out.setErrorLocked(err)
1371}
1372
David Benjamind5a4ecb2016-07-18 01:17:13 +02001373func (c *Conn) handlePostHandshakeMessage() error {
Adam Langley2ae77d22014-10-28 17:29:33 -07001374 msg, err := c.readHandshake()
1375 if err != nil {
1376 return err
1377 }
David Benjamind5a4ecb2016-07-18 01:17:13 +02001378
1379 if c.vers < VersionTLS13 {
1380 if !c.isClient {
1381 c.sendAlert(alertUnexpectedMessage)
1382 return errors.New("tls: unexpected post-handshake message")
1383 }
1384
1385 _, ok := msg.(*helloRequestMsg)
1386 if !ok {
1387 c.sendAlert(alertUnexpectedMessage)
1388 return alertUnexpectedMessage
1389 }
1390
1391 c.handshakeComplete = false
1392 return c.Handshake()
Adam Langley2ae77d22014-10-28 17:29:33 -07001393 }
1394
David Benjamind5a4ecb2016-07-18 01:17:13 +02001395 if c.isClient {
1396 if newSessionTicket, ok := msg.(*newSessionTicketMsg); ok {
1397 if c.config.ClientSessionCache == nil || newSessionTicket.ticketLifetime == 0 {
1398 return nil
1399 }
1400
1401 session := &ClientSessionState{
1402 sessionTicket: newSessionTicket.ticket,
1403 vers: c.vers,
1404 cipherSuite: c.cipherSuite.id,
1405 masterSecret: c.resumptionSecret,
1406 serverCertificates: c.peerCertificates,
1407 sctList: c.sctList,
1408 ocspResponse: c.ocspResponse,
Nick Harper0b3625b2016-07-25 16:16:28 -07001409 ticketCreationTime: c.config.time(),
1410 ticketExpiration: c.config.time().Add(time.Duration(newSessionTicket.ticketLifetime) * time.Second),
1411 ticketFlags: newSessionTicket.ticketFlags,
1412 ticketAgeAdd: newSessionTicket.ticketAgeAdd,
David Benjamind5a4ecb2016-07-18 01:17:13 +02001413 }
1414
1415 cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
1416 c.config.ClientSessionCache.Put(cacheKey, session)
1417 return nil
1418 }
1419 }
1420
David Benjamin21c00282016-07-18 21:56:23 +02001421 if _, ok := msg.(*keyUpdateMsg); ok {
Steven Valdez1dc53d22016-07-26 12:27:38 -04001422 c.in.doKeyUpdate(c, false)
David Benjamin21c00282016-07-18 21:56:23 +02001423 return nil
1424 }
1425
David Benjamind5a4ecb2016-07-18 01:17:13 +02001426 // TODO(davidben): Add support for KeyUpdate.
1427 c.sendAlert(alertUnexpectedMessage)
1428 return alertUnexpectedMessage
Adam Langley2ae77d22014-10-28 17:29:33 -07001429}
1430
Adam Langleycf2d4f42014-10-28 19:06:14 -07001431func (c *Conn) Renegotiate() error {
1432 if !c.isClient {
David Benjaminef5dfd22015-12-06 13:17:07 -05001433 helloReq := new(helloRequestMsg).marshal()
1434 if c.config.Bugs.BadHelloRequest != nil {
1435 helloReq = c.config.Bugs.BadHelloRequest
1436 }
1437 c.writeRecord(recordTypeHandshake, helloReq)
David Benjamin582ba042016-07-07 12:33:25 -07001438 c.flushHandshake()
Adam Langleycf2d4f42014-10-28 19:06:14 -07001439 }
1440
1441 c.handshakeComplete = false
1442 return c.Handshake()
1443}
1444
Adam Langley95c29f32014-06-20 12:00:00 -07001445// Read can be made to time out and return a net.Error with Timeout() == true
1446// after a fixed time limit; see SetDeadline and SetReadDeadline.
1447func (c *Conn) Read(b []byte) (n int, err error) {
1448 if err = c.Handshake(); err != nil {
1449 return
1450 }
1451
1452 c.in.Lock()
1453 defer c.in.Unlock()
1454
1455 // Some OpenSSL servers send empty records in order to randomize the
1456 // CBC IV. So this loop ignores a limited number of empty records.
1457 const maxConsecutiveEmptyRecords = 100
1458 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1459 for c.input == nil && c.in.err == nil {
1460 if err := c.readRecord(recordTypeApplicationData); err != nil {
1461 // Soft error, like EAGAIN
1462 return 0, err
1463 }
David Benjamind9b091b2015-01-27 01:10:54 -05001464 if c.hand.Len() > 0 {
David Benjamind5a4ecb2016-07-18 01:17:13 +02001465 // We received handshake bytes, indicating a
1466 // post-handshake message.
1467 if err := c.handlePostHandshakeMessage(); err != nil {
Adam Langley2ae77d22014-10-28 17:29:33 -07001468 return 0, err
1469 }
1470 continue
1471 }
Adam Langley95c29f32014-06-20 12:00:00 -07001472 }
1473 if err := c.in.err; err != nil {
1474 return 0, err
1475 }
1476
1477 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001478 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001479 c.in.freeBlock(c.input)
1480 c.input = nil
1481 }
1482
1483 // If a close-notify alert is waiting, read it so that
1484 // we can return (n, EOF) instead of (n, nil), to signal
1485 // to the HTTP response reading goroutine that the
1486 // connection is now closed. This eliminates a race
1487 // where the HTTP response reading goroutine would
1488 // otherwise not observe the EOF until its next read,
1489 // by which time a client goroutine might have already
1490 // tried to reuse the HTTP connection for a new
1491 // request.
1492 // See https://codereview.appspot.com/76400046
1493 // and http://golang.org/issue/3514
1494 if ri := c.rawInput; ri != nil &&
1495 n != 0 && err == nil &&
1496 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1497 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1498 err = recErr // will be io.EOF on closeNotify
1499 }
1500 }
1501
1502 if n != 0 || err != nil {
1503 return n, err
1504 }
1505 }
1506
1507 return 0, io.ErrNoProgress
1508}
1509
1510// Close closes the connection.
1511func (c *Conn) Close() error {
1512 var alertErr error
1513
1514 c.handshakeMutex.Lock()
1515 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001516 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
David Benjaminfa214e42016-05-10 17:03:10 -04001517 alert := alertCloseNotify
1518 if c.config.Bugs.SendAlertOnShutdown != 0 {
1519 alert = c.config.Bugs.SendAlertOnShutdown
1520 }
1521 alertErr = c.sendAlert(alert)
David Benjamin4d559612016-05-18 14:31:51 -04001522 // Clear local alerts when sending alerts so we continue to wait
1523 // for the peer rather than closing the socket early.
1524 if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1525 alertErr = nil
1526 }
Adam Langley95c29f32014-06-20 12:00:00 -07001527 }
1528
David Benjamin30789da2015-08-29 22:56:45 -04001529 // Consume a close_notify from the peer if one hasn't been received
1530 // already. This avoids the peer from failing |SSL_shutdown| due to a
1531 // write failing.
1532 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1533 for c.in.error() == nil {
1534 c.readRecord(recordTypeAlert)
1535 }
1536 if c.in.error() != io.EOF {
1537 alertErr = c.in.error()
1538 }
1539 }
1540
Adam Langley95c29f32014-06-20 12:00:00 -07001541 if err := c.conn.Close(); err != nil {
1542 return err
1543 }
1544 return alertErr
1545}
1546
1547// Handshake runs the client or server handshake
1548// protocol if it has not yet been run.
1549// Most uses of this package need not call Handshake
1550// explicitly: the first Read or Write will call it automatically.
1551func (c *Conn) Handshake() error {
1552 c.handshakeMutex.Lock()
1553 defer c.handshakeMutex.Unlock()
1554 if err := c.handshakeErr; err != nil {
1555 return err
1556 }
1557 if c.handshakeComplete {
1558 return nil
1559 }
1560
David Benjamin9a41d1b2015-05-16 01:30:09 -04001561 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1562 c.conn.Write([]byte{
1563 byte(recordTypeAlert), // type
1564 0xfe, 0xff, // version
1565 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1566 0x0, 0x2, // length
1567 })
1568 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1569 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001570 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1571 c.writeRecord(recordTypeApplicationData, data)
1572 }
Adam Langley95c29f32014-06-20 12:00:00 -07001573 if c.isClient {
1574 c.handshakeErr = c.clientHandshake()
1575 } else {
1576 c.handshakeErr = c.serverHandshake()
1577 }
David Benjaminddb9f152015-02-03 15:44:39 -05001578 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1579 c.writeRecord(recordType(42), []byte("invalid record"))
1580 }
Adam Langley95c29f32014-06-20 12:00:00 -07001581 return c.handshakeErr
1582}
1583
1584// ConnectionState returns basic TLS details about the connection.
1585func (c *Conn) ConnectionState() ConnectionState {
1586 c.handshakeMutex.Lock()
1587 defer c.handshakeMutex.Unlock()
1588
1589 var state ConnectionState
1590 state.HandshakeComplete = c.handshakeComplete
1591 if c.handshakeComplete {
1592 state.Version = c.vers
1593 state.NegotiatedProtocol = c.clientProtocol
1594 state.DidResume = c.didResume
1595 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001596 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001597 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001598 state.PeerCertificates = c.peerCertificates
1599 state.VerifiedChains = c.verifiedChains
1600 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001601 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001602 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001603 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001604 state.SCTList = c.sctList
Nick Harper60edffd2016-06-21 15:19:24 -07001605 state.PeerSignatureAlgorithm = c.peerSignatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -04001606 state.CurveID = c.curveID
Adam Langley95c29f32014-06-20 12:00:00 -07001607 }
1608
1609 return state
1610}
1611
1612// OCSPResponse returns the stapled OCSP response from the TLS server, if
1613// any. (Only valid for client connections.)
1614func (c *Conn) OCSPResponse() []byte {
1615 c.handshakeMutex.Lock()
1616 defer c.handshakeMutex.Unlock()
1617
1618 return c.ocspResponse
1619}
1620
1621// VerifyHostname checks that the peer certificate chain is valid for
1622// connecting to host. If so, it returns nil; if not, it returns an error
1623// describing the problem.
1624func (c *Conn) VerifyHostname(host string) error {
1625 c.handshakeMutex.Lock()
1626 defer c.handshakeMutex.Unlock()
1627 if !c.isClient {
1628 return errors.New("tls: VerifyHostname called on TLS server connection")
1629 }
1630 if !c.handshakeComplete {
1631 return errors.New("tls: handshake has not yet been performed")
1632 }
1633 return c.peerCertificates[0].VerifyHostname(host)
1634}
David Benjaminc565ebb2015-04-03 04:06:36 -04001635
1636// ExportKeyingMaterial exports keying material from the current connection
1637// state, as per RFC 5705.
1638func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1639 c.handshakeMutex.Lock()
1640 defer c.handshakeMutex.Unlock()
1641 if !c.handshakeComplete {
1642 return nil, errors.New("tls: handshake has not yet been performed")
1643 }
1644
David Benjamin8d315d72016-07-18 01:03:18 +02001645 if c.vers >= VersionTLS13 {
David Benjamin97a0a082016-07-13 17:57:35 -04001646 // TODO(davidben): What should we do with useContext? See
1647 // https://github.com/tlswg/tls13-spec/issues/546
1648 return hkdfExpandLabel(c.cipherSuite.hash(), c.exporterSecret, label, context, length), nil
1649 }
1650
David Benjaminc565ebb2015-04-03 04:06:36 -04001651 seedLen := len(c.clientRandom) + len(c.serverRandom)
1652 if useContext {
1653 seedLen += 2 + len(context)
1654 }
1655 seed := make([]byte, 0, seedLen)
1656 seed = append(seed, c.clientRandom[:]...)
1657 seed = append(seed, c.serverRandom[:]...)
1658 if useContext {
1659 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1660 seed = append(seed, context...)
1661 }
1662 result := make([]byte, length)
David Benjamin97a0a082016-07-13 17:57:35 -04001663 prfForVersion(c.vers, c.cipherSuite)(result, c.exporterSecret, label, seed)
David Benjaminc565ebb2015-04-03 04:06:36 -04001664 return result, nil
1665}
David Benjamin3e052de2015-11-25 20:10:31 -05001666
1667// noRenegotiationInfo returns true if the renegotiation info extension
1668// should be supported in the current handshake.
1669func (c *Conn) noRenegotiationInfo() bool {
1670 if c.config.Bugs.NoRenegotiationInfo {
1671 return true
1672 }
1673 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1674 return true
1675 }
1676 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1677 return true
1678 }
1679 return false
1680}
David Benjamin58104882016-07-18 01:25:41 +02001681
1682func (c *Conn) SendNewSessionTicket() error {
1683 if c.isClient || c.vers < VersionTLS13 {
1684 return errors.New("tls: cannot send post-handshake NewSessionTicket")
1685 }
1686
1687 var peerCertificatesRaw [][]byte
1688 for _, cert := range c.peerCertificates {
1689 peerCertificatesRaw = append(peerCertificatesRaw, cert.Raw)
1690 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001691
1692 var ageAdd uint32
1693 if err := binary.Read(c.config.rand(), binary.LittleEndian, &ageAdd); err != nil {
1694 return err
David Benjamin58104882016-07-18 01:25:41 +02001695 }
1696
1697 // TODO(davidben): Allow configuring these values.
1698 m := &newSessionTicketMsg{
1699 version: c.vers,
1700 ticketLifetime: uint32(24 * time.Hour / time.Second),
1701 ticketFlags: ticketAllowDHEResumption | ticketAllowPSKResumption,
Nick Harper0b3625b2016-07-25 16:16:28 -07001702 ticketAgeAdd: ageAdd,
David Benjamin58104882016-07-18 01:25:41 +02001703 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001704
1705 state := sessionState{
1706 vers: c.vers,
1707 cipherSuite: c.cipherSuite.id,
1708 masterSecret: c.resumptionSecret,
1709 certificates: peerCertificatesRaw,
1710 ticketCreationTime: c.config.time(),
1711 ticketExpiration: c.config.time().Add(time.Duration(m.ticketLifetime) * time.Second),
1712 ticketFlags: m.ticketFlags,
1713 ticketAgeAdd: ageAdd,
1714 }
1715
David Benjamin58104882016-07-18 01:25:41 +02001716 if !c.config.Bugs.SendEmptySessionTicket {
1717 var err error
1718 m.ticket, err = c.encryptTicket(&state)
1719 if err != nil {
1720 return err
1721 }
1722 }
1723
1724 c.out.Lock()
1725 defer c.out.Unlock()
1726 _, err := c.writeRecord(recordTypeHandshake, m.marshal())
1727 return err
1728}
David Benjamin21c00282016-07-18 21:56:23 +02001729
1730func (c *Conn) SendKeyUpdate() error {
1731 c.out.Lock()
1732 defer c.out.Unlock()
1733 return c.sendKeyUpdateLocked()
1734}
1735
1736func (c *Conn) sendKeyUpdateLocked() error {
1737 m := new(keyUpdateMsg)
1738 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
1739 return err
1740 }
1741 if err := c.flushHandshake(); err != nil {
1742 return err
1743 }
Steven Valdez1dc53d22016-07-26 12:27:38 -04001744 c.out.doKeyUpdate(c, true)
David Benjamin21c00282016-07-18 21:56:23 +02001745 return nil
1746}