blob: 10e841a529ef1422cbff9d235ab1bb74365e3864 [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 }
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
Adam Langley95c29f32014-06-20 12:00:00 -0700583 hs := &clientHandshakeState{
584 c: c,
585 serverHello: serverHello,
586 hello: hello,
587 suite: suite,
588 finishedHash: newFinishedHash(c.vers, suite),
Nick Harperb41d2e42016-07-01 17:50:32 -0400589 keyShares: keyShares,
Adam Langley95c29f32014-06-20 12:00:00 -0700590 session: session,
591 }
592
David Benjamin83c0bc92014-08-04 01:23:53 -0400593 hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1)
Nick Harperdcfbc672016-07-16 17:47:31 +0200594 if haveHelloRetryRequest {
595 hs.writeServerHash(helloRetryRequest.marshal())
596 hs.writeClientHash(secondHelloBytes)
597 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400598 hs.writeServerHash(hs.serverHello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700599
David Benjamin8d315d72016-07-18 01:03:18 +0200600 if c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -0400601 if err := hs.doTLS13Handshake(); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700602 return err
603 }
604 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400605 if c.config.Bugs.EarlyChangeCipherSpec > 0 {
606 hs.establishKeys()
607 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
608 }
609
610 if hs.serverHello.compressionMethod != compressionNone {
611 c.sendAlert(alertUnexpectedMessage)
612 return errors.New("tls: server selected unsupported compression format")
613 }
614
615 err = hs.processServerExtensions(&serverHello.extensions)
616 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700617 return err
618 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400619
620 isResume, err := hs.processServerHello()
621 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700622 return err
623 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400624
625 if isResume {
626 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
627 if err := hs.establishKeys(); err != nil {
628 return err
629 }
630 }
631 if err := hs.readSessionTicket(); err != nil {
632 return err
633 }
634 if err := hs.readFinished(c.firstFinished[:]); err != nil {
635 return err
636 }
637 if err := hs.sendFinished(nil, isResume); err != nil {
638 return err
639 }
640 } else {
641 if err := hs.doFullHandshake(); err != nil {
642 return err
643 }
644 if err := hs.establishKeys(); err != nil {
645 return err
646 }
647 if err := hs.sendFinished(c.firstFinished[:], isResume); err != nil {
648 return err
649 }
650 // Most retransmits are triggered by a timeout, but the final
651 // leg of the handshake is retransmited upon re-receiving a
652 // Finished.
653 if err := c.simulatePacketLoss(func() {
David Benjamin02edcd02016-07-27 17:40:37 -0400654 c.sendHandshakeSeq--
Nick Harperb41d2e42016-07-01 17:50:32 -0400655 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
656 c.flushHandshake()
657 }); err != nil {
658 return err
659 }
660 if err := hs.readSessionTicket(); err != nil {
661 return err
662 }
663 if err := hs.readFinished(nil); err != nil {
664 return err
665 }
Adam Langley95c29f32014-06-20 12:00:00 -0700666 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400667
668 if sessionCache != nil && hs.session != nil && session != hs.session {
669 if c.config.Bugs.RequireSessionTickets && len(hs.session.sessionTicket) == 0 {
670 return errors.New("tls: new session used session IDs instead of tickets")
671 }
672 sessionCache.Put(cacheKey, hs.session)
David Benjamin83f90402015-01-27 01:09:43 -0500673 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400674
675 c.didResume = isResume
David Benjamin97a0a082016-07-13 17:57:35 -0400676 c.exporterSecret = hs.masterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700677 }
678
Adam Langley95c29f32014-06-20 12:00:00 -0700679 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400680 c.cipherSuite = suite
681 copy(c.clientRandom[:], hs.hello.random)
682 copy(c.serverRandom[:], hs.serverHello.random)
Paul Lietar4fac72e2015-09-09 13:44:55 +0100683
Adam Langley95c29f32014-06-20 12:00:00 -0700684 return nil
685}
686
Nick Harperb41d2e42016-07-01 17:50:32 -0400687func (hs *clientHandshakeState) doTLS13Handshake() error {
688 c := hs.c
689
Steven Valdez0e4a4482017-07-17 11:12:34 -0400690 if c.wireVersion == tls13ExperimentVersion && !bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) {
691 return errors.New("tls: session IDs did not match.")
692 }
693
Nick Harperb41d2e42016-07-01 17:50:32 -0400694 // Once the PRF hash is known, TLS 1.3 does not require a handshake
695 // buffer.
696 hs.finishedHash.discardHandshakeBuffer()
697
698 zeroSecret := hs.finishedHash.zeroSecret()
699
700 // Resolve PSK and compute the early secret.
701 //
702 // TODO(davidben): This will need to be handled slightly earlier once
703 // 0-RTT is implemented.
Steven Valdez803c77a2016-09-06 14:13:43 -0400704 if hs.serverHello.hasPSKIdentity {
Nick Harper0b3625b2016-07-25 16:16:28 -0700705 // We send at most one PSK identity.
706 if hs.session == nil || hs.serverHello.pskIdentity != 0 {
707 c.sendAlert(alertUnknownPSKIdentity)
708 return errors.New("tls: server sent unknown PSK identity")
709 }
David Benjamin2b02f4b2016-11-16 16:11:47 +0900710 sessionCipher := cipherSuiteFromID(hs.session.cipherSuite)
711 if sessionCipher == nil || sessionCipher.hash() != hs.suite.hash() {
Nick Harper0b3625b2016-07-25 16:16:28 -0700712 c.sendAlert(alertHandshakeFailure)
David Benjamin2b02f4b2016-11-16 16:11:47 +0900713 return errors.New("tls: server resumed an invalid session for the cipher suite")
Nick Harper0b3625b2016-07-25 16:16:28 -0700714 }
David Benjamin48891ad2016-12-04 00:02:43 -0500715 hs.finishedHash.addEntropy(hs.session.masterSecret)
Nick Harper0b3625b2016-07-25 16:16:28 -0700716 c.didResume = true
Nick Harperb41d2e42016-07-01 17:50:32 -0400717 } else {
David Benjamin48891ad2016-12-04 00:02:43 -0500718 hs.finishedHash.addEntropy(zeroSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400719 }
720
Steven Valdeza833c352016-11-01 13:39:36 -0400721 if !hs.serverHello.hasKeyShare {
722 c.sendAlert(alertUnsupportedExtension)
723 return errors.New("tls: server omitted KeyShare on resumption.")
724 }
725
Nick Harperb41d2e42016-07-01 17:50:32 -0400726 // Resolve ECDHE and compute the handshake secret.
Steven Valdez803c77a2016-09-06 14:13:43 -0400727 if !c.config.Bugs.MissingKeyShare && !c.config.Bugs.SecondClientHelloMissingKeyShare {
Nick Harperb41d2e42016-07-01 17:50:32 -0400728 curve, ok := hs.keyShares[hs.serverHello.keyShare.group]
729 if !ok {
730 c.sendAlert(alertHandshakeFailure)
731 return errors.New("tls: server selected an unsupported group")
732 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400733 c.curveID = hs.serverHello.keyShare.group
Nick Harperb41d2e42016-07-01 17:50:32 -0400734
David Benjamin48891ad2016-12-04 00:02:43 -0500735 ecdheSecret, err := curve.finish(hs.serverHello.keyShare.keyExchange)
Nick Harperb41d2e42016-07-01 17:50:32 -0400736 if err != nil {
737 return err
738 }
David Benjamin48891ad2016-12-04 00:02:43 -0500739 hs.finishedHash.addEntropy(ecdheSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400740 } else {
David Benjamin48891ad2016-12-04 00:02:43 -0500741 hs.finishedHash.addEntropy(zeroSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400742 }
743
Steven Valdez520e1222017-06-13 12:45:25 -0400744 if c.wireVersion == tls13ExperimentVersion {
745 if err := c.readRecord(recordTypeChangeCipherSpec); err != nil {
746 return err
747 }
748 }
749
Nick Harperf2511f12016-12-06 16:02:31 -0800750 // Derive handshake traffic keys and switch read key to handshake
751 // traffic key.
David Benjamin48891ad2016-12-04 00:02:43 -0500752 clientHandshakeTrafficSecret := hs.finishedHash.deriveSecret(clientHandshakeTrafficLabel)
David Benjamin48891ad2016-12-04 00:02:43 -0500753 serverHandshakeTrafficSecret := hs.finishedHash.deriveSecret(serverHandshakeTrafficLabel)
Steven Valdeza833c352016-11-01 13:39:36 -0400754 c.in.useTrafficSecret(c.vers, hs.suite, serverHandshakeTrafficSecret, serverWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -0400755
756 msg, err := c.readHandshake()
757 if err != nil {
758 return err
759 }
760
761 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
762 if !ok {
763 c.sendAlert(alertUnexpectedMessage)
764 return unexpectedMessageError(encryptedExtensions, msg)
765 }
766 hs.writeServerHash(encryptedExtensions.marshal())
767
768 err = hs.processServerExtensions(&encryptedExtensions.extensions)
769 if err != nil {
770 return err
771 }
772
773 var chainToSend *Certificate
David Benjamin8d343b42016-07-09 14:26:01 -0700774 var certReq *certificateRequestMsg
Steven Valdeza833c352016-11-01 13:39:36 -0400775 if c.didResume {
Nick Harper0b3625b2016-07-25 16:16:28 -0700776 // Copy over authentication from the session.
777 c.peerCertificates = hs.session.serverCertificates
778 c.sctList = hs.session.sctList
779 c.ocspResponse = hs.session.ocspResponse
David Benjamin44b33bc2016-07-01 22:40:23 -0400780 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400781 msg, err := c.readHandshake()
782 if err != nil {
783 return err
784 }
785
David Benjamin8d343b42016-07-09 14:26:01 -0700786 var ok bool
787 certReq, ok = msg.(*certificateRequestMsg)
Nick Harperb41d2e42016-07-01 17:50:32 -0400788 if ok {
David Benjamin8a8349b2016-08-18 02:32:23 -0400789 if len(certReq.requestContext) != 0 {
790 return errors.New("tls: non-empty certificate request context sent in handshake")
791 }
792
David Benjaminb62d2872016-07-18 14:55:02 +0200793 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
794 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
795 }
796
Nick Harperb41d2e42016-07-01 17:50:32 -0400797 hs.writeServerHash(certReq.marshal())
Nick Harperb41d2e42016-07-01 17:50:32 -0400798
799 chainToSend, err = selectClientCertificate(c, certReq)
800 if err != nil {
801 return err
802 }
803
804 msg, err = c.readHandshake()
805 if err != nil {
806 return err
807 }
808 }
809
810 certMsg, ok := msg.(*certificateMsg)
811 if !ok {
812 c.sendAlert(alertUnexpectedMessage)
813 return unexpectedMessageError(certMsg, msg)
814 }
815 hs.writeServerHash(certMsg.marshal())
816
David Benjamin53210cb2016-11-16 09:01:48 +0900817 // Check for unsolicited extensions.
818 for i, cert := range certMsg.certificates {
819 if c.config.Bugs.NoOCSPStapling && cert.ocspResponse != nil {
820 c.sendAlert(alertUnsupportedExtension)
821 return errors.New("tls: unexpected OCSP response in the server certificate")
822 }
823 if c.config.Bugs.NoSignedCertificateTimestamps && cert.sctList != nil {
824 c.sendAlert(alertUnsupportedExtension)
825 return errors.New("tls: unexpected SCT list in the server certificate")
826 }
827 if i > 0 && c.config.Bugs.ExpectNoExtensionsOnIntermediate && (cert.ocspResponse != nil || cert.sctList != nil) {
828 c.sendAlert(alertUnsupportedExtension)
829 return errors.New("tls: unexpected extensions in the server certificate")
830 }
831 }
832
Nick Harperb41d2e42016-07-01 17:50:32 -0400833 if err := hs.verifyCertificates(certMsg); err != nil {
834 return err
835 }
836 leaf := c.peerCertificates[0]
Steven Valdeza833c352016-11-01 13:39:36 -0400837 c.ocspResponse = certMsg.certificates[0].ocspResponse
838 c.sctList = certMsg.certificates[0].sctList
839
Nick Harperb41d2e42016-07-01 17:50:32 -0400840 msg, err = c.readHandshake()
841 if err != nil {
842 return err
843 }
844 certVerifyMsg, ok := msg.(*certificateVerifyMsg)
845 if !ok {
846 c.sendAlert(alertUnexpectedMessage)
847 return unexpectedMessageError(certVerifyMsg, msg)
848 }
849
David Benjaminf74ec792016-07-13 21:18:49 -0400850 c.peerSignatureAlgorithm = certVerifyMsg.signatureAlgorithm
Nick Harperb41d2e42016-07-01 17:50:32 -0400851 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
David Benjamind768c5d2017-03-28 18:28:44 -0500852 err = verifyMessage(c.vers, getCertificatePublicKey(leaf), c.config, certVerifyMsg.signatureAlgorithm, input, certVerifyMsg.signature)
Nick Harperb41d2e42016-07-01 17:50:32 -0400853 if err != nil {
854 return err
855 }
856
857 hs.writeServerHash(certVerifyMsg.marshal())
858 }
859
860 msg, err = c.readHandshake()
861 if err != nil {
862 return err
863 }
864 serverFinished, ok := msg.(*finishedMsg)
865 if !ok {
866 c.sendAlert(alertUnexpectedMessage)
867 return unexpectedMessageError(serverFinished, msg)
868 }
869
Steven Valdezc4aa7272016-10-03 12:25:56 -0400870 verify := hs.finishedHash.serverSum(serverHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400871 if len(verify) != len(serverFinished.verifyData) ||
872 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
873 c.sendAlert(alertHandshakeFailure)
874 return errors.New("tls: server's Finished message was incorrect")
875 }
876
877 hs.writeServerHash(serverFinished.marshal())
878
879 // The various secrets do not incorporate the client's final leg, so
880 // derive them now before updating the handshake context.
David Benjamin48891ad2016-12-04 00:02:43 -0500881 hs.finishedHash.addEntropy(zeroSecret)
882 clientTrafficSecret := hs.finishedHash.deriveSecret(clientApplicationTrafficLabel)
883 serverTrafficSecret := hs.finishedHash.deriveSecret(serverApplicationTrafficLabel)
David Benjamincdb6fe92017-02-07 16:06:48 -0500884 c.exporterSecret = hs.finishedHash.deriveSecret(exporterLabel)
885
886 // Switch to application data keys on read. In particular, any alerts
887 // from the client certificate are read over these keys.
Nick Harper7cd0a972016-12-02 11:08:40 -0800888 c.in.useTrafficSecret(c.vers, hs.suite, serverTrafficSecret, serverWrite)
889
890 // If we're expecting 0.5-RTT messages from the server, read them
891 // now.
David Benjamin794cc592017-03-25 22:24:23 -0500892 if encryptedExtensions.extensions.hasEarlyData {
893 // BoringSSL will always send two tickets half-RTT when
894 // negotiating 0-RTT.
895 for i := 0; i < shimConfig.HalfRTTTickets; i++ {
896 msg, err := c.readHandshake()
897 if err != nil {
898 return fmt.Errorf("tls: error reading half-RTT ticket: %s", err)
899 }
900 newSessionTicket, ok := msg.(*newSessionTicketMsg)
901 if !ok {
902 return errors.New("tls: expected half-RTT ticket")
903 }
904 if err := c.processTLS13NewSessionTicket(newSessionTicket, hs.suite); err != nil {
905 return err
906 }
Nick Harper7cd0a972016-12-02 11:08:40 -0800907 }
David Benjamin794cc592017-03-25 22:24:23 -0500908 for _, expectedMsg := range c.config.Bugs.ExpectHalfRTTData {
909 if err := c.readRecord(recordTypeApplicationData); err != nil {
910 return err
911 }
912 if !bytes.Equal(c.input.data[c.input.off:], expectedMsg) {
913 return errors.New("ExpectHalfRTTData: did not get expected message")
914 }
915 c.in.freeBlock(c.input)
916 c.input = nil
Nick Harper7cd0a972016-12-02 11:08:40 -0800917 }
Nick Harper7cd0a972016-12-02 11:08:40 -0800918 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400919
Nick Harperf2511f12016-12-06 16:02:31 -0800920 // Send EndOfEarlyData and then switch write key to handshake
921 // traffic key.
David Benjamin32c89272017-03-26 13:54:21 -0500922 if c.out.cipher != nil && !c.config.Bugs.SkipEndOfEarlyData {
Steven Valdez681eb6a2016-12-19 13:19:29 -0500923 if c.config.Bugs.SendStrayEarlyHandshake {
924 helloRequest := new(helloRequestMsg)
925 c.writeRecord(recordTypeHandshake, helloRequest.marshal())
926 }
Nick Harperf2511f12016-12-06 16:02:31 -0800927 c.sendAlert(alertEndOfEarlyData)
928 }
Steven Valdez520e1222017-06-13 12:45:25 -0400929
930 if c.wireVersion == tls13ExperimentVersion {
931 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
932 }
933
Nick Harperf2511f12016-12-06 16:02:31 -0800934 c.out.useTrafficSecret(c.vers, hs.suite, clientHandshakeTrafficSecret, clientWrite)
935
Steven Valdez0ee2e112016-07-15 06:51:15 -0400936 if certReq != nil && !c.config.Bugs.SkipClientCertificate {
David Benjamin8d343b42016-07-09 14:26:01 -0700937 certMsg := &certificateMsg{
938 hasRequestContext: true,
939 requestContext: certReq.requestContext,
940 }
941 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -0400942 for _, certData := range chainToSend.Certificate {
943 certMsg.certificates = append(certMsg.certificates, certificateEntry{
944 data: certData,
945 extraExtension: c.config.Bugs.SendExtensionOnCertificate,
946 })
947 }
David Benjamin8d343b42016-07-09 14:26:01 -0700948 }
949 hs.writeClientHash(certMsg.marshal())
950 c.writeRecord(recordTypeHandshake, certMsg.marshal())
951
952 if chainToSend != nil {
953 certVerify := &certificateVerifyMsg{
954 hasSignatureAlgorithm: true,
955 }
956
957 // Determine the hash to sign.
958 privKey := chainToSend.PrivateKey
959
960 var err error
961 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
962 if err != nil {
963 c.sendAlert(alertInternalError)
964 return err
965 }
966
967 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
968 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
969 if err != nil {
970 c.sendAlert(alertInternalError)
971 return err
972 }
Steven Valdez0ee2e112016-07-15 06:51:15 -0400973 if c.config.Bugs.SendSignatureAlgorithm != 0 {
974 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
975 }
David Benjamin8d343b42016-07-09 14:26:01 -0700976
977 hs.writeClientHash(certVerify.marshal())
978 c.writeRecord(recordTypeHandshake, certVerify.marshal())
979 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400980 }
981
Nick Harper60a85cb2016-09-23 16:25:11 -0700982 if encryptedExtensions.extensions.channelIDRequested {
983 channelIDHash := crypto.SHA256.New()
984 channelIDHash.Write(hs.finishedHash.certificateVerifyInput(channelIDContextTLS13))
985 channelIDMsgBytes, err := hs.writeChannelIDMessage(channelIDHash.Sum(nil))
986 if err != nil {
987 return err
988 }
989 hs.writeClientHash(channelIDMsgBytes)
990 c.writeRecord(recordTypeHandshake, channelIDMsgBytes)
991 }
992
Nick Harperb41d2e42016-07-01 17:50:32 -0400993 // Send a client Finished message.
994 finished := new(finishedMsg)
Steven Valdezc4aa7272016-10-03 12:25:56 -0400995 finished.verifyData = hs.finishedHash.clientSum(clientHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400996 if c.config.Bugs.BadFinished {
997 finished.verifyData[0]++
998 }
David Benjamin97a0a082016-07-13 17:57:35 -0400999 hs.writeClientHash(finished.marshal())
David Benjamin7964b182016-07-14 23:36:30 -04001000 if c.config.Bugs.PartialClientFinishedWithClientHello {
1001 // The first byte has already been sent.
1002 c.writeRecord(recordTypeHandshake, finished.marshal()[1:])
Steven Valdeza4ee74d2016-11-29 13:36:45 -05001003 } else if c.config.Bugs.InterleaveEarlyData {
1004 finishedBytes := finished.marshal()
1005 c.sendFakeEarlyData(4)
1006 c.writeRecord(recordTypeHandshake, finishedBytes[:1])
1007 c.sendFakeEarlyData(4)
1008 c.writeRecord(recordTypeHandshake, finishedBytes[1:])
David Benjamin7964b182016-07-14 23:36:30 -04001009 } else {
1010 c.writeRecord(recordTypeHandshake, finished.marshal())
1011 }
David Benjamin02edcd02016-07-27 17:40:37 -04001012 if c.config.Bugs.SendExtraFinished {
1013 c.writeRecord(recordTypeHandshake, finished.marshal())
1014 }
David Benjaminee51a222016-07-07 18:34:12 -07001015 c.flushHandshake()
Nick Harperb41d2e42016-07-01 17:50:32 -04001016
1017 // Switch to application data keys.
Steven Valdeza833c352016-11-01 13:39:36 -04001018 c.out.useTrafficSecret(c.vers, hs.suite, clientTrafficSecret, clientWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -04001019
David Benjamin48891ad2016-12-04 00:02:43 -05001020 c.resumptionSecret = hs.finishedHash.deriveSecret(resumptionLabel)
Nick Harperb41d2e42016-07-01 17:50:32 -04001021 return nil
1022}
1023
Adam Langley95c29f32014-06-20 12:00:00 -07001024func (hs *clientHandshakeState) doFullHandshake() error {
1025 c := hs.c
1026
David Benjamin48cae082014-10-27 01:06:24 -04001027 var leaf *x509.Certificate
1028 if hs.suite.flags&suitePSK == 0 {
1029 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001030 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -07001031 return err
1032 }
Adam Langley95c29f32014-06-20 12:00:00 -07001033
David Benjamin48cae082014-10-27 01:06:24 -04001034 certMsg, ok := msg.(*certificateMsg)
David Benjamin75051442016-07-01 18:58:51 -04001035 if !ok {
David Benjamin48cae082014-10-27 01:06:24 -04001036 c.sendAlert(alertUnexpectedMessage)
1037 return unexpectedMessageError(certMsg, msg)
1038 }
1039 hs.writeServerHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001040
David Benjamin75051442016-07-01 18:58:51 -04001041 if err := hs.verifyCertificates(certMsg); err != nil {
1042 return err
David Benjamin48cae082014-10-27 01:06:24 -04001043 }
David Benjamin75051442016-07-01 18:58:51 -04001044 leaf = c.peerCertificates[0]
David Benjamin48cae082014-10-27 01:06:24 -04001045 }
Adam Langley95c29f32014-06-20 12:00:00 -07001046
Nick Harperb3d51be2016-07-01 11:43:18 -04001047 if hs.serverHello.extensions.ocspStapling {
David Benjamin48cae082014-10-27 01:06:24 -04001048 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001049 if err != nil {
1050 return err
1051 }
1052 cs, ok := msg.(*certificateStatusMsg)
1053 if !ok {
1054 c.sendAlert(alertUnexpectedMessage)
1055 return unexpectedMessageError(cs, msg)
1056 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001057 hs.writeServerHash(cs.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001058
1059 if cs.statusType == statusTypeOCSP {
1060 c.ocspResponse = cs.response
1061 }
1062 }
1063
David Benjamin48cae082014-10-27 01:06:24 -04001064 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001065 if err != nil {
1066 return err
1067 }
1068
1069 keyAgreement := hs.suite.ka(c.vers)
1070
1071 skx, ok := msg.(*serverKeyExchangeMsg)
1072 if ok {
David Benjamin83c0bc92014-08-04 01:23:53 -04001073 hs.writeServerHash(skx.marshal())
David Benjamin48cae082014-10-27 01:06:24 -04001074 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx)
Adam Langley95c29f32014-06-20 12:00:00 -07001075 if err != nil {
1076 c.sendAlert(alertUnexpectedMessage)
1077 return err
1078 }
Steven Valdez5440fe02016-07-18 12:40:30 -04001079 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1080 c.curveID = ecdhe.curveID
1081 }
Adam Langley95c29f32014-06-20 12:00:00 -07001082
Nick Harper60edffd2016-06-21 15:19:24 -07001083 c.peerSignatureAlgorithm = keyAgreement.peerSignatureAlgorithm()
1084
Adam Langley95c29f32014-06-20 12:00:00 -07001085 msg, err = c.readHandshake()
1086 if err != nil {
1087 return err
1088 }
1089 }
1090
1091 var chainToSend *Certificate
1092 var certRequested bool
1093 certReq, ok := msg.(*certificateRequestMsg)
1094 if ok {
1095 certRequested = true
David Benjamin7a41d372016-07-09 11:21:54 -07001096 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
1097 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
1098 }
Adam Langley95c29f32014-06-20 12:00:00 -07001099
David Benjamin83c0bc92014-08-04 01:23:53 -04001100 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001101
David Benjamina6f82632016-07-01 18:44:02 -04001102 chainToSend, err = selectClientCertificate(c, certReq)
1103 if err != nil {
1104 return err
Adam Langley95c29f32014-06-20 12:00:00 -07001105 }
1106
1107 msg, err = c.readHandshake()
1108 if err != nil {
1109 return err
1110 }
1111 }
1112
1113 shd, ok := msg.(*serverHelloDoneMsg)
1114 if !ok {
1115 c.sendAlert(alertUnexpectedMessage)
1116 return unexpectedMessageError(shd, msg)
1117 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001118 hs.writeServerHash(shd.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001119
1120 // If the server requested a certificate then we have to send a
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001121 // Certificate message in TLS, even if it's empty because we don't have
1122 // a certificate to send. In SSL 3.0, skip the message and send a
1123 // no_certificate warning alert.
Adam Langley95c29f32014-06-20 12:00:00 -07001124 if certRequested {
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001125 if c.vers == VersionSSL30 && chainToSend == nil {
David Benjamin053fee92017-01-02 08:30:36 -05001126 c.sendAlert(alertNoCertificate)
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001127 } else if !c.config.Bugs.SkipClientCertificate {
1128 certMsg := new(certificateMsg)
1129 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -04001130 for _, certData := range chainToSend.Certificate {
1131 certMsg.certificates = append(certMsg.certificates, certificateEntry{
1132 data: certData,
1133 })
1134 }
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001135 }
1136 hs.writeClientHash(certMsg.marshal())
1137 c.writeRecord(recordTypeHandshake, certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001138 }
Adam Langley95c29f32014-06-20 12:00:00 -07001139 }
1140
David Benjamin48cae082014-10-27 01:06:24 -04001141 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf)
Adam Langley95c29f32014-06-20 12:00:00 -07001142 if err != nil {
1143 c.sendAlert(alertInternalError)
1144 return err
1145 }
1146 if ckx != nil {
David Benjaminf3ec83d2014-07-21 22:42:34 -04001147 if c.config.Bugs.EarlyChangeCipherSpec < 2 {
David Benjamin83c0bc92014-08-04 01:23:53 -04001148 hs.writeClientHash(ckx.marshal())
David Benjaminf3ec83d2014-07-21 22:42:34 -04001149 }
Adam Langley95c29f32014-06-20 12:00:00 -07001150 c.writeRecord(recordTypeHandshake, ckx.marshal())
1151 }
1152
Nick Harperb3d51be2016-07-01 11:43:18 -04001153 if hs.serverHello.extensions.extendedMasterSecret && c.vers >= VersionTLS10 {
Adam Langley75712922014-10-10 16:23:43 -07001154 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1155 c.extendedMasterSecret = true
1156 } else {
1157 if c.config.Bugs.RequireExtendedMasterSecret {
1158 return errors.New("tls: extended master secret required but not supported by peer")
1159 }
1160 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
1161 }
David Benjamine098ec22014-08-27 23:13:20 -04001162
Adam Langley95c29f32014-06-20 12:00:00 -07001163 if chainToSend != nil {
Adam Langley95c29f32014-06-20 12:00:00 -07001164 certVerify := &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001165 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001166 }
1167
David Benjamin72dc7832015-03-16 17:49:43 -04001168 // Determine the hash to sign.
Nick Harper60edffd2016-06-21 15:19:24 -07001169 privKey := c.config.Certificates[0].PrivateKey
David Benjamin72dc7832015-03-16 17:49:43 -04001170
Nick Harper60edffd2016-06-21 15:19:24 -07001171 if certVerify.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001172 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
Nick Harper60edffd2016-06-21 15:19:24 -07001173 if err != nil {
1174 c.sendAlert(alertInternalError)
1175 return err
Adam Langley95c29f32014-06-20 12:00:00 -07001176 }
Nick Harper60edffd2016-06-21 15:19:24 -07001177 }
1178
1179 if c.vers > VersionSSL30 {
David Benjamin5208fd42016-07-13 21:43:25 -04001180 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, hs.finishedHash.buffer)
David Benjamina95e9f32016-07-08 16:28:04 -07001181 if err == nil && c.config.Bugs.SendSignatureAlgorithm != 0 {
1182 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
1183 }
Nick Harper60edffd2016-06-21 15:19:24 -07001184 } else {
1185 // SSL 3.0's client certificate construction is
1186 // incompatible with signatureAlgorithm.
1187 rsaKey, ok := privKey.(*rsa.PrivateKey)
1188 if !ok {
1189 err = errors.New("unsupported signature type for client certificate")
1190 } else {
1191 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
David Benjamin5208fd42016-07-13 21:43:25 -04001192 if c.config.Bugs.InvalidSignature {
Nick Harper60edffd2016-06-21 15:19:24 -07001193 digest[0] ^= 0x80
1194 }
1195 certVerify.signature, err = rsa.SignPKCS1v15(c.config.rand(), rsaKey, crypto.MD5SHA1, digest)
1196 }
Adam Langley95c29f32014-06-20 12:00:00 -07001197 }
1198 if err != nil {
1199 c.sendAlert(alertInternalError)
1200 return errors.New("tls: failed to sign handshake with client certificate: " + err.Error())
1201 }
Adam Langley95c29f32014-06-20 12:00:00 -07001202
David Benjamin83c0bc92014-08-04 01:23:53 -04001203 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001204 c.writeRecord(recordTypeHandshake, certVerify.marshal())
1205 }
David Benjamin82261be2016-07-07 14:32:50 -07001206 // flushHandshake will be called in sendFinished.
Adam Langley95c29f32014-06-20 12:00:00 -07001207
David Benjamine098ec22014-08-27 23:13:20 -04001208 hs.finishedHash.discardHandshakeBuffer()
1209
Adam Langley95c29f32014-06-20 12:00:00 -07001210 return nil
1211}
1212
David Benjamin75051442016-07-01 18:58:51 -04001213func (hs *clientHandshakeState) verifyCertificates(certMsg *certificateMsg) error {
1214 c := hs.c
1215
1216 if len(certMsg.certificates) == 0 {
1217 c.sendAlert(alertIllegalParameter)
1218 return errors.New("tls: no certificates sent")
1219 }
1220
1221 certs := make([]*x509.Certificate, len(certMsg.certificates))
Steven Valdeza833c352016-11-01 13:39:36 -04001222 for i, certEntry := range certMsg.certificates {
1223 cert, err := x509.ParseCertificate(certEntry.data)
David Benjamin75051442016-07-01 18:58:51 -04001224 if err != nil {
1225 c.sendAlert(alertBadCertificate)
1226 return errors.New("tls: failed to parse certificate from server: " + err.Error())
1227 }
1228 certs[i] = cert
1229 }
1230
1231 if !c.config.InsecureSkipVerify {
1232 opts := x509.VerifyOptions{
1233 Roots: c.config.RootCAs,
1234 CurrentTime: c.config.time(),
1235 DNSName: c.config.ServerName,
1236 Intermediates: x509.NewCertPool(),
1237 }
1238
1239 for i, cert := range certs {
1240 if i == 0 {
1241 continue
1242 }
1243 opts.Intermediates.AddCert(cert)
1244 }
1245 var err error
1246 c.verifiedChains, err = certs[0].Verify(opts)
1247 if err != nil {
1248 c.sendAlert(alertBadCertificate)
1249 return err
1250 }
1251 }
1252
David Benjamind768c5d2017-03-28 18:28:44 -05001253 publicKey := getCertificatePublicKey(certs[0])
1254 switch publicKey.(type) {
1255 case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
David Benjamin75051442016-07-01 18:58:51 -04001256 break
1257 default:
1258 c.sendAlert(alertUnsupportedCertificate)
David Benjamind768c5d2017-03-28 18:28:44 -05001259 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", publicKey)
David Benjamin75051442016-07-01 18:58:51 -04001260 }
1261
1262 c.peerCertificates = certs
1263 return nil
1264}
1265
Adam Langley95c29f32014-06-20 12:00:00 -07001266func (hs *clientHandshakeState) establishKeys() error {
1267 c := hs.c
1268
1269 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001270 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 -07001271 var clientCipher, serverCipher interface{}
1272 var clientHash, serverHash macFunction
1273 if hs.suite.cipher != nil {
1274 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
1275 clientHash = hs.suite.mac(c.vers, clientMAC)
1276 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
1277 serverHash = hs.suite.mac(c.vers, serverMAC)
1278 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001279 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1280 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001281 }
1282
1283 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
1284 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
1285 return nil
1286}
1287
David Benjamin75101402016-07-01 13:40:23 -04001288func (hs *clientHandshakeState) processServerExtensions(serverExtensions *serverExtensions) error {
1289 c := hs.c
1290
David Benjamin8d315d72016-07-18 01:03:18 +02001291 if c.vers < VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001292 if c.config.Bugs.RequireRenegotiationInfo && serverExtensions.secureRenegotiation == nil {
1293 return errors.New("tls: renegotiation extension missing")
1294 }
David Benjamin75101402016-07-01 13:40:23 -04001295
Nick Harperb41d2e42016-07-01 17:50:32 -04001296 if len(c.clientVerify) > 0 && !c.noRenegotiationInfo() {
1297 var expectedRenegInfo []byte
1298 expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...)
1299 expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...)
1300 if !bytes.Equal(serverExtensions.secureRenegotiation, expectedRenegInfo) {
1301 c.sendAlert(alertHandshakeFailure)
1302 return fmt.Errorf("tls: renegotiation mismatch")
1303 }
David Benjamin75101402016-07-01 13:40:23 -04001304 }
David Benjamincea0ab42016-07-14 12:33:14 -04001305 } else if serverExtensions.secureRenegotiation != nil {
1306 return errors.New("tls: renegotiation info sent in TLS 1.3")
David Benjamin75101402016-07-01 13:40:23 -04001307 }
1308
1309 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
1310 if serverExtensions.customExtension != *expected {
1311 return fmt.Errorf("tls: bad custom extension contents %q", serverExtensions.customExtension)
1312 }
1313 }
1314
1315 clientDidNPN := hs.hello.nextProtoNeg
1316 clientDidALPN := len(hs.hello.alpnProtocols) > 0
1317 serverHasNPN := serverExtensions.nextProtoNeg
1318 serverHasALPN := len(serverExtensions.alpnProtocol) > 0
1319
1320 if !clientDidNPN && serverHasNPN {
1321 c.sendAlert(alertHandshakeFailure)
1322 return errors.New("server advertised unrequested NPN extension")
1323 }
1324
1325 if !clientDidALPN && serverHasALPN {
1326 c.sendAlert(alertHandshakeFailure)
1327 return errors.New("server advertised unrequested ALPN extension")
1328 }
1329
1330 if serverHasNPN && serverHasALPN {
1331 c.sendAlert(alertHandshakeFailure)
1332 return errors.New("server advertised both NPN and ALPN extensions")
1333 }
1334
1335 if serverHasALPN {
1336 c.clientProtocol = serverExtensions.alpnProtocol
1337 c.clientProtocolFallback = false
1338 c.usedALPN = true
1339 }
1340
David Benjamin8d315d72016-07-18 01:03:18 +02001341 if serverHasNPN && c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001342 c.sendAlert(alertHandshakeFailure)
1343 return errors.New("server advertised NPN over TLS 1.3")
1344 }
1345
David Benjamin75101402016-07-01 13:40:23 -04001346 if !hs.hello.channelIDSupported && serverExtensions.channelIDRequested {
1347 c.sendAlert(alertHandshakeFailure)
1348 return errors.New("server advertised unrequested Channel ID extension")
1349 }
1350
David Benjamin8d315d72016-07-18 01:03:18 +02001351 if serverExtensions.extendedMasterSecret && c.vers >= VersionTLS13 {
David Benjamine9077652016-07-13 21:02:08 -04001352 return errors.New("tls: server advertised extended master secret over TLS 1.3")
1353 }
1354
David Benjamin8d315d72016-07-18 01:03:18 +02001355 if serverExtensions.ticketSupported && c.vers >= VersionTLS13 {
Steven Valdez143e8b32016-07-11 13:19:03 -04001356 return errors.New("tls: server advertised ticket extension over TLS 1.3")
1357 }
1358
Steven Valdeza833c352016-11-01 13:39:36 -04001359 if serverExtensions.ocspStapling && c.vers >= VersionTLS13 {
1360 return errors.New("tls: server advertised OCSP in ServerHello over TLS 1.3")
1361 }
1362
David Benjamin53210cb2016-11-16 09:01:48 +09001363 if serverExtensions.ocspStapling && c.config.Bugs.NoOCSPStapling {
1364 return errors.New("tls: server advertised unrequested OCSP extension")
1365 }
1366
Steven Valdeza833c352016-11-01 13:39:36 -04001367 if len(serverExtensions.sctList) > 0 && c.vers >= VersionTLS13 {
1368 return errors.New("tls: server advertised SCTs in ServerHello over TLS 1.3")
1369 }
1370
David Benjamin53210cb2016-11-16 09:01:48 +09001371 if len(serverExtensions.sctList) > 0 && c.config.Bugs.NoSignedCertificateTimestamps {
1372 return errors.New("tls: server advertised unrequested SCTs")
1373 }
1374
David Benjamin75101402016-07-01 13:40:23 -04001375 if serverExtensions.srtpProtectionProfile != 0 {
1376 if serverExtensions.srtpMasterKeyIdentifier != "" {
1377 return errors.New("tls: server selected SRTP MKI value")
1378 }
1379
1380 found := false
1381 for _, p := range c.config.SRTPProtectionProfiles {
1382 if p == serverExtensions.srtpProtectionProfile {
1383 found = true
1384 break
1385 }
1386 }
1387 if !found {
1388 return errors.New("tls: server advertised unsupported SRTP profile")
1389 }
1390
1391 c.srtpProtectionProfile = serverExtensions.srtpProtectionProfile
1392 }
1393
Steven Valdez2d850622017-01-11 11:34:52 -05001394 if c.vers >= VersionTLS13 && c.didResume {
1395 if c.config.Bugs.ExpectEarlyDataAccepted && !serverExtensions.hasEarlyData {
1396 c.sendAlert(alertHandshakeFailure)
1397 return errors.New("tls: server did not accept early data when expected")
1398 }
1399
1400 if !c.config.Bugs.ExpectEarlyDataAccepted && serverExtensions.hasEarlyData {
1401 c.sendAlert(alertHandshakeFailure)
1402 return errors.New("tls: server accepted early data when not expected")
1403 }
1404 }
1405
David Benjamin75101402016-07-01 13:40:23 -04001406 return nil
1407}
1408
Adam Langley95c29f32014-06-20 12:00:00 -07001409func (hs *clientHandshakeState) serverResumedSession() bool {
1410 // If the server responded with the same sessionId then it means the
1411 // sessionTicket is being used to resume a TLS session.
David Benjamind4c349b2017-02-09 14:07:17 -05001412 //
1413 // Note that, if hs.hello.sessionId is a non-nil empty array, this will
1414 // accept an empty session ID from the server as resumption. See
1415 // EmptyTicketSessionID.
Adam Langley95c29f32014-06-20 12:00:00 -07001416 return hs.session != nil && hs.hello.sessionId != nil &&
1417 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
1418}
1419
1420func (hs *clientHandshakeState) processServerHello() (bool, error) {
1421 c := hs.c
1422
Adam Langley95c29f32014-06-20 12:00:00 -07001423 if hs.serverResumedSession() {
David Benjamin4b27d9f2015-05-12 22:42:52 -04001424 // For test purposes, assert that the server never accepts the
1425 // resumption offer on renegotiation.
1426 if c.cipherSuite != nil && c.config.Bugs.FailIfResumeOnRenego {
1427 return false, errors.New("tls: server resumed session on renegotiation")
1428 }
1429
Nick Harperb3d51be2016-07-01 11:43:18 -04001430 if hs.serverHello.extensions.sctList != nil {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001431 return false, errors.New("tls: server sent SCT extension on session resumption")
1432 }
1433
Nick Harperb3d51be2016-07-01 11:43:18 -04001434 if hs.serverHello.extensions.ocspStapling {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001435 return false, errors.New("tls: server sent OCSP extension on session resumption")
1436 }
1437
Adam Langley95c29f32014-06-20 12:00:00 -07001438 // Restore masterSecret and peerCerts from previous state
1439 hs.masterSecret = hs.session.masterSecret
1440 c.peerCertificates = hs.session.serverCertificates
Adam Langley75712922014-10-10 16:23:43 -07001441 c.extendedMasterSecret = hs.session.extendedMasterSecret
Paul Lietar62be8ac2015-09-16 10:03:30 +01001442 c.sctList = hs.session.sctList
1443 c.ocspResponse = hs.session.ocspResponse
David Benjamine098ec22014-08-27 23:13:20 -04001444 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001445 return true, nil
1446 }
Paul Lietar62be8ac2015-09-16 10:03:30 +01001447
Nick Harperb3d51be2016-07-01 11:43:18 -04001448 if hs.serverHello.extensions.sctList != nil {
1449 c.sctList = hs.serverHello.extensions.sctList
Paul Lietar62be8ac2015-09-16 10:03:30 +01001450 }
1451
Adam Langley95c29f32014-06-20 12:00:00 -07001452 return false, nil
1453}
1454
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001455func (hs *clientHandshakeState) readFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001456 c := hs.c
1457
1458 c.readRecord(recordTypeChangeCipherSpec)
1459 if err := c.in.error(); err != nil {
1460 return err
1461 }
1462
1463 msg, err := c.readHandshake()
1464 if err != nil {
1465 return err
1466 }
1467 serverFinished, ok := msg.(*finishedMsg)
1468 if !ok {
1469 c.sendAlert(alertUnexpectedMessage)
1470 return unexpectedMessageError(serverFinished, msg)
1471 }
1472
David Benjaminf3ec83d2014-07-21 22:42:34 -04001473 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
1474 verify := hs.finishedHash.serverSum(hs.masterSecret)
1475 if len(verify) != len(serverFinished.verifyData) ||
1476 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
1477 c.sendAlert(alertHandshakeFailure)
1478 return errors.New("tls: server's Finished message was incorrect")
1479 }
Adam Langley95c29f32014-06-20 12:00:00 -07001480 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001481 c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001482 copy(out, serverFinished.verifyData)
David Benjamin83c0bc92014-08-04 01:23:53 -04001483 hs.writeServerHash(serverFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001484 return nil
1485}
1486
1487func (hs *clientHandshakeState) readSessionTicket() error {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001488 c := hs.c
1489
1490 // Create a session with no server identifier. Either a
1491 // session ID or session ticket will be attached.
1492 session := &ClientSessionState{
1493 vers: c.vers,
1494 cipherSuite: hs.suite.id,
1495 masterSecret: hs.masterSecret,
Nick Harperc9846112016-10-17 15:05:35 -07001496 handshakeHash: hs.finishedHash.Sum(),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001497 serverCertificates: c.peerCertificates,
Paul Lietar62be8ac2015-09-16 10:03:30 +01001498 sctList: c.sctList,
1499 ocspResponse: c.ocspResponse,
Nick Harper0b3625b2016-07-25 16:16:28 -07001500 ticketExpiration: c.config.time().Add(time.Duration(7 * 24 * time.Hour)),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001501 }
1502
Nick Harperb3d51be2016-07-01 11:43:18 -04001503 if !hs.serverHello.extensions.ticketSupported {
David Benjamind98452d2015-06-16 14:16:23 -04001504 if c.config.Bugs.ExpectNewTicket {
1505 return errors.New("tls: expected new ticket")
1506 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001507 if hs.session == nil && len(hs.serverHello.sessionId) > 0 {
1508 session.sessionId = hs.serverHello.sessionId
1509 hs.session = session
1510 }
Adam Langley95c29f32014-06-20 12:00:00 -07001511 return nil
1512 }
1513
David Benjaminc7ce9772015-10-09 19:32:41 -04001514 if c.vers == VersionSSL30 {
1515 return errors.New("tls: negotiated session tickets in SSL 3.0")
1516 }
1517
Adam Langley95c29f32014-06-20 12:00:00 -07001518 msg, err := c.readHandshake()
1519 if err != nil {
1520 return err
1521 }
1522 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
1523 if !ok {
1524 c.sendAlert(alertUnexpectedMessage)
1525 return unexpectedMessageError(sessionTicketMsg, msg)
1526 }
Adam Langley95c29f32014-06-20 12:00:00 -07001527
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001528 session.sessionTicket = sessionTicketMsg.ticket
1529 hs.session = session
Adam Langley95c29f32014-06-20 12:00:00 -07001530
David Benjamind30a9902014-08-24 01:44:23 -04001531 hs.writeServerHash(sessionTicketMsg.marshal())
1532
Adam Langley95c29f32014-06-20 12:00:00 -07001533 return nil
1534}
1535
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001536func (hs *clientHandshakeState) sendFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001537 c := hs.c
1538
David Benjamin0b8d5da2016-07-15 00:39:56 -04001539 var postCCSMsgs [][]byte
David Benjamin83c0bc92014-08-04 01:23:53 -04001540 seqno := hs.c.sendHandshakeSeq
Nick Harperb3d51be2016-07-01 11:43:18 -04001541 if hs.serverHello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001542 nextProto := new(nextProtoMsg)
Nick Harperb3d51be2016-07-01 11:43:18 -04001543 proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.extensions.nextProtos)
Adam Langley95c29f32014-06-20 12:00:00 -07001544 nextProto.proto = proto
1545 c.clientProtocol = proto
1546 c.clientProtocolFallback = fallback
1547
David Benjamin86271ee2014-07-21 16:14:03 -04001548 nextProtoBytes := nextProto.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -04001549 hs.writeHash(nextProtoBytes, seqno)
1550 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001551 postCCSMsgs = append(postCCSMsgs, nextProtoBytes)
Adam Langley95c29f32014-06-20 12:00:00 -07001552 }
1553
Nick Harperb3d51be2016-07-01 11:43:18 -04001554 if hs.serverHello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001555 var resumeHash []byte
1556 if isResume {
1557 resumeHash = hs.session.handshakeHash
1558 }
Nick Harper60a85cb2016-09-23 16:25:11 -07001559 channelIDMsgBytes, err := hs.writeChannelIDMessage(hs.finishedHash.hashForChannelID(resumeHash))
David Benjamind30a9902014-08-24 01:44:23 -04001560 if err != nil {
1561 return err
1562 }
David Benjamin24599a82016-06-30 18:56:53 -04001563 hs.writeHash(channelIDMsgBytes, seqno)
David Benjamind30a9902014-08-24 01:44:23 -04001564 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001565 postCCSMsgs = append(postCCSMsgs, channelIDMsgBytes)
David Benjamind30a9902014-08-24 01:44:23 -04001566 }
1567
Adam Langley95c29f32014-06-20 12:00:00 -07001568 finished := new(finishedMsg)
David Benjaminf3ec83d2014-07-21 22:42:34 -04001569 if c.config.Bugs.EarlyChangeCipherSpec == 2 {
1570 finished.verifyData = hs.finishedHash.clientSum(nil)
1571 } else {
1572 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
1573 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001574 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001575 if c.config.Bugs.BadFinished {
1576 finished.verifyData[0]++
1577 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001578 c.clientVerify = append(c.clientVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001579 hs.finishedBytes = finished.marshal()
1580 hs.writeHash(hs.finishedBytes, seqno)
David Benjamin0b8d5da2016-07-15 00:39:56 -04001581 postCCSMsgs = append(postCCSMsgs, hs.finishedBytes)
David Benjamin86271ee2014-07-21 16:14:03 -04001582
1583 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001584 c.writeRecord(recordTypeHandshake, postCCSMsgs[0][:5])
1585 postCCSMsgs[0] = postCCSMsgs[0][5:]
David Benjamin61672812016-07-14 23:10:43 -04001586 } else if c.config.Bugs.SendUnencryptedFinished {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001587 c.writeRecord(recordTypeHandshake, postCCSMsgs[0])
1588 postCCSMsgs = postCCSMsgs[1:]
David Benjamin86271ee2014-07-21 16:14:03 -04001589 }
David Benjamin582ba042016-07-07 12:33:25 -07001590 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001591
1592 if !c.config.Bugs.SkipChangeCipherSpec &&
1593 c.config.Bugs.EarlyChangeCipherSpec == 0 {
David Benjamin8411b242015-11-26 12:07:28 -05001594 ccs := []byte{1}
1595 if c.config.Bugs.BadChangeCipherSpec != nil {
1596 ccs = c.config.Bugs.BadChangeCipherSpec
1597 }
1598 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamin86271ee2014-07-21 16:14:03 -04001599 }
1600
David Benjamin4189bd92015-01-25 23:52:39 -05001601 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1602 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1603 }
David Benjamindc3da932015-03-12 15:09:02 -04001604 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1605 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1606 return errors.New("tls: simulating post-CCS alert")
1607 }
David Benjamin4189bd92015-01-25 23:52:39 -05001608
David Benjamin0b8d5da2016-07-15 00:39:56 -04001609 if !c.config.Bugs.SkipFinished {
1610 for _, msg := range postCCSMsgs {
1611 c.writeRecord(recordTypeHandshake, msg)
1612 }
David Benjamin02edcd02016-07-27 17:40:37 -04001613
1614 if c.config.Bugs.SendExtraFinished {
1615 c.writeRecord(recordTypeHandshake, finished.marshal())
1616 }
1617
David Benjamin582ba042016-07-07 12:33:25 -07001618 c.flushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -05001619 }
Adam Langley95c29f32014-06-20 12:00:00 -07001620 return nil
1621}
1622
Nick Harper60a85cb2016-09-23 16:25:11 -07001623func (hs *clientHandshakeState) writeChannelIDMessage(channelIDHash []byte) ([]byte, error) {
1624 c := hs.c
1625 channelIDMsg := new(channelIDMsg)
1626 if c.config.ChannelID.Curve != elliptic.P256() {
1627 return nil, fmt.Errorf("tls: Channel ID is not on P-256.")
1628 }
1629 r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, channelIDHash)
1630 if err != nil {
1631 return nil, err
1632 }
1633 channelID := make([]byte, 128)
1634 writeIntPadded(channelID[0:32], c.config.ChannelID.X)
1635 writeIntPadded(channelID[32:64], c.config.ChannelID.Y)
1636 writeIntPadded(channelID[64:96], r)
1637 writeIntPadded(channelID[96:128], s)
1638 if c.config.Bugs.InvalidChannelIDSignature {
1639 channelID[64] ^= 1
1640 }
1641 channelIDMsg.channelID = channelID
1642
1643 c.channelID = &c.config.ChannelID.PublicKey
1644
1645 return channelIDMsg.marshal(), nil
1646}
1647
David Benjamin83c0bc92014-08-04 01:23:53 -04001648func (hs *clientHandshakeState) writeClientHash(msg []byte) {
1649 // writeClientHash is called before writeRecord.
1650 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1651}
1652
1653func (hs *clientHandshakeState) writeServerHash(msg []byte) {
1654 // writeServerHash is called after readHandshake.
1655 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1656}
1657
1658func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) {
1659 if hs.c.isDTLS {
1660 // This is somewhat hacky. DTLS hashes a slightly different format.
1661 // First, the TLS header.
1662 hs.finishedHash.Write(msg[:4])
1663 // Then the sequence number and reassembled fragment offset (always 0).
1664 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1665 // Then the reassembled fragment (always equal to the message length).
1666 hs.finishedHash.Write(msg[1:4])
1667 // And then the message body.
1668 hs.finishedHash.Write(msg[4:])
1669 } else {
1670 hs.finishedHash.Write(msg)
1671 }
1672}
1673
David Benjamina6f82632016-07-01 18:44:02 -04001674// selectClientCertificate selects a certificate for use with the given
1675// certificate, or none if none match. It may return a particular certificate or
1676// nil on success, or an error on internal error.
1677func selectClientCertificate(c *Conn, certReq *certificateRequestMsg) (*Certificate, error) {
1678 // RFC 4346 on the certificateAuthorities field:
1679 // A list of the distinguished names of acceptable certificate
1680 // authorities. These distinguished names may specify a desired
1681 // distinguished name for a root CA or for a subordinate CA; thus, this
1682 // message can be used to describe both known roots and a desired
1683 // authorization space. If the certificate_authorities list is empty
1684 // then the client MAY send any certificate of the appropriate
1685 // ClientCertificateType, unless there is some external arrangement to
1686 // the contrary.
1687
1688 var rsaAvail, ecdsaAvail bool
Nick Harperb41d2e42016-07-01 17:50:32 -04001689 if !certReq.hasRequestContext {
1690 for _, certType := range certReq.certificateTypes {
1691 switch certType {
1692 case CertTypeRSASign:
1693 rsaAvail = true
1694 case CertTypeECDSASign:
1695 ecdsaAvail = true
1696 }
David Benjamina6f82632016-07-01 18:44:02 -04001697 }
1698 }
1699
1700 // We need to search our list of client certs for one
1701 // where SignatureAlgorithm is RSA and the Issuer is in
1702 // certReq.certificateAuthorities
1703findCert:
1704 for i, chain := range c.config.Certificates {
Nick Harperb41d2e42016-07-01 17:50:32 -04001705 if !certReq.hasRequestContext && !rsaAvail && !ecdsaAvail {
David Benjamina6f82632016-07-01 18:44:02 -04001706 continue
1707 }
1708
1709 // Ensure the private key supports one of the advertised
1710 // signature algorithms.
1711 if certReq.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001712 if _, err := selectSignatureAlgorithm(c.vers, chain.PrivateKey, c.config, certReq.signatureAlgorithms); err != nil {
David Benjamina6f82632016-07-01 18:44:02 -04001713 continue
1714 }
1715 }
1716
1717 for j, cert := range chain.Certificate {
1718 x509Cert := chain.Leaf
1719 // parse the certificate if this isn't the leaf
1720 // node, or if chain.Leaf was nil
1721 if j != 0 || x509Cert == nil {
1722 var err error
1723 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
1724 c.sendAlert(alertInternalError)
1725 return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
1726 }
1727 }
1728
Nick Harperb41d2e42016-07-01 17:50:32 -04001729 if !certReq.hasRequestContext {
1730 switch {
1731 case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
1732 case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
David Benjamind768c5d2017-03-28 18:28:44 -05001733 case ecdsaAvail && isEd25519Certificate(x509Cert):
Nick Harperb41d2e42016-07-01 17:50:32 -04001734 default:
1735 continue findCert
1736 }
David Benjamina6f82632016-07-01 18:44:02 -04001737 }
1738
Adam Langley2ff79332017-02-28 13:45:39 -08001739 if expected := c.config.Bugs.ExpectCertificateReqNames; expected != nil {
1740 if !eqByteSlices(expected, certReq.certificateAuthorities) {
1741 return nil, fmt.Errorf("tls: CertificateRequest names differed, got %#v but expected %#v", certReq.certificateAuthorities, expected)
David Benjamina6f82632016-07-01 18:44:02 -04001742 }
1743 }
Adam Langley2ff79332017-02-28 13:45:39 -08001744
1745 return &chain, nil
David Benjamina6f82632016-07-01 18:44:02 -04001746 }
1747 }
1748
1749 return nil, nil
1750}
1751
Adam Langley95c29f32014-06-20 12:00:00 -07001752// clientSessionCacheKey returns a key used to cache sessionTickets that could
1753// be used to resume previously negotiated TLS sessions with a server.
1754func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
1755 if len(config.ServerName) > 0 {
1756 return config.ServerName
1757 }
1758 return serverAddr.String()
1759}
1760
David Benjaminfa055a22014-09-15 16:51:51 -04001761// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
1762// given list of possible protocols and a list of the preference order. The
1763// first list must not be empty. It returns the resulting protocol and flag
Adam Langley95c29f32014-06-20 12:00:00 -07001764// indicating if the fallback case was reached.
David Benjaminfa055a22014-09-15 16:51:51 -04001765func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
1766 for _, s := range preferenceProtos {
1767 for _, c := range protos {
Adam Langley95c29f32014-06-20 12:00:00 -07001768 if s == c {
1769 return s, false
1770 }
1771 }
1772 }
1773
David Benjaminfa055a22014-09-15 16:51:51 -04001774 return protos[0], true
Adam Langley95c29f32014-06-20 12:00:00 -07001775}
David Benjamind30a9902014-08-24 01:44:23 -04001776
1777// writeIntPadded writes x into b, padded up with leading zeros as
1778// needed.
1779func writeIntPadded(b []byte, x *big.Int) {
1780 for i := range b {
1781 b[i] = 0
1782 }
1783 xb := x.Bytes()
1784 copy(b[len(b)-len(xb):], xb)
1785}
Steven Valdeza833c352016-11-01 13:39:36 -04001786
1787func generatePSKBinders(hello *clientHelloMsg, pskCipherSuite *cipherSuite, psk, transcript []byte, config *Config) {
1788 if config.Bugs.SendNoPSKBinder {
1789 return
1790 }
1791
1792 binderLen := pskCipherSuite.hash().Size()
1793 if config.Bugs.SendShortPSKBinder {
1794 binderLen--
1795 }
1796
David Benjaminaedf3032016-12-01 16:47:56 -05001797 numBinders := 1
1798 if config.Bugs.SendExtraPSKBinder {
1799 numBinders++
1800 }
1801
Steven Valdeza833c352016-11-01 13:39:36 -04001802 // Fill hello.pskBinders with appropriate length arrays of zeros so the
1803 // length prefixes are correct when computing the binder over the truncated
1804 // ClientHello message.
David Benjaminaedf3032016-12-01 16:47:56 -05001805 hello.pskBinders = make([][]byte, numBinders)
1806 for i := range hello.pskBinders {
Steven Valdeza833c352016-11-01 13:39:36 -04001807 hello.pskBinders[i] = make([]byte, binderLen)
1808 }
1809
1810 helloBytes := hello.marshal()
1811 binderSize := len(hello.pskBinders)*(binderLen+1) + 2
1812 truncatedHello := helloBytes[:len(helloBytes)-binderSize]
1813 binder := computePSKBinder(psk, resumptionPSKBinderLabel, pskCipherSuite, transcript, truncatedHello)
1814 if config.Bugs.SendShortPSKBinder {
1815 binder = binder[:binderLen]
1816 }
1817 if config.Bugs.SendInvalidPSKBinder {
1818 binder[0] ^= 1
1819 }
1820
1821 for i := range hello.pskBinders {
1822 hello.pskBinders[i] = binder
1823 }
1824
1825 hello.raw = nil
1826}