blob: 05e7311cf7198147001dd13d918c6bdfbd55a35e [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"
20 "strconv"
Nick Harper0b3625b2016-07-25 16:16:28 -070021 "time"
David Benjamind768c5d2017-03-28 18:28:44 -050022
23 "./ed25519"
Adam Langley95c29f32014-06-20 12:00:00 -070024)
25
26type clientHandshakeState struct {
David Benjamin83f90402015-01-27 01:09:43 -050027 c *Conn
28 serverHello *serverHelloMsg
29 hello *clientHelloMsg
30 suite *cipherSuite
31 finishedHash finishedHash
Nick Harperb41d2e42016-07-01 17:50:32 -040032 keyShares map[CurveID]ecdhCurve
David Benjamin83f90402015-01-27 01:09:43 -050033 masterSecret []byte
34 session *ClientSessionState
35 finishedBytes []byte
Adam Langley95c29f32014-06-20 12:00:00 -070036}
37
Steven Valdezc94998a2017-06-20 10:55:02 -040038func mapClientHelloVersion(vers uint16, isDTLS bool) uint16 {
39 if !isDTLS {
40 return vers
41 }
42
43 switch vers {
44 case VersionTLS12:
45 return VersionDTLS12
46 case VersionTLS10:
47 return VersionDTLS10
48 }
49
50 panic("Unknown ClientHello version.")
51}
52
Adam Langley95c29f32014-06-20 12:00:00 -070053func (c *Conn) clientHandshake() error {
54 if c.config == nil {
55 c.config = defaultConfig()
56 }
57
58 if len(c.config.ServerName) == 0 && !c.config.InsecureSkipVerify {
59 return errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
60 }
61
David Benjamin83c0bc92014-08-04 01:23:53 -040062 c.sendHandshakeSeq = 0
63 c.recvHandshakeSeq = 0
64
David Benjaminfa055a22014-09-15 16:51:51 -040065 nextProtosLength := 0
66 for _, proto := range c.config.NextProtos {
Adam Langleyefb0e162015-07-09 11:35:04 -070067 if l := len(proto); l > 255 {
David Benjaminfa055a22014-09-15 16:51:51 -040068 return errors.New("tls: invalid NextProtos value")
69 } else {
70 nextProtosLength += 1 + l
71 }
72 }
73 if nextProtosLength > 0xffff {
74 return errors.New("tls: NextProtos values too large")
75 }
76
Steven Valdezfdd10992016-09-15 16:27:05 -040077 minVersion := c.config.minVersion(c.isDTLS)
David Benjamin3c6a1ea2016-09-26 18:30:05 -040078 maxVersion := c.config.maxVersion(c.isDTLS)
Adam Langley95c29f32014-06-20 12:00:00 -070079 hello := &clientHelloMsg{
David Benjaminca6c8262014-11-15 19:06:08 -050080 isDTLS: c.isDTLS,
David Benjaminca6c8262014-11-15 19:06:08 -050081 compressionMethods: []uint8{compressionNone},
82 random: make([]byte, 32),
David Benjamin53210cb2016-11-16 09:01:48 +090083 ocspStapling: !c.config.Bugs.NoOCSPStapling,
84 sctListSupported: !c.config.Bugs.NoSignedCertificateTimestamps,
David Benjaminca6c8262014-11-15 19:06:08 -050085 serverName: c.config.ServerName,
86 supportedCurves: c.config.curvePreferences(),
87 supportedPoints: []uint8{pointFormatUncompressed},
88 nextProtoNeg: len(c.config.NextProtos) > 0,
89 secureRenegotiation: []byte{},
90 alpnProtocols: c.config.NextProtos,
91 duplicateExtension: c.config.Bugs.DuplicateExtension,
92 channelIDSupported: c.config.ChannelID != nil,
Steven Valdeza833c352016-11-01 13:39:36 -040093 npnAfterAlpn: c.config.Bugs.SwapNPNAndALPN,
Steven Valdezfdd10992016-09-15 16:27:05 -040094 extendedMasterSecret: maxVersion >= VersionTLS10,
David Benjaminca6c8262014-11-15 19:06:08 -050095 srtpProtectionProfiles: c.config.SRTPProtectionProfiles,
96 srtpMasterKeyIdentifier: c.config.Bugs.SRTPMasterKeyIdentifer,
Adam Langley09505632015-07-30 18:10:13 -070097 customExtension: c.config.Bugs.CustomExtension,
Steven Valdeza833c352016-11-01 13:39:36 -040098 pskBinderFirst: c.config.Bugs.PSKBinderFirst,
David Benjaminb853f312017-07-14 18:40:34 -040099 omitExtensions: c.config.Bugs.OmitExtensions,
100 emptyExtensions: c.config.Bugs.EmptyExtensions,
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 }
361
David Benjamind86c7672014-08-02 04:07:12 -0400362 var helloBytes []byte
363 if c.config.Bugs.SendV2ClientHello {
David Benjamin94d701b2014-11-30 13:54:41 -0500364 // Test that the peer left-pads random.
365 hello.random[0] = 0
David Benjamind86c7672014-08-02 04:07:12 -0400366 v2Hello := &v2ClientHelloMsg{
367 vers: hello.vers,
368 cipherSuites: hello.cipherSuites,
369 // No session resumption for V2ClientHello.
370 sessionId: nil,
David Benjamin94d701b2014-11-30 13:54:41 -0500371 challenge: hello.random[1:],
David Benjamind86c7672014-08-02 04:07:12 -0400372 }
373 helloBytes = v2Hello.marshal()
374 c.writeV2Record(helloBytes)
375 } else {
Steven Valdeza833c352016-11-01 13:39:36 -0400376 if len(hello.pskIdentities) > 0 {
377 generatePSKBinders(hello, pskCipherSuite, session.masterSecret, []byte{}, c.config)
378 }
David Benjamind86c7672014-08-02 04:07:12 -0400379 helloBytes = hello.marshal()
Steven Valdeza833c352016-11-01 13:39:36 -0400380
David Benjamin7964b182016-07-14 23:36:30 -0400381 if c.config.Bugs.PartialClientFinishedWithClientHello {
382 // Include one byte of Finished. We can compute it
383 // without completing the handshake. This assumes we
384 // negotiate TLS 1.3 with no HelloRetryRequest or
385 // CertificateRequest.
386 toWrite := make([]byte, 0, len(helloBytes)+1)
387 toWrite = append(toWrite, helloBytes...)
388 toWrite = append(toWrite, typeFinished)
389 c.writeRecord(recordTypeHandshake, toWrite)
390 } else {
391 c.writeRecord(recordTypeHandshake, helloBytes)
392 }
David Benjamind86c7672014-08-02 04:07:12 -0400393 }
David Benjamin582ba042016-07-07 12:33:25 -0700394 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700395
David Benjamin83f90402015-01-27 01:09:43 -0500396 if err := c.simulatePacketLoss(nil); err != nil {
397 return err
398 }
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500399 if c.config.Bugs.SendEarlyAlert {
400 c.sendAlert(alertHandshakeFailure)
401 }
Nick Harperf2511f12016-12-06 16:02:31 -0800402 if c.config.Bugs.SendFakeEarlyDataLength > 0 {
403 c.sendFakeEarlyData(c.config.Bugs.SendFakeEarlyDataLength)
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500404 }
Nick Harperf2511f12016-12-06 16:02:31 -0800405
406 // Derive early write keys and set Conn state to allow early writes.
407 if sendEarlyData {
408 finishedHash := newFinishedHash(session.vers, pskCipherSuite)
409 finishedHash.addEntropy(session.masterSecret)
410 finishedHash.Write(helloBytes)
411 earlyTrafficSecret := finishedHash.deriveSecret(earlyTrafficLabel)
412 c.out.useTrafficSecret(session.vers, pskCipherSuite, earlyTrafficSecret, clientWrite)
Nick Harperf2511f12016-12-06 16:02:31 -0800413 for _, earlyData := range c.config.Bugs.SendEarlyData {
414 if _, err := c.writeRecord(recordTypeApplicationData, earlyData); err != nil {
415 return err
416 }
417 }
418 }
419
Adam Langley95c29f32014-06-20 12:00:00 -0700420 msg, err := c.readHandshake()
421 if err != nil {
422 return err
423 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400424
425 if c.isDTLS {
426 helloVerifyRequest, ok := msg.(*helloVerifyRequestMsg)
427 if ok {
Steven Valdezc94998a2017-06-20 10:55:02 -0400428 if helloVerifyRequest.vers != VersionDTLS10 {
David Benjamin8bc38f52014-08-16 12:07:27 -0400429 // Per RFC 6347, the version field in
430 // HelloVerifyRequest SHOULD be always DTLS
431 // 1.0. Enforce this for testing purposes.
432 return errors.New("dtls: bad HelloVerifyRequest version")
433 }
434
David Benjamin83c0bc92014-08-04 01:23:53 -0400435 hello.raw = nil
436 hello.cookie = helloVerifyRequest.cookie
437 helloBytes = hello.marshal()
438 c.writeRecord(recordTypeHandshake, helloBytes)
David Benjamin582ba042016-07-07 12:33:25 -0700439 c.flushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400440
David Benjamin83f90402015-01-27 01:09:43 -0500441 if err := c.simulatePacketLoss(nil); err != nil {
442 return err
443 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400444 msg, err = c.readHandshake()
445 if err != nil {
446 return err
447 }
448 }
449 }
450
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400451 var serverWireVersion uint16
Nick Harperdcfbc672016-07-16 17:47:31 +0200452 switch m := msg.(type) {
453 case *helloRetryRequestMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400454 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200455 case *serverHelloMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400456 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200457 default:
458 c.sendAlert(alertUnexpectedMessage)
459 return fmt.Errorf("tls: received unexpected message of type %T when waiting for HelloRetryRequest or ServerHello", msg)
460 }
461
Steven Valdezc94998a2017-06-20 10:55:02 -0400462 serverVersion, ok := c.config.isSupportedVersion(serverWireVersion, c.isDTLS)
Nick Harperdcfbc672016-07-16 17:47:31 +0200463 if !ok {
464 c.sendAlert(alertProtocolVersion)
465 return fmt.Errorf("tls: server selected unsupported protocol version %x", c.vers)
466 }
Steven Valdezc94998a2017-06-20 10:55:02 -0400467 c.wireVersion = serverWireVersion
Steven Valdezfdd10992016-09-15 16:27:05 -0400468 c.vers = serverVersion
Nick Harperdcfbc672016-07-16 17:47:31 +0200469 c.haveVers = true
470
471 helloRetryRequest, haveHelloRetryRequest := msg.(*helloRetryRequestMsg)
472 var secondHelloBytes []byte
473 if haveHelloRetryRequest {
Nick Harperf2511f12016-12-06 16:02:31 -0800474 c.out.resetCipher()
David Benjamin3baa6e12016-10-07 21:10:38 -0400475 if len(helloRetryRequest.cookie) > 0 {
476 hello.tls13Cookie = helloRetryRequest.cookie
477 }
478
Steven Valdez5440fe02016-07-18 12:40:30 -0400479 if c.config.Bugs.MisinterpretHelloRetryRequestCurve != 0 {
David Benjamin3baa6e12016-10-07 21:10:38 -0400480 helloRetryRequest.hasSelectedGroup = true
Steven Valdez5440fe02016-07-18 12:40:30 -0400481 helloRetryRequest.selectedGroup = c.config.Bugs.MisinterpretHelloRetryRequestCurve
482 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400483 if helloRetryRequest.hasSelectedGroup {
484 var hrrCurveFound bool
485 group := helloRetryRequest.selectedGroup
486 for _, curveID := range hello.supportedCurves {
487 if group == curveID {
488 hrrCurveFound = true
489 break
490 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200491 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400492 if !hrrCurveFound || keyShares[group] != nil {
493 c.sendAlert(alertHandshakeFailure)
494 return errors.New("tls: received invalid HelloRetryRequest")
495 }
496 curve, ok := curveForCurveID(group)
497 if !ok {
498 return errors.New("tls: Unable to get curve requested in HelloRetryRequest")
499 }
500 publicKey, err := curve.offer(c.config.rand())
501 if err != nil {
502 return err
503 }
504 keyShares[group] = curve
Steven Valdeza833c352016-11-01 13:39:36 -0400505 hello.keyShares = []keyShareEntry{{
David Benjamin3baa6e12016-10-07 21:10:38 -0400506 group: group,
507 keyExchange: publicKey,
Steven Valdeza833c352016-11-01 13:39:36 -0400508 }}
Nick Harperdcfbc672016-07-16 17:47:31 +0200509 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200510
Steven Valdez5440fe02016-07-18 12:40:30 -0400511 if c.config.Bugs.SecondClientHelloMissingKeyShare {
512 hello.hasKeyShares = false
513 }
514
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500515 hello.hasEarlyData = c.config.Bugs.SendEarlyDataOnSecondClientHello
Nick Harperdcfbc672016-07-16 17:47:31 +0200516 hello.raw = nil
517
Steven Valdeza833c352016-11-01 13:39:36 -0400518 if len(hello.pskIdentities) > 0 {
519 generatePSKBinders(hello, pskCipherSuite, session.masterSecret, append(helloBytes, helloRetryRequest.marshal()...), c.config)
520 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200521 secondHelloBytes = hello.marshal()
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500522
523 if c.config.Bugs.InterleaveEarlyData {
524 c.sendFakeEarlyData(4)
525 c.writeRecord(recordTypeHandshake, secondHelloBytes[:16])
526 c.sendFakeEarlyData(4)
527 c.writeRecord(recordTypeHandshake, secondHelloBytes[16:])
528 } else {
529 c.writeRecord(recordTypeHandshake, secondHelloBytes)
530 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200531 c.flushHandshake()
532
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500533 if c.config.Bugs.SendEarlyDataOnSecondClientHello {
534 c.sendFakeEarlyData(4)
535 }
536
Nick Harperdcfbc672016-07-16 17:47:31 +0200537 msg, err = c.readHandshake()
538 if err != nil {
539 return err
540 }
541 }
542
Adam Langley95c29f32014-06-20 12:00:00 -0700543 serverHello, ok := msg.(*serverHelloMsg)
544 if !ok {
545 c.sendAlert(alertUnexpectedMessage)
546 return unexpectedMessageError(serverHello, msg)
547 }
548
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400549 if serverWireVersion != serverHello.vers {
Adam Langley95c29f32014-06-20 12:00:00 -0700550 c.sendAlert(alertProtocolVersion)
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400551 return fmt.Errorf("tls: server sent non-matching version %x vs %x", serverWireVersion, serverHello.vers)
Adam Langley95c29f32014-06-20 12:00:00 -0700552 }
Adam Langley95c29f32014-06-20 12:00:00 -0700553
Nick Harper85f20c22016-07-04 10:11:59 -0700554 // Check for downgrade signals in the server random, per
David Benjamina128a552016-10-13 14:26:33 -0400555 // draft-ietf-tls-tls13-16, section 4.1.3.
Nick Harper85f20c22016-07-04 10:11:59 -0700556 if c.vers <= VersionTLS12 && c.config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400557 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS13) {
Nick Harper85f20c22016-07-04 10:11:59 -0700558 c.sendAlert(alertProtocolVersion)
559 return errors.New("tls: downgrade from TLS 1.3 detected")
560 }
561 }
562 if c.vers <= VersionTLS11 && c.config.maxVersion(c.isDTLS) >= VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400563 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS12) {
Nick Harper85f20c22016-07-04 10:11:59 -0700564 c.sendAlert(alertProtocolVersion)
565 return errors.New("tls: downgrade from TLS 1.2 detected")
566 }
567 }
568
Nick Harper0b3625b2016-07-25 16:16:28 -0700569 suite := mutualCipherSuite(hello.cipherSuites, serverHello.cipherSuite)
Adam Langley95c29f32014-06-20 12:00:00 -0700570 if suite == nil {
571 c.sendAlert(alertHandshakeFailure)
572 return fmt.Errorf("tls: server selected an unsupported cipher suite")
573 }
574
David Benjamin3baa6e12016-10-07 21:10:38 -0400575 if haveHelloRetryRequest && helloRetryRequest.hasSelectedGroup && helloRetryRequest.selectedGroup != serverHello.keyShare.group {
Nick Harperdcfbc672016-07-16 17:47:31 +0200576 c.sendAlert(alertHandshakeFailure)
577 return errors.New("tls: ServerHello parameters did not match HelloRetryRequest")
578 }
579
Adam Langley95c29f32014-06-20 12:00:00 -0700580 hs := &clientHandshakeState{
581 c: c,
582 serverHello: serverHello,
583 hello: hello,
584 suite: suite,
585 finishedHash: newFinishedHash(c.vers, suite),
Nick Harperb41d2e42016-07-01 17:50:32 -0400586 keyShares: keyShares,
Adam Langley95c29f32014-06-20 12:00:00 -0700587 session: session,
588 }
589
David Benjamin83c0bc92014-08-04 01:23:53 -0400590 hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1)
Nick Harperdcfbc672016-07-16 17:47:31 +0200591 if haveHelloRetryRequest {
592 hs.writeServerHash(helloRetryRequest.marshal())
593 hs.writeClientHash(secondHelloBytes)
594 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400595 hs.writeServerHash(hs.serverHello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700596
David Benjamin8d315d72016-07-18 01:03:18 +0200597 if c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -0400598 if err := hs.doTLS13Handshake(); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700599 return err
600 }
601 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400602 if c.config.Bugs.EarlyChangeCipherSpec > 0 {
603 hs.establishKeys()
604 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
605 }
606
607 if hs.serverHello.compressionMethod != compressionNone {
608 c.sendAlert(alertUnexpectedMessage)
609 return errors.New("tls: server selected unsupported compression format")
610 }
611
612 err = hs.processServerExtensions(&serverHello.extensions)
613 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700614 return err
615 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400616
617 isResume, err := hs.processServerHello()
618 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700619 return err
620 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400621
622 if isResume {
623 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
624 if err := hs.establishKeys(); err != nil {
625 return err
626 }
627 }
628 if err := hs.readSessionTicket(); err != nil {
629 return err
630 }
631 if err := hs.readFinished(c.firstFinished[:]); err != nil {
632 return err
633 }
634 if err := hs.sendFinished(nil, isResume); err != nil {
635 return err
636 }
637 } else {
638 if err := hs.doFullHandshake(); err != nil {
639 return err
640 }
641 if err := hs.establishKeys(); err != nil {
642 return err
643 }
644 if err := hs.sendFinished(c.firstFinished[:], isResume); err != nil {
645 return err
646 }
647 // Most retransmits are triggered by a timeout, but the final
648 // leg of the handshake is retransmited upon re-receiving a
649 // Finished.
650 if err := c.simulatePacketLoss(func() {
David Benjamin02edcd02016-07-27 17:40:37 -0400651 c.sendHandshakeSeq--
Nick Harperb41d2e42016-07-01 17:50:32 -0400652 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
653 c.flushHandshake()
654 }); err != nil {
655 return err
656 }
657 if err := hs.readSessionTicket(); err != nil {
658 return err
659 }
660 if err := hs.readFinished(nil); err != nil {
661 return err
662 }
Adam Langley95c29f32014-06-20 12:00:00 -0700663 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400664
665 if sessionCache != nil && hs.session != nil && session != hs.session {
666 if c.config.Bugs.RequireSessionTickets && len(hs.session.sessionTicket) == 0 {
667 return errors.New("tls: new session used session IDs instead of tickets")
668 }
669 sessionCache.Put(cacheKey, hs.session)
David Benjamin83f90402015-01-27 01:09:43 -0500670 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400671
672 c.didResume = isResume
David Benjamin97a0a082016-07-13 17:57:35 -0400673 c.exporterSecret = hs.masterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700674 }
675
Adam Langley95c29f32014-06-20 12:00:00 -0700676 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400677 c.cipherSuite = suite
678 copy(c.clientRandom[:], hs.hello.random)
679 copy(c.serverRandom[:], hs.serverHello.random)
Paul Lietar4fac72e2015-09-09 13:44:55 +0100680
Adam Langley95c29f32014-06-20 12:00:00 -0700681 return nil
682}
683
Nick Harperb41d2e42016-07-01 17:50:32 -0400684func (hs *clientHandshakeState) doTLS13Handshake() error {
685 c := hs.c
686
687 // Once the PRF hash is known, TLS 1.3 does not require a handshake
688 // buffer.
689 hs.finishedHash.discardHandshakeBuffer()
690
691 zeroSecret := hs.finishedHash.zeroSecret()
692
693 // Resolve PSK and compute the early secret.
694 //
695 // TODO(davidben): This will need to be handled slightly earlier once
696 // 0-RTT is implemented.
Steven Valdez803c77a2016-09-06 14:13:43 -0400697 if hs.serverHello.hasPSKIdentity {
Nick Harper0b3625b2016-07-25 16:16:28 -0700698 // We send at most one PSK identity.
699 if hs.session == nil || hs.serverHello.pskIdentity != 0 {
700 c.sendAlert(alertUnknownPSKIdentity)
701 return errors.New("tls: server sent unknown PSK identity")
702 }
David Benjamin2b02f4b2016-11-16 16:11:47 +0900703 sessionCipher := cipherSuiteFromID(hs.session.cipherSuite)
704 if sessionCipher == nil || sessionCipher.hash() != hs.suite.hash() {
Nick Harper0b3625b2016-07-25 16:16:28 -0700705 c.sendAlert(alertHandshakeFailure)
David Benjamin2b02f4b2016-11-16 16:11:47 +0900706 return errors.New("tls: server resumed an invalid session for the cipher suite")
Nick Harper0b3625b2016-07-25 16:16:28 -0700707 }
David Benjamin48891ad2016-12-04 00:02:43 -0500708 hs.finishedHash.addEntropy(hs.session.masterSecret)
Nick Harper0b3625b2016-07-25 16:16:28 -0700709 c.didResume = true
Nick Harperb41d2e42016-07-01 17:50:32 -0400710 } else {
David Benjamin48891ad2016-12-04 00:02:43 -0500711 hs.finishedHash.addEntropy(zeroSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400712 }
713
Steven Valdeza833c352016-11-01 13:39:36 -0400714 if !hs.serverHello.hasKeyShare {
715 c.sendAlert(alertUnsupportedExtension)
716 return errors.New("tls: server omitted KeyShare on resumption.")
717 }
718
Nick Harperb41d2e42016-07-01 17:50:32 -0400719 // Resolve ECDHE and compute the handshake secret.
Steven Valdez803c77a2016-09-06 14:13:43 -0400720 if !c.config.Bugs.MissingKeyShare && !c.config.Bugs.SecondClientHelloMissingKeyShare {
Nick Harperb41d2e42016-07-01 17:50:32 -0400721 curve, ok := hs.keyShares[hs.serverHello.keyShare.group]
722 if !ok {
723 c.sendAlert(alertHandshakeFailure)
724 return errors.New("tls: server selected an unsupported group")
725 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400726 c.curveID = hs.serverHello.keyShare.group
Nick Harperb41d2e42016-07-01 17:50:32 -0400727
David Benjamin48891ad2016-12-04 00:02:43 -0500728 ecdheSecret, err := curve.finish(hs.serverHello.keyShare.keyExchange)
Nick Harperb41d2e42016-07-01 17:50:32 -0400729 if err != nil {
730 return err
731 }
David Benjamin48891ad2016-12-04 00:02:43 -0500732 hs.finishedHash.addEntropy(ecdheSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400733 } else {
David Benjamin48891ad2016-12-04 00:02:43 -0500734 hs.finishedHash.addEntropy(zeroSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400735 }
736
Steven Valdez520e1222017-06-13 12:45:25 -0400737 if c.wireVersion == tls13ExperimentVersion {
738 if err := c.readRecord(recordTypeChangeCipherSpec); err != nil {
739 return err
740 }
741 }
742
Nick Harperf2511f12016-12-06 16:02:31 -0800743 // Derive handshake traffic keys and switch read key to handshake
744 // traffic key.
David Benjamin48891ad2016-12-04 00:02:43 -0500745 clientHandshakeTrafficSecret := hs.finishedHash.deriveSecret(clientHandshakeTrafficLabel)
David Benjamin48891ad2016-12-04 00:02:43 -0500746 serverHandshakeTrafficSecret := hs.finishedHash.deriveSecret(serverHandshakeTrafficLabel)
Steven Valdeza833c352016-11-01 13:39:36 -0400747 c.in.useTrafficSecret(c.vers, hs.suite, serverHandshakeTrafficSecret, serverWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -0400748
749 msg, err := c.readHandshake()
750 if err != nil {
751 return err
752 }
753
754 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
755 if !ok {
756 c.sendAlert(alertUnexpectedMessage)
757 return unexpectedMessageError(encryptedExtensions, msg)
758 }
759 hs.writeServerHash(encryptedExtensions.marshal())
760
761 err = hs.processServerExtensions(&encryptedExtensions.extensions)
762 if err != nil {
763 return err
764 }
765
766 var chainToSend *Certificate
David Benjamin8d343b42016-07-09 14:26:01 -0700767 var certReq *certificateRequestMsg
Steven Valdeza833c352016-11-01 13:39:36 -0400768 if c.didResume {
Nick Harper0b3625b2016-07-25 16:16:28 -0700769 // Copy over authentication from the session.
770 c.peerCertificates = hs.session.serverCertificates
771 c.sctList = hs.session.sctList
772 c.ocspResponse = hs.session.ocspResponse
David Benjamin44b33bc2016-07-01 22:40:23 -0400773 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400774 msg, err := c.readHandshake()
775 if err != nil {
776 return err
777 }
778
David Benjamin8d343b42016-07-09 14:26:01 -0700779 var ok bool
780 certReq, ok = msg.(*certificateRequestMsg)
Nick Harperb41d2e42016-07-01 17:50:32 -0400781 if ok {
David Benjamin8a8349b2016-08-18 02:32:23 -0400782 if len(certReq.requestContext) != 0 {
783 return errors.New("tls: non-empty certificate request context sent in handshake")
784 }
785
David Benjaminb62d2872016-07-18 14:55:02 +0200786 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
787 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
788 }
789
Nick Harperb41d2e42016-07-01 17:50:32 -0400790 hs.writeServerHash(certReq.marshal())
Nick Harperb41d2e42016-07-01 17:50:32 -0400791
792 chainToSend, err = selectClientCertificate(c, certReq)
793 if err != nil {
794 return err
795 }
796
797 msg, err = c.readHandshake()
798 if err != nil {
799 return err
800 }
801 }
802
803 certMsg, ok := msg.(*certificateMsg)
804 if !ok {
805 c.sendAlert(alertUnexpectedMessage)
806 return unexpectedMessageError(certMsg, msg)
807 }
808 hs.writeServerHash(certMsg.marshal())
809
David Benjamin53210cb2016-11-16 09:01:48 +0900810 // Check for unsolicited extensions.
811 for i, cert := range certMsg.certificates {
812 if c.config.Bugs.NoOCSPStapling && cert.ocspResponse != nil {
813 c.sendAlert(alertUnsupportedExtension)
814 return errors.New("tls: unexpected OCSP response in the server certificate")
815 }
816 if c.config.Bugs.NoSignedCertificateTimestamps && cert.sctList != nil {
817 c.sendAlert(alertUnsupportedExtension)
818 return errors.New("tls: unexpected SCT list in the server certificate")
819 }
820 if i > 0 && c.config.Bugs.ExpectNoExtensionsOnIntermediate && (cert.ocspResponse != nil || cert.sctList != nil) {
821 c.sendAlert(alertUnsupportedExtension)
822 return errors.New("tls: unexpected extensions in the server certificate")
823 }
824 }
825
Nick Harperb41d2e42016-07-01 17:50:32 -0400826 if err := hs.verifyCertificates(certMsg); err != nil {
827 return err
828 }
829 leaf := c.peerCertificates[0]
Steven Valdeza833c352016-11-01 13:39:36 -0400830 c.ocspResponse = certMsg.certificates[0].ocspResponse
831 c.sctList = certMsg.certificates[0].sctList
832
Nick Harperb41d2e42016-07-01 17:50:32 -0400833 msg, err = c.readHandshake()
834 if err != nil {
835 return err
836 }
837 certVerifyMsg, ok := msg.(*certificateVerifyMsg)
838 if !ok {
839 c.sendAlert(alertUnexpectedMessage)
840 return unexpectedMessageError(certVerifyMsg, msg)
841 }
842
David Benjaminf74ec792016-07-13 21:18:49 -0400843 c.peerSignatureAlgorithm = certVerifyMsg.signatureAlgorithm
Nick Harperb41d2e42016-07-01 17:50:32 -0400844 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
David Benjamind768c5d2017-03-28 18:28:44 -0500845 err = verifyMessage(c.vers, getCertificatePublicKey(leaf), c.config, certVerifyMsg.signatureAlgorithm, input, certVerifyMsg.signature)
Nick Harperb41d2e42016-07-01 17:50:32 -0400846 if err != nil {
847 return err
848 }
849
850 hs.writeServerHash(certVerifyMsg.marshal())
851 }
852
853 msg, err = c.readHandshake()
854 if err != nil {
855 return err
856 }
857 serverFinished, ok := msg.(*finishedMsg)
858 if !ok {
859 c.sendAlert(alertUnexpectedMessage)
860 return unexpectedMessageError(serverFinished, msg)
861 }
862
Steven Valdezc4aa7272016-10-03 12:25:56 -0400863 verify := hs.finishedHash.serverSum(serverHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400864 if len(verify) != len(serverFinished.verifyData) ||
865 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
866 c.sendAlert(alertHandshakeFailure)
867 return errors.New("tls: server's Finished message was incorrect")
868 }
869
870 hs.writeServerHash(serverFinished.marshal())
871
872 // The various secrets do not incorporate the client's final leg, so
873 // derive them now before updating the handshake context.
David Benjamin48891ad2016-12-04 00:02:43 -0500874 hs.finishedHash.addEntropy(zeroSecret)
875 clientTrafficSecret := hs.finishedHash.deriveSecret(clientApplicationTrafficLabel)
876 serverTrafficSecret := hs.finishedHash.deriveSecret(serverApplicationTrafficLabel)
David Benjamincdb6fe92017-02-07 16:06:48 -0500877 c.exporterSecret = hs.finishedHash.deriveSecret(exporterLabel)
878
879 // Switch to application data keys on read. In particular, any alerts
880 // from the client certificate are read over these keys.
Nick Harper7cd0a972016-12-02 11:08:40 -0800881 c.in.useTrafficSecret(c.vers, hs.suite, serverTrafficSecret, serverWrite)
882
883 // If we're expecting 0.5-RTT messages from the server, read them
884 // now.
David Benjamin794cc592017-03-25 22:24:23 -0500885 if encryptedExtensions.extensions.hasEarlyData {
886 // BoringSSL will always send two tickets half-RTT when
887 // negotiating 0-RTT.
888 for i := 0; i < shimConfig.HalfRTTTickets; i++ {
889 msg, err := c.readHandshake()
890 if err != nil {
891 return fmt.Errorf("tls: error reading half-RTT ticket: %s", err)
892 }
893 newSessionTicket, ok := msg.(*newSessionTicketMsg)
894 if !ok {
895 return errors.New("tls: expected half-RTT ticket")
896 }
897 if err := c.processTLS13NewSessionTicket(newSessionTicket, hs.suite); err != nil {
898 return err
899 }
Nick Harper7cd0a972016-12-02 11:08:40 -0800900 }
David Benjamin794cc592017-03-25 22:24:23 -0500901 for _, expectedMsg := range c.config.Bugs.ExpectHalfRTTData {
902 if err := c.readRecord(recordTypeApplicationData); err != nil {
903 return err
904 }
905 if !bytes.Equal(c.input.data[c.input.off:], expectedMsg) {
906 return errors.New("ExpectHalfRTTData: did not get expected message")
907 }
908 c.in.freeBlock(c.input)
909 c.input = nil
Nick Harper7cd0a972016-12-02 11:08:40 -0800910 }
Nick Harper7cd0a972016-12-02 11:08:40 -0800911 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400912
Nick Harperf2511f12016-12-06 16:02:31 -0800913 // Send EndOfEarlyData and then switch write key to handshake
914 // traffic key.
David Benjamin32c89272017-03-26 13:54:21 -0500915 if c.out.cipher != nil && !c.config.Bugs.SkipEndOfEarlyData {
Steven Valdez681eb6a2016-12-19 13:19:29 -0500916 if c.config.Bugs.SendStrayEarlyHandshake {
917 helloRequest := new(helloRequestMsg)
918 c.writeRecord(recordTypeHandshake, helloRequest.marshal())
919 }
Nick Harperf2511f12016-12-06 16:02:31 -0800920 c.sendAlert(alertEndOfEarlyData)
921 }
Steven Valdez520e1222017-06-13 12:45:25 -0400922
923 if c.wireVersion == tls13ExperimentVersion {
924 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
925 }
926
Nick Harperf2511f12016-12-06 16:02:31 -0800927 c.out.useTrafficSecret(c.vers, hs.suite, clientHandshakeTrafficSecret, clientWrite)
928
Steven Valdez0ee2e112016-07-15 06:51:15 -0400929 if certReq != nil && !c.config.Bugs.SkipClientCertificate {
David Benjamin8d343b42016-07-09 14:26:01 -0700930 certMsg := &certificateMsg{
931 hasRequestContext: true,
932 requestContext: certReq.requestContext,
933 }
934 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -0400935 for _, certData := range chainToSend.Certificate {
936 certMsg.certificates = append(certMsg.certificates, certificateEntry{
937 data: certData,
938 extraExtension: c.config.Bugs.SendExtensionOnCertificate,
939 })
940 }
David Benjamin8d343b42016-07-09 14:26:01 -0700941 }
942 hs.writeClientHash(certMsg.marshal())
943 c.writeRecord(recordTypeHandshake, certMsg.marshal())
944
945 if chainToSend != nil {
946 certVerify := &certificateVerifyMsg{
947 hasSignatureAlgorithm: true,
948 }
949
950 // Determine the hash to sign.
951 privKey := chainToSend.PrivateKey
952
953 var err error
954 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
955 if err != nil {
956 c.sendAlert(alertInternalError)
957 return err
958 }
959
960 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
961 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
962 if err != nil {
963 c.sendAlert(alertInternalError)
964 return err
965 }
Steven Valdez0ee2e112016-07-15 06:51:15 -0400966 if c.config.Bugs.SendSignatureAlgorithm != 0 {
967 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
968 }
David Benjamin8d343b42016-07-09 14:26:01 -0700969
970 hs.writeClientHash(certVerify.marshal())
971 c.writeRecord(recordTypeHandshake, certVerify.marshal())
972 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400973 }
974
Nick Harper60a85cb2016-09-23 16:25:11 -0700975 if encryptedExtensions.extensions.channelIDRequested {
976 channelIDHash := crypto.SHA256.New()
977 channelIDHash.Write(hs.finishedHash.certificateVerifyInput(channelIDContextTLS13))
978 channelIDMsgBytes, err := hs.writeChannelIDMessage(channelIDHash.Sum(nil))
979 if err != nil {
980 return err
981 }
982 hs.writeClientHash(channelIDMsgBytes)
983 c.writeRecord(recordTypeHandshake, channelIDMsgBytes)
984 }
985
Nick Harperb41d2e42016-07-01 17:50:32 -0400986 // Send a client Finished message.
987 finished := new(finishedMsg)
Steven Valdezc4aa7272016-10-03 12:25:56 -0400988 finished.verifyData = hs.finishedHash.clientSum(clientHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400989 if c.config.Bugs.BadFinished {
990 finished.verifyData[0]++
991 }
David Benjamin97a0a082016-07-13 17:57:35 -0400992 hs.writeClientHash(finished.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400993 if c.config.Bugs.PartialClientFinishedWithClientHello {
994 // The first byte has already been sent.
995 c.writeRecord(recordTypeHandshake, finished.marshal()[1:])
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500996 } else if c.config.Bugs.InterleaveEarlyData {
997 finishedBytes := finished.marshal()
998 c.sendFakeEarlyData(4)
999 c.writeRecord(recordTypeHandshake, finishedBytes[:1])
1000 c.sendFakeEarlyData(4)
1001 c.writeRecord(recordTypeHandshake, finishedBytes[1:])
David Benjamin7964b182016-07-14 23:36:30 -04001002 } else {
1003 c.writeRecord(recordTypeHandshake, finished.marshal())
1004 }
David Benjamin02edcd02016-07-27 17:40:37 -04001005 if c.config.Bugs.SendExtraFinished {
1006 c.writeRecord(recordTypeHandshake, finished.marshal())
1007 }
David Benjaminee51a222016-07-07 18:34:12 -07001008 c.flushHandshake()
Nick Harperb41d2e42016-07-01 17:50:32 -04001009
1010 // Switch to application data keys.
Steven Valdeza833c352016-11-01 13:39:36 -04001011 c.out.useTrafficSecret(c.vers, hs.suite, clientTrafficSecret, clientWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -04001012
David Benjamin48891ad2016-12-04 00:02:43 -05001013 c.resumptionSecret = hs.finishedHash.deriveSecret(resumptionLabel)
Nick Harperb41d2e42016-07-01 17:50:32 -04001014 return nil
1015}
1016
Adam Langley95c29f32014-06-20 12:00:00 -07001017func (hs *clientHandshakeState) doFullHandshake() error {
1018 c := hs.c
1019
David Benjamin48cae082014-10-27 01:06:24 -04001020 var leaf *x509.Certificate
1021 if hs.suite.flags&suitePSK == 0 {
1022 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001023 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -07001024 return err
1025 }
Adam Langley95c29f32014-06-20 12:00:00 -07001026
David Benjamin48cae082014-10-27 01:06:24 -04001027 certMsg, ok := msg.(*certificateMsg)
David Benjamin75051442016-07-01 18:58:51 -04001028 if !ok {
David Benjamin48cae082014-10-27 01:06:24 -04001029 c.sendAlert(alertUnexpectedMessage)
1030 return unexpectedMessageError(certMsg, msg)
1031 }
1032 hs.writeServerHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001033
David Benjamin75051442016-07-01 18:58:51 -04001034 if err := hs.verifyCertificates(certMsg); err != nil {
1035 return err
David Benjamin48cae082014-10-27 01:06:24 -04001036 }
David Benjamin75051442016-07-01 18:58:51 -04001037 leaf = c.peerCertificates[0]
David Benjamin48cae082014-10-27 01:06:24 -04001038 }
Adam Langley95c29f32014-06-20 12:00:00 -07001039
Nick Harperb3d51be2016-07-01 11:43:18 -04001040 if hs.serverHello.extensions.ocspStapling {
David Benjamin48cae082014-10-27 01:06:24 -04001041 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001042 if err != nil {
1043 return err
1044 }
1045 cs, ok := msg.(*certificateStatusMsg)
1046 if !ok {
1047 c.sendAlert(alertUnexpectedMessage)
1048 return unexpectedMessageError(cs, msg)
1049 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001050 hs.writeServerHash(cs.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001051
1052 if cs.statusType == statusTypeOCSP {
1053 c.ocspResponse = cs.response
1054 }
1055 }
1056
David Benjamin48cae082014-10-27 01:06:24 -04001057 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001058 if err != nil {
1059 return err
1060 }
1061
1062 keyAgreement := hs.suite.ka(c.vers)
1063
1064 skx, ok := msg.(*serverKeyExchangeMsg)
1065 if ok {
David Benjamin83c0bc92014-08-04 01:23:53 -04001066 hs.writeServerHash(skx.marshal())
David Benjamin48cae082014-10-27 01:06:24 -04001067 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx)
Adam Langley95c29f32014-06-20 12:00:00 -07001068 if err != nil {
1069 c.sendAlert(alertUnexpectedMessage)
1070 return err
1071 }
Steven Valdez5440fe02016-07-18 12:40:30 -04001072 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1073 c.curveID = ecdhe.curveID
1074 }
Adam Langley95c29f32014-06-20 12:00:00 -07001075
Nick Harper60edffd2016-06-21 15:19:24 -07001076 c.peerSignatureAlgorithm = keyAgreement.peerSignatureAlgorithm()
1077
Adam Langley95c29f32014-06-20 12:00:00 -07001078 msg, err = c.readHandshake()
1079 if err != nil {
1080 return err
1081 }
1082 }
1083
1084 var chainToSend *Certificate
1085 var certRequested bool
1086 certReq, ok := msg.(*certificateRequestMsg)
1087 if ok {
1088 certRequested = true
David Benjamin7a41d372016-07-09 11:21:54 -07001089 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
1090 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
1091 }
Adam Langley95c29f32014-06-20 12:00:00 -07001092
David Benjamin83c0bc92014-08-04 01:23:53 -04001093 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001094
David Benjamina6f82632016-07-01 18:44:02 -04001095 chainToSend, err = selectClientCertificate(c, certReq)
1096 if err != nil {
1097 return err
Adam Langley95c29f32014-06-20 12:00:00 -07001098 }
1099
1100 msg, err = c.readHandshake()
1101 if err != nil {
1102 return err
1103 }
1104 }
1105
1106 shd, ok := msg.(*serverHelloDoneMsg)
1107 if !ok {
1108 c.sendAlert(alertUnexpectedMessage)
1109 return unexpectedMessageError(shd, msg)
1110 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001111 hs.writeServerHash(shd.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001112
1113 // If the server requested a certificate then we have to send a
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001114 // Certificate message in TLS, even if it's empty because we don't have
1115 // a certificate to send. In SSL 3.0, skip the message and send a
1116 // no_certificate warning alert.
Adam Langley95c29f32014-06-20 12:00:00 -07001117 if certRequested {
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001118 if c.vers == VersionSSL30 && chainToSend == nil {
David Benjamin053fee92017-01-02 08:30:36 -05001119 c.sendAlert(alertNoCertificate)
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001120 } else if !c.config.Bugs.SkipClientCertificate {
1121 certMsg := new(certificateMsg)
1122 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -04001123 for _, certData := range chainToSend.Certificate {
1124 certMsg.certificates = append(certMsg.certificates, certificateEntry{
1125 data: certData,
1126 })
1127 }
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001128 }
1129 hs.writeClientHash(certMsg.marshal())
1130 c.writeRecord(recordTypeHandshake, certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001131 }
Adam Langley95c29f32014-06-20 12:00:00 -07001132 }
1133
David Benjamin48cae082014-10-27 01:06:24 -04001134 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf)
Adam Langley95c29f32014-06-20 12:00:00 -07001135 if err != nil {
1136 c.sendAlert(alertInternalError)
1137 return err
1138 }
1139 if ckx != nil {
David Benjaminf3ec83d2014-07-21 22:42:34 -04001140 if c.config.Bugs.EarlyChangeCipherSpec < 2 {
David Benjamin83c0bc92014-08-04 01:23:53 -04001141 hs.writeClientHash(ckx.marshal())
David Benjaminf3ec83d2014-07-21 22:42:34 -04001142 }
Adam Langley95c29f32014-06-20 12:00:00 -07001143 c.writeRecord(recordTypeHandshake, ckx.marshal())
1144 }
1145
Nick Harperb3d51be2016-07-01 11:43:18 -04001146 if hs.serverHello.extensions.extendedMasterSecret && c.vers >= VersionTLS10 {
Adam Langley75712922014-10-10 16:23:43 -07001147 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1148 c.extendedMasterSecret = true
1149 } else {
1150 if c.config.Bugs.RequireExtendedMasterSecret {
1151 return errors.New("tls: extended master secret required but not supported by peer")
1152 }
1153 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
1154 }
David Benjamine098ec22014-08-27 23:13:20 -04001155
Adam Langley95c29f32014-06-20 12:00:00 -07001156 if chainToSend != nil {
Adam Langley95c29f32014-06-20 12:00:00 -07001157 certVerify := &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001158 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001159 }
1160
David Benjamin72dc7832015-03-16 17:49:43 -04001161 // Determine the hash to sign.
Nick Harper60edffd2016-06-21 15:19:24 -07001162 privKey := c.config.Certificates[0].PrivateKey
David Benjamin72dc7832015-03-16 17:49:43 -04001163
Nick Harper60edffd2016-06-21 15:19:24 -07001164 if certVerify.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001165 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
Nick Harper60edffd2016-06-21 15:19:24 -07001166 if err != nil {
1167 c.sendAlert(alertInternalError)
1168 return err
Adam Langley95c29f32014-06-20 12:00:00 -07001169 }
Nick Harper60edffd2016-06-21 15:19:24 -07001170 }
1171
1172 if c.vers > VersionSSL30 {
David Benjamin5208fd42016-07-13 21:43:25 -04001173 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, hs.finishedHash.buffer)
David Benjamina95e9f32016-07-08 16:28:04 -07001174 if err == nil && c.config.Bugs.SendSignatureAlgorithm != 0 {
1175 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
1176 }
Nick Harper60edffd2016-06-21 15:19:24 -07001177 } else {
1178 // SSL 3.0's client certificate construction is
1179 // incompatible with signatureAlgorithm.
1180 rsaKey, ok := privKey.(*rsa.PrivateKey)
1181 if !ok {
1182 err = errors.New("unsupported signature type for client certificate")
1183 } else {
1184 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
David Benjamin5208fd42016-07-13 21:43:25 -04001185 if c.config.Bugs.InvalidSignature {
Nick Harper60edffd2016-06-21 15:19:24 -07001186 digest[0] ^= 0x80
1187 }
1188 certVerify.signature, err = rsa.SignPKCS1v15(c.config.rand(), rsaKey, crypto.MD5SHA1, digest)
1189 }
Adam Langley95c29f32014-06-20 12:00:00 -07001190 }
1191 if err != nil {
1192 c.sendAlert(alertInternalError)
1193 return errors.New("tls: failed to sign handshake with client certificate: " + err.Error())
1194 }
Adam Langley95c29f32014-06-20 12:00:00 -07001195
David Benjamin83c0bc92014-08-04 01:23:53 -04001196 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001197 c.writeRecord(recordTypeHandshake, certVerify.marshal())
1198 }
David Benjamin82261be2016-07-07 14:32:50 -07001199 // flushHandshake will be called in sendFinished.
Adam Langley95c29f32014-06-20 12:00:00 -07001200
David Benjamine098ec22014-08-27 23:13:20 -04001201 hs.finishedHash.discardHandshakeBuffer()
1202
Adam Langley95c29f32014-06-20 12:00:00 -07001203 return nil
1204}
1205
David Benjamin75051442016-07-01 18:58:51 -04001206func (hs *clientHandshakeState) verifyCertificates(certMsg *certificateMsg) error {
1207 c := hs.c
1208
1209 if len(certMsg.certificates) == 0 {
1210 c.sendAlert(alertIllegalParameter)
1211 return errors.New("tls: no certificates sent")
1212 }
1213
1214 certs := make([]*x509.Certificate, len(certMsg.certificates))
Steven Valdeza833c352016-11-01 13:39:36 -04001215 for i, certEntry := range certMsg.certificates {
1216 cert, err := x509.ParseCertificate(certEntry.data)
David Benjamin75051442016-07-01 18:58:51 -04001217 if err != nil {
1218 c.sendAlert(alertBadCertificate)
1219 return errors.New("tls: failed to parse certificate from server: " + err.Error())
1220 }
1221 certs[i] = cert
1222 }
1223
1224 if !c.config.InsecureSkipVerify {
1225 opts := x509.VerifyOptions{
1226 Roots: c.config.RootCAs,
1227 CurrentTime: c.config.time(),
1228 DNSName: c.config.ServerName,
1229 Intermediates: x509.NewCertPool(),
1230 }
1231
1232 for i, cert := range certs {
1233 if i == 0 {
1234 continue
1235 }
1236 opts.Intermediates.AddCert(cert)
1237 }
1238 var err error
1239 c.verifiedChains, err = certs[0].Verify(opts)
1240 if err != nil {
1241 c.sendAlert(alertBadCertificate)
1242 return err
1243 }
1244 }
1245
David Benjamind768c5d2017-03-28 18:28:44 -05001246 publicKey := getCertificatePublicKey(certs[0])
1247 switch publicKey.(type) {
1248 case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
David Benjamin75051442016-07-01 18:58:51 -04001249 break
1250 default:
1251 c.sendAlert(alertUnsupportedCertificate)
David Benjamind768c5d2017-03-28 18:28:44 -05001252 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", publicKey)
David Benjamin75051442016-07-01 18:58:51 -04001253 }
1254
1255 c.peerCertificates = certs
1256 return nil
1257}
1258
Adam Langley95c29f32014-06-20 12:00:00 -07001259func (hs *clientHandshakeState) establishKeys() error {
1260 c := hs.c
1261
1262 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001263 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 -07001264 var clientCipher, serverCipher interface{}
1265 var clientHash, serverHash macFunction
1266 if hs.suite.cipher != nil {
1267 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
1268 clientHash = hs.suite.mac(c.vers, clientMAC)
1269 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
1270 serverHash = hs.suite.mac(c.vers, serverMAC)
1271 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001272 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1273 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001274 }
1275
1276 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
1277 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
1278 return nil
1279}
1280
David Benjamin75101402016-07-01 13:40:23 -04001281func (hs *clientHandshakeState) processServerExtensions(serverExtensions *serverExtensions) error {
1282 c := hs.c
1283
David Benjamin8d315d72016-07-18 01:03:18 +02001284 if c.vers < VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001285 if c.config.Bugs.RequireRenegotiationInfo && serverExtensions.secureRenegotiation == nil {
1286 return errors.New("tls: renegotiation extension missing")
1287 }
David Benjamin75101402016-07-01 13:40:23 -04001288
Nick Harperb41d2e42016-07-01 17:50:32 -04001289 if len(c.clientVerify) > 0 && !c.noRenegotiationInfo() {
1290 var expectedRenegInfo []byte
1291 expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...)
1292 expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...)
1293 if !bytes.Equal(serverExtensions.secureRenegotiation, expectedRenegInfo) {
1294 c.sendAlert(alertHandshakeFailure)
1295 return fmt.Errorf("tls: renegotiation mismatch")
1296 }
David Benjamin75101402016-07-01 13:40:23 -04001297 }
David Benjamincea0ab42016-07-14 12:33:14 -04001298 } else if serverExtensions.secureRenegotiation != nil {
1299 return errors.New("tls: renegotiation info sent in TLS 1.3")
David Benjamin75101402016-07-01 13:40:23 -04001300 }
1301
1302 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
1303 if serverExtensions.customExtension != *expected {
1304 return fmt.Errorf("tls: bad custom extension contents %q", serverExtensions.customExtension)
1305 }
1306 }
1307
1308 clientDidNPN := hs.hello.nextProtoNeg
1309 clientDidALPN := len(hs.hello.alpnProtocols) > 0
1310 serverHasNPN := serverExtensions.nextProtoNeg
1311 serverHasALPN := len(serverExtensions.alpnProtocol) > 0
1312
1313 if !clientDidNPN && serverHasNPN {
1314 c.sendAlert(alertHandshakeFailure)
1315 return errors.New("server advertised unrequested NPN extension")
1316 }
1317
1318 if !clientDidALPN && serverHasALPN {
1319 c.sendAlert(alertHandshakeFailure)
1320 return errors.New("server advertised unrequested ALPN extension")
1321 }
1322
1323 if serverHasNPN && serverHasALPN {
1324 c.sendAlert(alertHandshakeFailure)
1325 return errors.New("server advertised both NPN and ALPN extensions")
1326 }
1327
1328 if serverHasALPN {
1329 c.clientProtocol = serverExtensions.alpnProtocol
1330 c.clientProtocolFallback = false
1331 c.usedALPN = true
1332 }
1333
David Benjamin8d315d72016-07-18 01:03:18 +02001334 if serverHasNPN && c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001335 c.sendAlert(alertHandshakeFailure)
1336 return errors.New("server advertised NPN over TLS 1.3")
1337 }
1338
David Benjamin75101402016-07-01 13:40:23 -04001339 if !hs.hello.channelIDSupported && serverExtensions.channelIDRequested {
1340 c.sendAlert(alertHandshakeFailure)
1341 return errors.New("server advertised unrequested Channel ID extension")
1342 }
1343
David Benjamin8d315d72016-07-18 01:03:18 +02001344 if serverExtensions.extendedMasterSecret && c.vers >= VersionTLS13 {
David Benjamine9077652016-07-13 21:02:08 -04001345 return errors.New("tls: server advertised extended master secret over TLS 1.3")
1346 }
1347
David Benjamin8d315d72016-07-18 01:03:18 +02001348 if serverExtensions.ticketSupported && c.vers >= VersionTLS13 {
Steven Valdez143e8b32016-07-11 13:19:03 -04001349 return errors.New("tls: server advertised ticket extension over TLS 1.3")
1350 }
1351
Steven Valdeza833c352016-11-01 13:39:36 -04001352 if serverExtensions.ocspStapling && c.vers >= VersionTLS13 {
1353 return errors.New("tls: server advertised OCSP in ServerHello over TLS 1.3")
1354 }
1355
David Benjamin53210cb2016-11-16 09:01:48 +09001356 if serverExtensions.ocspStapling && c.config.Bugs.NoOCSPStapling {
1357 return errors.New("tls: server advertised unrequested OCSP extension")
1358 }
1359
Steven Valdeza833c352016-11-01 13:39:36 -04001360 if len(serverExtensions.sctList) > 0 && c.vers >= VersionTLS13 {
1361 return errors.New("tls: server advertised SCTs in ServerHello over TLS 1.3")
1362 }
1363
David Benjamin53210cb2016-11-16 09:01:48 +09001364 if len(serverExtensions.sctList) > 0 && c.config.Bugs.NoSignedCertificateTimestamps {
1365 return errors.New("tls: server advertised unrequested SCTs")
1366 }
1367
David Benjamin75101402016-07-01 13:40:23 -04001368 if serverExtensions.srtpProtectionProfile != 0 {
1369 if serverExtensions.srtpMasterKeyIdentifier != "" {
1370 return errors.New("tls: server selected SRTP MKI value")
1371 }
1372
1373 found := false
1374 for _, p := range c.config.SRTPProtectionProfiles {
1375 if p == serverExtensions.srtpProtectionProfile {
1376 found = true
1377 break
1378 }
1379 }
1380 if !found {
1381 return errors.New("tls: server advertised unsupported SRTP profile")
1382 }
1383
1384 c.srtpProtectionProfile = serverExtensions.srtpProtectionProfile
1385 }
1386
Steven Valdez2d850622017-01-11 11:34:52 -05001387 if c.vers >= VersionTLS13 && c.didResume {
1388 if c.config.Bugs.ExpectEarlyDataAccepted && !serverExtensions.hasEarlyData {
1389 c.sendAlert(alertHandshakeFailure)
1390 return errors.New("tls: server did not accept early data when expected")
1391 }
1392
1393 if !c.config.Bugs.ExpectEarlyDataAccepted && serverExtensions.hasEarlyData {
1394 c.sendAlert(alertHandshakeFailure)
1395 return errors.New("tls: server accepted early data when not expected")
1396 }
1397 }
1398
David Benjamin75101402016-07-01 13:40:23 -04001399 return nil
1400}
1401
Adam Langley95c29f32014-06-20 12:00:00 -07001402func (hs *clientHandshakeState) serverResumedSession() bool {
1403 // If the server responded with the same sessionId then it means the
1404 // sessionTicket is being used to resume a TLS session.
David Benjamind4c349b2017-02-09 14:07:17 -05001405 //
1406 // Note that, if hs.hello.sessionId is a non-nil empty array, this will
1407 // accept an empty session ID from the server as resumption. See
1408 // EmptyTicketSessionID.
Adam Langley95c29f32014-06-20 12:00:00 -07001409 return hs.session != nil && hs.hello.sessionId != nil &&
1410 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
1411}
1412
1413func (hs *clientHandshakeState) processServerHello() (bool, error) {
1414 c := hs.c
1415
Adam Langley95c29f32014-06-20 12:00:00 -07001416 if hs.serverResumedSession() {
David Benjamin4b27d9f2015-05-12 22:42:52 -04001417 // For test purposes, assert that the server never accepts the
1418 // resumption offer on renegotiation.
1419 if c.cipherSuite != nil && c.config.Bugs.FailIfResumeOnRenego {
1420 return false, errors.New("tls: server resumed session on renegotiation")
1421 }
1422
Nick Harperb3d51be2016-07-01 11:43:18 -04001423 if hs.serverHello.extensions.sctList != nil {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001424 return false, errors.New("tls: server sent SCT extension on session resumption")
1425 }
1426
Nick Harperb3d51be2016-07-01 11:43:18 -04001427 if hs.serverHello.extensions.ocspStapling {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001428 return false, errors.New("tls: server sent OCSP extension on session resumption")
1429 }
1430
Adam Langley95c29f32014-06-20 12:00:00 -07001431 // Restore masterSecret and peerCerts from previous state
1432 hs.masterSecret = hs.session.masterSecret
1433 c.peerCertificates = hs.session.serverCertificates
Adam Langley75712922014-10-10 16:23:43 -07001434 c.extendedMasterSecret = hs.session.extendedMasterSecret
Paul Lietar62be8ac2015-09-16 10:03:30 +01001435 c.sctList = hs.session.sctList
1436 c.ocspResponse = hs.session.ocspResponse
David Benjamine098ec22014-08-27 23:13:20 -04001437 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001438 return true, nil
1439 }
Paul Lietar62be8ac2015-09-16 10:03:30 +01001440
Nick Harperb3d51be2016-07-01 11:43:18 -04001441 if hs.serverHello.extensions.sctList != nil {
1442 c.sctList = hs.serverHello.extensions.sctList
Paul Lietar62be8ac2015-09-16 10:03:30 +01001443 }
1444
Adam Langley95c29f32014-06-20 12:00:00 -07001445 return false, nil
1446}
1447
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001448func (hs *clientHandshakeState) readFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001449 c := hs.c
1450
1451 c.readRecord(recordTypeChangeCipherSpec)
1452 if err := c.in.error(); err != nil {
1453 return err
1454 }
1455
1456 msg, err := c.readHandshake()
1457 if err != nil {
1458 return err
1459 }
1460 serverFinished, ok := msg.(*finishedMsg)
1461 if !ok {
1462 c.sendAlert(alertUnexpectedMessage)
1463 return unexpectedMessageError(serverFinished, msg)
1464 }
1465
David Benjaminf3ec83d2014-07-21 22:42:34 -04001466 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
1467 verify := hs.finishedHash.serverSum(hs.masterSecret)
1468 if len(verify) != len(serverFinished.verifyData) ||
1469 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
1470 c.sendAlert(alertHandshakeFailure)
1471 return errors.New("tls: server's Finished message was incorrect")
1472 }
Adam Langley95c29f32014-06-20 12:00:00 -07001473 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001474 c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001475 copy(out, serverFinished.verifyData)
David Benjamin83c0bc92014-08-04 01:23:53 -04001476 hs.writeServerHash(serverFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001477 return nil
1478}
1479
1480func (hs *clientHandshakeState) readSessionTicket() error {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001481 c := hs.c
1482
1483 // Create a session with no server identifier. Either a
1484 // session ID or session ticket will be attached.
1485 session := &ClientSessionState{
1486 vers: c.vers,
1487 cipherSuite: hs.suite.id,
1488 masterSecret: hs.masterSecret,
Nick Harperc9846112016-10-17 15:05:35 -07001489 handshakeHash: hs.finishedHash.Sum(),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001490 serverCertificates: c.peerCertificates,
Paul Lietar62be8ac2015-09-16 10:03:30 +01001491 sctList: c.sctList,
1492 ocspResponse: c.ocspResponse,
Nick Harper0b3625b2016-07-25 16:16:28 -07001493 ticketExpiration: c.config.time().Add(time.Duration(7 * 24 * time.Hour)),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001494 }
1495
Nick Harperb3d51be2016-07-01 11:43:18 -04001496 if !hs.serverHello.extensions.ticketSupported {
David Benjamind98452d2015-06-16 14:16:23 -04001497 if c.config.Bugs.ExpectNewTicket {
1498 return errors.New("tls: expected new ticket")
1499 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001500 if hs.session == nil && len(hs.serverHello.sessionId) > 0 {
1501 session.sessionId = hs.serverHello.sessionId
1502 hs.session = session
1503 }
Adam Langley95c29f32014-06-20 12:00:00 -07001504 return nil
1505 }
1506
David Benjaminc7ce9772015-10-09 19:32:41 -04001507 if c.vers == VersionSSL30 {
1508 return errors.New("tls: negotiated session tickets in SSL 3.0")
1509 }
1510
Adam Langley95c29f32014-06-20 12:00:00 -07001511 msg, err := c.readHandshake()
1512 if err != nil {
1513 return err
1514 }
1515 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
1516 if !ok {
1517 c.sendAlert(alertUnexpectedMessage)
1518 return unexpectedMessageError(sessionTicketMsg, msg)
1519 }
Adam Langley95c29f32014-06-20 12:00:00 -07001520
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001521 session.sessionTicket = sessionTicketMsg.ticket
1522 hs.session = session
Adam Langley95c29f32014-06-20 12:00:00 -07001523
David Benjamind30a9902014-08-24 01:44:23 -04001524 hs.writeServerHash(sessionTicketMsg.marshal())
1525
Adam Langley95c29f32014-06-20 12:00:00 -07001526 return nil
1527}
1528
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001529func (hs *clientHandshakeState) sendFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001530 c := hs.c
1531
David Benjamin0b8d5da2016-07-15 00:39:56 -04001532 var postCCSMsgs [][]byte
David Benjamin83c0bc92014-08-04 01:23:53 -04001533 seqno := hs.c.sendHandshakeSeq
Nick Harperb3d51be2016-07-01 11:43:18 -04001534 if hs.serverHello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001535 nextProto := new(nextProtoMsg)
Nick Harperb3d51be2016-07-01 11:43:18 -04001536 proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.extensions.nextProtos)
Adam Langley95c29f32014-06-20 12:00:00 -07001537 nextProto.proto = proto
1538 c.clientProtocol = proto
1539 c.clientProtocolFallback = fallback
1540
David Benjamin86271ee2014-07-21 16:14:03 -04001541 nextProtoBytes := nextProto.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -04001542 hs.writeHash(nextProtoBytes, seqno)
1543 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001544 postCCSMsgs = append(postCCSMsgs, nextProtoBytes)
Adam Langley95c29f32014-06-20 12:00:00 -07001545 }
1546
Nick Harperb3d51be2016-07-01 11:43:18 -04001547 if hs.serverHello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001548 var resumeHash []byte
1549 if isResume {
1550 resumeHash = hs.session.handshakeHash
1551 }
Nick Harper60a85cb2016-09-23 16:25:11 -07001552 channelIDMsgBytes, err := hs.writeChannelIDMessage(hs.finishedHash.hashForChannelID(resumeHash))
David Benjamind30a9902014-08-24 01:44:23 -04001553 if err != nil {
1554 return err
1555 }
David Benjamin24599a82016-06-30 18:56:53 -04001556 hs.writeHash(channelIDMsgBytes, seqno)
David Benjamind30a9902014-08-24 01:44:23 -04001557 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001558 postCCSMsgs = append(postCCSMsgs, channelIDMsgBytes)
David Benjamind30a9902014-08-24 01:44:23 -04001559 }
1560
Adam Langley95c29f32014-06-20 12:00:00 -07001561 finished := new(finishedMsg)
David Benjaminf3ec83d2014-07-21 22:42:34 -04001562 if c.config.Bugs.EarlyChangeCipherSpec == 2 {
1563 finished.verifyData = hs.finishedHash.clientSum(nil)
1564 } else {
1565 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
1566 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001567 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001568 if c.config.Bugs.BadFinished {
1569 finished.verifyData[0]++
1570 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001571 c.clientVerify = append(c.clientVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001572 hs.finishedBytes = finished.marshal()
1573 hs.writeHash(hs.finishedBytes, seqno)
David Benjamin0b8d5da2016-07-15 00:39:56 -04001574 postCCSMsgs = append(postCCSMsgs, hs.finishedBytes)
David Benjamin86271ee2014-07-21 16:14:03 -04001575
1576 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001577 c.writeRecord(recordTypeHandshake, postCCSMsgs[0][:5])
1578 postCCSMsgs[0] = postCCSMsgs[0][5:]
David Benjamin61672812016-07-14 23:10:43 -04001579 } else if c.config.Bugs.SendUnencryptedFinished {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001580 c.writeRecord(recordTypeHandshake, postCCSMsgs[0])
1581 postCCSMsgs = postCCSMsgs[1:]
David Benjamin86271ee2014-07-21 16:14:03 -04001582 }
David Benjamin582ba042016-07-07 12:33:25 -07001583 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001584
1585 if !c.config.Bugs.SkipChangeCipherSpec &&
1586 c.config.Bugs.EarlyChangeCipherSpec == 0 {
David Benjamin8411b242015-11-26 12:07:28 -05001587 ccs := []byte{1}
1588 if c.config.Bugs.BadChangeCipherSpec != nil {
1589 ccs = c.config.Bugs.BadChangeCipherSpec
1590 }
1591 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamin86271ee2014-07-21 16:14:03 -04001592 }
1593
David Benjamin4189bd92015-01-25 23:52:39 -05001594 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1595 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1596 }
David Benjamindc3da932015-03-12 15:09:02 -04001597 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1598 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1599 return errors.New("tls: simulating post-CCS alert")
1600 }
David Benjamin4189bd92015-01-25 23:52:39 -05001601
David Benjamin0b8d5da2016-07-15 00:39:56 -04001602 if !c.config.Bugs.SkipFinished {
1603 for _, msg := range postCCSMsgs {
1604 c.writeRecord(recordTypeHandshake, msg)
1605 }
David Benjamin02edcd02016-07-27 17:40:37 -04001606
1607 if c.config.Bugs.SendExtraFinished {
1608 c.writeRecord(recordTypeHandshake, finished.marshal())
1609 }
1610
David Benjamin582ba042016-07-07 12:33:25 -07001611 c.flushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -05001612 }
Adam Langley95c29f32014-06-20 12:00:00 -07001613 return nil
1614}
1615
Nick Harper60a85cb2016-09-23 16:25:11 -07001616func (hs *clientHandshakeState) writeChannelIDMessage(channelIDHash []byte) ([]byte, error) {
1617 c := hs.c
1618 channelIDMsg := new(channelIDMsg)
1619 if c.config.ChannelID.Curve != elliptic.P256() {
1620 return nil, fmt.Errorf("tls: Channel ID is not on P-256.")
1621 }
1622 r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, channelIDHash)
1623 if err != nil {
1624 return nil, err
1625 }
1626 channelID := make([]byte, 128)
1627 writeIntPadded(channelID[0:32], c.config.ChannelID.X)
1628 writeIntPadded(channelID[32:64], c.config.ChannelID.Y)
1629 writeIntPadded(channelID[64:96], r)
1630 writeIntPadded(channelID[96:128], s)
1631 if c.config.Bugs.InvalidChannelIDSignature {
1632 channelID[64] ^= 1
1633 }
1634 channelIDMsg.channelID = channelID
1635
1636 c.channelID = &c.config.ChannelID.PublicKey
1637
1638 return channelIDMsg.marshal(), nil
1639}
1640
David Benjamin83c0bc92014-08-04 01:23:53 -04001641func (hs *clientHandshakeState) writeClientHash(msg []byte) {
1642 // writeClientHash is called before writeRecord.
1643 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1644}
1645
1646func (hs *clientHandshakeState) writeServerHash(msg []byte) {
1647 // writeServerHash is called after readHandshake.
1648 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1649}
1650
1651func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) {
1652 if hs.c.isDTLS {
1653 // This is somewhat hacky. DTLS hashes a slightly different format.
1654 // First, the TLS header.
1655 hs.finishedHash.Write(msg[:4])
1656 // Then the sequence number and reassembled fragment offset (always 0).
1657 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1658 // Then the reassembled fragment (always equal to the message length).
1659 hs.finishedHash.Write(msg[1:4])
1660 // And then the message body.
1661 hs.finishedHash.Write(msg[4:])
1662 } else {
1663 hs.finishedHash.Write(msg)
1664 }
1665}
1666
David Benjamina6f82632016-07-01 18:44:02 -04001667// selectClientCertificate selects a certificate for use with the given
1668// certificate, or none if none match. It may return a particular certificate or
1669// nil on success, or an error on internal error.
1670func selectClientCertificate(c *Conn, certReq *certificateRequestMsg) (*Certificate, error) {
1671 // RFC 4346 on the certificateAuthorities field:
1672 // A list of the distinguished names of acceptable certificate
1673 // authorities. These distinguished names may specify a desired
1674 // distinguished name for a root CA or for a subordinate CA; thus, this
1675 // message can be used to describe both known roots and a desired
1676 // authorization space. If the certificate_authorities list is empty
1677 // then the client MAY send any certificate of the appropriate
1678 // ClientCertificateType, unless there is some external arrangement to
1679 // the contrary.
1680
1681 var rsaAvail, ecdsaAvail bool
Nick Harperb41d2e42016-07-01 17:50:32 -04001682 if !certReq.hasRequestContext {
1683 for _, certType := range certReq.certificateTypes {
1684 switch certType {
1685 case CertTypeRSASign:
1686 rsaAvail = true
1687 case CertTypeECDSASign:
1688 ecdsaAvail = true
1689 }
David Benjamina6f82632016-07-01 18:44:02 -04001690 }
1691 }
1692
1693 // We need to search our list of client certs for one
1694 // where SignatureAlgorithm is RSA and the Issuer is in
1695 // certReq.certificateAuthorities
1696findCert:
1697 for i, chain := range c.config.Certificates {
Nick Harperb41d2e42016-07-01 17:50:32 -04001698 if !certReq.hasRequestContext && !rsaAvail && !ecdsaAvail {
David Benjamina6f82632016-07-01 18:44:02 -04001699 continue
1700 }
1701
1702 // Ensure the private key supports one of the advertised
1703 // signature algorithms.
1704 if certReq.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001705 if _, err := selectSignatureAlgorithm(c.vers, chain.PrivateKey, c.config, certReq.signatureAlgorithms); err != nil {
David Benjamina6f82632016-07-01 18:44:02 -04001706 continue
1707 }
1708 }
1709
1710 for j, cert := range chain.Certificate {
1711 x509Cert := chain.Leaf
1712 // parse the certificate if this isn't the leaf
1713 // node, or if chain.Leaf was nil
1714 if j != 0 || x509Cert == nil {
1715 var err error
1716 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
1717 c.sendAlert(alertInternalError)
1718 return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
1719 }
1720 }
1721
Nick Harperb41d2e42016-07-01 17:50:32 -04001722 if !certReq.hasRequestContext {
1723 switch {
1724 case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
1725 case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
David Benjamind768c5d2017-03-28 18:28:44 -05001726 case ecdsaAvail && isEd25519Certificate(x509Cert):
Nick Harperb41d2e42016-07-01 17:50:32 -04001727 default:
1728 continue findCert
1729 }
David Benjamina6f82632016-07-01 18:44:02 -04001730 }
1731
Adam Langley2ff79332017-02-28 13:45:39 -08001732 if expected := c.config.Bugs.ExpectCertificateReqNames; expected != nil {
1733 if !eqByteSlices(expected, certReq.certificateAuthorities) {
1734 return nil, fmt.Errorf("tls: CertificateRequest names differed, got %#v but expected %#v", certReq.certificateAuthorities, expected)
David Benjamina6f82632016-07-01 18:44:02 -04001735 }
1736 }
Adam Langley2ff79332017-02-28 13:45:39 -08001737
1738 return &chain, nil
David Benjamina6f82632016-07-01 18:44:02 -04001739 }
1740 }
1741
1742 return nil, nil
1743}
1744
Adam Langley95c29f32014-06-20 12:00:00 -07001745// clientSessionCacheKey returns a key used to cache sessionTickets that could
1746// be used to resume previously negotiated TLS sessions with a server.
1747func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
1748 if len(config.ServerName) > 0 {
1749 return config.ServerName
1750 }
1751 return serverAddr.String()
1752}
1753
David Benjaminfa055a22014-09-15 16:51:51 -04001754// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
1755// given list of possible protocols and a list of the preference order. The
1756// first list must not be empty. It returns the resulting protocol and flag
Adam Langley95c29f32014-06-20 12:00:00 -07001757// indicating if the fallback case was reached.
David Benjaminfa055a22014-09-15 16:51:51 -04001758func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
1759 for _, s := range preferenceProtos {
1760 for _, c := range protos {
Adam Langley95c29f32014-06-20 12:00:00 -07001761 if s == c {
1762 return s, false
1763 }
1764 }
1765 }
1766
David Benjaminfa055a22014-09-15 16:51:51 -04001767 return protos[0], true
Adam Langley95c29f32014-06-20 12:00:00 -07001768}
David Benjamind30a9902014-08-24 01:44:23 -04001769
1770// writeIntPadded writes x into b, padded up with leading zeros as
1771// needed.
1772func writeIntPadded(b []byte, x *big.Int) {
1773 for i := range b {
1774 b[i] = 0
1775 }
1776 xb := x.Bytes()
1777 copy(b[len(b)-len(xb):], xb)
1778}
Steven Valdeza833c352016-11-01 13:39:36 -04001779
1780func generatePSKBinders(hello *clientHelloMsg, pskCipherSuite *cipherSuite, psk, transcript []byte, config *Config) {
1781 if config.Bugs.SendNoPSKBinder {
1782 return
1783 }
1784
1785 binderLen := pskCipherSuite.hash().Size()
1786 if config.Bugs.SendShortPSKBinder {
1787 binderLen--
1788 }
1789
David Benjaminaedf3032016-12-01 16:47:56 -05001790 numBinders := 1
1791 if config.Bugs.SendExtraPSKBinder {
1792 numBinders++
1793 }
1794
Steven Valdeza833c352016-11-01 13:39:36 -04001795 // Fill hello.pskBinders with appropriate length arrays of zeros so the
1796 // length prefixes are correct when computing the binder over the truncated
1797 // ClientHello message.
David Benjaminaedf3032016-12-01 16:47:56 -05001798 hello.pskBinders = make([][]byte, numBinders)
1799 for i := range hello.pskBinders {
Steven Valdeza833c352016-11-01 13:39:36 -04001800 hello.pskBinders[i] = make([]byte, binderLen)
1801 }
1802
1803 helloBytes := hello.marshal()
1804 binderSize := len(hello.pskBinders)*(binderLen+1) + 2
1805 truncatedHello := helloBytes[:len(helloBytes)-binderSize]
1806 binder := computePSKBinder(psk, resumptionPSKBinderLabel, pskCipherSuite, transcript, truncatedHello)
1807 if config.Bugs.SendShortPSKBinder {
1808 binder = binder[:binderLen]
1809 }
1810 if config.Bugs.SendInvalidPSKBinder {
1811 binder[0] ^= 1
1812 }
1813
1814 for i := range hello.pskBinders {
1815 hello.pskBinders[i] = binder
1816 }
1817
1818 hello.raw = nil
1819}