blob: 13c3a199ea17fed67a191be2cc36fabadc14cf54 [file] [log] [blame]
Adam Langley95c29f32014-06-20 12:00:00 -07001// Copyright 2009 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
Adam Langleydc7e9c42015-09-29 15:21:04 -07005package runner
Adam Langley95c29f32014-06-20 12:00:00 -07006
7import (
8 "bytes"
Nick Harper60edffd2016-06-21 15:19:24 -07009 "crypto"
Adam Langley95c29f32014-06-20 12:00:00 -070010 "crypto/ecdsa"
David Benjamind30a9902014-08-24 01:44:23 -040011 "crypto/elliptic"
Adam Langley95c29f32014-06-20 12:00:00 -070012 "crypto/rsa"
13 "crypto/subtle"
14 "crypto/x509"
Adam Langley95c29f32014-06-20 12:00:00 -070015 "errors"
16 "fmt"
17 "io"
David Benjaminde620d92014-07-18 15:03:41 -040018 "math/big"
Adam Langley95c29f32014-06-20 12:00:00 -070019 "net"
Nick Harper0b3625b2016-07-25 16:16:28 -070020 "time"
David Benjamind768c5d2017-03-28 18:28:44 -050021
22 "./ed25519"
Adam Langley95c29f32014-06-20 12:00:00 -070023)
24
25type clientHandshakeState struct {
David Benjamin83f90402015-01-27 01:09:43 -050026 c *Conn
27 serverHello *serverHelloMsg
28 hello *clientHelloMsg
29 suite *cipherSuite
30 finishedHash finishedHash
Nick Harperb41d2e42016-07-01 17:50:32 -040031 keyShares map[CurveID]ecdhCurve
David Benjamin83f90402015-01-27 01:09:43 -050032 masterSecret []byte
33 session *ClientSessionState
34 finishedBytes []byte
Adam Langley95c29f32014-06-20 12:00:00 -070035}
36
Steven Valdezc94998a2017-06-20 10:55:02 -040037func mapClientHelloVersion(vers uint16, isDTLS bool) uint16 {
38 if !isDTLS {
39 return vers
40 }
41
42 switch vers {
43 case VersionTLS12:
44 return VersionDTLS12
45 case VersionTLS10:
46 return VersionDTLS10
47 }
48
49 panic("Unknown ClientHello version.")
50}
51
Adam Langley95c29f32014-06-20 12:00:00 -070052func (c *Conn) clientHandshake() error {
53 if c.config == nil {
54 c.config = defaultConfig()
55 }
56
57 if len(c.config.ServerName) == 0 && !c.config.InsecureSkipVerify {
58 return errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
59 }
60
David Benjamin83c0bc92014-08-04 01:23:53 -040061 c.sendHandshakeSeq = 0
62 c.recvHandshakeSeq = 0
63
David Benjaminfa055a22014-09-15 16:51:51 -040064 nextProtosLength := 0
65 for _, proto := range c.config.NextProtos {
Adam Langleyefb0e162015-07-09 11:35:04 -070066 if l := len(proto); l > 255 {
David Benjaminfa055a22014-09-15 16:51:51 -040067 return errors.New("tls: invalid NextProtos value")
68 } else {
69 nextProtosLength += 1 + l
70 }
71 }
72 if nextProtosLength > 0xffff {
73 return errors.New("tls: NextProtos values too large")
74 }
75
Steven Valdezfdd10992016-09-15 16:27:05 -040076 minVersion := c.config.minVersion(c.isDTLS)
David Benjamin3c6a1ea2016-09-26 18:30:05 -040077 maxVersion := c.config.maxVersion(c.isDTLS)
Adam Langley95c29f32014-06-20 12:00:00 -070078 hello := &clientHelloMsg{
David Benjaminca6c8262014-11-15 19:06:08 -050079 isDTLS: c.isDTLS,
David Benjaminca6c8262014-11-15 19:06:08 -050080 compressionMethods: []uint8{compressionNone},
81 random: make([]byte, 32),
David Benjamin53210cb2016-11-16 09:01:48 +090082 ocspStapling: !c.config.Bugs.NoOCSPStapling,
83 sctListSupported: !c.config.Bugs.NoSignedCertificateTimestamps,
David Benjaminca6c8262014-11-15 19:06:08 -050084 serverName: c.config.ServerName,
85 supportedCurves: c.config.curvePreferences(),
86 supportedPoints: []uint8{pointFormatUncompressed},
87 nextProtoNeg: len(c.config.NextProtos) > 0,
88 secureRenegotiation: []byte{},
89 alpnProtocols: c.config.NextProtos,
90 duplicateExtension: c.config.Bugs.DuplicateExtension,
91 channelIDSupported: c.config.ChannelID != nil,
Steven Valdeza833c352016-11-01 13:39:36 -040092 npnAfterAlpn: c.config.Bugs.SwapNPNAndALPN,
Steven Valdezfdd10992016-09-15 16:27:05 -040093 extendedMasterSecret: maxVersion >= VersionTLS10,
David Benjaminca6c8262014-11-15 19:06:08 -050094 srtpProtectionProfiles: c.config.SRTPProtectionProfiles,
95 srtpMasterKeyIdentifier: c.config.Bugs.SRTPMasterKeyIdentifer,
Adam Langley09505632015-07-30 18:10:13 -070096 customExtension: c.config.Bugs.CustomExtension,
Steven Valdeza833c352016-11-01 13:39:36 -040097 pskBinderFirst: c.config.Bugs.PSKBinderFirst,
David Benjaminb853f312017-07-14 18:40:34 -040098 omitExtensions: c.config.Bugs.OmitExtensions,
99 emptyExtensions: c.config.Bugs.EmptyExtensions,
David Benjaminaba057a2017-09-11 15:21:43 -0400100 sendOnlyECExtensions: c.config.Bugs.SendOnlyECExtensions,
Adam Langley95c29f32014-06-20 12:00:00 -0700101 }
102
Steven Valdezc94998a2017-06-20 10:55:02 -0400103 if maxVersion >= VersionTLS13 {
104 hello.vers = mapClientHelloVersion(VersionTLS12, c.isDTLS)
105 if !c.config.Bugs.OmitSupportedVersions {
106 hello.supportedVersions = c.config.supportedVersions(c.isDTLS)
107 }
David Benjaminb853f312017-07-14 18:40:34 -0400108 hello.pskKEModes = []byte{pskDHEKEMode}
Steven Valdezc94998a2017-06-20 10:55:02 -0400109 } else {
110 hello.vers = mapClientHelloVersion(maxVersion, c.isDTLS)
111 }
112
113 if c.config.Bugs.SendClientVersion != 0 {
114 hello.vers = c.config.Bugs.SendClientVersion
115 }
116
117 if len(c.config.Bugs.SendSupportedVersions) > 0 {
118 hello.supportedVersions = c.config.Bugs.SendSupportedVersions
119 }
120
David Benjamin163c9562016-08-29 23:14:17 -0400121 disableEMS := c.config.Bugs.NoExtendedMasterSecret
122 if c.cipherSuite != nil {
123 disableEMS = c.config.Bugs.NoExtendedMasterSecretOnRenegotiation
124 }
125
126 if disableEMS {
Adam Langley75712922014-10-10 16:23:43 -0700127 hello.extendedMasterSecret = false
128 }
129
David Benjamin55a43642015-04-20 14:45:55 -0400130 if c.config.Bugs.NoSupportedCurves {
131 hello.supportedCurves = nil
132 }
133
Steven Valdeza833c352016-11-01 13:39:36 -0400134 if len(c.config.Bugs.SendPSKKeyExchangeModes) != 0 {
135 hello.pskKEModes = c.config.Bugs.SendPSKKeyExchangeModes
136 }
137
David Benjaminc241d792016-09-09 10:34:20 -0400138 if c.config.Bugs.SendCompressionMethods != nil {
139 hello.compressionMethods = c.config.Bugs.SendCompressionMethods
140 }
141
David Benjamina81967b2016-12-22 09:16:57 -0500142 if c.config.Bugs.SendSupportedPointFormats != nil {
143 hello.supportedPoints = c.config.Bugs.SendSupportedPointFormats
144 }
145
Adam Langley2ae77d22014-10-28 17:29:33 -0700146 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
147 if c.config.Bugs.BadRenegotiationInfo {
148 hello.secureRenegotiation = append(hello.secureRenegotiation, c.clientVerify...)
149 hello.secureRenegotiation[0] ^= 0x80
150 } else {
151 hello.secureRenegotiation = c.clientVerify
152 }
153 }
154
David Benjamin3e052de2015-11-25 20:10:31 -0500155 if c.noRenegotiationInfo() {
David Benjaminca6554b2014-11-08 12:31:52 -0500156 hello.secureRenegotiation = nil
157 }
158
Nick Harperb41d2e42016-07-01 17:50:32 -0400159 var keyShares map[CurveID]ecdhCurve
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400160 if maxVersion >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -0400161 keyShares = make(map[CurveID]ecdhCurve)
Nick Harperdcfbc672016-07-16 17:47:31 +0200162 hello.hasKeyShares = true
David Benjamin7e1f9842016-09-20 19:24:40 -0400163 hello.trailingKeyShareData = c.config.Bugs.TrailingKeyShareData
Nick Harperdcfbc672016-07-16 17:47:31 +0200164 curvesToSend := c.config.defaultCurves()
Nick Harperb41d2e42016-07-01 17:50:32 -0400165 for _, curveID := range hello.supportedCurves {
Nick Harperdcfbc672016-07-16 17:47:31 +0200166 if !curvesToSend[curveID] {
167 continue
168 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400169 curve, ok := curveForCurveID(curveID)
170 if !ok {
171 continue
172 }
173 publicKey, err := curve.offer(c.config.rand())
174 if err != nil {
175 return err
176 }
Steven Valdez0ee2e112016-07-15 06:51:15 -0400177
178 if c.config.Bugs.SendCurve != 0 {
179 curveID = c.config.Bugs.SendCurve
180 }
181 if c.config.Bugs.InvalidECDHPoint {
182 publicKey[0] ^= 0xff
183 }
184
Nick Harperb41d2e42016-07-01 17:50:32 -0400185 hello.keyShares = append(hello.keyShares, keyShareEntry{
186 group: curveID,
187 keyExchange: publicKey,
188 })
189 keyShares[curveID] = curve
Steven Valdez143e8b32016-07-11 13:19:03 -0400190
191 if c.config.Bugs.DuplicateKeyShares {
192 hello.keyShares = append(hello.keyShares, hello.keyShares[len(hello.keyShares)-1])
193 }
194 }
195
196 if c.config.Bugs.MissingKeyShare {
Steven Valdez5440fe02016-07-18 12:40:30 -0400197 hello.hasKeyShares = false
Nick Harperb41d2e42016-07-01 17:50:32 -0400198 }
199 }
200
Adam Langley95c29f32014-06-20 12:00:00 -0700201 possibleCipherSuites := c.config.cipherSuites()
202 hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
203
204NextCipherSuite:
205 for _, suiteId := range possibleCipherSuites {
206 for _, suite := range cipherSuites {
207 if suite.id != suiteId {
208 continue
209 }
David Benjamin5ecb88b2016-10-04 17:51:35 -0400210 // Don't advertise TLS 1.2-only cipher suites unless
211 // we're attempting TLS 1.2.
212 if maxVersion < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
213 continue
214 }
215 // Don't advertise non-DTLS cipher suites in DTLS.
216 if c.isDTLS && suite.flags&suiteNoDTLS != 0 {
217 continue
David Benjamin83c0bc92014-08-04 01:23:53 -0400218 }
Adam Langley95c29f32014-06-20 12:00:00 -0700219 hello.cipherSuites = append(hello.cipherSuites, suiteId)
220 continue NextCipherSuite
221 }
222 }
223
David Benjamin5ecb88b2016-10-04 17:51:35 -0400224 if c.config.Bugs.AdvertiseAllConfiguredCiphers {
225 hello.cipherSuites = possibleCipherSuites
226 }
227
Adam Langley5021b222015-06-12 18:27:58 -0700228 if c.config.Bugs.SendRenegotiationSCSV {
229 hello.cipherSuites = append(hello.cipherSuites, renegotiationSCSV)
230 }
231
David Benjaminbef270a2014-08-02 04:22:02 -0400232 if c.config.Bugs.SendFallbackSCSV {
233 hello.cipherSuites = append(hello.cipherSuites, fallbackSCSV)
234 }
235
Adam Langley95c29f32014-06-20 12:00:00 -0700236 _, err := io.ReadFull(c.config.rand(), hello.random)
237 if err != nil {
238 c.sendAlert(alertInternalError)
239 return errors.New("tls: short read from Rand: " + err.Error())
240 }
241
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400242 if maxVersion >= VersionTLS12 && !c.config.Bugs.NoSignatureAlgorithms {
David Benjamin7a41d372016-07-09 11:21:54 -0700243 hello.signatureAlgorithms = c.config.verifySignatureAlgorithms()
Adam Langley95c29f32014-06-20 12:00:00 -0700244 }
245
246 var session *ClientSessionState
247 var cacheKey string
248 sessionCache := c.config.ClientSessionCache
Adam Langley95c29f32014-06-20 12:00:00 -0700249
250 if sessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500251 hello.ticketSupported = !c.config.SessionTicketsDisabled
Adam Langley95c29f32014-06-20 12:00:00 -0700252
253 // Try to resume a previously negotiated TLS session, if
254 // available.
255 cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
Nick Harper0b3625b2016-07-25 16:16:28 -0700256 // TODO(nharper): Support storing more than one session
257 // ticket for TLS 1.3.
Adam Langley95c29f32014-06-20 12:00:00 -0700258 candidateSession, ok := sessionCache.Get(cacheKey)
259 if ok {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500260 ticketOk := !c.config.SessionTicketsDisabled || candidateSession.sessionTicket == nil
261
Adam Langley95c29f32014-06-20 12:00:00 -0700262 // Check that the ciphersuite/version used for the
263 // previous session are still valid.
264 cipherSuiteOk := false
David Benjamin2b02f4b2016-11-16 16:11:47 +0900265 if candidateSession.vers <= VersionTLS12 {
266 for _, id := range hello.cipherSuites {
267 if id == candidateSession.cipherSuite {
268 cipherSuiteOk = true
269 break
270 }
Adam Langley95c29f32014-06-20 12:00:00 -0700271 }
David Benjamin2b02f4b2016-11-16 16:11:47 +0900272 } else {
273 // TLS 1.3 allows the cipher to change on
274 // resumption.
275 cipherSuiteOk = true
Adam Langley95c29f32014-06-20 12:00:00 -0700276 }
277
Steven Valdezfdd10992016-09-15 16:27:05 -0400278 versOk := candidateSession.vers >= minVersion &&
279 candidateSession.vers <= maxVersion
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500280 if ticketOk && versOk && cipherSuiteOk {
Adam Langley95c29f32014-06-20 12:00:00 -0700281 session = candidateSession
282 }
283 }
284 }
285
Steven Valdeza833c352016-11-01 13:39:36 -0400286 var pskCipherSuite *cipherSuite
Nick Harper0b3625b2016-07-25 16:16:28 -0700287 if session != nil && c.config.time().Before(session.ticketExpiration) {
David Benjamind5a4ecb2016-07-18 01:17:13 +0200288 ticket := session.sessionTicket
David Benjamin4199b0d2016-11-01 13:58:25 -0400289 if c.config.Bugs.FilterTicket != nil && len(ticket) > 0 {
290 // Copy the ticket so FilterTicket may act in-place.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200291 ticket = make([]byte, len(session.sessionTicket))
292 copy(ticket, session.sessionTicket)
David Benjamin4199b0d2016-11-01 13:58:25 -0400293
294 ticket, err = c.config.Bugs.FilterTicket(ticket)
295 if err != nil {
296 return err
Adam Langley38311732014-10-16 19:04:35 -0700297 }
David Benjamind5a4ecb2016-07-18 01:17:13 +0200298 }
299
David Benjamin405da482016-08-08 17:25:07 -0400300 if session.vers >= VersionTLS13 || c.config.Bugs.SendBothTickets {
Steven Valdeza833c352016-11-01 13:39:36 -0400301 pskCipherSuite = cipherSuiteFromID(session.cipherSuite)
302 if pskCipherSuite == nil {
303 return errors.New("tls: client session cache has invalid cipher suite")
304 }
Nick Harper0b3625b2016-07-25 16:16:28 -0700305 // TODO(nharper): Support sending more
306 // than one PSK identity.
Steven Valdeza833c352016-11-01 13:39:36 -0400307 ticketAge := uint32(c.config.time().Sub(session.ticketCreationTime) / time.Millisecond)
David Benjamin35ac5b72017-03-03 15:05:56 -0500308 if c.config.Bugs.SendTicketAge != 0 {
309 ticketAge = uint32(c.config.Bugs.SendTicketAge / time.Millisecond)
310 }
Steven Valdez5b986082016-09-01 12:29:49 -0400311 psk := pskIdentity{
Steven Valdeza833c352016-11-01 13:39:36 -0400312 ticket: ticket,
313 obfuscatedTicketAge: session.ticketAgeAdd + ticketAge,
Nick Harper0b3625b2016-07-25 16:16:28 -0700314 }
Steven Valdez5b986082016-09-01 12:29:49 -0400315 hello.pskIdentities = []pskIdentity{psk}
Steven Valdezaf3b8a92016-11-01 12:49:22 -0400316
317 if c.config.Bugs.ExtraPSKIdentity {
318 hello.pskIdentities = append(hello.pskIdentities, psk)
319 }
David Benjamin405da482016-08-08 17:25:07 -0400320 }
321
322 if session.vers < VersionTLS13 || c.config.Bugs.SendBothTickets {
323 if ticket != nil {
324 hello.sessionTicket = ticket
325 // A random session ID is used to detect when the
326 // server accepted the ticket and is resuming a session
327 // (see RFC 5077).
328 sessionIdLen := 16
David Benjamind4c349b2017-02-09 14:07:17 -0500329 if c.config.Bugs.TicketSessionIDLength != 0 {
330 sessionIdLen = c.config.Bugs.TicketSessionIDLength
331 }
332 if c.config.Bugs.EmptyTicketSessionID {
333 sessionIdLen = 0
David Benjamin405da482016-08-08 17:25:07 -0400334 }
335 hello.sessionId = make([]byte, sessionIdLen)
336 if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
337 c.sendAlert(alertInternalError)
338 return errors.New("tls: short read from Rand: " + err.Error())
339 }
340 } else {
341 hello.sessionId = session.sessionId
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500342 }
Adam Langley95c29f32014-06-20 12:00:00 -0700343 }
344 }
345
David Benjamin75f99142016-11-12 12:36:06 +0900346 if c.config.Bugs.SendCipherSuites != nil {
347 hello.cipherSuites = c.config.Bugs.SendCipherSuites
348 }
349
Nick Harperf2511f12016-12-06 16:02:31 -0800350 var sendEarlyData bool
Steven Valdez2d850622017-01-11 11:34:52 -0500351 if len(hello.pskIdentities) > 0 && c.config.Bugs.SendEarlyData != nil {
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500352 hello.hasEarlyData = true
Nick Harperf2511f12016-12-06 16:02:31 -0800353 sendEarlyData = true
354 }
355 if c.config.Bugs.SendFakeEarlyDataLength > 0 {
356 hello.hasEarlyData = true
357 }
358 if c.config.Bugs.OmitEarlyDataExtension {
359 hello.hasEarlyData = false
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500360 }
Steven Valdez0e4a4482017-07-17 11:12:34 -0400361 if c.config.Bugs.SendClientHelloSessionID != nil {
362 hello.sessionId = c.config.Bugs.SendClientHelloSessionID
363 }
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500364
David Benjamind86c7672014-08-02 04:07:12 -0400365 var helloBytes []byte
366 if c.config.Bugs.SendV2ClientHello {
David Benjamin94d701b2014-11-30 13:54:41 -0500367 // Test that the peer left-pads random.
368 hello.random[0] = 0
David Benjamind86c7672014-08-02 04:07:12 -0400369 v2Hello := &v2ClientHelloMsg{
370 vers: hello.vers,
371 cipherSuites: hello.cipherSuites,
372 // No session resumption for V2ClientHello.
373 sessionId: nil,
David Benjamin94d701b2014-11-30 13:54:41 -0500374 challenge: hello.random[1:],
David Benjamind86c7672014-08-02 04:07:12 -0400375 }
376 helloBytes = v2Hello.marshal()
377 c.writeV2Record(helloBytes)
378 } else {
Steven Valdeza833c352016-11-01 13:39:36 -0400379 if len(hello.pskIdentities) > 0 {
380 generatePSKBinders(hello, pskCipherSuite, session.masterSecret, []byte{}, c.config)
381 }
David Benjamind86c7672014-08-02 04:07:12 -0400382 helloBytes = hello.marshal()
Steven Valdeza833c352016-11-01 13:39:36 -0400383
David Benjamin7964b182016-07-14 23:36:30 -0400384 if c.config.Bugs.PartialClientFinishedWithClientHello {
385 // Include one byte of Finished. We can compute it
386 // without completing the handshake. This assumes we
387 // negotiate TLS 1.3 with no HelloRetryRequest or
388 // CertificateRequest.
389 toWrite := make([]byte, 0, len(helloBytes)+1)
390 toWrite = append(toWrite, helloBytes...)
391 toWrite = append(toWrite, typeFinished)
392 c.writeRecord(recordTypeHandshake, toWrite)
393 } else {
394 c.writeRecord(recordTypeHandshake, helloBytes)
395 }
David Benjamind86c7672014-08-02 04:07:12 -0400396 }
David Benjamin582ba042016-07-07 12:33:25 -0700397 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700398
David Benjamin83f90402015-01-27 01:09:43 -0500399 if err := c.simulatePacketLoss(nil); err != nil {
400 return err
401 }
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500402 if c.config.Bugs.SendEarlyAlert {
403 c.sendAlert(alertHandshakeFailure)
404 }
Nick Harperf2511f12016-12-06 16:02:31 -0800405 if c.config.Bugs.SendFakeEarlyDataLength > 0 {
406 c.sendFakeEarlyData(c.config.Bugs.SendFakeEarlyDataLength)
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500407 }
Nick Harperf2511f12016-12-06 16:02:31 -0800408
409 // Derive early write keys and set Conn state to allow early writes.
410 if sendEarlyData {
411 finishedHash := newFinishedHash(session.vers, pskCipherSuite)
412 finishedHash.addEntropy(session.masterSecret)
413 finishedHash.Write(helloBytes)
414 earlyTrafficSecret := finishedHash.deriveSecret(earlyTrafficLabel)
415 c.out.useTrafficSecret(session.vers, pskCipherSuite, earlyTrafficSecret, clientWrite)
Nick Harperf2511f12016-12-06 16:02:31 -0800416 for _, earlyData := range c.config.Bugs.SendEarlyData {
417 if _, err := c.writeRecord(recordTypeApplicationData, earlyData); err != nil {
418 return err
419 }
420 }
421 }
422
Adam Langley95c29f32014-06-20 12:00:00 -0700423 msg, err := c.readHandshake()
424 if err != nil {
425 return err
426 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400427
428 if c.isDTLS {
429 helloVerifyRequest, ok := msg.(*helloVerifyRequestMsg)
430 if ok {
Steven Valdezc94998a2017-06-20 10:55:02 -0400431 if helloVerifyRequest.vers != VersionDTLS10 {
David Benjamin8bc38f52014-08-16 12:07:27 -0400432 // Per RFC 6347, the version field in
433 // HelloVerifyRequest SHOULD be always DTLS
434 // 1.0. Enforce this for testing purposes.
435 return errors.New("dtls: bad HelloVerifyRequest version")
436 }
437
David Benjamin83c0bc92014-08-04 01:23:53 -0400438 hello.raw = nil
439 hello.cookie = helloVerifyRequest.cookie
440 helloBytes = hello.marshal()
441 c.writeRecord(recordTypeHandshake, helloBytes)
David Benjamin582ba042016-07-07 12:33:25 -0700442 c.flushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400443
David Benjamin83f90402015-01-27 01:09:43 -0500444 if err := c.simulatePacketLoss(nil); err != nil {
445 return err
446 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400447 msg, err = c.readHandshake()
448 if err != nil {
449 return err
450 }
451 }
452 }
453
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400454 var serverWireVersion uint16
Nick Harperdcfbc672016-07-16 17:47:31 +0200455 switch m := msg.(type) {
456 case *helloRetryRequestMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400457 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200458 case *serverHelloMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400459 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200460 default:
461 c.sendAlert(alertUnexpectedMessage)
462 return fmt.Errorf("tls: received unexpected message of type %T when waiting for HelloRetryRequest or ServerHello", msg)
463 }
464
Steven Valdezc94998a2017-06-20 10:55:02 -0400465 serverVersion, ok := c.config.isSupportedVersion(serverWireVersion, c.isDTLS)
Nick Harperdcfbc672016-07-16 17:47:31 +0200466 if !ok {
467 c.sendAlert(alertProtocolVersion)
468 return fmt.Errorf("tls: server selected unsupported protocol version %x", c.vers)
469 }
Steven Valdezc94998a2017-06-20 10:55:02 -0400470 c.wireVersion = serverWireVersion
Steven Valdezfdd10992016-09-15 16:27:05 -0400471 c.vers = serverVersion
Nick Harperdcfbc672016-07-16 17:47:31 +0200472 c.haveVers = true
473
474 helloRetryRequest, haveHelloRetryRequest := msg.(*helloRetryRequestMsg)
475 var secondHelloBytes []byte
476 if haveHelloRetryRequest {
Nick Harperf2511f12016-12-06 16:02:31 -0800477 c.out.resetCipher()
David Benjamin3baa6e12016-10-07 21:10:38 -0400478 if len(helloRetryRequest.cookie) > 0 {
479 hello.tls13Cookie = helloRetryRequest.cookie
480 }
481
Steven Valdez5440fe02016-07-18 12:40:30 -0400482 if c.config.Bugs.MisinterpretHelloRetryRequestCurve != 0 {
David Benjamin3baa6e12016-10-07 21:10:38 -0400483 helloRetryRequest.hasSelectedGroup = true
Steven Valdez5440fe02016-07-18 12:40:30 -0400484 helloRetryRequest.selectedGroup = c.config.Bugs.MisinterpretHelloRetryRequestCurve
485 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400486 if helloRetryRequest.hasSelectedGroup {
487 var hrrCurveFound bool
488 group := helloRetryRequest.selectedGroup
489 for _, curveID := range hello.supportedCurves {
490 if group == curveID {
491 hrrCurveFound = true
492 break
493 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200494 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400495 if !hrrCurveFound || keyShares[group] != nil {
496 c.sendAlert(alertHandshakeFailure)
497 return errors.New("tls: received invalid HelloRetryRequest")
498 }
499 curve, ok := curveForCurveID(group)
500 if !ok {
501 return errors.New("tls: Unable to get curve requested in HelloRetryRequest")
502 }
503 publicKey, err := curve.offer(c.config.rand())
504 if err != nil {
505 return err
506 }
507 keyShares[group] = curve
Steven Valdeza833c352016-11-01 13:39:36 -0400508 hello.keyShares = []keyShareEntry{{
David Benjamin3baa6e12016-10-07 21:10:38 -0400509 group: group,
510 keyExchange: publicKey,
Steven Valdeza833c352016-11-01 13:39:36 -0400511 }}
Nick Harperdcfbc672016-07-16 17:47:31 +0200512 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200513
Steven Valdez5440fe02016-07-18 12:40:30 -0400514 if c.config.Bugs.SecondClientHelloMissingKeyShare {
515 hello.hasKeyShares = false
516 }
517
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500518 hello.hasEarlyData = c.config.Bugs.SendEarlyDataOnSecondClientHello
Nick Harperdcfbc672016-07-16 17:47:31 +0200519 hello.raw = nil
520
Steven Valdeza833c352016-11-01 13:39:36 -0400521 if len(hello.pskIdentities) > 0 {
522 generatePSKBinders(hello, pskCipherSuite, session.masterSecret, append(helloBytes, helloRetryRequest.marshal()...), c.config)
523 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200524 secondHelloBytes = hello.marshal()
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500525
526 if c.config.Bugs.InterleaveEarlyData {
527 c.sendFakeEarlyData(4)
528 c.writeRecord(recordTypeHandshake, secondHelloBytes[:16])
529 c.sendFakeEarlyData(4)
530 c.writeRecord(recordTypeHandshake, secondHelloBytes[16:])
531 } else {
532 c.writeRecord(recordTypeHandshake, secondHelloBytes)
533 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200534 c.flushHandshake()
535
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500536 if c.config.Bugs.SendEarlyDataOnSecondClientHello {
537 c.sendFakeEarlyData(4)
538 }
539
Nick Harperdcfbc672016-07-16 17:47:31 +0200540 msg, err = c.readHandshake()
541 if err != nil {
542 return err
543 }
544 }
545
Adam Langley95c29f32014-06-20 12:00:00 -0700546 serverHello, ok := msg.(*serverHelloMsg)
547 if !ok {
548 c.sendAlert(alertUnexpectedMessage)
549 return unexpectedMessageError(serverHello, msg)
550 }
551
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400552 if serverWireVersion != serverHello.vers {
Adam Langley95c29f32014-06-20 12:00:00 -0700553 c.sendAlert(alertProtocolVersion)
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400554 return fmt.Errorf("tls: server sent non-matching version %x vs %x", serverWireVersion, serverHello.vers)
Adam Langley95c29f32014-06-20 12:00:00 -0700555 }
Adam Langley95c29f32014-06-20 12:00:00 -0700556
Nick Harper85f20c22016-07-04 10:11:59 -0700557 // Check for downgrade signals in the server random, per
David Benjamina128a552016-10-13 14:26:33 -0400558 // draft-ietf-tls-tls13-16, section 4.1.3.
Nick Harper85f20c22016-07-04 10:11:59 -0700559 if c.vers <= VersionTLS12 && c.config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400560 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS13) {
Nick Harper85f20c22016-07-04 10:11:59 -0700561 c.sendAlert(alertProtocolVersion)
562 return errors.New("tls: downgrade from TLS 1.3 detected")
563 }
564 }
565 if c.vers <= VersionTLS11 && c.config.maxVersion(c.isDTLS) >= VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400566 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS12) {
Nick Harper85f20c22016-07-04 10:11:59 -0700567 c.sendAlert(alertProtocolVersion)
568 return errors.New("tls: downgrade from TLS 1.2 detected")
569 }
570 }
571
Nick Harper0b3625b2016-07-25 16:16:28 -0700572 suite := mutualCipherSuite(hello.cipherSuites, serverHello.cipherSuite)
Adam Langley95c29f32014-06-20 12:00:00 -0700573 if suite == nil {
574 c.sendAlert(alertHandshakeFailure)
575 return fmt.Errorf("tls: server selected an unsupported cipher suite")
576 }
577
David Benjamin3baa6e12016-10-07 21:10:38 -0400578 if haveHelloRetryRequest && helloRetryRequest.hasSelectedGroup && helloRetryRequest.selectedGroup != serverHello.keyShare.group {
Nick Harperdcfbc672016-07-16 17:47:31 +0200579 c.sendAlert(alertHandshakeFailure)
580 return errors.New("tls: ServerHello parameters did not match HelloRetryRequest")
581 }
582
David Benjamin0a471912017-08-31 00:19:57 -0400583 if c.config.Bugs.ExpectOmitExtensions && !serverHello.omitExtensions {
584 return errors.New("tls: ServerHello did not omit extensions")
585 }
586
Adam Langley95c29f32014-06-20 12:00:00 -0700587 hs := &clientHandshakeState{
588 c: c,
589 serverHello: serverHello,
590 hello: hello,
591 suite: suite,
592 finishedHash: newFinishedHash(c.vers, suite),
Nick Harperb41d2e42016-07-01 17:50:32 -0400593 keyShares: keyShares,
Adam Langley95c29f32014-06-20 12:00:00 -0700594 session: session,
595 }
596
David Benjamin83c0bc92014-08-04 01:23:53 -0400597 hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1)
Nick Harperdcfbc672016-07-16 17:47:31 +0200598 if haveHelloRetryRequest {
599 hs.writeServerHash(helloRetryRequest.marshal())
600 hs.writeClientHash(secondHelloBytes)
601 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400602 hs.writeServerHash(hs.serverHello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700603
David Benjamin8d315d72016-07-18 01:03:18 +0200604 if c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -0400605 if err := hs.doTLS13Handshake(); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700606 return err
607 }
608 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400609 if c.config.Bugs.EarlyChangeCipherSpec > 0 {
610 hs.establishKeys()
611 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
612 }
613
614 if hs.serverHello.compressionMethod != compressionNone {
615 c.sendAlert(alertUnexpectedMessage)
616 return errors.New("tls: server selected unsupported compression format")
617 }
618
619 err = hs.processServerExtensions(&serverHello.extensions)
620 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700621 return err
622 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400623
624 isResume, err := hs.processServerHello()
625 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700626 return err
627 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400628
629 if isResume {
630 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
631 if err := hs.establishKeys(); err != nil {
632 return err
633 }
634 }
635 if err := hs.readSessionTicket(); err != nil {
636 return err
637 }
638 if err := hs.readFinished(c.firstFinished[:]); err != nil {
639 return err
640 }
641 if err := hs.sendFinished(nil, isResume); err != nil {
642 return err
643 }
644 } else {
645 if err := hs.doFullHandshake(); err != nil {
646 return err
647 }
648 if err := hs.establishKeys(); err != nil {
649 return err
650 }
651 if err := hs.sendFinished(c.firstFinished[:], isResume); err != nil {
652 return err
653 }
654 // Most retransmits are triggered by a timeout, but the final
655 // leg of the handshake is retransmited upon re-receiving a
656 // Finished.
657 if err := c.simulatePacketLoss(func() {
David Benjamin02edcd02016-07-27 17:40:37 -0400658 c.sendHandshakeSeq--
Nick Harperb41d2e42016-07-01 17:50:32 -0400659 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
660 c.flushHandshake()
661 }); err != nil {
662 return err
663 }
664 if err := hs.readSessionTicket(); err != nil {
665 return err
666 }
667 if err := hs.readFinished(nil); err != nil {
668 return err
669 }
Adam Langley95c29f32014-06-20 12:00:00 -0700670 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400671
672 if sessionCache != nil && hs.session != nil && session != hs.session {
673 if c.config.Bugs.RequireSessionTickets && len(hs.session.sessionTicket) == 0 {
674 return errors.New("tls: new session used session IDs instead of tickets")
675 }
676 sessionCache.Put(cacheKey, hs.session)
David Benjamin83f90402015-01-27 01:09:43 -0500677 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400678
679 c.didResume = isResume
David Benjamin97a0a082016-07-13 17:57:35 -0400680 c.exporterSecret = hs.masterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700681 }
682
Adam Langley95c29f32014-06-20 12:00:00 -0700683 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400684 c.cipherSuite = suite
685 copy(c.clientRandom[:], hs.hello.random)
686 copy(c.serverRandom[:], hs.serverHello.random)
Paul Lietar4fac72e2015-09-09 13:44:55 +0100687
Adam Langley95c29f32014-06-20 12:00:00 -0700688 return nil
689}
690
Nick Harperb41d2e42016-07-01 17:50:32 -0400691func (hs *clientHandshakeState) doTLS13Handshake() error {
692 c := hs.c
693
Steven Valdez16821262017-09-08 17:03:42 -0400694 if isResumptionExperiment(c.wireVersion) && !bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) {
Steven Valdez0e4a4482017-07-17 11:12:34 -0400695 return errors.New("tls: session IDs did not match.")
696 }
697
Nick Harperb41d2e42016-07-01 17:50:32 -0400698 // Once the PRF hash is known, TLS 1.3 does not require a handshake
699 // buffer.
700 hs.finishedHash.discardHandshakeBuffer()
701
702 zeroSecret := hs.finishedHash.zeroSecret()
703
704 // Resolve PSK and compute the early secret.
705 //
706 // TODO(davidben): This will need to be handled slightly earlier once
707 // 0-RTT is implemented.
Steven Valdez803c77a2016-09-06 14:13:43 -0400708 if hs.serverHello.hasPSKIdentity {
Nick Harper0b3625b2016-07-25 16:16:28 -0700709 // We send at most one PSK identity.
710 if hs.session == nil || hs.serverHello.pskIdentity != 0 {
711 c.sendAlert(alertUnknownPSKIdentity)
712 return errors.New("tls: server sent unknown PSK identity")
713 }
David Benjamin2b02f4b2016-11-16 16:11:47 +0900714 sessionCipher := cipherSuiteFromID(hs.session.cipherSuite)
715 if sessionCipher == nil || sessionCipher.hash() != hs.suite.hash() {
Nick Harper0b3625b2016-07-25 16:16:28 -0700716 c.sendAlert(alertHandshakeFailure)
David Benjamin2b02f4b2016-11-16 16:11:47 +0900717 return errors.New("tls: server resumed an invalid session for the cipher suite")
Nick Harper0b3625b2016-07-25 16:16:28 -0700718 }
David Benjamin48891ad2016-12-04 00:02:43 -0500719 hs.finishedHash.addEntropy(hs.session.masterSecret)
Nick Harper0b3625b2016-07-25 16:16:28 -0700720 c.didResume = true
Nick Harperb41d2e42016-07-01 17:50:32 -0400721 } else {
David Benjamin48891ad2016-12-04 00:02:43 -0500722 hs.finishedHash.addEntropy(zeroSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400723 }
724
Steven Valdeza833c352016-11-01 13:39:36 -0400725 if !hs.serverHello.hasKeyShare {
726 c.sendAlert(alertUnsupportedExtension)
727 return errors.New("tls: server omitted KeyShare on resumption.")
728 }
729
Nick Harperb41d2e42016-07-01 17:50:32 -0400730 // Resolve ECDHE and compute the handshake secret.
Steven Valdez803c77a2016-09-06 14:13:43 -0400731 if !c.config.Bugs.MissingKeyShare && !c.config.Bugs.SecondClientHelloMissingKeyShare {
Nick Harperb41d2e42016-07-01 17:50:32 -0400732 curve, ok := hs.keyShares[hs.serverHello.keyShare.group]
733 if !ok {
734 c.sendAlert(alertHandshakeFailure)
735 return errors.New("tls: server selected an unsupported group")
736 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400737 c.curveID = hs.serverHello.keyShare.group
Nick Harperb41d2e42016-07-01 17:50:32 -0400738
David Benjamin48891ad2016-12-04 00:02:43 -0500739 ecdheSecret, err := curve.finish(hs.serverHello.keyShare.keyExchange)
Nick Harperb41d2e42016-07-01 17:50:32 -0400740 if err != nil {
741 return err
742 }
David Benjamin48891ad2016-12-04 00:02:43 -0500743 hs.finishedHash.addEntropy(ecdheSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400744 } else {
David Benjamin48891ad2016-12-04 00:02:43 -0500745 hs.finishedHash.addEntropy(zeroSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400746 }
747
Steven Valdez16821262017-09-08 17:03:42 -0400748 if isResumptionExperiment(c.wireVersion) {
Steven Valdez520e1222017-06-13 12:45:25 -0400749 if err := c.readRecord(recordTypeChangeCipherSpec); err != nil {
750 return err
751 }
752 }
753
Nick Harperf2511f12016-12-06 16:02:31 -0800754 // Derive handshake traffic keys and switch read key to handshake
755 // traffic key.
David Benjamin48891ad2016-12-04 00:02:43 -0500756 clientHandshakeTrafficSecret := hs.finishedHash.deriveSecret(clientHandshakeTrafficLabel)
David Benjamin48891ad2016-12-04 00:02:43 -0500757 serverHandshakeTrafficSecret := hs.finishedHash.deriveSecret(serverHandshakeTrafficLabel)
Steven Valdeza833c352016-11-01 13:39:36 -0400758 c.in.useTrafficSecret(c.vers, hs.suite, serverHandshakeTrafficSecret, serverWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -0400759
760 msg, err := c.readHandshake()
761 if err != nil {
762 return err
763 }
764
765 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
766 if !ok {
767 c.sendAlert(alertUnexpectedMessage)
768 return unexpectedMessageError(encryptedExtensions, msg)
769 }
770 hs.writeServerHash(encryptedExtensions.marshal())
771
772 err = hs.processServerExtensions(&encryptedExtensions.extensions)
773 if err != nil {
774 return err
775 }
776
777 var chainToSend *Certificate
David Benjamin8d343b42016-07-09 14:26:01 -0700778 var certReq *certificateRequestMsg
Steven Valdeza833c352016-11-01 13:39:36 -0400779 if c.didResume {
Nick Harper0b3625b2016-07-25 16:16:28 -0700780 // Copy over authentication from the session.
781 c.peerCertificates = hs.session.serverCertificates
782 c.sctList = hs.session.sctList
783 c.ocspResponse = hs.session.ocspResponse
David Benjamin44b33bc2016-07-01 22:40:23 -0400784 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400785 msg, err := c.readHandshake()
786 if err != nil {
787 return err
788 }
789
David Benjamin8d343b42016-07-09 14:26:01 -0700790 var ok bool
791 certReq, ok = msg.(*certificateRequestMsg)
Nick Harperb41d2e42016-07-01 17:50:32 -0400792 if ok {
David Benjamin8a8349b2016-08-18 02:32:23 -0400793 if len(certReq.requestContext) != 0 {
794 return errors.New("tls: non-empty certificate request context sent in handshake")
795 }
796
David Benjaminb62d2872016-07-18 14:55:02 +0200797 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
798 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
799 }
800
Nick Harperb41d2e42016-07-01 17:50:32 -0400801 hs.writeServerHash(certReq.marshal())
Nick Harperb41d2e42016-07-01 17:50:32 -0400802
803 chainToSend, err = selectClientCertificate(c, certReq)
804 if err != nil {
805 return err
806 }
807
808 msg, err = c.readHandshake()
809 if err != nil {
810 return err
811 }
812 }
813
814 certMsg, ok := msg.(*certificateMsg)
815 if !ok {
816 c.sendAlert(alertUnexpectedMessage)
817 return unexpectedMessageError(certMsg, msg)
818 }
819 hs.writeServerHash(certMsg.marshal())
820
David Benjamin53210cb2016-11-16 09:01:48 +0900821 // Check for unsolicited extensions.
822 for i, cert := range certMsg.certificates {
823 if c.config.Bugs.NoOCSPStapling && cert.ocspResponse != nil {
824 c.sendAlert(alertUnsupportedExtension)
825 return errors.New("tls: unexpected OCSP response in the server certificate")
826 }
827 if c.config.Bugs.NoSignedCertificateTimestamps && cert.sctList != nil {
828 c.sendAlert(alertUnsupportedExtension)
829 return errors.New("tls: unexpected SCT list in the server certificate")
830 }
831 if i > 0 && c.config.Bugs.ExpectNoExtensionsOnIntermediate && (cert.ocspResponse != nil || cert.sctList != nil) {
832 c.sendAlert(alertUnsupportedExtension)
833 return errors.New("tls: unexpected extensions in the server certificate")
834 }
835 }
836
Nick Harperb41d2e42016-07-01 17:50:32 -0400837 if err := hs.verifyCertificates(certMsg); err != nil {
838 return err
839 }
840 leaf := c.peerCertificates[0]
Steven Valdeza833c352016-11-01 13:39:36 -0400841 c.ocspResponse = certMsg.certificates[0].ocspResponse
842 c.sctList = certMsg.certificates[0].sctList
843
Nick Harperb41d2e42016-07-01 17:50:32 -0400844 msg, err = c.readHandshake()
845 if err != nil {
846 return err
847 }
848 certVerifyMsg, ok := msg.(*certificateVerifyMsg)
849 if !ok {
850 c.sendAlert(alertUnexpectedMessage)
851 return unexpectedMessageError(certVerifyMsg, msg)
852 }
853
David Benjaminf74ec792016-07-13 21:18:49 -0400854 c.peerSignatureAlgorithm = certVerifyMsg.signatureAlgorithm
Nick Harperb41d2e42016-07-01 17:50:32 -0400855 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
David Benjamind768c5d2017-03-28 18:28:44 -0500856 err = verifyMessage(c.vers, getCertificatePublicKey(leaf), c.config, certVerifyMsg.signatureAlgorithm, input, certVerifyMsg.signature)
Nick Harperb41d2e42016-07-01 17:50:32 -0400857 if err != nil {
858 return err
859 }
860
861 hs.writeServerHash(certVerifyMsg.marshal())
862 }
863
864 msg, err = c.readHandshake()
865 if err != nil {
866 return err
867 }
868 serverFinished, ok := msg.(*finishedMsg)
869 if !ok {
870 c.sendAlert(alertUnexpectedMessage)
871 return unexpectedMessageError(serverFinished, msg)
872 }
873
Steven Valdezc4aa7272016-10-03 12:25:56 -0400874 verify := hs.finishedHash.serverSum(serverHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400875 if len(verify) != len(serverFinished.verifyData) ||
876 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
877 c.sendAlert(alertHandshakeFailure)
878 return errors.New("tls: server's Finished message was incorrect")
879 }
880
881 hs.writeServerHash(serverFinished.marshal())
882
883 // The various secrets do not incorporate the client's final leg, so
884 // derive them now before updating the handshake context.
David Benjamin48891ad2016-12-04 00:02:43 -0500885 hs.finishedHash.addEntropy(zeroSecret)
886 clientTrafficSecret := hs.finishedHash.deriveSecret(clientApplicationTrafficLabel)
887 serverTrafficSecret := hs.finishedHash.deriveSecret(serverApplicationTrafficLabel)
David Benjamincdb6fe92017-02-07 16:06:48 -0500888 c.exporterSecret = hs.finishedHash.deriveSecret(exporterLabel)
889
890 // Switch to application data keys on read. In particular, any alerts
891 // from the client certificate are read over these keys.
Nick Harper7cd0a972016-12-02 11:08:40 -0800892 c.in.useTrafficSecret(c.vers, hs.suite, serverTrafficSecret, serverWrite)
893
894 // If we're expecting 0.5-RTT messages from the server, read them
895 // now.
David Benjamin794cc592017-03-25 22:24:23 -0500896 if encryptedExtensions.extensions.hasEarlyData {
897 // BoringSSL will always send two tickets half-RTT when
898 // negotiating 0-RTT.
899 for i := 0; i < shimConfig.HalfRTTTickets; i++ {
900 msg, err := c.readHandshake()
901 if err != nil {
902 return fmt.Errorf("tls: error reading half-RTT ticket: %s", err)
903 }
904 newSessionTicket, ok := msg.(*newSessionTicketMsg)
905 if !ok {
906 return errors.New("tls: expected half-RTT ticket")
907 }
908 if err := c.processTLS13NewSessionTicket(newSessionTicket, hs.suite); err != nil {
909 return err
910 }
Nick Harper7cd0a972016-12-02 11:08:40 -0800911 }
David Benjamin794cc592017-03-25 22:24:23 -0500912 for _, expectedMsg := range c.config.Bugs.ExpectHalfRTTData {
913 if err := c.readRecord(recordTypeApplicationData); err != nil {
914 return err
915 }
916 if !bytes.Equal(c.input.data[c.input.off:], expectedMsg) {
917 return errors.New("ExpectHalfRTTData: did not get expected message")
918 }
919 c.in.freeBlock(c.input)
920 c.input = nil
Nick Harper7cd0a972016-12-02 11:08:40 -0800921 }
Nick Harper7cd0a972016-12-02 11:08:40 -0800922 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400923
Nick Harperf2511f12016-12-06 16:02:31 -0800924 // Send EndOfEarlyData and then switch write key to handshake
925 // traffic key.
David Benjamin32c89272017-03-26 13:54:21 -0500926 if c.out.cipher != nil && !c.config.Bugs.SkipEndOfEarlyData {
Steven Valdez681eb6a2016-12-19 13:19:29 -0500927 if c.config.Bugs.SendStrayEarlyHandshake {
928 helloRequest := new(helloRequestMsg)
929 c.writeRecord(recordTypeHandshake, helloRequest.marshal())
930 }
Nick Harperf2511f12016-12-06 16:02:31 -0800931 c.sendAlert(alertEndOfEarlyData)
932 }
Steven Valdez520e1222017-06-13 12:45:25 -0400933
Steven Valdez16821262017-09-08 17:03:42 -0400934 if isResumptionExperiment(c.wireVersion) {
Steven Valdez520e1222017-06-13 12:45:25 -0400935 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
936 }
937
Nick Harperf2511f12016-12-06 16:02:31 -0800938 c.out.useTrafficSecret(c.vers, hs.suite, clientHandshakeTrafficSecret, clientWrite)
939
Steven Valdez0ee2e112016-07-15 06:51:15 -0400940 if certReq != nil && !c.config.Bugs.SkipClientCertificate {
David Benjamin8d343b42016-07-09 14:26:01 -0700941 certMsg := &certificateMsg{
942 hasRequestContext: true,
943 requestContext: certReq.requestContext,
944 }
945 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -0400946 for _, certData := range chainToSend.Certificate {
947 certMsg.certificates = append(certMsg.certificates, certificateEntry{
948 data: certData,
949 extraExtension: c.config.Bugs.SendExtensionOnCertificate,
950 })
951 }
David Benjamin8d343b42016-07-09 14:26:01 -0700952 }
953 hs.writeClientHash(certMsg.marshal())
954 c.writeRecord(recordTypeHandshake, certMsg.marshal())
955
956 if chainToSend != nil {
957 certVerify := &certificateVerifyMsg{
958 hasSignatureAlgorithm: true,
959 }
960
961 // Determine the hash to sign.
962 privKey := chainToSend.PrivateKey
963
964 var err error
965 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
966 if err != nil {
967 c.sendAlert(alertInternalError)
968 return err
969 }
970
971 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
972 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
973 if err != nil {
974 c.sendAlert(alertInternalError)
975 return err
976 }
Steven Valdez0ee2e112016-07-15 06:51:15 -0400977 if c.config.Bugs.SendSignatureAlgorithm != 0 {
978 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
979 }
David Benjamin8d343b42016-07-09 14:26:01 -0700980
Dimitar Vlahovskibd708452017-08-10 18:01:06 +0200981 if !c.config.Bugs.SkipCertificateVerify {
982 hs.writeClientHash(certVerify.marshal())
983 c.writeRecord(recordTypeHandshake, certVerify.marshal())
984 }
David Benjamin8d343b42016-07-09 14:26:01 -0700985 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400986 }
987
Nick Harper60a85cb2016-09-23 16:25:11 -0700988 if encryptedExtensions.extensions.channelIDRequested {
989 channelIDHash := crypto.SHA256.New()
990 channelIDHash.Write(hs.finishedHash.certificateVerifyInput(channelIDContextTLS13))
991 channelIDMsgBytes, err := hs.writeChannelIDMessage(channelIDHash.Sum(nil))
992 if err != nil {
993 return err
994 }
995 hs.writeClientHash(channelIDMsgBytes)
996 c.writeRecord(recordTypeHandshake, channelIDMsgBytes)
997 }
998
Nick Harperb41d2e42016-07-01 17:50:32 -0400999 // Send a client Finished message.
1000 finished := new(finishedMsg)
Steven Valdezc4aa7272016-10-03 12:25:56 -04001001 finished.verifyData = hs.finishedHash.clientSum(clientHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -04001002 if c.config.Bugs.BadFinished {
1003 finished.verifyData[0]++
1004 }
David Benjamin97a0a082016-07-13 17:57:35 -04001005 hs.writeClientHash(finished.marshal())
David Benjamin7964b182016-07-14 23:36:30 -04001006 if c.config.Bugs.PartialClientFinishedWithClientHello {
1007 // The first byte has already been sent.
1008 c.writeRecord(recordTypeHandshake, finished.marshal()[1:])
Steven Valdeza4ee74d2016-11-29 13:36:45 -05001009 } else if c.config.Bugs.InterleaveEarlyData {
1010 finishedBytes := finished.marshal()
1011 c.sendFakeEarlyData(4)
1012 c.writeRecord(recordTypeHandshake, finishedBytes[:1])
1013 c.sendFakeEarlyData(4)
1014 c.writeRecord(recordTypeHandshake, finishedBytes[1:])
David Benjamin7964b182016-07-14 23:36:30 -04001015 } else {
1016 c.writeRecord(recordTypeHandshake, finished.marshal())
1017 }
David Benjamin02edcd02016-07-27 17:40:37 -04001018 if c.config.Bugs.SendExtraFinished {
1019 c.writeRecord(recordTypeHandshake, finished.marshal())
1020 }
David Benjaminee51a222016-07-07 18:34:12 -07001021 c.flushHandshake()
Nick Harperb41d2e42016-07-01 17:50:32 -04001022
1023 // Switch to application data keys.
Steven Valdeza833c352016-11-01 13:39:36 -04001024 c.out.useTrafficSecret(c.vers, hs.suite, clientTrafficSecret, clientWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -04001025
David Benjamin48891ad2016-12-04 00:02:43 -05001026 c.resumptionSecret = hs.finishedHash.deriveSecret(resumptionLabel)
Nick Harperb41d2e42016-07-01 17:50:32 -04001027 return nil
1028}
1029
Adam Langley95c29f32014-06-20 12:00:00 -07001030func (hs *clientHandshakeState) doFullHandshake() error {
1031 c := hs.c
1032
David Benjamin48cae082014-10-27 01:06:24 -04001033 var leaf *x509.Certificate
1034 if hs.suite.flags&suitePSK == 0 {
1035 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001036 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -07001037 return err
1038 }
Adam Langley95c29f32014-06-20 12:00:00 -07001039
David Benjamin48cae082014-10-27 01:06:24 -04001040 certMsg, ok := msg.(*certificateMsg)
David Benjamin75051442016-07-01 18:58:51 -04001041 if !ok {
David Benjamin48cae082014-10-27 01:06:24 -04001042 c.sendAlert(alertUnexpectedMessage)
1043 return unexpectedMessageError(certMsg, msg)
1044 }
1045 hs.writeServerHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001046
David Benjamin75051442016-07-01 18:58:51 -04001047 if err := hs.verifyCertificates(certMsg); err != nil {
1048 return err
David Benjamin48cae082014-10-27 01:06:24 -04001049 }
David Benjamin75051442016-07-01 18:58:51 -04001050 leaf = c.peerCertificates[0]
David Benjamin48cae082014-10-27 01:06:24 -04001051 }
Adam Langley95c29f32014-06-20 12:00:00 -07001052
Nick Harperb3d51be2016-07-01 11:43:18 -04001053 if hs.serverHello.extensions.ocspStapling {
David Benjamin48cae082014-10-27 01:06:24 -04001054 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001055 if err != nil {
1056 return err
1057 }
1058 cs, ok := msg.(*certificateStatusMsg)
1059 if !ok {
1060 c.sendAlert(alertUnexpectedMessage)
1061 return unexpectedMessageError(cs, msg)
1062 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001063 hs.writeServerHash(cs.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001064
1065 if cs.statusType == statusTypeOCSP {
1066 c.ocspResponse = cs.response
1067 }
1068 }
1069
David Benjamin48cae082014-10-27 01:06:24 -04001070 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001071 if err != nil {
1072 return err
1073 }
1074
1075 keyAgreement := hs.suite.ka(c.vers)
1076
1077 skx, ok := msg.(*serverKeyExchangeMsg)
1078 if ok {
David Benjamin83c0bc92014-08-04 01:23:53 -04001079 hs.writeServerHash(skx.marshal())
David Benjamin48cae082014-10-27 01:06:24 -04001080 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx)
Adam Langley95c29f32014-06-20 12:00:00 -07001081 if err != nil {
1082 c.sendAlert(alertUnexpectedMessage)
1083 return err
1084 }
Steven Valdez5440fe02016-07-18 12:40:30 -04001085 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1086 c.curveID = ecdhe.curveID
1087 }
Adam Langley95c29f32014-06-20 12:00:00 -07001088
Nick Harper60edffd2016-06-21 15:19:24 -07001089 c.peerSignatureAlgorithm = keyAgreement.peerSignatureAlgorithm()
1090
Adam Langley95c29f32014-06-20 12:00:00 -07001091 msg, err = c.readHandshake()
1092 if err != nil {
1093 return err
1094 }
1095 }
1096
1097 var chainToSend *Certificate
1098 var certRequested bool
1099 certReq, ok := msg.(*certificateRequestMsg)
1100 if ok {
1101 certRequested = true
David Benjamin7a41d372016-07-09 11:21:54 -07001102 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
1103 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
1104 }
Adam Langley95c29f32014-06-20 12:00:00 -07001105
David Benjamin83c0bc92014-08-04 01:23:53 -04001106 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001107
David Benjamina6f82632016-07-01 18:44:02 -04001108 chainToSend, err = selectClientCertificate(c, certReq)
1109 if err != nil {
1110 return err
Adam Langley95c29f32014-06-20 12:00:00 -07001111 }
1112
1113 msg, err = c.readHandshake()
1114 if err != nil {
1115 return err
1116 }
1117 }
1118
1119 shd, ok := msg.(*serverHelloDoneMsg)
1120 if !ok {
1121 c.sendAlert(alertUnexpectedMessage)
1122 return unexpectedMessageError(shd, msg)
1123 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001124 hs.writeServerHash(shd.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001125
1126 // If the server requested a certificate then we have to send a
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001127 // Certificate message in TLS, even if it's empty because we don't have
1128 // a certificate to send. In SSL 3.0, skip the message and send a
1129 // no_certificate warning alert.
Adam Langley95c29f32014-06-20 12:00:00 -07001130 if certRequested {
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001131 if c.vers == VersionSSL30 && chainToSend == nil {
David Benjamin053fee92017-01-02 08:30:36 -05001132 c.sendAlert(alertNoCertificate)
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001133 } else if !c.config.Bugs.SkipClientCertificate {
1134 certMsg := new(certificateMsg)
1135 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -04001136 for _, certData := range chainToSend.Certificate {
1137 certMsg.certificates = append(certMsg.certificates, certificateEntry{
1138 data: certData,
1139 })
1140 }
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001141 }
1142 hs.writeClientHash(certMsg.marshal())
1143 c.writeRecord(recordTypeHandshake, certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001144 }
Adam Langley95c29f32014-06-20 12:00:00 -07001145 }
1146
David Benjamin48cae082014-10-27 01:06:24 -04001147 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf)
Adam Langley95c29f32014-06-20 12:00:00 -07001148 if err != nil {
1149 c.sendAlert(alertInternalError)
1150 return err
1151 }
1152 if ckx != nil {
David Benjaminf3ec83d2014-07-21 22:42:34 -04001153 if c.config.Bugs.EarlyChangeCipherSpec < 2 {
David Benjamin83c0bc92014-08-04 01:23:53 -04001154 hs.writeClientHash(ckx.marshal())
David Benjaminf3ec83d2014-07-21 22:42:34 -04001155 }
Adam Langley95c29f32014-06-20 12:00:00 -07001156 c.writeRecord(recordTypeHandshake, ckx.marshal())
1157 }
1158
Nick Harperb3d51be2016-07-01 11:43:18 -04001159 if hs.serverHello.extensions.extendedMasterSecret && c.vers >= VersionTLS10 {
Adam Langley75712922014-10-10 16:23:43 -07001160 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1161 c.extendedMasterSecret = true
1162 } else {
1163 if c.config.Bugs.RequireExtendedMasterSecret {
1164 return errors.New("tls: extended master secret required but not supported by peer")
1165 }
1166 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
1167 }
David Benjamine098ec22014-08-27 23:13:20 -04001168
Adam Langley95c29f32014-06-20 12:00:00 -07001169 if chainToSend != nil {
Adam Langley95c29f32014-06-20 12:00:00 -07001170 certVerify := &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001171 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001172 }
1173
David Benjamin72dc7832015-03-16 17:49:43 -04001174 // Determine the hash to sign.
Nick Harper60edffd2016-06-21 15:19:24 -07001175 privKey := c.config.Certificates[0].PrivateKey
David Benjamin72dc7832015-03-16 17:49:43 -04001176
Nick Harper60edffd2016-06-21 15:19:24 -07001177 if certVerify.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001178 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
Nick Harper60edffd2016-06-21 15:19:24 -07001179 if err != nil {
1180 c.sendAlert(alertInternalError)
1181 return err
Adam Langley95c29f32014-06-20 12:00:00 -07001182 }
Nick Harper60edffd2016-06-21 15:19:24 -07001183 }
1184
1185 if c.vers > VersionSSL30 {
David Benjamin5208fd42016-07-13 21:43:25 -04001186 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, hs.finishedHash.buffer)
David Benjamina95e9f32016-07-08 16:28:04 -07001187 if err == nil && c.config.Bugs.SendSignatureAlgorithm != 0 {
1188 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
1189 }
Nick Harper60edffd2016-06-21 15:19:24 -07001190 } else {
1191 // SSL 3.0's client certificate construction is
1192 // incompatible with signatureAlgorithm.
1193 rsaKey, ok := privKey.(*rsa.PrivateKey)
1194 if !ok {
1195 err = errors.New("unsupported signature type for client certificate")
1196 } else {
1197 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
David Benjamin5208fd42016-07-13 21:43:25 -04001198 if c.config.Bugs.InvalidSignature {
Nick Harper60edffd2016-06-21 15:19:24 -07001199 digest[0] ^= 0x80
1200 }
1201 certVerify.signature, err = rsa.SignPKCS1v15(c.config.rand(), rsaKey, crypto.MD5SHA1, digest)
1202 }
Adam Langley95c29f32014-06-20 12:00:00 -07001203 }
1204 if err != nil {
1205 c.sendAlert(alertInternalError)
1206 return errors.New("tls: failed to sign handshake with client certificate: " + err.Error())
1207 }
Adam Langley95c29f32014-06-20 12:00:00 -07001208
Dimitar Vlahovskibd708452017-08-10 18:01:06 +02001209 if !c.config.Bugs.SkipCertificateVerify {
1210 hs.writeClientHash(certVerify.marshal())
1211 c.writeRecord(recordTypeHandshake, certVerify.marshal())
1212 }
Adam Langley95c29f32014-06-20 12:00:00 -07001213 }
David Benjamin82261be2016-07-07 14:32:50 -07001214 // flushHandshake will be called in sendFinished.
Adam Langley95c29f32014-06-20 12:00:00 -07001215
David Benjamine098ec22014-08-27 23:13:20 -04001216 hs.finishedHash.discardHandshakeBuffer()
1217
Adam Langley95c29f32014-06-20 12:00:00 -07001218 return nil
1219}
1220
David Benjamin75051442016-07-01 18:58:51 -04001221func (hs *clientHandshakeState) verifyCertificates(certMsg *certificateMsg) error {
1222 c := hs.c
1223
1224 if len(certMsg.certificates) == 0 {
1225 c.sendAlert(alertIllegalParameter)
1226 return errors.New("tls: no certificates sent")
1227 }
1228
1229 certs := make([]*x509.Certificate, len(certMsg.certificates))
Steven Valdeza833c352016-11-01 13:39:36 -04001230 for i, certEntry := range certMsg.certificates {
1231 cert, err := x509.ParseCertificate(certEntry.data)
David Benjamin75051442016-07-01 18:58:51 -04001232 if err != nil {
1233 c.sendAlert(alertBadCertificate)
1234 return errors.New("tls: failed to parse certificate from server: " + err.Error())
1235 }
1236 certs[i] = cert
1237 }
1238
1239 if !c.config.InsecureSkipVerify {
1240 opts := x509.VerifyOptions{
1241 Roots: c.config.RootCAs,
1242 CurrentTime: c.config.time(),
1243 DNSName: c.config.ServerName,
1244 Intermediates: x509.NewCertPool(),
1245 }
1246
1247 for i, cert := range certs {
1248 if i == 0 {
1249 continue
1250 }
1251 opts.Intermediates.AddCert(cert)
1252 }
1253 var err error
1254 c.verifiedChains, err = certs[0].Verify(opts)
1255 if err != nil {
1256 c.sendAlert(alertBadCertificate)
1257 return err
1258 }
1259 }
1260
David Benjamind768c5d2017-03-28 18:28:44 -05001261 publicKey := getCertificatePublicKey(certs[0])
1262 switch publicKey.(type) {
1263 case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
David Benjamin75051442016-07-01 18:58:51 -04001264 break
1265 default:
1266 c.sendAlert(alertUnsupportedCertificate)
David Benjamind768c5d2017-03-28 18:28:44 -05001267 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", publicKey)
David Benjamin75051442016-07-01 18:58:51 -04001268 }
1269
1270 c.peerCertificates = certs
1271 return nil
1272}
1273
Adam Langley95c29f32014-06-20 12:00:00 -07001274func (hs *clientHandshakeState) establishKeys() error {
1275 c := hs.c
1276
1277 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001278 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen(c.vers))
Adam Langley95c29f32014-06-20 12:00:00 -07001279 var clientCipher, serverCipher interface{}
1280 var clientHash, serverHash macFunction
1281 if hs.suite.cipher != nil {
1282 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
1283 clientHash = hs.suite.mac(c.vers, clientMAC)
1284 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
1285 serverHash = hs.suite.mac(c.vers, serverMAC)
1286 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001287 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1288 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001289 }
1290
1291 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
1292 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
1293 return nil
1294}
1295
David Benjamin75101402016-07-01 13:40:23 -04001296func (hs *clientHandshakeState) processServerExtensions(serverExtensions *serverExtensions) error {
1297 c := hs.c
1298
David Benjamin8d315d72016-07-18 01:03:18 +02001299 if c.vers < VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001300 if c.config.Bugs.RequireRenegotiationInfo && serverExtensions.secureRenegotiation == nil {
1301 return errors.New("tls: renegotiation extension missing")
1302 }
David Benjamin75101402016-07-01 13:40:23 -04001303
Nick Harperb41d2e42016-07-01 17:50:32 -04001304 if len(c.clientVerify) > 0 && !c.noRenegotiationInfo() {
1305 var expectedRenegInfo []byte
1306 expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...)
1307 expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...)
1308 if !bytes.Equal(serverExtensions.secureRenegotiation, expectedRenegInfo) {
1309 c.sendAlert(alertHandshakeFailure)
1310 return fmt.Errorf("tls: renegotiation mismatch")
1311 }
David Benjamin75101402016-07-01 13:40:23 -04001312 }
David Benjamincea0ab42016-07-14 12:33:14 -04001313 } else if serverExtensions.secureRenegotiation != nil {
1314 return errors.New("tls: renegotiation info sent in TLS 1.3")
David Benjamin75101402016-07-01 13:40:23 -04001315 }
1316
1317 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
1318 if serverExtensions.customExtension != *expected {
1319 return fmt.Errorf("tls: bad custom extension contents %q", serverExtensions.customExtension)
1320 }
1321 }
1322
1323 clientDidNPN := hs.hello.nextProtoNeg
1324 clientDidALPN := len(hs.hello.alpnProtocols) > 0
1325 serverHasNPN := serverExtensions.nextProtoNeg
1326 serverHasALPN := len(serverExtensions.alpnProtocol) > 0
1327
1328 if !clientDidNPN && serverHasNPN {
1329 c.sendAlert(alertHandshakeFailure)
1330 return errors.New("server advertised unrequested NPN extension")
1331 }
1332
1333 if !clientDidALPN && serverHasALPN {
1334 c.sendAlert(alertHandshakeFailure)
1335 return errors.New("server advertised unrequested ALPN extension")
1336 }
1337
1338 if serverHasNPN && serverHasALPN {
1339 c.sendAlert(alertHandshakeFailure)
1340 return errors.New("server advertised both NPN and ALPN extensions")
1341 }
1342
1343 if serverHasALPN {
1344 c.clientProtocol = serverExtensions.alpnProtocol
1345 c.clientProtocolFallback = false
1346 c.usedALPN = true
1347 }
1348
David Benjamin8d315d72016-07-18 01:03:18 +02001349 if serverHasNPN && c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001350 c.sendAlert(alertHandshakeFailure)
1351 return errors.New("server advertised NPN over TLS 1.3")
1352 }
1353
David Benjamin75101402016-07-01 13:40:23 -04001354 if !hs.hello.channelIDSupported && serverExtensions.channelIDRequested {
1355 c.sendAlert(alertHandshakeFailure)
1356 return errors.New("server advertised unrequested Channel ID extension")
1357 }
1358
David Benjamin8d315d72016-07-18 01:03:18 +02001359 if serverExtensions.extendedMasterSecret && c.vers >= VersionTLS13 {
David Benjamine9077652016-07-13 21:02:08 -04001360 return errors.New("tls: server advertised extended master secret over TLS 1.3")
1361 }
1362
David Benjamin8d315d72016-07-18 01:03:18 +02001363 if serverExtensions.ticketSupported && c.vers >= VersionTLS13 {
Steven Valdez143e8b32016-07-11 13:19:03 -04001364 return errors.New("tls: server advertised ticket extension over TLS 1.3")
1365 }
1366
Steven Valdeza833c352016-11-01 13:39:36 -04001367 if serverExtensions.ocspStapling && c.vers >= VersionTLS13 {
1368 return errors.New("tls: server advertised OCSP in ServerHello over TLS 1.3")
1369 }
1370
David Benjamin53210cb2016-11-16 09:01:48 +09001371 if serverExtensions.ocspStapling && c.config.Bugs.NoOCSPStapling {
1372 return errors.New("tls: server advertised unrequested OCSP extension")
1373 }
1374
Steven Valdeza833c352016-11-01 13:39:36 -04001375 if len(serverExtensions.sctList) > 0 && c.vers >= VersionTLS13 {
1376 return errors.New("tls: server advertised SCTs in ServerHello over TLS 1.3")
1377 }
1378
David Benjamin53210cb2016-11-16 09:01:48 +09001379 if len(serverExtensions.sctList) > 0 && c.config.Bugs.NoSignedCertificateTimestamps {
1380 return errors.New("tls: server advertised unrequested SCTs")
1381 }
1382
David Benjamin75101402016-07-01 13:40:23 -04001383 if serverExtensions.srtpProtectionProfile != 0 {
1384 if serverExtensions.srtpMasterKeyIdentifier != "" {
1385 return errors.New("tls: server selected SRTP MKI value")
1386 }
1387
1388 found := false
1389 for _, p := range c.config.SRTPProtectionProfiles {
1390 if p == serverExtensions.srtpProtectionProfile {
1391 found = true
1392 break
1393 }
1394 }
1395 if !found {
1396 return errors.New("tls: server advertised unsupported SRTP profile")
1397 }
1398
1399 c.srtpProtectionProfile = serverExtensions.srtpProtectionProfile
1400 }
1401
Steven Valdez2d850622017-01-11 11:34:52 -05001402 if c.vers >= VersionTLS13 && c.didResume {
1403 if c.config.Bugs.ExpectEarlyDataAccepted && !serverExtensions.hasEarlyData {
1404 c.sendAlert(alertHandshakeFailure)
1405 return errors.New("tls: server did not accept early data when expected")
1406 }
1407
1408 if !c.config.Bugs.ExpectEarlyDataAccepted && serverExtensions.hasEarlyData {
1409 c.sendAlert(alertHandshakeFailure)
1410 return errors.New("tls: server accepted early data when not expected")
1411 }
1412 }
1413
David Benjamin75101402016-07-01 13:40:23 -04001414 return nil
1415}
1416
Adam Langley95c29f32014-06-20 12:00:00 -07001417func (hs *clientHandshakeState) serverResumedSession() bool {
1418 // If the server responded with the same sessionId then it means the
1419 // sessionTicket is being used to resume a TLS session.
David Benjamind4c349b2017-02-09 14:07:17 -05001420 //
1421 // Note that, if hs.hello.sessionId is a non-nil empty array, this will
1422 // accept an empty session ID from the server as resumption. See
1423 // EmptyTicketSessionID.
Adam Langley95c29f32014-06-20 12:00:00 -07001424 return hs.session != nil && hs.hello.sessionId != nil &&
1425 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
1426}
1427
1428func (hs *clientHandshakeState) processServerHello() (bool, error) {
1429 c := hs.c
1430
Adam Langley95c29f32014-06-20 12:00:00 -07001431 if hs.serverResumedSession() {
David Benjamin4b27d9f2015-05-12 22:42:52 -04001432 // For test purposes, assert that the server never accepts the
1433 // resumption offer on renegotiation.
1434 if c.cipherSuite != nil && c.config.Bugs.FailIfResumeOnRenego {
1435 return false, errors.New("tls: server resumed session on renegotiation")
1436 }
1437
Nick Harperb3d51be2016-07-01 11:43:18 -04001438 if hs.serverHello.extensions.sctList != nil {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001439 return false, errors.New("tls: server sent SCT extension on session resumption")
1440 }
1441
Nick Harperb3d51be2016-07-01 11:43:18 -04001442 if hs.serverHello.extensions.ocspStapling {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001443 return false, errors.New("tls: server sent OCSP extension on session resumption")
1444 }
1445
Adam Langley95c29f32014-06-20 12:00:00 -07001446 // Restore masterSecret and peerCerts from previous state
1447 hs.masterSecret = hs.session.masterSecret
1448 c.peerCertificates = hs.session.serverCertificates
Adam Langley75712922014-10-10 16:23:43 -07001449 c.extendedMasterSecret = hs.session.extendedMasterSecret
Paul Lietar62be8ac2015-09-16 10:03:30 +01001450 c.sctList = hs.session.sctList
1451 c.ocspResponse = hs.session.ocspResponse
David Benjamine098ec22014-08-27 23:13:20 -04001452 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001453 return true, nil
1454 }
Paul Lietar62be8ac2015-09-16 10:03:30 +01001455
Nick Harperb3d51be2016-07-01 11:43:18 -04001456 if hs.serverHello.extensions.sctList != nil {
1457 c.sctList = hs.serverHello.extensions.sctList
Paul Lietar62be8ac2015-09-16 10:03:30 +01001458 }
1459
Adam Langley95c29f32014-06-20 12:00:00 -07001460 return false, nil
1461}
1462
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001463func (hs *clientHandshakeState) readFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001464 c := hs.c
1465
1466 c.readRecord(recordTypeChangeCipherSpec)
1467 if err := c.in.error(); err != nil {
1468 return err
1469 }
1470
1471 msg, err := c.readHandshake()
1472 if err != nil {
1473 return err
1474 }
1475 serverFinished, ok := msg.(*finishedMsg)
1476 if !ok {
1477 c.sendAlert(alertUnexpectedMessage)
1478 return unexpectedMessageError(serverFinished, msg)
1479 }
1480
David Benjaminf3ec83d2014-07-21 22:42:34 -04001481 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
1482 verify := hs.finishedHash.serverSum(hs.masterSecret)
1483 if len(verify) != len(serverFinished.verifyData) ||
1484 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
1485 c.sendAlert(alertHandshakeFailure)
1486 return errors.New("tls: server's Finished message was incorrect")
1487 }
Adam Langley95c29f32014-06-20 12:00:00 -07001488 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001489 c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001490 copy(out, serverFinished.verifyData)
David Benjamin83c0bc92014-08-04 01:23:53 -04001491 hs.writeServerHash(serverFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001492 return nil
1493}
1494
1495func (hs *clientHandshakeState) readSessionTicket() error {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001496 c := hs.c
1497
1498 // Create a session with no server identifier. Either a
1499 // session ID or session ticket will be attached.
1500 session := &ClientSessionState{
1501 vers: c.vers,
1502 cipherSuite: hs.suite.id,
1503 masterSecret: hs.masterSecret,
Nick Harperc9846112016-10-17 15:05:35 -07001504 handshakeHash: hs.finishedHash.Sum(),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001505 serverCertificates: c.peerCertificates,
Paul Lietar62be8ac2015-09-16 10:03:30 +01001506 sctList: c.sctList,
1507 ocspResponse: c.ocspResponse,
Nick Harper0b3625b2016-07-25 16:16:28 -07001508 ticketExpiration: c.config.time().Add(time.Duration(7 * 24 * time.Hour)),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001509 }
1510
Nick Harperb3d51be2016-07-01 11:43:18 -04001511 if !hs.serverHello.extensions.ticketSupported {
David Benjamind98452d2015-06-16 14:16:23 -04001512 if c.config.Bugs.ExpectNewTicket {
1513 return errors.New("tls: expected new ticket")
1514 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001515 if hs.session == nil && len(hs.serverHello.sessionId) > 0 {
1516 session.sessionId = hs.serverHello.sessionId
1517 hs.session = session
1518 }
Adam Langley95c29f32014-06-20 12:00:00 -07001519 return nil
1520 }
1521
David Benjaminc7ce9772015-10-09 19:32:41 -04001522 if c.vers == VersionSSL30 {
1523 return errors.New("tls: negotiated session tickets in SSL 3.0")
1524 }
1525
Adam Langley95c29f32014-06-20 12:00:00 -07001526 msg, err := c.readHandshake()
1527 if err != nil {
1528 return err
1529 }
1530 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
1531 if !ok {
1532 c.sendAlert(alertUnexpectedMessage)
1533 return unexpectedMessageError(sessionTicketMsg, msg)
1534 }
Adam Langley95c29f32014-06-20 12:00:00 -07001535
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001536 session.sessionTicket = sessionTicketMsg.ticket
1537 hs.session = session
Adam Langley95c29f32014-06-20 12:00:00 -07001538
David Benjamind30a9902014-08-24 01:44:23 -04001539 hs.writeServerHash(sessionTicketMsg.marshal())
1540
Adam Langley95c29f32014-06-20 12:00:00 -07001541 return nil
1542}
1543
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001544func (hs *clientHandshakeState) sendFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001545 c := hs.c
1546
David Benjamin0b8d5da2016-07-15 00:39:56 -04001547 var postCCSMsgs [][]byte
David Benjamin83c0bc92014-08-04 01:23:53 -04001548 seqno := hs.c.sendHandshakeSeq
Nick Harperb3d51be2016-07-01 11:43:18 -04001549 if hs.serverHello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001550 nextProto := new(nextProtoMsg)
Nick Harperb3d51be2016-07-01 11:43:18 -04001551 proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.extensions.nextProtos)
Adam Langley95c29f32014-06-20 12:00:00 -07001552 nextProto.proto = proto
1553 c.clientProtocol = proto
1554 c.clientProtocolFallback = fallback
1555
David Benjamin86271ee2014-07-21 16:14:03 -04001556 nextProtoBytes := nextProto.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -04001557 hs.writeHash(nextProtoBytes, seqno)
1558 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001559 postCCSMsgs = append(postCCSMsgs, nextProtoBytes)
Adam Langley95c29f32014-06-20 12:00:00 -07001560 }
1561
Nick Harperb3d51be2016-07-01 11:43:18 -04001562 if hs.serverHello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001563 var resumeHash []byte
1564 if isResume {
1565 resumeHash = hs.session.handshakeHash
1566 }
Nick Harper60a85cb2016-09-23 16:25:11 -07001567 channelIDMsgBytes, err := hs.writeChannelIDMessage(hs.finishedHash.hashForChannelID(resumeHash))
David Benjamind30a9902014-08-24 01:44:23 -04001568 if err != nil {
1569 return err
1570 }
David Benjamin24599a82016-06-30 18:56:53 -04001571 hs.writeHash(channelIDMsgBytes, seqno)
David Benjamind30a9902014-08-24 01:44:23 -04001572 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001573 postCCSMsgs = append(postCCSMsgs, channelIDMsgBytes)
David Benjamind30a9902014-08-24 01:44:23 -04001574 }
1575
Adam Langley95c29f32014-06-20 12:00:00 -07001576 finished := new(finishedMsg)
David Benjaminf3ec83d2014-07-21 22:42:34 -04001577 if c.config.Bugs.EarlyChangeCipherSpec == 2 {
1578 finished.verifyData = hs.finishedHash.clientSum(nil)
1579 } else {
1580 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
1581 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001582 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001583 if c.config.Bugs.BadFinished {
1584 finished.verifyData[0]++
1585 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001586 c.clientVerify = append(c.clientVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001587 hs.finishedBytes = finished.marshal()
1588 hs.writeHash(hs.finishedBytes, seqno)
David Benjamin0b8d5da2016-07-15 00:39:56 -04001589 postCCSMsgs = append(postCCSMsgs, hs.finishedBytes)
David Benjamin86271ee2014-07-21 16:14:03 -04001590
1591 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001592 c.writeRecord(recordTypeHandshake, postCCSMsgs[0][:5])
1593 postCCSMsgs[0] = postCCSMsgs[0][5:]
David Benjamin61672812016-07-14 23:10:43 -04001594 } else if c.config.Bugs.SendUnencryptedFinished {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001595 c.writeRecord(recordTypeHandshake, postCCSMsgs[0])
1596 postCCSMsgs = postCCSMsgs[1:]
David Benjamin86271ee2014-07-21 16:14:03 -04001597 }
1598
1599 if !c.config.Bugs.SkipChangeCipherSpec &&
1600 c.config.Bugs.EarlyChangeCipherSpec == 0 {
David Benjamin8411b242015-11-26 12:07:28 -05001601 ccs := []byte{1}
1602 if c.config.Bugs.BadChangeCipherSpec != nil {
1603 ccs = c.config.Bugs.BadChangeCipherSpec
1604 }
1605 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamin86271ee2014-07-21 16:14:03 -04001606 }
1607
David Benjamin4189bd92015-01-25 23:52:39 -05001608 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1609 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1610 }
David Benjamindc3da932015-03-12 15:09:02 -04001611 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1612 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1613 return errors.New("tls: simulating post-CCS alert")
1614 }
David Benjamin4189bd92015-01-25 23:52:39 -05001615
David Benjamin0b8d5da2016-07-15 00:39:56 -04001616 if !c.config.Bugs.SkipFinished {
1617 for _, msg := range postCCSMsgs {
1618 c.writeRecord(recordTypeHandshake, msg)
1619 }
David Benjamin02edcd02016-07-27 17:40:37 -04001620
1621 if c.config.Bugs.SendExtraFinished {
1622 c.writeRecord(recordTypeHandshake, finished.marshal())
1623 }
David Benjaminb3774b92015-01-31 17:16:01 -05001624 }
David Benjaminb0c761e2017-06-25 22:42:55 -04001625
1626 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001627 return nil
1628}
1629
Nick Harper60a85cb2016-09-23 16:25:11 -07001630func (hs *clientHandshakeState) writeChannelIDMessage(channelIDHash []byte) ([]byte, error) {
1631 c := hs.c
1632 channelIDMsg := new(channelIDMsg)
1633 if c.config.ChannelID.Curve != elliptic.P256() {
1634 return nil, fmt.Errorf("tls: Channel ID is not on P-256.")
1635 }
1636 r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, channelIDHash)
1637 if err != nil {
1638 return nil, err
1639 }
1640 channelID := make([]byte, 128)
1641 writeIntPadded(channelID[0:32], c.config.ChannelID.X)
1642 writeIntPadded(channelID[32:64], c.config.ChannelID.Y)
1643 writeIntPadded(channelID[64:96], r)
1644 writeIntPadded(channelID[96:128], s)
1645 if c.config.Bugs.InvalidChannelIDSignature {
1646 channelID[64] ^= 1
1647 }
1648 channelIDMsg.channelID = channelID
1649
1650 c.channelID = &c.config.ChannelID.PublicKey
1651
1652 return channelIDMsg.marshal(), nil
1653}
1654
David Benjamin83c0bc92014-08-04 01:23:53 -04001655func (hs *clientHandshakeState) writeClientHash(msg []byte) {
1656 // writeClientHash is called before writeRecord.
1657 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1658}
1659
1660func (hs *clientHandshakeState) writeServerHash(msg []byte) {
1661 // writeServerHash is called after readHandshake.
1662 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1663}
1664
1665func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) {
1666 if hs.c.isDTLS {
1667 // This is somewhat hacky. DTLS hashes a slightly different format.
1668 // First, the TLS header.
1669 hs.finishedHash.Write(msg[:4])
1670 // Then the sequence number and reassembled fragment offset (always 0).
1671 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1672 // Then the reassembled fragment (always equal to the message length).
1673 hs.finishedHash.Write(msg[1:4])
1674 // And then the message body.
1675 hs.finishedHash.Write(msg[4:])
1676 } else {
1677 hs.finishedHash.Write(msg)
1678 }
1679}
1680
David Benjamina6f82632016-07-01 18:44:02 -04001681// selectClientCertificate selects a certificate for use with the given
1682// certificate, or none if none match. It may return a particular certificate or
1683// nil on success, or an error on internal error.
1684func selectClientCertificate(c *Conn, certReq *certificateRequestMsg) (*Certificate, error) {
David Benjamin3969fdf2017-08-29 15:50:58 -04001685 if len(c.config.Certificates) == 0 {
1686 return nil, nil
David Benjamina6f82632016-07-01 18:44:02 -04001687 }
1688
David Benjamin3969fdf2017-08-29 15:50:58 -04001689 // The test is assumed to have configured the certificate it meant to
1690 // send.
1691 if len(c.config.Certificates) > 1 {
1692 return nil, errors.New("tls: multiple certificates configured")
David Benjamina6f82632016-07-01 18:44:02 -04001693 }
1694
David Benjamin3969fdf2017-08-29 15:50:58 -04001695 return &c.config.Certificates[0], nil
David Benjamina6f82632016-07-01 18:44:02 -04001696}
1697
Adam Langley95c29f32014-06-20 12:00:00 -07001698// clientSessionCacheKey returns a key used to cache sessionTickets that could
1699// be used to resume previously negotiated TLS sessions with a server.
1700func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
1701 if len(config.ServerName) > 0 {
1702 return config.ServerName
1703 }
1704 return serverAddr.String()
1705}
1706
David Benjaminfa055a22014-09-15 16:51:51 -04001707// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
1708// given list of possible protocols and a list of the preference order. The
1709// first list must not be empty. It returns the resulting protocol and flag
Adam Langley95c29f32014-06-20 12:00:00 -07001710// indicating if the fallback case was reached.
David Benjaminfa055a22014-09-15 16:51:51 -04001711func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
1712 for _, s := range preferenceProtos {
1713 for _, c := range protos {
Adam Langley95c29f32014-06-20 12:00:00 -07001714 if s == c {
1715 return s, false
1716 }
1717 }
1718 }
1719
David Benjaminfa055a22014-09-15 16:51:51 -04001720 return protos[0], true
Adam Langley95c29f32014-06-20 12:00:00 -07001721}
David Benjamind30a9902014-08-24 01:44:23 -04001722
1723// writeIntPadded writes x into b, padded up with leading zeros as
1724// needed.
1725func writeIntPadded(b []byte, x *big.Int) {
1726 for i := range b {
1727 b[i] = 0
1728 }
1729 xb := x.Bytes()
1730 copy(b[len(b)-len(xb):], xb)
1731}
Steven Valdeza833c352016-11-01 13:39:36 -04001732
1733func generatePSKBinders(hello *clientHelloMsg, pskCipherSuite *cipherSuite, psk, transcript []byte, config *Config) {
1734 if config.Bugs.SendNoPSKBinder {
1735 return
1736 }
1737
1738 binderLen := pskCipherSuite.hash().Size()
1739 if config.Bugs.SendShortPSKBinder {
1740 binderLen--
1741 }
1742
David Benjaminaedf3032016-12-01 16:47:56 -05001743 numBinders := 1
1744 if config.Bugs.SendExtraPSKBinder {
1745 numBinders++
1746 }
1747
Steven Valdeza833c352016-11-01 13:39:36 -04001748 // Fill hello.pskBinders with appropriate length arrays of zeros so the
1749 // length prefixes are correct when computing the binder over the truncated
1750 // ClientHello message.
David Benjaminaedf3032016-12-01 16:47:56 -05001751 hello.pskBinders = make([][]byte, numBinders)
1752 for i := range hello.pskBinders {
Steven Valdeza833c352016-11-01 13:39:36 -04001753 hello.pskBinders[i] = make([]byte, binderLen)
1754 }
1755
1756 helloBytes := hello.marshal()
1757 binderSize := len(hello.pskBinders)*(binderLen+1) + 2
1758 truncatedHello := helloBytes[:len(helloBytes)-binderSize]
1759 binder := computePSKBinder(psk, resumptionPSKBinderLabel, pskCipherSuite, transcript, truncatedHello)
1760 if config.Bugs.SendShortPSKBinder {
1761 binder = binder[:binderLen]
1762 }
1763 if config.Bugs.SendInvalidPSKBinder {
1764 binder[0] ^= 1
1765 }
1766
1767 for i := range hello.pskBinders {
1768 hello.pskBinders[i] = binder
1769 }
1770
1771 hello.raw = nil
1772}