blob: 0cc0b38bb7ea950783a5a9f79f0ebe4be7251027 [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
David Benjamin053fee92017-01-02 08:30:36 -050024var errNoCertificateAlert = errors.New("tls: no certificate alert")
25
Adam Langley95c29f32014-06-20 12:00:00 -070026// A Conn represents a secured connection.
27// It implements the net.Conn interface.
28type Conn struct {
29 // constant
30 conn net.Conn
David Benjamin83c0bc92014-08-04 01:23:53 -040031 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -070032 isClient bool
33
34 // constant after handshake; protected by handshakeMutex
Adam Langley75712922014-10-10 16:23:43 -070035 handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
36 handshakeErr error // error resulting from handshake
37 vers uint16 // TLS version
38 haveVers bool // version has been negotiated
39 config *Config // configuration passed to constructor
40 handshakeComplete bool
Nick Harper47383aa2016-11-30 12:50:43 -080041 skipEarlyData bool
Adam Langley75712922014-10-10 16:23:43 -070042 didResume bool // whether this connection was a session resumption
43 extendedMasterSecret bool // whether this session used an extended master secret
David Benjaminc565ebb2015-04-03 04:06:36 -040044 cipherSuite *cipherSuite
Adam Langley75712922014-10-10 16:23:43 -070045 ocspResponse []byte // stapled OCSP response
Paul Lietar4fac72e2015-09-09 13:44:55 +010046 sctList []byte // signed certificate timestamp list
Adam Langley75712922014-10-10 16:23:43 -070047 peerCertificates []*x509.Certificate
Adam Langley95c29f32014-06-20 12:00:00 -070048 // verifiedChains contains the certificate chains that we built, as
49 // opposed to the ones presented by the server.
50 verifiedChains [][]*x509.Certificate
51 // serverName contains the server name indicated by the client, if any.
Adam Langleyaf0e32c2015-06-03 09:57:23 -070052 serverName string
53 // firstFinished contains the first Finished hash sent during the
54 // handshake. This is the "tls-unique" channel binding value.
55 firstFinished [12]byte
Nick Harper60edffd2016-06-21 15:19:24 -070056 // peerSignatureAlgorithm contains the signature algorithm that was used
57 // by the peer in the handshake, or zero if not applicable.
58 peerSignatureAlgorithm signatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -040059 // curveID contains the curve that was used in the handshake, or zero if
60 // not applicable.
61 curveID CurveID
Adam Langleyaf0e32c2015-06-03 09:57:23 -070062
David Benjaminc565ebb2015-04-03 04:06:36 -040063 clientRandom, serverRandom [32]byte
David Benjamin97a0a082016-07-13 17:57:35 -040064 exporterSecret []byte
David Benjamin58104882016-07-18 01:25:41 +020065 resumptionSecret []byte
Adam Langley95c29f32014-06-20 12:00:00 -070066
67 clientProtocol string
68 clientProtocolFallback bool
David Benjaminfc7b0862014-09-06 13:21:53 -040069 usedALPN bool
Adam Langley95c29f32014-06-20 12:00:00 -070070
Adam Langley2ae77d22014-10-28 17:29:33 -070071 // verify_data values for the renegotiation extension.
72 clientVerify []byte
73 serverVerify []byte
74
David Benjamind30a9902014-08-24 01:44:23 -040075 channelID *ecdsa.PublicKey
76
David Benjaminca6c8262014-11-15 19:06:08 -050077 srtpProtectionProfile uint16
78
David Benjaminc44b1df2014-11-23 12:11:01 -050079 clientVersion uint16
80
Adam Langley95c29f32014-06-20 12:00:00 -070081 // input/output
82 in, out halfConn // in.Mutex < out.Mutex
83 rawInput *block // raw input, right off the wire
David Benjamin83c0bc92014-08-04 01:23:53 -040084 input *block // application record waiting to be read
85 hand bytes.Buffer // handshake record waiting to be read
86
David Benjamin582ba042016-07-07 12:33:25 -070087 // pendingFlight, if PackHandshakeFlight is enabled, is the buffer of
88 // handshake data to be split into records at the end of the flight.
89 pendingFlight bytes.Buffer
90
David Benjamin83c0bc92014-08-04 01:23:53 -040091 // DTLS state
92 sendHandshakeSeq uint16
93 recvHandshakeSeq uint16
David Benjaminb3774b92015-01-31 17:16:01 -050094 handMsg []byte // pending assembled handshake message
95 handMsgLen int // handshake message length, not including the header
96 pendingFragments [][]byte // pending outgoing handshake fragments.
Adam Langley95c29f32014-06-20 12:00:00 -070097
Steven Valdezc4aa7272016-10-03 12:25:56 -040098 keyUpdateRequested bool
99
Adam Langley95c29f32014-06-20 12:00:00 -0700100 tmp [16]byte
101}
102
David Benjamin5e961c12014-11-07 01:48:35 -0500103func (c *Conn) init() {
104 c.in.isDTLS = c.isDTLS
105 c.out.isDTLS = c.isDTLS
106 c.in.config = c.config
107 c.out.config = c.config
David Benjamin8e6db492015-07-25 18:29:23 -0400108
109 c.out.updateOutSeq()
David Benjamin5e961c12014-11-07 01:48:35 -0500110}
111
Adam Langley95c29f32014-06-20 12:00:00 -0700112// Access to net.Conn methods.
113// Cannot just embed net.Conn because that would
114// export the struct field too.
115
116// LocalAddr returns the local network address.
117func (c *Conn) LocalAddr() net.Addr {
118 return c.conn.LocalAddr()
119}
120
121// RemoteAddr returns the remote network address.
122func (c *Conn) RemoteAddr() net.Addr {
123 return c.conn.RemoteAddr()
124}
125
126// SetDeadline sets the read and write deadlines associated with the connection.
127// A zero value for t means Read and Write will not time out.
128// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
129func (c *Conn) SetDeadline(t time.Time) error {
130 return c.conn.SetDeadline(t)
131}
132
133// SetReadDeadline sets the read deadline on the underlying connection.
134// A zero value for t means Read will not time out.
135func (c *Conn) SetReadDeadline(t time.Time) error {
136 return c.conn.SetReadDeadline(t)
137}
138
139// SetWriteDeadline sets the write deadline on the underlying conneciton.
140// A zero value for t means Write will not time out.
141// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
142func (c *Conn) SetWriteDeadline(t time.Time) error {
143 return c.conn.SetWriteDeadline(t)
144}
145
146// A halfConn represents one direction of the record layer
147// connection, either sending or receiving.
148type halfConn struct {
149 sync.Mutex
150
David Benjamin83c0bc92014-08-04 01:23:53 -0400151 err error // first permanent error
152 version uint16 // protocol version
153 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -0700154 cipher interface{} // cipher algorithm
155 mac macFunction
156 seq [8]byte // 64-bit sequence number
David Benjamin8e6db492015-07-25 18:29:23 -0400157 outSeq [8]byte // Mapped sequence number
Adam Langley95c29f32014-06-20 12:00:00 -0700158 bfree *block // list of free blocks
159
160 nextCipher interface{} // next encryption state
161 nextMac macFunction // next MAC algorithm
David Benjamin83f90402015-01-27 01:09:43 -0500162 nextSeq [6]byte // next epoch's starting sequence number in DTLS
Adam Langley95c29f32014-06-20 12:00:00 -0700163
164 // used to save allocating a new buffer for each MAC.
165 inDigestBuf, outDigestBuf []byte
Adam Langley80842bd2014-06-20 12:00:00 -0700166
Steven Valdezc4aa7272016-10-03 12:25:56 -0400167 trafficSecret []byte
David Benjamin21c00282016-07-18 21:56:23 +0200168
David Benjamin6f600d62016-12-21 16:06:54 -0500169 shortHeader bool
170
Adam Langley80842bd2014-06-20 12:00:00 -0700171 config *Config
Adam Langley95c29f32014-06-20 12:00:00 -0700172}
173
174func (hc *halfConn) setErrorLocked(err error) error {
175 hc.err = err
176 return err
177}
178
179func (hc *halfConn) error() error {
Adam Langley2ae77d22014-10-28 17:29:33 -0700180 // This should be locked, but I've removed it for the renegotiation
181 // tests since we don't concurrently read and write the same tls.Conn
182 // in any case during testing.
Adam Langley95c29f32014-06-20 12:00:00 -0700183 err := hc.err
Adam Langley95c29f32014-06-20 12:00:00 -0700184 return err
185}
186
187// prepareCipherSpec sets the encryption and MAC states
188// that a subsequent changeCipherSpec will use.
189func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
190 hc.version = version
191 hc.nextCipher = cipher
192 hc.nextMac = mac
193}
194
195// changeCipherSpec changes the encryption and MAC states
196// to the ones previously passed to prepareCipherSpec.
Adam Langley80842bd2014-06-20 12:00:00 -0700197func (hc *halfConn) changeCipherSpec(config *Config) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700198 if hc.nextCipher == nil {
199 return alertInternalError
200 }
201 hc.cipher = hc.nextCipher
202 hc.mac = hc.nextMac
203 hc.nextCipher = nil
204 hc.nextMac = nil
Adam Langley80842bd2014-06-20 12:00:00 -0700205 hc.config = config
David Benjamin83c0bc92014-08-04 01:23:53 -0400206 hc.incEpoch()
David Benjaminf2b83632016-03-01 22:57:46 -0500207
208 if config.Bugs.NullAllCiphers {
David Benjamin7a4aaa42016-09-20 17:58:14 -0400209 hc.cipher = nullCipher{}
David Benjaminf2b83632016-03-01 22:57:46 -0500210 hc.mac = nil
211 }
Adam Langley95c29f32014-06-20 12:00:00 -0700212 return nil
213}
214
David Benjamin21c00282016-07-18 21:56:23 +0200215// useTrafficSecret sets the current cipher state for TLS 1.3.
Steven Valdeza833c352016-11-01 13:39:36 -0400216func (hc *halfConn) useTrafficSecret(version uint16, suite *cipherSuite, secret []byte, side trafficDirection) {
Nick Harperb41d2e42016-07-01 17:50:32 -0400217 hc.version = version
Steven Valdeza833c352016-11-01 13:39:36 -0400218 hc.cipher = deriveTrafficAEAD(version, suite, secret, side)
David Benjamin7a4aaa42016-09-20 17:58:14 -0400219 if hc.config.Bugs.NullAllCiphers {
220 hc.cipher = nullCipher{}
221 }
David Benjamin21c00282016-07-18 21:56:23 +0200222 hc.trafficSecret = secret
Nick Harperb41d2e42016-07-01 17:50:32 -0400223 hc.incEpoch()
224}
225
David Benjamin21c00282016-07-18 21:56:23 +0200226func (hc *halfConn) doKeyUpdate(c *Conn, isOutgoing bool) {
227 side := serverWrite
228 if c.isClient == isOutgoing {
229 side = clientWrite
230 }
Steven Valdeza833c352016-11-01 13:39:36 -0400231 hc.useTrafficSecret(hc.version, c.cipherSuite, updateTrafficSecret(c.cipherSuite.hash(), hc.trafficSecret), side)
David Benjamin21c00282016-07-18 21:56:23 +0200232}
233
Adam Langley95c29f32014-06-20 12:00:00 -0700234// incSeq increments the sequence number.
David Benjamin5e961c12014-11-07 01:48:35 -0500235func (hc *halfConn) incSeq(isOutgoing bool) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400236 limit := 0
David Benjamin5e961c12014-11-07 01:48:35 -0500237 increment := uint64(1)
David Benjamin83c0bc92014-08-04 01:23:53 -0400238 if hc.isDTLS {
239 // Increment up to the epoch in DTLS.
240 limit = 2
241 }
242 for i := 7; i >= limit; i-- {
David Benjamin5e961c12014-11-07 01:48:35 -0500243 increment += uint64(hc.seq[i])
244 hc.seq[i] = byte(increment)
245 increment >>= 8
Adam Langley95c29f32014-06-20 12:00:00 -0700246 }
247
248 // Not allowed to let sequence number wrap.
249 // Instead, must renegotiate before it does.
250 // Not likely enough to bother.
David Benjamin5e961c12014-11-07 01:48:35 -0500251 if increment != 0 {
252 panic("TLS: sequence number wraparound")
253 }
David Benjamin8e6db492015-07-25 18:29:23 -0400254
255 hc.updateOutSeq()
Adam Langley95c29f32014-06-20 12:00:00 -0700256}
257
David Benjamin83f90402015-01-27 01:09:43 -0500258// incNextSeq increments the starting sequence number for the next epoch.
259func (hc *halfConn) incNextSeq() {
260 for i := len(hc.nextSeq) - 1; i >= 0; i-- {
261 hc.nextSeq[i]++
262 if hc.nextSeq[i] != 0 {
263 return
264 }
265 }
266 panic("TLS: sequence number wraparound")
267}
268
269// incEpoch resets the sequence number. In DTLS, it also increments the epoch
270// half of the sequence number.
David Benjamin83c0bc92014-08-04 01:23:53 -0400271func (hc *halfConn) incEpoch() {
David Benjamin83c0bc92014-08-04 01:23:53 -0400272 if hc.isDTLS {
273 for i := 1; i >= 0; i-- {
274 hc.seq[i]++
275 if hc.seq[i] != 0 {
276 break
277 }
278 if i == 0 {
279 panic("TLS: epoch number wraparound")
280 }
281 }
David Benjamin83f90402015-01-27 01:09:43 -0500282 copy(hc.seq[2:], hc.nextSeq[:])
283 for i := range hc.nextSeq {
284 hc.nextSeq[i] = 0
285 }
286 } else {
287 for i := range hc.seq {
288 hc.seq[i] = 0
289 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400290 }
David Benjamin8e6db492015-07-25 18:29:23 -0400291
292 hc.updateOutSeq()
293}
294
295func (hc *halfConn) updateOutSeq() {
296 if hc.config.Bugs.SequenceNumberMapping != nil {
297 seqU64 := binary.BigEndian.Uint64(hc.seq[:])
298 seqU64 = hc.config.Bugs.SequenceNumberMapping(seqU64)
299 binary.BigEndian.PutUint64(hc.outSeq[:], seqU64)
300
301 // The DTLS epoch cannot be changed.
302 copy(hc.outSeq[:2], hc.seq[:2])
303 return
304 }
305
306 copy(hc.outSeq[:], hc.seq[:])
David Benjamin83c0bc92014-08-04 01:23:53 -0400307}
308
David Benjamin6f600d62016-12-21 16:06:54 -0500309func (hc *halfConn) isShortHeader() bool {
310 return hc.shortHeader && hc.cipher != nil
311}
312
David Benjamin83c0bc92014-08-04 01:23:53 -0400313func (hc *halfConn) recordHeaderLen() int {
314 if hc.isDTLS {
315 return dtlsRecordHeaderLen
316 }
David Benjamin6f600d62016-12-21 16:06:54 -0500317 if hc.isShortHeader() {
318 return 2
319 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400320 return tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700321}
322
323// removePadding returns an unpadded slice, in constant time, which is a prefix
324// of the input. It also returns a byte which is equal to 255 if the padding
325// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
326func removePadding(payload []byte) ([]byte, byte) {
327 if len(payload) < 1 {
328 return payload, 0
329 }
330
331 paddingLen := payload[len(payload)-1]
332 t := uint(len(payload)-1) - uint(paddingLen)
333 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
334 good := byte(int32(^t) >> 31)
335
336 toCheck := 255 // the maximum possible padding length
337 // The length of the padded data is public, so we can use an if here
338 if toCheck+1 > len(payload) {
339 toCheck = len(payload) - 1
340 }
341
342 for i := 0; i < toCheck; i++ {
343 t := uint(paddingLen) - uint(i)
344 // if i <= paddingLen then the MSB of t is zero
345 mask := byte(int32(^t) >> 31)
346 b := payload[len(payload)-1-i]
347 good &^= mask&paddingLen ^ mask&b
348 }
349
350 // We AND together the bits of good and replicate the result across
351 // all the bits.
352 good &= good << 4
353 good &= good << 2
354 good &= good << 1
355 good = uint8(int8(good) >> 7)
356
357 toRemove := good&paddingLen + 1
358 return payload[:len(payload)-int(toRemove)], good
359}
360
361// removePaddingSSL30 is a replacement for removePadding in the case that the
362// protocol version is SSLv3. In this version, the contents of the padding
363// are random and cannot be checked.
364func removePaddingSSL30(payload []byte) ([]byte, byte) {
365 if len(payload) < 1 {
366 return payload, 0
367 }
368
369 paddingLen := int(payload[len(payload)-1]) + 1
370 if paddingLen > len(payload) {
371 return payload, 0
372 }
373
374 return payload[:len(payload)-paddingLen], 255
375}
376
377func roundUp(a, b int) int {
378 return a + (b-a%b)%b
379}
380
381// cbcMode is an interface for block ciphers using cipher block chaining.
382type cbcMode interface {
383 cipher.BlockMode
384 SetIV([]byte)
385}
386
387// decrypt checks and strips the mac and decrypts the data in b. Returns a
388// success boolean, the number of bytes to skip from the start of the record in
Nick Harper1fd39d82016-06-14 18:14:35 -0700389// order to get the application payload, the encrypted record type (or 0
390// if there is none), and an optional alert value.
391func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, contentType recordType, alertValue alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400392 recordHeaderLen := hc.recordHeaderLen()
393
Adam Langley95c29f32014-06-20 12:00:00 -0700394 // pull out payload
395 payload := b.data[recordHeaderLen:]
396
397 macSize := 0
398 if hc.mac != nil {
399 macSize = hc.mac.Size()
400 }
401
402 paddingGood := byte(255)
403 explicitIVLen := 0
404
David Benjamin83c0bc92014-08-04 01:23:53 -0400405 seq := hc.seq[:]
406 if hc.isDTLS {
407 // DTLS sequence numbers are explicit.
408 seq = b.data[3:11]
409 }
410
Adam Langley95c29f32014-06-20 12:00:00 -0700411 // decrypt
412 if hc.cipher != nil {
413 switch c := hc.cipher.(type) {
414 case cipher.Stream:
415 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400416 case *tlsAead:
417 nonce := seq
418 if c.explicitNonce {
419 explicitIVLen = 8
420 if len(payload) < explicitIVLen {
Nick Harper1fd39d82016-06-14 18:14:35 -0700421 return false, 0, 0, alertBadRecordMAC
David Benjamine9a80ff2015-04-07 00:46:46 -0400422 }
423 nonce = payload[:8]
424 payload = payload[8:]
Adam Langley95c29f32014-06-20 12:00:00 -0700425 }
Adam Langley95c29f32014-06-20 12:00:00 -0700426
Nick Harper1fd39d82016-06-14 18:14:35 -0700427 var additionalData []byte
428 if hc.version < VersionTLS13 {
429 additionalData = make([]byte, 13)
430 copy(additionalData, seq)
431 copy(additionalData[8:], b.data[:3])
432 n := len(payload) - c.Overhead()
433 additionalData[11] = byte(n >> 8)
434 additionalData[12] = byte(n)
435 }
Adam Langley95c29f32014-06-20 12:00:00 -0700436 var err error
Nick Harper1fd39d82016-06-14 18:14:35 -0700437 payload, err = c.Open(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700438 if err != nil {
Nick Harper1fd39d82016-06-14 18:14:35 -0700439 return false, 0, 0, alertBadRecordMAC
440 }
Adam Langley95c29f32014-06-20 12:00:00 -0700441 b.resize(recordHeaderLen + explicitIVLen + len(payload))
442 case cbcMode:
443 blockSize := c.BlockSize()
David Benjamin83c0bc92014-08-04 01:23:53 -0400444 if hc.version >= VersionTLS11 || hc.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700445 explicitIVLen = blockSize
446 }
447
448 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
Nick Harper1fd39d82016-06-14 18:14:35 -0700449 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700450 }
451
452 if explicitIVLen > 0 {
453 c.SetIV(payload[:explicitIVLen])
454 payload = payload[explicitIVLen:]
455 }
456 c.CryptBlocks(payload, payload)
457 if hc.version == VersionSSL30 {
458 payload, paddingGood = removePaddingSSL30(payload)
459 } else {
460 payload, paddingGood = removePadding(payload)
461 }
462 b.resize(recordHeaderLen + explicitIVLen + len(payload))
463
464 // note that we still have a timing side-channel in the
465 // MAC check, below. An attacker can align the record
466 // so that a correct padding will cause one less hash
467 // block to be calculated. Then they can iteratively
468 // decrypt a record by breaking each byte. See
469 // "Password Interception in a SSL/TLS Channel", Brice
470 // Canvel et al.
471 //
472 // However, our behavior matches OpenSSL, so we leak
473 // only as much as they do.
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700474 case nullCipher:
475 break
Adam Langley95c29f32014-06-20 12:00:00 -0700476 default:
477 panic("unknown cipher type")
478 }
David Benjamin7a4aaa42016-09-20 17:58:14 -0400479
480 if hc.version >= VersionTLS13 {
481 i := len(payload)
482 for i > 0 && payload[i-1] == 0 {
483 i--
484 }
485 payload = payload[:i]
486 if len(payload) == 0 {
487 return false, 0, 0, alertUnexpectedMessage
488 }
489 contentType = recordType(payload[len(payload)-1])
490 payload = payload[:len(payload)-1]
491 b.resize(recordHeaderLen + len(payload))
492 }
Adam Langley95c29f32014-06-20 12:00:00 -0700493 }
494
495 // check, strip mac
496 if hc.mac != nil {
497 if len(payload) < macSize {
Nick Harper1fd39d82016-06-14 18:14:35 -0700498 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700499 }
500
501 // strip mac off payload, b.data
502 n := len(payload) - macSize
David Benjamin83c0bc92014-08-04 01:23:53 -0400503 b.data[recordHeaderLen-2] = byte(n >> 8)
504 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700505 b.resize(recordHeaderLen + explicitIVLen + n)
506 remoteMAC := payload[n:]
David Benjamin83c0bc92014-08-04 01:23:53 -0400507 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
Adam Langley95c29f32014-06-20 12:00:00 -0700508
509 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
Nick Harper1fd39d82016-06-14 18:14:35 -0700510 return false, 0, 0, alertBadRecordMAC
Adam Langley95c29f32014-06-20 12:00:00 -0700511 }
512 hc.inDigestBuf = localMAC
513 }
David Benjamin5e961c12014-11-07 01:48:35 -0500514 hc.incSeq(false)
Adam Langley95c29f32014-06-20 12:00:00 -0700515
Nick Harper1fd39d82016-06-14 18:14:35 -0700516 return true, recordHeaderLen + explicitIVLen, contentType, 0
Adam Langley95c29f32014-06-20 12:00:00 -0700517}
518
519// padToBlockSize calculates the needed padding block, if any, for a payload.
520// On exit, prefix aliases payload and extends to the end of the last full
521// block of payload. finalBlock is a fresh slice which contains the contents of
522// any suffix of payload as well as the needed padding to make finalBlock a
523// full block.
Adam Langley80842bd2014-06-20 12:00:00 -0700524func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
Adam Langley95c29f32014-06-20 12:00:00 -0700525 overrun := len(payload) % blockSize
Adam Langley95c29f32014-06-20 12:00:00 -0700526 prefix = payload[:len(payload)-overrun]
Adam Langley80842bd2014-06-20 12:00:00 -0700527
528 paddingLen := blockSize - overrun
529 finalSize := blockSize
530 if config.Bugs.MaxPadding {
531 for paddingLen+blockSize <= 256 {
532 paddingLen += blockSize
533 }
534 finalSize = 256
535 }
536 finalBlock = make([]byte, finalSize)
537 for i := range finalBlock {
Adam Langley95c29f32014-06-20 12:00:00 -0700538 finalBlock[i] = byte(paddingLen - 1)
539 }
Adam Langley80842bd2014-06-20 12:00:00 -0700540 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
541 finalBlock[overrun] ^= 0xff
542 }
543 copy(finalBlock, payload[len(payload)-overrun:])
Adam Langley95c29f32014-06-20 12:00:00 -0700544 return
545}
546
547// encrypt encrypts and macs the data in b.
Nick Harper1fd39d82016-06-14 18:14:35 -0700548func (hc *halfConn) encrypt(b *block, explicitIVLen int, typ recordType) (bool, alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400549 recordHeaderLen := hc.recordHeaderLen()
550
Adam Langley95c29f32014-06-20 12:00:00 -0700551 // mac
552 if hc.mac != nil {
David Benjamin8e6db492015-07-25 18:29:23 -0400553 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 -0700554
555 n := len(b.data)
556 b.resize(n + len(mac))
557 copy(b.data[n:], mac)
558 hc.outDigestBuf = mac
559 }
560
561 payload := b.data[recordHeaderLen:]
562
563 // encrypt
564 if hc.cipher != nil {
David Benjamin7a4aaa42016-09-20 17:58:14 -0400565 // Add TLS 1.3 padding.
566 if hc.version >= VersionTLS13 {
567 paddingLen := hc.config.Bugs.RecordPadding
568 if hc.config.Bugs.OmitRecordContents {
569 b.resize(recordHeaderLen + paddingLen)
570 } else {
571 b.resize(len(b.data) + 1 + paddingLen)
572 b.data[len(b.data)-paddingLen-1] = byte(typ)
573 }
574 for i := 0; i < paddingLen; i++ {
575 b.data[len(b.data)-paddingLen+i] = 0
576 }
577 }
578
Adam Langley95c29f32014-06-20 12:00:00 -0700579 switch c := hc.cipher.(type) {
580 case cipher.Stream:
581 c.XORKeyStream(payload, payload)
David Benjamine9a80ff2015-04-07 00:46:46 -0400582 case *tlsAead:
Adam Langley95c29f32014-06-20 12:00:00 -0700583 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
David Benjamin7a4aaa42016-09-20 17:58:14 -0400584 b.resize(len(b.data) + c.Overhead())
David Benjamin8e6db492015-07-25 18:29:23 -0400585 nonce := hc.outSeq[:]
David Benjamine9a80ff2015-04-07 00:46:46 -0400586 if c.explicitNonce {
587 nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
588 }
Adam Langley95c29f32014-06-20 12:00:00 -0700589 payload := b.data[recordHeaderLen+explicitIVLen:]
590 payload = payload[:payloadLen]
591
Nick Harper1fd39d82016-06-14 18:14:35 -0700592 var additionalData []byte
593 if hc.version < VersionTLS13 {
594 additionalData = make([]byte, 13)
595 copy(additionalData, hc.outSeq[:])
596 copy(additionalData[8:], b.data[:3])
597 additionalData[11] = byte(payloadLen >> 8)
598 additionalData[12] = byte(payloadLen)
599 }
Adam Langley95c29f32014-06-20 12:00:00 -0700600
Nick Harper1fd39d82016-06-14 18:14:35 -0700601 c.Seal(payload[:0], nonce, payload, additionalData)
Adam Langley95c29f32014-06-20 12:00:00 -0700602 case cbcMode:
603 blockSize := c.BlockSize()
604 if explicitIVLen > 0 {
605 c.SetIV(payload[:explicitIVLen])
606 payload = payload[explicitIVLen:]
607 }
Adam Langley80842bd2014-06-20 12:00:00 -0700608 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700609 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
610 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
611 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
Matt Braithwaiteaf096752015-09-02 19:48:16 -0700612 case nullCipher:
613 break
Adam Langley95c29f32014-06-20 12:00:00 -0700614 default:
615 panic("unknown cipher type")
616 }
617 }
618
619 // update length to include MAC and any block padding needed.
620 n := len(b.data) - recordHeaderLen
David Benjamin83c0bc92014-08-04 01:23:53 -0400621 b.data[recordHeaderLen-2] = byte(n >> 8)
622 b.data[recordHeaderLen-1] = byte(n)
David Benjamin6f600d62016-12-21 16:06:54 -0500623 if hc.isShortHeader() && !hc.config.Bugs.ClearShortHeaderBit {
624 b.data[0] |= 0x80
625 }
David Benjamin5e961c12014-11-07 01:48:35 -0500626 hc.incSeq(true)
Adam Langley95c29f32014-06-20 12:00:00 -0700627
628 return true, 0
629}
630
631// A block is a simple data buffer.
632type block struct {
633 data []byte
634 off int // index for Read
635 link *block
636}
637
638// resize resizes block to be n bytes, growing if necessary.
639func (b *block) resize(n int) {
640 if n > cap(b.data) {
641 b.reserve(n)
642 }
643 b.data = b.data[0:n]
644}
645
646// reserve makes sure that block contains a capacity of at least n bytes.
647func (b *block) reserve(n int) {
648 if cap(b.data) >= n {
649 return
650 }
651 m := cap(b.data)
652 if m == 0 {
653 m = 1024
654 }
655 for m < n {
656 m *= 2
657 }
658 data := make([]byte, len(b.data), m)
659 copy(data, b.data)
660 b.data = data
661}
662
663// readFromUntil reads from r into b until b contains at least n bytes
664// or else returns an error.
665func (b *block) readFromUntil(r io.Reader, n int) error {
666 // quick case
667 if len(b.data) >= n {
668 return nil
669 }
670
671 // read until have enough.
672 b.reserve(n)
673 for {
674 m, err := r.Read(b.data[len(b.data):cap(b.data)])
675 b.data = b.data[0 : len(b.data)+m]
676 if len(b.data) >= n {
677 // TODO(bradfitz,agl): slightly suspicious
678 // that we're throwing away r.Read's err here.
679 break
680 }
681 if err != nil {
682 return err
683 }
684 }
685 return nil
686}
687
688func (b *block) Read(p []byte) (n int, err error) {
689 n = copy(p, b.data[b.off:])
690 b.off += n
691 return
692}
693
694// newBlock allocates a new block, from hc's free list if possible.
695func (hc *halfConn) newBlock() *block {
696 b := hc.bfree
697 if b == nil {
698 return new(block)
699 }
700 hc.bfree = b.link
701 b.link = nil
702 b.resize(0)
703 return b
704}
705
706// freeBlock returns a block to hc's free list.
707// The protocol is such that each side only has a block or two on
708// its free list at a time, so there's no need to worry about
709// trimming the list, etc.
710func (hc *halfConn) freeBlock(b *block) {
711 b.link = hc.bfree
712 hc.bfree = b
713}
714
715// splitBlock splits a block after the first n bytes,
716// returning a block with those n bytes and a
717// block with the remainder. the latter may be nil.
718func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
719 if len(b.data) <= n {
720 return b, nil
721 }
722 bb := hc.newBlock()
723 bb.resize(len(b.data) - n)
724 copy(bb.data, b.data[n:])
725 b.data = b.data[0:n]
726 return b, bb
727}
728
David Benjamin83c0bc92014-08-04 01:23:53 -0400729func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
Nick Harper47383aa2016-11-30 12:50:43 -0800730RestartReadRecord:
David Benjamin83c0bc92014-08-04 01:23:53 -0400731 if c.isDTLS {
732 return c.dtlsDoReadRecord(want)
733 }
734
David Benjamin6f600d62016-12-21 16:06:54 -0500735 recordHeaderLen := c.in.recordHeaderLen()
David Benjamin83c0bc92014-08-04 01:23:53 -0400736
737 if c.rawInput == nil {
738 c.rawInput = c.in.newBlock()
739 }
740 b := c.rawInput
741
742 // Read header, payload.
743 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
744 // RFC suggests that EOF without an alertCloseNotify is
745 // an error, but popular web sites seem to do this,
David Benjamin30789da2015-08-29 22:56:45 -0400746 // so we can't make it an error, outside of tests.
747 if err == io.EOF && c.config.Bugs.ExpectCloseNotify {
748 err = io.ErrUnexpectedEOF
749 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400750 if e, ok := err.(net.Error); !ok || !e.Temporary() {
751 c.in.setErrorLocked(err)
752 }
753 return 0, nil, err
754 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400755
David Benjamin6f600d62016-12-21 16:06:54 -0500756 var typ recordType
757 var vers uint16
758 var n int
759 if c.in.isShortHeader() {
760 typ = recordTypeApplicationData
761 vers = VersionTLS10
762 n = int(b.data[0])<<8 | int(b.data[1])
763 if n&0x8000 == 0 {
764 c.sendAlert(alertDecodeError)
765 return 0, nil, c.in.setErrorLocked(errors.New("tls: length did not have high bit set"))
766 }
767
768 n = n & 0x7fff
769 } else {
770 typ = recordType(b.data[0])
771
772 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
773 // start with a uint16 length where the MSB is set and the first record
774 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
775 // an SSLv2 client.
776 if want == recordTypeHandshake && typ == 0x80 {
777 c.sendAlert(alertProtocolVersion)
778 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
779 }
780
781 vers = uint16(b.data[1])<<8 | uint16(b.data[2])
782 n = int(b.data[3])<<8 | int(b.data[4])
David Benjamin83c0bc92014-08-04 01:23:53 -0400783 }
784
David Benjaminbde00392016-06-21 12:19:28 -0400785 // Alerts sent near version negotiation do not have a well-defined
786 // record-layer version prior to TLS 1.3. (In TLS 1.3, the record-layer
787 // version is irrelevant.)
788 if typ != recordTypeAlert {
David Benjamine6f22212016-11-08 14:28:24 -0500789 var expect uint16
David Benjaminbde00392016-06-21 12:19:28 -0400790 if c.haveVers {
David Benjamine6f22212016-11-08 14:28:24 -0500791 expect = c.vers
792 if c.vers >= VersionTLS13 {
793 expect = VersionTLS10
David Benjaminbde00392016-06-21 12:19:28 -0400794 }
795 } else {
David Benjamine6f22212016-11-08 14:28:24 -0500796 expect = c.config.Bugs.ExpectInitialRecordVersion
797 }
798 if expect != 0 && vers != expect {
799 c.sendAlert(alertProtocolVersion)
800 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect))
David Benjamin1e29a6b2014-12-10 02:27:24 -0500801 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400802 }
803 if n > maxCiphertext {
804 c.sendAlert(alertRecordOverflow)
805 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
806 }
807 if !c.haveVers {
808 // First message, be extra suspicious:
809 // this might not be a TLS client.
810 // Bail out before reading a full 'body', if possible.
811 // The current max version is 3.1.
812 // If the version is >= 16.0, it's probably not real.
813 // Similarly, a clientHello message encodes in
814 // well under a kilobyte. If the length is >= 12 kB,
815 // it's probably not real.
816 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
817 c.sendAlert(alertUnexpectedMessage)
818 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
819 }
820 }
821 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
822 if err == io.EOF {
823 err = io.ErrUnexpectedEOF
824 }
825 if e, ok := err.(net.Error); !ok || !e.Temporary() {
826 c.in.setErrorLocked(err)
827 }
828 return 0, nil, err
829 }
830
831 // Process message.
832 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
David Benjaminff26f092016-07-01 16:13:42 -0400833 ok, off, encTyp, alertValue := c.in.decrypt(b)
Nick Harper47383aa2016-11-30 12:50:43 -0800834
835 // Handle skipping over early data.
836 if !ok && c.skipEarlyData {
837 goto RestartReadRecord
838 }
839
840 // If the server is expecting a second ClientHello (in response to
841 // a HelloRetryRequest) and the client sends early data, there
842 // won't be a decryption failure but it still needs to be skipped.
843 if c.in.cipher == nil && typ == recordTypeApplicationData && c.skipEarlyData {
844 goto RestartReadRecord
845 }
846
David Benjaminff26f092016-07-01 16:13:42 -0400847 if !ok {
848 return 0, nil, c.in.setErrorLocked(c.sendAlert(alertValue))
849 }
850 b.off = off
Nick Harper47383aa2016-11-30 12:50:43 -0800851 c.skipEarlyData = false
David Benjaminff26f092016-07-01 16:13:42 -0400852
Nick Harper1fd39d82016-06-14 18:14:35 -0700853 if c.vers >= VersionTLS13 && c.in.cipher != nil {
David Benjaminc9ae27c2016-06-24 22:56:37 -0400854 if typ != recordTypeApplicationData {
855 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: outer record type is not application data"))
856 }
Nick Harper1fd39d82016-06-14 18:14:35 -0700857 typ = encTyp
858 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400859 return typ, b, nil
860}
861
Adam Langley95c29f32014-06-20 12:00:00 -0700862// readRecord reads the next TLS record from the connection
863// and updates the record layer state.
864// c.in.Mutex <= L; c.input == nil.
865func (c *Conn) readRecord(want recordType) error {
866 // Caller must be in sync with connection:
867 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700868 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700869 switch want {
870 default:
871 c.sendAlert(alertInternalError)
872 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
873 case recordTypeHandshake, recordTypeChangeCipherSpec:
874 if c.handshakeComplete {
875 c.sendAlert(alertInternalError)
876 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
877 }
878 case recordTypeApplicationData:
Nick Harper7cd0a972016-12-02 11:08:40 -0800879 if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart && len(c.config.Bugs.ExpectHalfRTTData) == 0 {
Adam Langley95c29f32014-06-20 12:00:00 -0700880 c.sendAlert(alertInternalError)
881 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
882 }
David Benjamin30789da2015-08-29 22:56:45 -0400883 case recordTypeAlert:
884 // Looking for a close_notify. Note: unlike a real
885 // implementation, this is not tolerant of additional records.
886 // See the documentation for ExpectCloseNotify.
Adam Langley95c29f32014-06-20 12:00:00 -0700887 }
888
889Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400890 typ, b, err := c.doReadRecord(want)
891 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700892 return err
893 }
Adam Langley95c29f32014-06-20 12:00:00 -0700894 data := b.data[b.off:]
David Benjamine3fbb362017-01-06 16:19:28 -0500895 max := maxPlaintext
896 if c.config.Bugs.MaxReceivePlaintext != 0 {
897 max = c.config.Bugs.MaxReceivePlaintext
898 }
899 if len(data) > max {
Adam Langley95c29f32014-06-20 12:00:00 -0700900 err := c.sendAlert(alertRecordOverflow)
901 c.in.freeBlock(b)
902 return c.in.setErrorLocked(err)
903 }
904
905 switch typ {
906 default:
907 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
908
909 case recordTypeAlert:
910 if len(data) != 2 {
911 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
912 break
913 }
914 if alert(data[1]) == alertCloseNotify {
915 c.in.setErrorLocked(io.EOF)
916 break
917 }
918 switch data[0] {
919 case alertLevelWarning:
David Benjamin053fee92017-01-02 08:30:36 -0500920 if alert(data[1]) == alertNoCertificate {
921 c.in.freeBlock(b)
922 return errNoCertificateAlert
923 }
924
Adam Langley95c29f32014-06-20 12:00:00 -0700925 // drop on the floor
926 c.in.freeBlock(b)
927 goto Again
928 case alertLevelError:
929 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
930 default:
931 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
932 }
933
934 case recordTypeChangeCipherSpec:
935 if typ != want || len(data) != 1 || data[0] != 1 {
936 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
937 break
938 }
Adam Langley80842bd2014-06-20 12:00:00 -0700939 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700940 if err != nil {
941 c.in.setErrorLocked(c.sendAlert(err.(alert)))
942 }
943
944 case recordTypeApplicationData:
945 if typ != want {
946 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
947 break
948 }
949 c.input = b
950 b = nil
951
952 case recordTypeHandshake:
David Benjamind5a4ecb2016-07-18 01:17:13 +0200953 // Allow handshake data while reading application data to
954 // trigger post-handshake messages.
Adam Langley95c29f32014-06-20 12:00:00 -0700955 // TODO(rsc): Should at least pick off connection close.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200956 if typ != want && want != recordTypeApplicationData {
957 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
Adam Langley95c29f32014-06-20 12:00:00 -0700958 }
959 c.hand.Write(data)
960 }
961
962 if b != nil {
963 c.in.freeBlock(b)
964 }
965 return c.in.err
966}
967
968// sendAlert sends a TLS alert message.
969// c.out.Mutex <= L.
David Benjamin24f346d2015-06-06 03:28:08 -0400970func (c *Conn) sendAlertLocked(level byte, err alert) error {
971 c.tmp[0] = level
Adam Langley95c29f32014-06-20 12:00:00 -0700972 c.tmp[1] = byte(err)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400973 if c.config.Bugs.FragmentAlert {
974 c.writeRecord(recordTypeAlert, c.tmp[0:1])
975 c.writeRecord(recordTypeAlert, c.tmp[1:2])
David Benjamin0d3a8c62016-03-11 22:25:18 -0500976 } else if c.config.Bugs.DoubleAlert {
977 copy(c.tmp[2:4], c.tmp[0:2])
978 c.writeRecord(recordTypeAlert, c.tmp[0:4])
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400979 } else {
980 c.writeRecord(recordTypeAlert, c.tmp[0:2])
981 }
David Benjamin24f346d2015-06-06 03:28:08 -0400982 // Error alerts are fatal to the connection.
983 if level == alertLevelError {
Adam Langley95c29f32014-06-20 12:00:00 -0700984 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
985 }
986 return nil
987}
988
989// sendAlert sends a TLS alert message.
990// L < c.out.Mutex.
991func (c *Conn) sendAlert(err alert) error {
David Benjamin24f346d2015-06-06 03:28:08 -0400992 level := byte(alertLevelError)
David Benjamin053fee92017-01-02 08:30:36 -0500993 if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertificate {
David Benjamin24f346d2015-06-06 03:28:08 -0400994 level = alertLevelWarning
995 }
996 return c.SendAlert(level, err)
997}
998
999func (c *Conn) SendAlert(level byte, err alert) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001000 c.out.Lock()
1001 defer c.out.Unlock()
David Benjamin24f346d2015-06-06 03:28:08 -04001002 return c.sendAlertLocked(level, err)
Adam Langley95c29f32014-06-20 12:00:00 -07001003}
1004
David Benjamind86c7672014-08-02 04:07:12 -04001005// writeV2Record writes a record for a V2ClientHello.
1006func (c *Conn) writeV2Record(data []byte) (n int, err error) {
1007 record := make([]byte, 2+len(data))
1008 record[0] = uint8(len(data)>>8) | 0x80
1009 record[1] = uint8(len(data))
1010 copy(record[2:], data)
1011 return c.conn.Write(record)
1012}
1013
Adam Langley95c29f32014-06-20 12:00:00 -07001014// writeRecord writes a TLS record with the given type and payload
1015// to the connection and updates the record layer state.
1016// c.out.Mutex <= L.
1017func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin639846e2016-09-09 11:41:18 -04001018 if msgType := c.config.Bugs.SendWrongMessageType; msgType != 0 {
1019 if typ == recordTypeHandshake && data[0] == msgType {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001020 newData := make([]byte, len(data))
1021 copy(newData, data)
1022 newData[0] += 42
1023 data = newData
1024 }
1025 }
1026
David Benjamin639846e2016-09-09 11:41:18 -04001027 if msgType := c.config.Bugs.SendTrailingMessageData; msgType != 0 {
1028 if typ == recordTypeHandshake && data[0] == msgType {
1029 newData := make([]byte, len(data))
1030 copy(newData, data)
1031
1032 // Add a 0 to the body.
1033 newData = append(newData, 0)
1034 // Fix the header.
1035 newLen := len(newData) - 4
1036 newData[1] = byte(newLen >> 16)
1037 newData[2] = byte(newLen >> 8)
1038 newData[3] = byte(newLen)
1039
1040 data = newData
1041 }
1042 }
1043
David Benjamin83c0bc92014-08-04 01:23:53 -04001044 if c.isDTLS {
1045 return c.dtlsWriteRecord(typ, data)
1046 }
1047
David Benjamin71dd6662016-07-08 14:10:48 -07001048 if typ == recordTypeHandshake {
1049 if c.config.Bugs.SendHelloRequestBeforeEveryHandshakeMessage {
1050 newData := make([]byte, 0, 4+len(data))
1051 newData = append(newData, typeHelloRequest, 0, 0, 0)
1052 newData = append(newData, data...)
1053 data = newData
1054 }
1055
1056 if c.config.Bugs.PackHandshakeFlight {
1057 c.pendingFlight.Write(data)
1058 return len(data), nil
1059 }
David Benjamin582ba042016-07-07 12:33:25 -07001060 }
1061
1062 return c.doWriteRecord(typ, data)
1063}
1064
1065func (c *Conn) doWriteRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin6f600d62016-12-21 16:06:54 -05001066 recordHeaderLen := c.out.recordHeaderLen()
Adam Langley95c29f32014-06-20 12:00:00 -07001067 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -04001068 first := true
1069 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
David Benjamina8ebe222015-06-06 03:04:39 -04001070 for len(data) > 0 || first {
Adam Langley95c29f32014-06-20 12:00:00 -07001071 m := len(data)
David Benjamin2c99d282015-09-01 10:23:00 -04001072 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords {
Adam Langley95c29f32014-06-20 12:00:00 -07001073 m = maxPlaintext
1074 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001075 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
1076 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -04001077 // By default, do not fragment the client_version or
1078 // server_version, which are located in the first 6
1079 // bytes.
1080 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
1081 m = 6
1082 }
David Benjamin43ec06f2014-08-05 02:28:57 -04001083 }
Adam Langley95c29f32014-06-20 12:00:00 -07001084 explicitIVLen := 0
1085 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -04001086 first = false
Adam Langley95c29f32014-06-20 12:00:00 -07001087
1088 var cbc cbcMode
1089 if c.out.version >= VersionTLS11 {
1090 var ok bool
1091 if cbc, ok = c.out.cipher.(cbcMode); ok {
1092 explicitIVLen = cbc.BlockSize()
1093 }
1094 }
1095 if explicitIVLen == 0 {
David Benjamine9a80ff2015-04-07 00:46:46 -04001096 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce {
Adam Langley95c29f32014-06-20 12:00:00 -07001097 explicitIVLen = 8
1098 // The AES-GCM construction in TLS has an
1099 // explicit nonce so that the nonce can be
1100 // random. However, the nonce is only 8 bytes
1101 // which is too small for a secure, random
1102 // nonce. Therefore we use the sequence number
1103 // as the nonce.
1104 explicitIVIsSeq = true
1105 }
1106 }
1107 b.resize(recordHeaderLen + explicitIVLen + m)
David Benjamin6f600d62016-12-21 16:06:54 -05001108 // If using a short record header, the length will be filled in
1109 // by encrypt.
1110 if !c.out.isShortHeader() {
1111 b.data[0] = byte(typ)
1112 if c.vers >= VersionTLS13 && c.out.cipher != nil {
1113 b.data[0] = byte(recordTypeApplicationData)
1114 if outerType := c.config.Bugs.OuterRecordType; outerType != 0 {
1115 b.data[0] = byte(outerType)
1116 }
David Benjaminc9ae27c2016-06-24 22:56:37 -04001117 }
David Benjamin6f600d62016-12-21 16:06:54 -05001118 vers := c.vers
1119 if vers == 0 || vers >= VersionTLS13 {
1120 // Some TLS servers fail if the record version is
1121 // greater than TLS 1.0 for the initial ClientHello.
1122 //
1123 // TLS 1.3 fixes the version number in the record
1124 // layer to {3, 1}.
1125 vers = VersionTLS10
1126 }
1127 if c.config.Bugs.SendRecordVersion != 0 {
1128 vers = c.config.Bugs.SendRecordVersion
1129 }
1130 if c.vers == 0 && c.config.Bugs.SendInitialRecordVersion != 0 {
1131 vers = c.config.Bugs.SendInitialRecordVersion
1132 }
1133 b.data[1] = byte(vers >> 8)
1134 b.data[2] = byte(vers)
1135 b.data[3] = byte(m >> 8)
1136 b.data[4] = byte(m)
Nick Harper1fd39d82016-06-14 18:14:35 -07001137 }
Adam Langley95c29f32014-06-20 12:00:00 -07001138 if explicitIVLen > 0 {
1139 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
1140 if explicitIVIsSeq {
1141 copy(explicitIV, c.out.seq[:])
1142 } else {
1143 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
1144 break
1145 }
1146 }
1147 }
1148 copy(b.data[recordHeaderLen+explicitIVLen:], data)
Nick Harper1fd39d82016-06-14 18:14:35 -07001149 c.out.encrypt(b, explicitIVLen, typ)
Adam Langley95c29f32014-06-20 12:00:00 -07001150 _, err = c.conn.Write(b.data)
1151 if err != nil {
1152 break
1153 }
1154 n += m
1155 data = data[m:]
1156 }
1157 c.out.freeBlock(b)
1158
1159 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -07001160 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -07001161 if err != nil {
1162 // Cannot call sendAlert directly,
1163 // because we already hold c.out.Mutex.
1164 c.tmp[0] = alertLevelError
1165 c.tmp[1] = byte(err.(alert))
1166 c.writeRecord(recordTypeAlert, c.tmp[0:2])
1167 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
1168 }
1169 }
1170 return
1171}
1172
David Benjamin582ba042016-07-07 12:33:25 -07001173func (c *Conn) flushHandshake() error {
1174 if c.isDTLS {
1175 return c.dtlsFlushHandshake()
1176 }
1177
1178 for c.pendingFlight.Len() > 0 {
1179 var buf [maxPlaintext]byte
1180 n, _ := c.pendingFlight.Read(buf[:])
1181 if _, err := c.doWriteRecord(recordTypeHandshake, buf[:n]); err != nil {
1182 return err
1183 }
1184 }
1185
1186 c.pendingFlight.Reset()
1187 return nil
1188}
1189
David Benjamin83c0bc92014-08-04 01:23:53 -04001190func (c *Conn) doReadHandshake() ([]byte, error) {
1191 if c.isDTLS {
1192 return c.dtlsDoReadHandshake()
1193 }
1194
Adam Langley95c29f32014-06-20 12:00:00 -07001195 for c.hand.Len() < 4 {
1196 if err := c.in.err; err != nil {
1197 return nil, err
1198 }
1199 if err := c.readRecord(recordTypeHandshake); err != nil {
1200 return nil, err
1201 }
1202 }
1203
1204 data := c.hand.Bytes()
1205 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1206 if n > maxHandshake {
1207 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
1208 }
1209 for c.hand.Len() < 4+n {
1210 if err := c.in.err; err != nil {
1211 return nil, err
1212 }
1213 if err := c.readRecord(recordTypeHandshake); err != nil {
1214 return nil, err
1215 }
1216 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001217 return c.hand.Next(4 + n), nil
1218}
1219
1220// readHandshake reads the next handshake message from
1221// the record layer.
1222// c.in.Mutex < L; c.out.Mutex < L.
1223func (c *Conn) readHandshake() (interface{}, error) {
1224 data, err := c.doReadHandshake()
David Benjamin053fee92017-01-02 08:30:36 -05001225 if err == errNoCertificateAlert {
1226 if c.hand.Len() != 0 {
1227 // The warning alert may not interleave with a handshake message.
1228 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1229 }
1230 return new(ssl3NoCertificateMsg), nil
1231 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001232 if err != nil {
1233 return nil, err
1234 }
1235
Adam Langley95c29f32014-06-20 12:00:00 -07001236 var m handshakeMessage
1237 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -07001238 case typeHelloRequest:
1239 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001240 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001241 m = &clientHelloMsg{
1242 isDTLS: c.isDTLS,
1243 }
Adam Langley95c29f32014-06-20 12:00:00 -07001244 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -04001245 m = &serverHelloMsg{
1246 isDTLS: c.isDTLS,
1247 }
Nick Harperdcfbc672016-07-16 17:47:31 +02001248 case typeHelloRetryRequest:
1249 m = new(helloRetryRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001250 case typeNewSessionTicket:
David Benjamin58104882016-07-18 01:25:41 +02001251 m = &newSessionTicketMsg{
1252 version: c.vers,
1253 }
Nick Harperb41d2e42016-07-01 17:50:32 -04001254 case typeEncryptedExtensions:
1255 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001256 case typeCertificate:
Nick Harperb41d2e42016-07-01 17:50:32 -04001257 m = &certificateMsg{
David Benjamin8d315d72016-07-18 01:03:18 +02001258 hasRequestContext: c.vers >= VersionTLS13,
Nick Harperb41d2e42016-07-01 17:50:32 -04001259 }
Adam Langley95c29f32014-06-20 12:00:00 -07001260 case typeCertificateRequest:
1261 m = &certificateRequestMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001262 hasSignatureAlgorithm: c.vers >= VersionTLS12,
David Benjamin8d315d72016-07-18 01:03:18 +02001263 hasRequestContext: c.vers >= VersionTLS13,
Adam Langley95c29f32014-06-20 12:00:00 -07001264 }
1265 case typeCertificateStatus:
1266 m = new(certificateStatusMsg)
1267 case typeServerKeyExchange:
1268 m = new(serverKeyExchangeMsg)
1269 case typeServerHelloDone:
1270 m = new(serverHelloDoneMsg)
1271 case typeClientKeyExchange:
1272 m = new(clientKeyExchangeMsg)
1273 case typeCertificateVerify:
1274 m = &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001275 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001276 }
1277 case typeNextProtocol:
1278 m = new(nextProtoMsg)
1279 case typeFinished:
1280 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001281 case typeHelloVerifyRequest:
1282 m = new(helloVerifyRequestMsg)
David Benjamin24599a82016-06-30 18:56:53 -04001283 case typeChannelID:
1284 m = new(channelIDMsg)
David Benjamin21c00282016-07-18 21:56:23 +02001285 case typeKeyUpdate:
1286 m = new(keyUpdateMsg)
Adam Langley95c29f32014-06-20 12:00:00 -07001287 default:
1288 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1289 }
1290
1291 // The handshake message unmarshallers
1292 // expect to be able to keep references to data,
1293 // so pass in a fresh copy that won't be overwritten.
1294 data = append([]byte(nil), data...)
1295
1296 if !m.unmarshal(data) {
1297 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
1298 }
1299 return m, nil
1300}
1301
David Benjamin83f90402015-01-27 01:09:43 -05001302// skipPacket processes all the DTLS records in packet. It updates
1303// sequence number expectations but otherwise ignores them.
1304func (c *Conn) skipPacket(packet []byte) error {
1305 for len(packet) > 0 {
David Benjamin6ca93552015-08-28 16:16:25 -04001306 if len(packet) < 13 {
1307 return errors.New("tls: bad packet")
1308 }
David Benjamin83f90402015-01-27 01:09:43 -05001309 // Dropped packets are completely ignored save to update
1310 // expected sequence numbers for this and the next epoch. (We
1311 // don't assert on the contents of the packets both for
1312 // simplicity and because a previous test with one shorter
1313 // timeout schedule would have done so.)
1314 epoch := packet[3:5]
1315 seq := packet[5:11]
1316 length := uint16(packet[11])<<8 | uint16(packet[12])
1317 if bytes.Equal(c.in.seq[:2], epoch) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001318 if bytes.Compare(seq, c.in.seq[2:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001319 return errors.New("tls: sequence mismatch")
1320 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001321 copy(c.in.seq[2:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001322 c.in.incSeq(false)
1323 } else {
David Benjamin13e81fc2015-11-02 17:16:13 -05001324 if bytes.Compare(seq, c.in.nextSeq[:]) < 0 {
David Benjamin83f90402015-01-27 01:09:43 -05001325 return errors.New("tls: sequence mismatch")
1326 }
David Benjamin13e81fc2015-11-02 17:16:13 -05001327 copy(c.in.nextSeq[:], seq)
David Benjamin83f90402015-01-27 01:09:43 -05001328 c.in.incNextSeq()
1329 }
David Benjamin6ca93552015-08-28 16:16:25 -04001330 if len(packet) < 13+int(length) {
1331 return errors.New("tls: bad packet")
1332 }
David Benjamin83f90402015-01-27 01:09:43 -05001333 packet = packet[13+length:]
1334 }
1335 return nil
1336}
1337
1338// simulatePacketLoss simulates the loss of a handshake leg from the
1339// peer based on the schedule in c.config.Bugs. If resendFunc is
1340// non-nil, it is called after each simulated timeout to retransmit
1341// handshake messages from the local end. This is used in cases where
1342// the peer retransmits on a stale Finished rather than a timeout.
1343func (c *Conn) simulatePacketLoss(resendFunc func()) error {
1344 if len(c.config.Bugs.TimeoutSchedule) == 0 {
1345 return nil
1346 }
1347 if !c.isDTLS {
1348 return errors.New("tls: TimeoutSchedule may only be set in DTLS")
1349 }
1350 if c.config.Bugs.PacketAdaptor == nil {
1351 return errors.New("tls: TimeoutSchedule set without PacketAdapter")
1352 }
1353 for _, timeout := range c.config.Bugs.TimeoutSchedule {
1354 // Simulate a timeout.
1355 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout)
1356 if err != nil {
1357 return err
1358 }
1359 for _, packet := range packets {
1360 if err := c.skipPacket(packet); err != nil {
1361 return err
1362 }
1363 }
1364 if resendFunc != nil {
1365 resendFunc()
1366 }
1367 }
1368 return nil
1369}
1370
David Benjamin47921102016-07-28 11:29:18 -04001371func (c *Conn) SendHalfHelloRequest() error {
1372 if err := c.Handshake(); err != nil {
1373 return err
1374 }
1375
1376 c.out.Lock()
1377 defer c.out.Unlock()
1378
1379 if _, err := c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0}); err != nil {
1380 return err
1381 }
1382 return c.flushHandshake()
1383}
1384
Adam Langley95c29f32014-06-20 12:00:00 -07001385// Write writes data to the connection.
1386func (c *Conn) Write(b []byte) (int, error) {
1387 if err := c.Handshake(); err != nil {
1388 return 0, err
1389 }
1390
1391 c.out.Lock()
1392 defer c.out.Unlock()
1393
David Benjamin12d2c482016-07-24 10:56:51 -04001394 // Flush any pending handshake data. PackHelloRequestWithFinished may
1395 // have been set and the handshake not followed by Renegotiate.
1396 c.flushHandshake()
1397
Adam Langley95c29f32014-06-20 12:00:00 -07001398 if err := c.out.err; err != nil {
1399 return 0, err
1400 }
1401
1402 if !c.handshakeComplete {
1403 return 0, alertInternalError
1404 }
1405
Steven Valdezc4aa7272016-10-03 12:25:56 -04001406 if c.keyUpdateRequested {
1407 if err := c.sendKeyUpdateLocked(keyUpdateNotRequested); err != nil {
David Benjamin21c00282016-07-18 21:56:23 +02001408 return 0, err
1409 }
Steven Valdezc4aa7272016-10-03 12:25:56 -04001410 c.keyUpdateRequested = false
David Benjamin21c00282016-07-18 21:56:23 +02001411 }
1412
David Benjamin3fd1fbd2015-02-03 16:07:32 -05001413 if c.config.Bugs.SendSpuriousAlert != 0 {
David Benjamin24f346d2015-06-06 03:28:08 -04001414 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001415 }
1416
Adam Langley27a0d082015-11-03 13:34:10 -08001417 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord {
1418 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0})
David Benjamin582ba042016-07-07 12:33:25 -07001419 c.flushHandshake()
Adam Langley27a0d082015-11-03 13:34:10 -08001420 }
1421
Adam Langley95c29f32014-06-20 12:00:00 -07001422 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1423 // attack when using block mode ciphers due to predictable IVs.
1424 // This can be prevented by splitting each Application Data
1425 // record into two records, effectively randomizing the IV.
1426 //
1427 // http://www.openssl.org/~bodo/tls-cbc.txt
1428 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1429 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1430
1431 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001432 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001433 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1434 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1435 if err != nil {
1436 return n, c.out.setErrorLocked(err)
1437 }
1438 m, b = 1, b[1:]
1439 }
1440 }
1441
1442 n, err := c.writeRecord(recordTypeApplicationData, b)
1443 return n + m, c.out.setErrorLocked(err)
1444}
1445
David Benjamind5a4ecb2016-07-18 01:17:13 +02001446func (c *Conn) handlePostHandshakeMessage() error {
Adam Langley2ae77d22014-10-28 17:29:33 -07001447 msg, err := c.readHandshake()
1448 if err != nil {
1449 return err
1450 }
David Benjamind5a4ecb2016-07-18 01:17:13 +02001451
1452 if c.vers < VersionTLS13 {
1453 if !c.isClient {
1454 c.sendAlert(alertUnexpectedMessage)
1455 return errors.New("tls: unexpected post-handshake message")
1456 }
1457
1458 _, ok := msg.(*helloRequestMsg)
1459 if !ok {
1460 c.sendAlert(alertUnexpectedMessage)
1461 return alertUnexpectedMessage
1462 }
1463
1464 c.handshakeComplete = false
1465 return c.Handshake()
Adam Langley2ae77d22014-10-28 17:29:33 -07001466 }
1467
David Benjamind5a4ecb2016-07-18 01:17:13 +02001468 if c.isClient {
1469 if newSessionTicket, ok := msg.(*newSessionTicketMsg); ok {
David Benjamin1a5e8ec2016-10-07 15:19:18 -04001470 if c.config.Bugs.ExpectGREASE && !newSessionTicket.hasGREASEExtension {
1471 return errors.New("tls: no GREASE ticket extension found")
1472 }
1473
Steven Valdez08b65f42016-12-07 15:29:45 -05001474 if c.config.Bugs.ExpectTicketEarlyDataInfo && newSessionTicket.earlyDataInfo == 0 {
1475 return errors.New("tls: no ticket_early_data_info extension found")
1476 }
1477
Steven Valdeza833c352016-11-01 13:39:36 -04001478 if c.config.Bugs.ExpectNoNewSessionTicket {
1479 return errors.New("tls: received unexpected NewSessionTicket")
1480 }
1481
David Benjamind5a4ecb2016-07-18 01:17:13 +02001482 if c.config.ClientSessionCache == nil || newSessionTicket.ticketLifetime == 0 {
1483 return nil
1484 }
1485
1486 session := &ClientSessionState{
1487 sessionTicket: newSessionTicket.ticket,
1488 vers: c.vers,
1489 cipherSuite: c.cipherSuite.id,
1490 masterSecret: c.resumptionSecret,
1491 serverCertificates: c.peerCertificates,
1492 sctList: c.sctList,
1493 ocspResponse: c.ocspResponse,
Nick Harper0b3625b2016-07-25 16:16:28 -07001494 ticketCreationTime: c.config.time(),
1495 ticketExpiration: c.config.time().Add(time.Duration(newSessionTicket.ticketLifetime) * time.Second),
Steven Valdeza833c352016-11-01 13:39:36 -04001496 ticketAgeAdd: newSessionTicket.ticketAgeAdd,
David Benjamind5a4ecb2016-07-18 01:17:13 +02001497 }
1498
1499 cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
1500 c.config.ClientSessionCache.Put(cacheKey, session)
1501 return nil
1502 }
1503 }
1504
Steven Valdezc4aa7272016-10-03 12:25:56 -04001505 if keyUpdate, ok := msg.(*keyUpdateMsg); ok {
Steven Valdez1dc53d22016-07-26 12:27:38 -04001506 c.in.doKeyUpdate(c, false)
Steven Valdezc4aa7272016-10-03 12:25:56 -04001507 if keyUpdate.keyUpdateRequest == keyUpdateRequested {
1508 c.keyUpdateRequested = true
1509 }
David Benjamin21c00282016-07-18 21:56:23 +02001510 return nil
1511 }
1512
David Benjamind5a4ecb2016-07-18 01:17:13 +02001513 // TODO(davidben): Add support for KeyUpdate.
1514 c.sendAlert(alertUnexpectedMessage)
1515 return alertUnexpectedMessage
Adam Langley2ae77d22014-10-28 17:29:33 -07001516}
1517
Adam Langleycf2d4f42014-10-28 19:06:14 -07001518func (c *Conn) Renegotiate() error {
1519 if !c.isClient {
David Benjaminef5dfd22015-12-06 13:17:07 -05001520 helloReq := new(helloRequestMsg).marshal()
1521 if c.config.Bugs.BadHelloRequest != nil {
1522 helloReq = c.config.Bugs.BadHelloRequest
1523 }
1524 c.writeRecord(recordTypeHandshake, helloReq)
David Benjamin582ba042016-07-07 12:33:25 -07001525 c.flushHandshake()
Adam Langleycf2d4f42014-10-28 19:06:14 -07001526 }
1527
1528 c.handshakeComplete = false
1529 return c.Handshake()
1530}
1531
Adam Langley95c29f32014-06-20 12:00:00 -07001532// Read can be made to time out and return a net.Error with Timeout() == true
1533// after a fixed time limit; see SetDeadline and SetReadDeadline.
1534func (c *Conn) Read(b []byte) (n int, err error) {
1535 if err = c.Handshake(); err != nil {
1536 return
1537 }
1538
1539 c.in.Lock()
1540 defer c.in.Unlock()
1541
1542 // Some OpenSSL servers send empty records in order to randomize the
1543 // CBC IV. So this loop ignores a limited number of empty records.
1544 const maxConsecutiveEmptyRecords = 100
1545 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1546 for c.input == nil && c.in.err == nil {
1547 if err := c.readRecord(recordTypeApplicationData); err != nil {
1548 // Soft error, like EAGAIN
1549 return 0, err
1550 }
David Benjamind9b091b2015-01-27 01:10:54 -05001551 if c.hand.Len() > 0 {
David Benjamind5a4ecb2016-07-18 01:17:13 +02001552 // We received handshake bytes, indicating a
1553 // post-handshake message.
1554 if err := c.handlePostHandshakeMessage(); err != nil {
Adam Langley2ae77d22014-10-28 17:29:33 -07001555 return 0, err
1556 }
1557 continue
1558 }
Adam Langley95c29f32014-06-20 12:00:00 -07001559 }
1560 if err := c.in.err; err != nil {
1561 return 0, err
1562 }
1563
1564 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001565 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001566 c.in.freeBlock(c.input)
1567 c.input = nil
1568 }
1569
1570 // If a close-notify alert is waiting, read it so that
1571 // we can return (n, EOF) instead of (n, nil), to signal
1572 // to the HTTP response reading goroutine that the
1573 // connection is now closed. This eliminates a race
1574 // where the HTTP response reading goroutine would
1575 // otherwise not observe the EOF until its next read,
1576 // by which time a client goroutine might have already
1577 // tried to reuse the HTTP connection for a new
1578 // request.
1579 // See https://codereview.appspot.com/76400046
1580 // and http://golang.org/issue/3514
1581 if ri := c.rawInput; ri != nil &&
1582 n != 0 && err == nil &&
1583 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1584 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1585 err = recErr // will be io.EOF on closeNotify
1586 }
1587 }
1588
1589 if n != 0 || err != nil {
1590 return n, err
1591 }
1592 }
1593
1594 return 0, io.ErrNoProgress
1595}
1596
1597// Close closes the connection.
1598func (c *Conn) Close() error {
1599 var alertErr error
1600
1601 c.handshakeMutex.Lock()
1602 defer c.handshakeMutex.Unlock()
David Benjamin30789da2015-08-29 22:56:45 -04001603 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify {
David Benjaminfa214e42016-05-10 17:03:10 -04001604 alert := alertCloseNotify
1605 if c.config.Bugs.SendAlertOnShutdown != 0 {
1606 alert = c.config.Bugs.SendAlertOnShutdown
1607 }
1608 alertErr = c.sendAlert(alert)
David Benjamin4d559612016-05-18 14:31:51 -04001609 // Clear local alerts when sending alerts so we continue to wait
1610 // for the peer rather than closing the socket early.
1611 if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" {
1612 alertErr = nil
1613 }
Adam Langley95c29f32014-06-20 12:00:00 -07001614 }
1615
David Benjamin30789da2015-08-29 22:56:45 -04001616 // Consume a close_notify from the peer if one hasn't been received
1617 // already. This avoids the peer from failing |SSL_shutdown| due to a
1618 // write failing.
1619 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify {
1620 for c.in.error() == nil {
1621 c.readRecord(recordTypeAlert)
1622 }
1623 if c.in.error() != io.EOF {
1624 alertErr = c.in.error()
1625 }
1626 }
1627
Adam Langley95c29f32014-06-20 12:00:00 -07001628 if err := c.conn.Close(); err != nil {
1629 return err
1630 }
1631 return alertErr
1632}
1633
1634// Handshake runs the client or server handshake
1635// protocol if it has not yet been run.
1636// Most uses of this package need not call Handshake
1637// explicitly: the first Read or Write will call it automatically.
1638func (c *Conn) Handshake() error {
1639 c.handshakeMutex.Lock()
1640 defer c.handshakeMutex.Unlock()
1641 if err := c.handshakeErr; err != nil {
1642 return err
1643 }
1644 if c.handshakeComplete {
1645 return nil
1646 }
1647
David Benjamin9a41d1b2015-05-16 01:30:09 -04001648 if c.isDTLS && c.config.Bugs.SendSplitAlert {
1649 c.conn.Write([]byte{
1650 byte(recordTypeAlert), // type
1651 0xfe, 0xff, // version
1652 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence
1653 0x0, 0x2, // length
1654 })
1655 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)})
1656 }
David Benjamin4cf369b2015-08-22 01:35:43 -04001657 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil {
1658 c.writeRecord(recordTypeApplicationData, data)
1659 }
Adam Langley95c29f32014-06-20 12:00:00 -07001660 if c.isClient {
1661 c.handshakeErr = c.clientHandshake()
1662 } else {
1663 c.handshakeErr = c.serverHandshake()
1664 }
David Benjaminddb9f152015-02-03 15:44:39 -05001665 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType {
1666 c.writeRecord(recordType(42), []byte("invalid record"))
1667 }
Adam Langley95c29f32014-06-20 12:00:00 -07001668 return c.handshakeErr
1669}
1670
1671// ConnectionState returns basic TLS details about the connection.
1672func (c *Conn) ConnectionState() ConnectionState {
1673 c.handshakeMutex.Lock()
1674 defer c.handshakeMutex.Unlock()
1675
1676 var state ConnectionState
1677 state.HandshakeComplete = c.handshakeComplete
1678 if c.handshakeComplete {
1679 state.Version = c.vers
1680 state.NegotiatedProtocol = c.clientProtocol
1681 state.DidResume = c.didResume
1682 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001683 state.NegotiatedProtocolFromALPN = c.usedALPN
David Benjaminc565ebb2015-04-03 04:06:36 -04001684 state.CipherSuite = c.cipherSuite.id
Adam Langley95c29f32014-06-20 12:00:00 -07001685 state.PeerCertificates = c.peerCertificates
1686 state.VerifiedChains = c.verifiedChains
1687 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001688 state.ChannelID = c.channelID
David Benjaminca6c8262014-11-15 19:06:08 -05001689 state.SRTPProtectionProfile = c.srtpProtectionProfile
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001690 state.TLSUnique = c.firstFinished[:]
Paul Lietar4fac72e2015-09-09 13:44:55 +01001691 state.SCTList = c.sctList
Nick Harper60edffd2016-06-21 15:19:24 -07001692 state.PeerSignatureAlgorithm = c.peerSignatureAlgorithm
Steven Valdez5440fe02016-07-18 12:40:30 -04001693 state.CurveID = c.curveID
David Benjamin6f600d62016-12-21 16:06:54 -05001694 state.ShortHeader = c.in.shortHeader
Adam Langley95c29f32014-06-20 12:00:00 -07001695 }
1696
1697 return state
1698}
1699
1700// OCSPResponse returns the stapled OCSP response from the TLS server, if
1701// any. (Only valid for client connections.)
1702func (c *Conn) OCSPResponse() []byte {
1703 c.handshakeMutex.Lock()
1704 defer c.handshakeMutex.Unlock()
1705
1706 return c.ocspResponse
1707}
1708
1709// VerifyHostname checks that the peer certificate chain is valid for
1710// connecting to host. If so, it returns nil; if not, it returns an error
1711// describing the problem.
1712func (c *Conn) VerifyHostname(host string) error {
1713 c.handshakeMutex.Lock()
1714 defer c.handshakeMutex.Unlock()
1715 if !c.isClient {
1716 return errors.New("tls: VerifyHostname called on TLS server connection")
1717 }
1718 if !c.handshakeComplete {
1719 return errors.New("tls: handshake has not yet been performed")
1720 }
1721 return c.peerCertificates[0].VerifyHostname(host)
1722}
David Benjaminc565ebb2015-04-03 04:06:36 -04001723
1724// ExportKeyingMaterial exports keying material from the current connection
1725// state, as per RFC 5705.
1726func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) {
1727 c.handshakeMutex.Lock()
1728 defer c.handshakeMutex.Unlock()
1729 if !c.handshakeComplete {
1730 return nil, errors.New("tls: handshake has not yet been performed")
1731 }
1732
David Benjamin8d315d72016-07-18 01:03:18 +02001733 if c.vers >= VersionTLS13 {
David Benjamin97a0a082016-07-13 17:57:35 -04001734 // TODO(davidben): What should we do with useContext? See
1735 // https://github.com/tlswg/tls13-spec/issues/546
1736 return hkdfExpandLabel(c.cipherSuite.hash(), c.exporterSecret, label, context, length), nil
1737 }
1738
David Benjaminc565ebb2015-04-03 04:06:36 -04001739 seedLen := len(c.clientRandom) + len(c.serverRandom)
1740 if useContext {
1741 seedLen += 2 + len(context)
1742 }
1743 seed := make([]byte, 0, seedLen)
1744 seed = append(seed, c.clientRandom[:]...)
1745 seed = append(seed, c.serverRandom[:]...)
1746 if useContext {
1747 seed = append(seed, byte(len(context)>>8), byte(len(context)))
1748 seed = append(seed, context...)
1749 }
1750 result := make([]byte, length)
David Benjamin97a0a082016-07-13 17:57:35 -04001751 prfForVersion(c.vers, c.cipherSuite)(result, c.exporterSecret, label, seed)
David Benjaminc565ebb2015-04-03 04:06:36 -04001752 return result, nil
1753}
David Benjamin3e052de2015-11-25 20:10:31 -05001754
1755// noRenegotiationInfo returns true if the renegotiation info extension
1756// should be supported in the current handshake.
1757func (c *Conn) noRenegotiationInfo() bool {
1758 if c.config.Bugs.NoRenegotiationInfo {
1759 return true
1760 }
1761 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial {
1762 return true
1763 }
1764 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial {
1765 return true
1766 }
1767 return false
1768}
David Benjamin58104882016-07-18 01:25:41 +02001769
1770func (c *Conn) SendNewSessionTicket() error {
1771 if c.isClient || c.vers < VersionTLS13 {
1772 return errors.New("tls: cannot send post-handshake NewSessionTicket")
1773 }
1774
1775 var peerCertificatesRaw [][]byte
1776 for _, cert := range c.peerCertificates {
1777 peerCertificatesRaw = append(peerCertificatesRaw, cert.Raw)
1778 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001779
Steven Valdeza833c352016-11-01 13:39:36 -04001780 addBuffer := make([]byte, 4)
1781 _, err := io.ReadFull(c.config.rand(), addBuffer)
1782 if err != nil {
1783 c.sendAlert(alertInternalError)
1784 return errors.New("tls: short read from Rand: " + err.Error())
1785 }
1786 ticketAgeAdd := uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0])
1787
David Benjamin58104882016-07-18 01:25:41 +02001788 // TODO(davidben): Allow configuring these values.
1789 m := &newSessionTicketMsg{
David Benjamin9c33ae82017-01-08 06:04:43 -05001790 version: c.vers,
1791 ticketLifetime: uint32(24 * time.Hour / time.Second),
1792 earlyDataInfo: c.config.Bugs.SendTicketEarlyDataInfo,
1793 duplicateEarlyDataInfo: c.config.Bugs.DuplicateTicketEarlyDataInfo,
1794 customExtension: c.config.Bugs.CustomTicketExtension,
1795 ticketAgeAdd: ticketAgeAdd,
David Benjamin58104882016-07-18 01:25:41 +02001796 }
Nick Harper0b3625b2016-07-25 16:16:28 -07001797
David Benjamin17b30832017-01-28 14:00:32 -05001798 if c.config.Bugs.SendTicketLifetime != 0 {
1799 m.ticketLifetime = uint32(c.config.Bugs.SendTicketLifetime / time.Second)
1800 }
1801
Nick Harper0b3625b2016-07-25 16:16:28 -07001802 state := sessionState{
1803 vers: c.vers,
1804 cipherSuite: c.cipherSuite.id,
1805 masterSecret: c.resumptionSecret,
1806 certificates: peerCertificatesRaw,
1807 ticketCreationTime: c.config.time(),
1808 ticketExpiration: c.config.time().Add(time.Duration(m.ticketLifetime) * time.Second),
Steven Valdeza833c352016-11-01 13:39:36 -04001809 ticketAgeAdd: uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0]),
Nick Harper0b3625b2016-07-25 16:16:28 -07001810 }
1811
David Benjamin58104882016-07-18 01:25:41 +02001812 if !c.config.Bugs.SendEmptySessionTicket {
1813 var err error
1814 m.ticket, err = c.encryptTicket(&state)
1815 if err != nil {
1816 return err
1817 }
1818 }
1819
1820 c.out.Lock()
1821 defer c.out.Unlock()
Steven Valdeza833c352016-11-01 13:39:36 -04001822 _, err = c.writeRecord(recordTypeHandshake, m.marshal())
David Benjamin58104882016-07-18 01:25:41 +02001823 return err
1824}
David Benjamin21c00282016-07-18 21:56:23 +02001825
Steven Valdezc4aa7272016-10-03 12:25:56 -04001826func (c *Conn) SendKeyUpdate(keyUpdateRequest byte) error {
David Benjamin21c00282016-07-18 21:56:23 +02001827 c.out.Lock()
1828 defer c.out.Unlock()
Steven Valdezc4aa7272016-10-03 12:25:56 -04001829 return c.sendKeyUpdateLocked(keyUpdateRequest)
David Benjamin21c00282016-07-18 21:56:23 +02001830}
1831
Steven Valdezc4aa7272016-10-03 12:25:56 -04001832func (c *Conn) sendKeyUpdateLocked(keyUpdateRequest byte) error {
David Benjamin7f0965a2016-09-30 15:14:01 -04001833 if c.vers < VersionTLS13 {
1834 return errors.New("tls: attempted to send KeyUpdate before TLS 1.3")
1835 }
1836
Steven Valdezc4aa7272016-10-03 12:25:56 -04001837 m := keyUpdateMsg{
1838 keyUpdateRequest: keyUpdateRequest,
1839 }
David Benjamin21c00282016-07-18 21:56:23 +02001840 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
1841 return err
1842 }
1843 if err := c.flushHandshake(); err != nil {
1844 return err
1845 }
Steven Valdez1dc53d22016-07-26 12:27:38 -04001846 c.out.doKeyUpdate(c, true)
David Benjamin21c00282016-07-18 21:56:23 +02001847 return nil
1848}
Steven Valdeza4ee74d2016-11-29 13:36:45 -05001849
1850func (c *Conn) sendFakeEarlyData(len int) error {
1851 // Assemble a fake early data record. This does not use writeRecord
1852 // because the record layer may be using different keys at this point.
1853 payload := make([]byte, 5+len)
1854 payload[0] = byte(recordTypeApplicationData)
1855 payload[1] = 3
1856 payload[2] = 1
1857 payload[3] = byte(len >> 8)
1858 payload[4] = byte(len)
1859 _, err := c.conn.Write(payload)
1860 return err
1861}
David Benjamin6f600d62016-12-21 16:06:54 -05001862
1863func (c *Conn) setShortHeader() {
1864 c.in.shortHeader = true
1865 c.out.shortHeader = true
1866}