blob: c531a281be20ffb05f1056824cd6a9ca21e47bdb [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
38func (c *Conn) clientHandshake() error {
39 if c.config == nil {
40 c.config = defaultConfig()
41 }
42
43 if len(c.config.ServerName) == 0 && !c.config.InsecureSkipVerify {
44 return errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
45 }
46
David Benjamin83c0bc92014-08-04 01:23:53 -040047 c.sendHandshakeSeq = 0
48 c.recvHandshakeSeq = 0
49
David Benjaminfa055a22014-09-15 16:51:51 -040050 nextProtosLength := 0
51 for _, proto := range c.config.NextProtos {
Adam Langleyefb0e162015-07-09 11:35:04 -070052 if l := len(proto); l > 255 {
David Benjaminfa055a22014-09-15 16:51:51 -040053 return errors.New("tls: invalid NextProtos value")
54 } else {
55 nextProtosLength += 1 + l
56 }
57 }
58 if nextProtosLength > 0xffff {
59 return errors.New("tls: NextProtos values too large")
60 }
61
Steven Valdezfdd10992016-09-15 16:27:05 -040062 minVersion := c.config.minVersion(c.isDTLS)
David Benjamin3c6a1ea2016-09-26 18:30:05 -040063 maxVersion := c.config.maxVersion(c.isDTLS)
Adam Langley95c29f32014-06-20 12:00:00 -070064 hello := &clientHelloMsg{
David Benjaminca6c8262014-11-15 19:06:08 -050065 isDTLS: c.isDTLS,
David Benjamin3c6a1ea2016-09-26 18:30:05 -040066 vers: versionToWire(maxVersion, c.isDTLS),
David Benjaminca6c8262014-11-15 19:06:08 -050067 compressionMethods: []uint8{compressionNone},
68 random: make([]byte, 32),
David Benjamin53210cb2016-11-16 09:01:48 +090069 ocspStapling: !c.config.Bugs.NoOCSPStapling,
70 sctListSupported: !c.config.Bugs.NoSignedCertificateTimestamps,
David Benjaminca6c8262014-11-15 19:06:08 -050071 serverName: c.config.ServerName,
72 supportedCurves: c.config.curvePreferences(),
Steven Valdeza833c352016-11-01 13:39:36 -040073 pskKEModes: []byte{pskDHEKEMode},
David Benjaminca6c8262014-11-15 19:06:08 -050074 supportedPoints: []uint8{pointFormatUncompressed},
75 nextProtoNeg: len(c.config.NextProtos) > 0,
76 secureRenegotiation: []byte{},
77 alpnProtocols: c.config.NextProtos,
78 duplicateExtension: c.config.Bugs.DuplicateExtension,
79 channelIDSupported: c.config.ChannelID != nil,
Steven Valdeza833c352016-11-01 13:39:36 -040080 npnAfterAlpn: c.config.Bugs.SwapNPNAndALPN,
Steven Valdezfdd10992016-09-15 16:27:05 -040081 extendedMasterSecret: maxVersion >= VersionTLS10,
David Benjaminca6c8262014-11-15 19:06:08 -050082 srtpProtectionProfiles: c.config.SRTPProtectionProfiles,
83 srtpMasterKeyIdentifier: c.config.Bugs.SRTPMasterKeyIdentifer,
Adam Langley09505632015-07-30 18:10:13 -070084 customExtension: c.config.Bugs.CustomExtension,
Steven Valdeza833c352016-11-01 13:39:36 -040085 pskBinderFirst: c.config.Bugs.PSKBinderFirst,
Adam Langley95c29f32014-06-20 12:00:00 -070086 }
87
David Benjamin163c9562016-08-29 23:14:17 -040088 disableEMS := c.config.Bugs.NoExtendedMasterSecret
89 if c.cipherSuite != nil {
90 disableEMS = c.config.Bugs.NoExtendedMasterSecretOnRenegotiation
91 }
92
93 if disableEMS {
Adam Langley75712922014-10-10 16:23:43 -070094 hello.extendedMasterSecret = false
95 }
96
David Benjamin55a43642015-04-20 14:45:55 -040097 if c.config.Bugs.NoSupportedCurves {
98 hello.supportedCurves = nil
99 }
100
Steven Valdeza833c352016-11-01 13:39:36 -0400101 if len(c.config.Bugs.SendPSKKeyExchangeModes) != 0 {
102 hello.pskKEModes = c.config.Bugs.SendPSKKeyExchangeModes
103 }
104
David Benjaminc241d792016-09-09 10:34:20 -0400105 if c.config.Bugs.SendCompressionMethods != nil {
106 hello.compressionMethods = c.config.Bugs.SendCompressionMethods
107 }
108
David Benjamina81967b2016-12-22 09:16:57 -0500109 if c.config.Bugs.SendSupportedPointFormats != nil {
110 hello.supportedPoints = c.config.Bugs.SendSupportedPointFormats
111 }
112
Adam Langley2ae77d22014-10-28 17:29:33 -0700113 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
114 if c.config.Bugs.BadRenegotiationInfo {
115 hello.secureRenegotiation = append(hello.secureRenegotiation, c.clientVerify...)
116 hello.secureRenegotiation[0] ^= 0x80
117 } else {
118 hello.secureRenegotiation = c.clientVerify
119 }
120 }
121
David Benjamin3e052de2015-11-25 20:10:31 -0500122 if c.noRenegotiationInfo() {
David Benjaminca6554b2014-11-08 12:31:52 -0500123 hello.secureRenegotiation = nil
124 }
125
Nick Harperb41d2e42016-07-01 17:50:32 -0400126 var keyShares map[CurveID]ecdhCurve
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400127 if maxVersion >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -0400128 keyShares = make(map[CurveID]ecdhCurve)
Nick Harperdcfbc672016-07-16 17:47:31 +0200129 hello.hasKeyShares = true
David Benjamin7e1f9842016-09-20 19:24:40 -0400130 hello.trailingKeyShareData = c.config.Bugs.TrailingKeyShareData
Nick Harperdcfbc672016-07-16 17:47:31 +0200131 curvesToSend := c.config.defaultCurves()
Nick Harperb41d2e42016-07-01 17:50:32 -0400132 for _, curveID := range hello.supportedCurves {
Nick Harperdcfbc672016-07-16 17:47:31 +0200133 if !curvesToSend[curveID] {
134 continue
135 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400136 curve, ok := curveForCurveID(curveID)
137 if !ok {
138 continue
139 }
140 publicKey, err := curve.offer(c.config.rand())
141 if err != nil {
142 return err
143 }
Steven Valdez0ee2e112016-07-15 06:51:15 -0400144
145 if c.config.Bugs.SendCurve != 0 {
146 curveID = c.config.Bugs.SendCurve
147 }
148 if c.config.Bugs.InvalidECDHPoint {
149 publicKey[0] ^= 0xff
150 }
151
Nick Harperb41d2e42016-07-01 17:50:32 -0400152 hello.keyShares = append(hello.keyShares, keyShareEntry{
153 group: curveID,
154 keyExchange: publicKey,
155 })
156 keyShares[curveID] = curve
Steven Valdez143e8b32016-07-11 13:19:03 -0400157
158 if c.config.Bugs.DuplicateKeyShares {
159 hello.keyShares = append(hello.keyShares, hello.keyShares[len(hello.keyShares)-1])
160 }
161 }
162
163 if c.config.Bugs.MissingKeyShare {
Steven Valdez5440fe02016-07-18 12:40:30 -0400164 hello.hasKeyShares = false
Nick Harperb41d2e42016-07-01 17:50:32 -0400165 }
166 }
167
Adam Langley95c29f32014-06-20 12:00:00 -0700168 possibleCipherSuites := c.config.cipherSuites()
169 hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
170
171NextCipherSuite:
172 for _, suiteId := range possibleCipherSuites {
173 for _, suite := range cipherSuites {
174 if suite.id != suiteId {
175 continue
176 }
David Benjamin5ecb88b2016-10-04 17:51:35 -0400177 // Don't advertise TLS 1.2-only cipher suites unless
178 // we're attempting TLS 1.2.
179 if maxVersion < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
180 continue
181 }
182 // Don't advertise non-DTLS cipher suites in DTLS.
183 if c.isDTLS && suite.flags&suiteNoDTLS != 0 {
184 continue
David Benjamin83c0bc92014-08-04 01:23:53 -0400185 }
Adam Langley95c29f32014-06-20 12:00:00 -0700186 hello.cipherSuites = append(hello.cipherSuites, suiteId)
187 continue NextCipherSuite
188 }
189 }
190
David Benjamin5ecb88b2016-10-04 17:51:35 -0400191 if c.config.Bugs.AdvertiseAllConfiguredCiphers {
192 hello.cipherSuites = possibleCipherSuites
193 }
194
Adam Langley5021b222015-06-12 18:27:58 -0700195 if c.config.Bugs.SendRenegotiationSCSV {
196 hello.cipherSuites = append(hello.cipherSuites, renegotiationSCSV)
197 }
198
David Benjaminbef270a2014-08-02 04:22:02 -0400199 if c.config.Bugs.SendFallbackSCSV {
200 hello.cipherSuites = append(hello.cipherSuites, fallbackSCSV)
201 }
202
Adam Langley95c29f32014-06-20 12:00:00 -0700203 _, err := io.ReadFull(c.config.rand(), hello.random)
204 if err != nil {
205 c.sendAlert(alertInternalError)
206 return errors.New("tls: short read from Rand: " + err.Error())
207 }
208
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400209 if maxVersion >= VersionTLS12 && !c.config.Bugs.NoSignatureAlgorithms {
David Benjamin7a41d372016-07-09 11:21:54 -0700210 hello.signatureAlgorithms = c.config.verifySignatureAlgorithms()
Adam Langley95c29f32014-06-20 12:00:00 -0700211 }
212
213 var session *ClientSessionState
214 var cacheKey string
215 sessionCache := c.config.ClientSessionCache
Adam Langley95c29f32014-06-20 12:00:00 -0700216
217 if sessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500218 hello.ticketSupported = !c.config.SessionTicketsDisabled
Adam Langley95c29f32014-06-20 12:00:00 -0700219
220 // Try to resume a previously negotiated TLS session, if
221 // available.
222 cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
Nick Harper0b3625b2016-07-25 16:16:28 -0700223 // TODO(nharper): Support storing more than one session
224 // ticket for TLS 1.3.
Adam Langley95c29f32014-06-20 12:00:00 -0700225 candidateSession, ok := sessionCache.Get(cacheKey)
226 if ok {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500227 ticketOk := !c.config.SessionTicketsDisabled || candidateSession.sessionTicket == nil
228
Adam Langley95c29f32014-06-20 12:00:00 -0700229 // Check that the ciphersuite/version used for the
230 // previous session are still valid.
231 cipherSuiteOk := false
David Benjamin2b02f4b2016-11-16 16:11:47 +0900232 if candidateSession.vers <= VersionTLS12 {
233 for _, id := range hello.cipherSuites {
234 if id == candidateSession.cipherSuite {
235 cipherSuiteOk = true
236 break
237 }
Adam Langley95c29f32014-06-20 12:00:00 -0700238 }
David Benjamin2b02f4b2016-11-16 16:11:47 +0900239 } else {
240 // TLS 1.3 allows the cipher to change on
241 // resumption.
242 cipherSuiteOk = true
Adam Langley95c29f32014-06-20 12:00:00 -0700243 }
244
Steven Valdezfdd10992016-09-15 16:27:05 -0400245 versOk := candidateSession.vers >= minVersion &&
246 candidateSession.vers <= maxVersion
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500247 if ticketOk && versOk && cipherSuiteOk {
Adam Langley95c29f32014-06-20 12:00:00 -0700248 session = candidateSession
249 }
250 }
251 }
252
Steven Valdeza833c352016-11-01 13:39:36 -0400253 var pskCipherSuite *cipherSuite
Nick Harper0b3625b2016-07-25 16:16:28 -0700254 if session != nil && c.config.time().Before(session.ticketExpiration) {
David Benjamind5a4ecb2016-07-18 01:17:13 +0200255 ticket := session.sessionTicket
David Benjamin4199b0d2016-11-01 13:58:25 -0400256 if c.config.Bugs.FilterTicket != nil && len(ticket) > 0 {
257 // Copy the ticket so FilterTicket may act in-place.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200258 ticket = make([]byte, len(session.sessionTicket))
259 copy(ticket, session.sessionTicket)
David Benjamin4199b0d2016-11-01 13:58:25 -0400260
261 ticket, err = c.config.Bugs.FilterTicket(ticket)
262 if err != nil {
263 return err
Adam Langley38311732014-10-16 19:04:35 -0700264 }
David Benjamind5a4ecb2016-07-18 01:17:13 +0200265 }
266
David Benjamin405da482016-08-08 17:25:07 -0400267 if session.vers >= VersionTLS13 || c.config.Bugs.SendBothTickets {
Steven Valdeza833c352016-11-01 13:39:36 -0400268 pskCipherSuite = cipherSuiteFromID(session.cipherSuite)
269 if pskCipherSuite == nil {
270 return errors.New("tls: client session cache has invalid cipher suite")
271 }
Nick Harper0b3625b2016-07-25 16:16:28 -0700272 // TODO(nharper): Support sending more
273 // than one PSK identity.
Steven Valdeza833c352016-11-01 13:39:36 -0400274 ticketAge := uint32(c.config.time().Sub(session.ticketCreationTime) / time.Millisecond)
David Benjamin35ac5b72017-03-03 15:05:56 -0500275 if c.config.Bugs.SendTicketAge != 0 {
276 ticketAge = uint32(c.config.Bugs.SendTicketAge / time.Millisecond)
277 }
Steven Valdez5b986082016-09-01 12:29:49 -0400278 psk := pskIdentity{
Steven Valdeza833c352016-11-01 13:39:36 -0400279 ticket: ticket,
280 obfuscatedTicketAge: session.ticketAgeAdd + ticketAge,
Nick Harper0b3625b2016-07-25 16:16:28 -0700281 }
Steven Valdez5b986082016-09-01 12:29:49 -0400282 hello.pskIdentities = []pskIdentity{psk}
Steven Valdezaf3b8a92016-11-01 12:49:22 -0400283
284 if c.config.Bugs.ExtraPSKIdentity {
285 hello.pskIdentities = append(hello.pskIdentities, psk)
286 }
David Benjamin405da482016-08-08 17:25:07 -0400287 }
288
289 if session.vers < VersionTLS13 || c.config.Bugs.SendBothTickets {
290 if ticket != nil {
291 hello.sessionTicket = ticket
292 // A random session ID is used to detect when the
293 // server accepted the ticket and is resuming a session
294 // (see RFC 5077).
295 sessionIdLen := 16
David Benjamind4c349b2017-02-09 14:07:17 -0500296 if c.config.Bugs.TicketSessionIDLength != 0 {
297 sessionIdLen = c.config.Bugs.TicketSessionIDLength
298 }
299 if c.config.Bugs.EmptyTicketSessionID {
300 sessionIdLen = 0
David Benjamin405da482016-08-08 17:25:07 -0400301 }
302 hello.sessionId = make([]byte, sessionIdLen)
303 if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
304 c.sendAlert(alertInternalError)
305 return errors.New("tls: short read from Rand: " + err.Error())
306 }
307 } else {
308 hello.sessionId = session.sessionId
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500309 }
Adam Langley95c29f32014-06-20 12:00:00 -0700310 }
311 }
312
Steven Valdezfdd10992016-09-15 16:27:05 -0400313 if maxVersion == VersionTLS13 && !c.config.Bugs.OmitSupportedVersions {
314 if hello.vers >= VersionTLS13 {
315 hello.vers = VersionTLS12
316 }
317 for version := maxVersion; version >= minVersion; version-- {
318 hello.supportedVersions = append(hello.supportedVersions, versionToWire(version, c.isDTLS))
319 }
320 }
321
322 if len(c.config.Bugs.SendSupportedVersions) > 0 {
323 hello.supportedVersions = c.config.Bugs.SendSupportedVersions
324 }
325
David Benjamineed24012016-08-13 19:26:00 -0400326 if c.config.Bugs.SendClientVersion != 0 {
327 hello.vers = c.config.Bugs.SendClientVersion
328 }
329
David Benjamin75f99142016-11-12 12:36:06 +0900330 if c.config.Bugs.SendCipherSuites != nil {
331 hello.cipherSuites = c.config.Bugs.SendCipherSuites
332 }
333
Nick Harperf2511f12016-12-06 16:02:31 -0800334 var sendEarlyData bool
Steven Valdez2d850622017-01-11 11:34:52 -0500335 if len(hello.pskIdentities) > 0 && c.config.Bugs.SendEarlyData != nil {
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500336 hello.hasEarlyData = true
Nick Harperf2511f12016-12-06 16:02:31 -0800337 sendEarlyData = true
338 }
339 if c.config.Bugs.SendFakeEarlyDataLength > 0 {
340 hello.hasEarlyData = true
341 }
342 if c.config.Bugs.OmitEarlyDataExtension {
343 hello.hasEarlyData = false
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500344 }
345
David Benjamind86c7672014-08-02 04:07:12 -0400346 var helloBytes []byte
347 if c.config.Bugs.SendV2ClientHello {
David Benjamin94d701b2014-11-30 13:54:41 -0500348 // Test that the peer left-pads random.
349 hello.random[0] = 0
David Benjamind86c7672014-08-02 04:07:12 -0400350 v2Hello := &v2ClientHelloMsg{
351 vers: hello.vers,
352 cipherSuites: hello.cipherSuites,
353 // No session resumption for V2ClientHello.
354 sessionId: nil,
David Benjamin94d701b2014-11-30 13:54:41 -0500355 challenge: hello.random[1:],
David Benjamind86c7672014-08-02 04:07:12 -0400356 }
357 helloBytes = v2Hello.marshal()
358 c.writeV2Record(helloBytes)
359 } else {
Steven Valdeza833c352016-11-01 13:39:36 -0400360 if len(hello.pskIdentities) > 0 {
361 generatePSKBinders(hello, pskCipherSuite, session.masterSecret, []byte{}, c.config)
362 }
David Benjamind86c7672014-08-02 04:07:12 -0400363 helloBytes = hello.marshal()
Steven Valdeza833c352016-11-01 13:39:36 -0400364
David Benjamin7964b182016-07-14 23:36:30 -0400365 if c.config.Bugs.PartialClientFinishedWithClientHello {
366 // Include one byte of Finished. We can compute it
367 // without completing the handshake. This assumes we
368 // negotiate TLS 1.3 with no HelloRetryRequest or
369 // CertificateRequest.
370 toWrite := make([]byte, 0, len(helloBytes)+1)
371 toWrite = append(toWrite, helloBytes...)
372 toWrite = append(toWrite, typeFinished)
373 c.writeRecord(recordTypeHandshake, toWrite)
374 } else {
375 c.writeRecord(recordTypeHandshake, helloBytes)
376 }
David Benjamind86c7672014-08-02 04:07:12 -0400377 }
David Benjamin582ba042016-07-07 12:33:25 -0700378 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700379
David Benjamin83f90402015-01-27 01:09:43 -0500380 if err := c.simulatePacketLoss(nil); err != nil {
381 return err
382 }
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500383 if c.config.Bugs.SendEarlyAlert {
384 c.sendAlert(alertHandshakeFailure)
385 }
Nick Harperf2511f12016-12-06 16:02:31 -0800386 if c.config.Bugs.SendFakeEarlyDataLength > 0 {
387 c.sendFakeEarlyData(c.config.Bugs.SendFakeEarlyDataLength)
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500388 }
Nick Harperf2511f12016-12-06 16:02:31 -0800389
390 // Derive early write keys and set Conn state to allow early writes.
391 if sendEarlyData {
392 finishedHash := newFinishedHash(session.vers, pskCipherSuite)
393 finishedHash.addEntropy(session.masterSecret)
394 finishedHash.Write(helloBytes)
395 earlyTrafficSecret := finishedHash.deriveSecret(earlyTrafficLabel)
396 c.out.useTrafficSecret(session.vers, pskCipherSuite, earlyTrafficSecret, clientWrite)
Nick Harperf2511f12016-12-06 16:02:31 -0800397 for _, earlyData := range c.config.Bugs.SendEarlyData {
398 if _, err := c.writeRecord(recordTypeApplicationData, earlyData); err != nil {
399 return err
400 }
401 }
402 }
403
Adam Langley95c29f32014-06-20 12:00:00 -0700404 msg, err := c.readHandshake()
405 if err != nil {
406 return err
407 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400408
409 if c.isDTLS {
410 helloVerifyRequest, ok := msg.(*helloVerifyRequestMsg)
411 if ok {
David Benjaminda4789e2016-10-31 19:23:34 -0400412 if helloVerifyRequest.vers != versionToWire(VersionTLS10, c.isDTLS) {
David Benjamin8bc38f52014-08-16 12:07:27 -0400413 // Per RFC 6347, the version field in
414 // HelloVerifyRequest SHOULD be always DTLS
415 // 1.0. Enforce this for testing purposes.
416 return errors.New("dtls: bad HelloVerifyRequest version")
417 }
418
David Benjamin83c0bc92014-08-04 01:23:53 -0400419 hello.raw = nil
420 hello.cookie = helloVerifyRequest.cookie
421 helloBytes = hello.marshal()
422 c.writeRecord(recordTypeHandshake, helloBytes)
David Benjamin582ba042016-07-07 12:33:25 -0700423 c.flushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400424
David Benjamin83f90402015-01-27 01:09:43 -0500425 if err := c.simulatePacketLoss(nil); err != nil {
426 return err
427 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400428 msg, err = c.readHandshake()
429 if err != nil {
430 return err
431 }
432 }
433 }
434
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400435 var serverWireVersion uint16
Nick Harperdcfbc672016-07-16 17:47:31 +0200436 switch m := msg.(type) {
437 case *helloRetryRequestMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400438 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200439 case *serverHelloMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400440 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200441 default:
442 c.sendAlert(alertUnexpectedMessage)
443 return fmt.Errorf("tls: received unexpected message of type %T when waiting for HelloRetryRequest or ServerHello", msg)
444 }
445
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400446 serverVersion, ok := wireToVersion(serverWireVersion, c.isDTLS)
447 if ok {
Steven Valdezfdd10992016-09-15 16:27:05 -0400448 ok = c.config.isSupportedVersion(serverVersion, c.isDTLS)
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400449 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200450 if !ok {
451 c.sendAlert(alertProtocolVersion)
452 return fmt.Errorf("tls: server selected unsupported protocol version %x", c.vers)
453 }
Steven Valdezfdd10992016-09-15 16:27:05 -0400454 c.vers = serverVersion
Nick Harperdcfbc672016-07-16 17:47:31 +0200455 c.haveVers = true
456
457 helloRetryRequest, haveHelloRetryRequest := msg.(*helloRetryRequestMsg)
458 var secondHelloBytes []byte
459 if haveHelloRetryRequest {
Nick Harperf2511f12016-12-06 16:02:31 -0800460 c.out.resetCipher()
David Benjamin3baa6e12016-10-07 21:10:38 -0400461 if len(helloRetryRequest.cookie) > 0 {
462 hello.tls13Cookie = helloRetryRequest.cookie
463 }
464
Steven Valdez5440fe02016-07-18 12:40:30 -0400465 if c.config.Bugs.MisinterpretHelloRetryRequestCurve != 0 {
David Benjamin3baa6e12016-10-07 21:10:38 -0400466 helloRetryRequest.hasSelectedGroup = true
Steven Valdez5440fe02016-07-18 12:40:30 -0400467 helloRetryRequest.selectedGroup = c.config.Bugs.MisinterpretHelloRetryRequestCurve
468 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400469 if helloRetryRequest.hasSelectedGroup {
470 var hrrCurveFound bool
471 group := helloRetryRequest.selectedGroup
472 for _, curveID := range hello.supportedCurves {
473 if group == curveID {
474 hrrCurveFound = true
475 break
476 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200477 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400478 if !hrrCurveFound || keyShares[group] != nil {
479 c.sendAlert(alertHandshakeFailure)
480 return errors.New("tls: received invalid HelloRetryRequest")
481 }
482 curve, ok := curveForCurveID(group)
483 if !ok {
484 return errors.New("tls: Unable to get curve requested in HelloRetryRequest")
485 }
486 publicKey, err := curve.offer(c.config.rand())
487 if err != nil {
488 return err
489 }
490 keyShares[group] = curve
Steven Valdeza833c352016-11-01 13:39:36 -0400491 hello.keyShares = []keyShareEntry{{
David Benjamin3baa6e12016-10-07 21:10:38 -0400492 group: group,
493 keyExchange: publicKey,
Steven Valdeza833c352016-11-01 13:39:36 -0400494 }}
Nick Harperdcfbc672016-07-16 17:47:31 +0200495 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200496
Steven Valdez5440fe02016-07-18 12:40:30 -0400497 if c.config.Bugs.SecondClientHelloMissingKeyShare {
498 hello.hasKeyShares = false
499 }
500
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500501 hello.hasEarlyData = c.config.Bugs.SendEarlyDataOnSecondClientHello
Nick Harperdcfbc672016-07-16 17:47:31 +0200502 hello.raw = nil
503
Steven Valdeza833c352016-11-01 13:39:36 -0400504 if len(hello.pskIdentities) > 0 {
505 generatePSKBinders(hello, pskCipherSuite, session.masterSecret, append(helloBytes, helloRetryRequest.marshal()...), c.config)
506 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200507 secondHelloBytes = hello.marshal()
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500508
509 if c.config.Bugs.InterleaveEarlyData {
510 c.sendFakeEarlyData(4)
511 c.writeRecord(recordTypeHandshake, secondHelloBytes[:16])
512 c.sendFakeEarlyData(4)
513 c.writeRecord(recordTypeHandshake, secondHelloBytes[16:])
514 } else {
515 c.writeRecord(recordTypeHandshake, secondHelloBytes)
516 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200517 c.flushHandshake()
518
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500519 if c.config.Bugs.SendEarlyDataOnSecondClientHello {
520 c.sendFakeEarlyData(4)
521 }
522
Nick Harperdcfbc672016-07-16 17:47:31 +0200523 msg, err = c.readHandshake()
524 if err != nil {
525 return err
526 }
527 }
528
Adam Langley95c29f32014-06-20 12:00:00 -0700529 serverHello, ok := msg.(*serverHelloMsg)
530 if !ok {
531 c.sendAlert(alertUnexpectedMessage)
532 return unexpectedMessageError(serverHello, msg)
533 }
534
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400535 if serverWireVersion != serverHello.vers {
Adam Langley95c29f32014-06-20 12:00:00 -0700536 c.sendAlert(alertProtocolVersion)
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400537 return fmt.Errorf("tls: server sent non-matching version %x vs %x", serverWireVersion, serverHello.vers)
Adam Langley95c29f32014-06-20 12:00:00 -0700538 }
Adam Langley95c29f32014-06-20 12:00:00 -0700539
Nick Harper85f20c22016-07-04 10:11:59 -0700540 // Check for downgrade signals in the server random, per
David Benjamina128a552016-10-13 14:26:33 -0400541 // draft-ietf-tls-tls13-16, section 4.1.3.
Nick Harper85f20c22016-07-04 10:11:59 -0700542 if c.vers <= VersionTLS12 && c.config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400543 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS13) {
Nick Harper85f20c22016-07-04 10:11:59 -0700544 c.sendAlert(alertProtocolVersion)
545 return errors.New("tls: downgrade from TLS 1.3 detected")
546 }
547 }
548 if c.vers <= VersionTLS11 && c.config.maxVersion(c.isDTLS) >= VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400549 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS12) {
Nick Harper85f20c22016-07-04 10:11:59 -0700550 c.sendAlert(alertProtocolVersion)
551 return errors.New("tls: downgrade from TLS 1.2 detected")
552 }
553 }
554
Nick Harper0b3625b2016-07-25 16:16:28 -0700555 suite := mutualCipherSuite(hello.cipherSuites, serverHello.cipherSuite)
Adam Langley95c29f32014-06-20 12:00:00 -0700556 if suite == nil {
557 c.sendAlert(alertHandshakeFailure)
558 return fmt.Errorf("tls: server selected an unsupported cipher suite")
559 }
560
David Benjamin3baa6e12016-10-07 21:10:38 -0400561 if haveHelloRetryRequest && helloRetryRequest.hasSelectedGroup && helloRetryRequest.selectedGroup != serverHello.keyShare.group {
Nick Harperdcfbc672016-07-16 17:47:31 +0200562 c.sendAlert(alertHandshakeFailure)
563 return errors.New("tls: ServerHello parameters did not match HelloRetryRequest")
564 }
565
Adam Langley95c29f32014-06-20 12:00:00 -0700566 hs := &clientHandshakeState{
567 c: c,
568 serverHello: serverHello,
569 hello: hello,
570 suite: suite,
571 finishedHash: newFinishedHash(c.vers, suite),
Nick Harperb41d2e42016-07-01 17:50:32 -0400572 keyShares: keyShares,
Adam Langley95c29f32014-06-20 12:00:00 -0700573 session: session,
574 }
575
David Benjamin83c0bc92014-08-04 01:23:53 -0400576 hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1)
Nick Harperdcfbc672016-07-16 17:47:31 +0200577 if haveHelloRetryRequest {
578 hs.writeServerHash(helloRetryRequest.marshal())
579 hs.writeClientHash(secondHelloBytes)
580 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400581 hs.writeServerHash(hs.serverHello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700582
David Benjamin8d315d72016-07-18 01:03:18 +0200583 if c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -0400584 if err := hs.doTLS13Handshake(); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700585 return err
586 }
587 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400588 if c.config.Bugs.EarlyChangeCipherSpec > 0 {
589 hs.establishKeys()
590 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
591 }
592
593 if hs.serverHello.compressionMethod != compressionNone {
594 c.sendAlert(alertUnexpectedMessage)
595 return errors.New("tls: server selected unsupported compression format")
596 }
597
598 err = hs.processServerExtensions(&serverHello.extensions)
599 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700600 return err
601 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400602
603 isResume, err := hs.processServerHello()
604 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700605 return err
606 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400607
608 if isResume {
609 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
610 if err := hs.establishKeys(); err != nil {
611 return err
612 }
613 }
614 if err := hs.readSessionTicket(); err != nil {
615 return err
616 }
617 if err := hs.readFinished(c.firstFinished[:]); err != nil {
618 return err
619 }
620 if err := hs.sendFinished(nil, isResume); err != nil {
621 return err
622 }
623 } else {
624 if err := hs.doFullHandshake(); err != nil {
625 return err
626 }
627 if err := hs.establishKeys(); err != nil {
628 return err
629 }
630 if err := hs.sendFinished(c.firstFinished[:], isResume); err != nil {
631 return err
632 }
633 // Most retransmits are triggered by a timeout, but the final
634 // leg of the handshake is retransmited upon re-receiving a
635 // Finished.
636 if err := c.simulatePacketLoss(func() {
David Benjamin02edcd02016-07-27 17:40:37 -0400637 c.sendHandshakeSeq--
Nick Harperb41d2e42016-07-01 17:50:32 -0400638 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
639 c.flushHandshake()
640 }); err != nil {
641 return err
642 }
643 if err := hs.readSessionTicket(); err != nil {
644 return err
645 }
646 if err := hs.readFinished(nil); err != nil {
647 return err
648 }
Adam Langley95c29f32014-06-20 12:00:00 -0700649 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400650
651 if sessionCache != nil && hs.session != nil && session != hs.session {
652 if c.config.Bugs.RequireSessionTickets && len(hs.session.sessionTicket) == 0 {
653 return errors.New("tls: new session used session IDs instead of tickets")
654 }
655 sessionCache.Put(cacheKey, hs.session)
David Benjamin83f90402015-01-27 01:09:43 -0500656 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400657
658 c.didResume = isResume
David Benjamin97a0a082016-07-13 17:57:35 -0400659 c.exporterSecret = hs.masterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700660 }
661
Adam Langley95c29f32014-06-20 12:00:00 -0700662 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400663 c.cipherSuite = suite
664 copy(c.clientRandom[:], hs.hello.random)
665 copy(c.serverRandom[:], hs.serverHello.random)
Paul Lietar4fac72e2015-09-09 13:44:55 +0100666
Adam Langley95c29f32014-06-20 12:00:00 -0700667 return nil
668}
669
Nick Harperb41d2e42016-07-01 17:50:32 -0400670func (hs *clientHandshakeState) doTLS13Handshake() error {
671 c := hs.c
672
673 // Once the PRF hash is known, TLS 1.3 does not require a handshake
674 // buffer.
675 hs.finishedHash.discardHandshakeBuffer()
676
677 zeroSecret := hs.finishedHash.zeroSecret()
678
679 // Resolve PSK and compute the early secret.
680 //
681 // TODO(davidben): This will need to be handled slightly earlier once
682 // 0-RTT is implemented.
Steven Valdez803c77a2016-09-06 14:13:43 -0400683 if hs.serverHello.hasPSKIdentity {
Nick Harper0b3625b2016-07-25 16:16:28 -0700684 // We send at most one PSK identity.
685 if hs.session == nil || hs.serverHello.pskIdentity != 0 {
686 c.sendAlert(alertUnknownPSKIdentity)
687 return errors.New("tls: server sent unknown PSK identity")
688 }
David Benjamin2b02f4b2016-11-16 16:11:47 +0900689 sessionCipher := cipherSuiteFromID(hs.session.cipherSuite)
690 if sessionCipher == nil || sessionCipher.hash() != hs.suite.hash() {
Nick Harper0b3625b2016-07-25 16:16:28 -0700691 c.sendAlert(alertHandshakeFailure)
David Benjamin2b02f4b2016-11-16 16:11:47 +0900692 return errors.New("tls: server resumed an invalid session for the cipher suite")
Nick Harper0b3625b2016-07-25 16:16:28 -0700693 }
David Benjamin48891ad2016-12-04 00:02:43 -0500694 hs.finishedHash.addEntropy(hs.session.masterSecret)
Nick Harper0b3625b2016-07-25 16:16:28 -0700695 c.didResume = true
Nick Harperb41d2e42016-07-01 17:50:32 -0400696 } else {
David Benjamin48891ad2016-12-04 00:02:43 -0500697 hs.finishedHash.addEntropy(zeroSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400698 }
699
Steven Valdeza833c352016-11-01 13:39:36 -0400700 if !hs.serverHello.hasKeyShare {
701 c.sendAlert(alertUnsupportedExtension)
702 return errors.New("tls: server omitted KeyShare on resumption.")
703 }
704
Nick Harperb41d2e42016-07-01 17:50:32 -0400705 // Resolve ECDHE and compute the handshake secret.
Steven Valdez803c77a2016-09-06 14:13:43 -0400706 if !c.config.Bugs.MissingKeyShare && !c.config.Bugs.SecondClientHelloMissingKeyShare {
Nick Harperb41d2e42016-07-01 17:50:32 -0400707 curve, ok := hs.keyShares[hs.serverHello.keyShare.group]
708 if !ok {
709 c.sendAlert(alertHandshakeFailure)
710 return errors.New("tls: server selected an unsupported group")
711 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400712 c.curveID = hs.serverHello.keyShare.group
Nick Harperb41d2e42016-07-01 17:50:32 -0400713
David Benjamin48891ad2016-12-04 00:02:43 -0500714 ecdheSecret, err := curve.finish(hs.serverHello.keyShare.keyExchange)
Nick Harperb41d2e42016-07-01 17:50:32 -0400715 if err != nil {
716 return err
717 }
David Benjamin48891ad2016-12-04 00:02:43 -0500718 hs.finishedHash.addEntropy(ecdheSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400719 } else {
David Benjamin48891ad2016-12-04 00:02:43 -0500720 hs.finishedHash.addEntropy(zeroSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400721 }
722
Nick Harperf2511f12016-12-06 16:02:31 -0800723 // Derive handshake traffic keys and switch read key to handshake
724 // traffic key.
David Benjamin48891ad2016-12-04 00:02:43 -0500725 clientHandshakeTrafficSecret := hs.finishedHash.deriveSecret(clientHandshakeTrafficLabel)
David Benjamin48891ad2016-12-04 00:02:43 -0500726 serverHandshakeTrafficSecret := hs.finishedHash.deriveSecret(serverHandshakeTrafficLabel)
Steven Valdeza833c352016-11-01 13:39:36 -0400727 c.in.useTrafficSecret(c.vers, hs.suite, serverHandshakeTrafficSecret, serverWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -0400728
729 msg, err := c.readHandshake()
730 if err != nil {
731 return err
732 }
733
734 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
735 if !ok {
736 c.sendAlert(alertUnexpectedMessage)
737 return unexpectedMessageError(encryptedExtensions, msg)
738 }
739 hs.writeServerHash(encryptedExtensions.marshal())
740
741 err = hs.processServerExtensions(&encryptedExtensions.extensions)
742 if err != nil {
743 return err
744 }
745
746 var chainToSend *Certificate
David Benjamin8d343b42016-07-09 14:26:01 -0700747 var certReq *certificateRequestMsg
Steven Valdeza833c352016-11-01 13:39:36 -0400748 if c.didResume {
Nick Harper0b3625b2016-07-25 16:16:28 -0700749 // Copy over authentication from the session.
750 c.peerCertificates = hs.session.serverCertificates
751 c.sctList = hs.session.sctList
752 c.ocspResponse = hs.session.ocspResponse
David Benjamin44b33bc2016-07-01 22:40:23 -0400753 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400754 msg, err := c.readHandshake()
755 if err != nil {
756 return err
757 }
758
David Benjamin8d343b42016-07-09 14:26:01 -0700759 var ok bool
760 certReq, ok = msg.(*certificateRequestMsg)
Nick Harperb41d2e42016-07-01 17:50:32 -0400761 if ok {
David Benjamin8a8349b2016-08-18 02:32:23 -0400762 if len(certReq.requestContext) != 0 {
763 return errors.New("tls: non-empty certificate request context sent in handshake")
764 }
765
David Benjaminb62d2872016-07-18 14:55:02 +0200766 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
767 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
768 }
769
Nick Harperb41d2e42016-07-01 17:50:32 -0400770 hs.writeServerHash(certReq.marshal())
Nick Harperb41d2e42016-07-01 17:50:32 -0400771
772 chainToSend, err = selectClientCertificate(c, certReq)
773 if err != nil {
774 return err
775 }
776
777 msg, err = c.readHandshake()
778 if err != nil {
779 return err
780 }
781 }
782
783 certMsg, ok := msg.(*certificateMsg)
784 if !ok {
785 c.sendAlert(alertUnexpectedMessage)
786 return unexpectedMessageError(certMsg, msg)
787 }
788 hs.writeServerHash(certMsg.marshal())
789
David Benjamin53210cb2016-11-16 09:01:48 +0900790 // Check for unsolicited extensions.
791 for i, cert := range certMsg.certificates {
792 if c.config.Bugs.NoOCSPStapling && cert.ocspResponse != nil {
793 c.sendAlert(alertUnsupportedExtension)
794 return errors.New("tls: unexpected OCSP response in the server certificate")
795 }
796 if c.config.Bugs.NoSignedCertificateTimestamps && cert.sctList != nil {
797 c.sendAlert(alertUnsupportedExtension)
798 return errors.New("tls: unexpected SCT list in the server certificate")
799 }
800 if i > 0 && c.config.Bugs.ExpectNoExtensionsOnIntermediate && (cert.ocspResponse != nil || cert.sctList != nil) {
801 c.sendAlert(alertUnsupportedExtension)
802 return errors.New("tls: unexpected extensions in the server certificate")
803 }
804 }
805
Nick Harperb41d2e42016-07-01 17:50:32 -0400806 if err := hs.verifyCertificates(certMsg); err != nil {
807 return err
808 }
809 leaf := c.peerCertificates[0]
Steven Valdeza833c352016-11-01 13:39:36 -0400810 c.ocspResponse = certMsg.certificates[0].ocspResponse
811 c.sctList = certMsg.certificates[0].sctList
812
Nick Harperb41d2e42016-07-01 17:50:32 -0400813 msg, err = c.readHandshake()
814 if err != nil {
815 return err
816 }
817 certVerifyMsg, ok := msg.(*certificateVerifyMsg)
818 if !ok {
819 c.sendAlert(alertUnexpectedMessage)
820 return unexpectedMessageError(certVerifyMsg, msg)
821 }
822
David Benjaminf74ec792016-07-13 21:18:49 -0400823 c.peerSignatureAlgorithm = certVerifyMsg.signatureAlgorithm
Nick Harperb41d2e42016-07-01 17:50:32 -0400824 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
David Benjamind768c5d2017-03-28 18:28:44 -0500825 err = verifyMessage(c.vers, getCertificatePublicKey(leaf), c.config, certVerifyMsg.signatureAlgorithm, input, certVerifyMsg.signature)
Nick Harperb41d2e42016-07-01 17:50:32 -0400826 if err != nil {
827 return err
828 }
829
830 hs.writeServerHash(certVerifyMsg.marshal())
831 }
832
833 msg, err = c.readHandshake()
834 if err != nil {
835 return err
836 }
837 serverFinished, ok := msg.(*finishedMsg)
838 if !ok {
839 c.sendAlert(alertUnexpectedMessage)
840 return unexpectedMessageError(serverFinished, msg)
841 }
842
Steven Valdezc4aa7272016-10-03 12:25:56 -0400843 verify := hs.finishedHash.serverSum(serverHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400844 if len(verify) != len(serverFinished.verifyData) ||
845 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
846 c.sendAlert(alertHandshakeFailure)
847 return errors.New("tls: server's Finished message was incorrect")
848 }
849
850 hs.writeServerHash(serverFinished.marshal())
851
852 // The various secrets do not incorporate the client's final leg, so
853 // derive them now before updating the handshake context.
David Benjamin48891ad2016-12-04 00:02:43 -0500854 hs.finishedHash.addEntropy(zeroSecret)
855 clientTrafficSecret := hs.finishedHash.deriveSecret(clientApplicationTrafficLabel)
856 serverTrafficSecret := hs.finishedHash.deriveSecret(serverApplicationTrafficLabel)
David Benjamincdb6fe92017-02-07 16:06:48 -0500857 c.exporterSecret = hs.finishedHash.deriveSecret(exporterLabel)
858
859 // Switch to application data keys on read. In particular, any alerts
860 // from the client certificate are read over these keys.
Nick Harper7cd0a972016-12-02 11:08:40 -0800861 c.in.useTrafficSecret(c.vers, hs.suite, serverTrafficSecret, serverWrite)
862
863 // If we're expecting 0.5-RTT messages from the server, read them
864 // now.
David Benjamin794cc592017-03-25 22:24:23 -0500865 if encryptedExtensions.extensions.hasEarlyData {
866 // BoringSSL will always send two tickets half-RTT when
867 // negotiating 0-RTT.
868 for i := 0; i < shimConfig.HalfRTTTickets; i++ {
869 msg, err := c.readHandshake()
870 if err != nil {
871 return fmt.Errorf("tls: error reading half-RTT ticket: %s", err)
872 }
873 newSessionTicket, ok := msg.(*newSessionTicketMsg)
874 if !ok {
875 return errors.New("tls: expected half-RTT ticket")
876 }
877 if err := c.processTLS13NewSessionTicket(newSessionTicket, hs.suite); err != nil {
878 return err
879 }
Nick Harper7cd0a972016-12-02 11:08:40 -0800880 }
David Benjamin794cc592017-03-25 22:24:23 -0500881 for _, expectedMsg := range c.config.Bugs.ExpectHalfRTTData {
882 if err := c.readRecord(recordTypeApplicationData); err != nil {
883 return err
884 }
885 if !bytes.Equal(c.input.data[c.input.off:], expectedMsg) {
886 return errors.New("ExpectHalfRTTData: did not get expected message")
887 }
888 c.in.freeBlock(c.input)
889 c.input = nil
Nick Harper7cd0a972016-12-02 11:08:40 -0800890 }
Nick Harper7cd0a972016-12-02 11:08:40 -0800891 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400892
Nick Harperf2511f12016-12-06 16:02:31 -0800893 // Send EndOfEarlyData and then switch write key to handshake
894 // traffic key.
David Benjamin32c89272017-03-26 13:54:21 -0500895 if c.out.cipher != nil && !c.config.Bugs.SkipEndOfEarlyData {
Steven Valdez681eb6a2016-12-19 13:19:29 -0500896 if c.config.Bugs.SendStrayEarlyHandshake {
897 helloRequest := new(helloRequestMsg)
898 c.writeRecord(recordTypeHandshake, helloRequest.marshal())
899 }
Nick Harperf2511f12016-12-06 16:02:31 -0800900 c.sendAlert(alertEndOfEarlyData)
901 }
902 c.out.useTrafficSecret(c.vers, hs.suite, clientHandshakeTrafficSecret, clientWrite)
903
Steven Valdez0ee2e112016-07-15 06:51:15 -0400904 if certReq != nil && !c.config.Bugs.SkipClientCertificate {
David Benjamin8d343b42016-07-09 14:26:01 -0700905 certMsg := &certificateMsg{
906 hasRequestContext: true,
907 requestContext: certReq.requestContext,
908 }
909 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -0400910 for _, certData := range chainToSend.Certificate {
911 certMsg.certificates = append(certMsg.certificates, certificateEntry{
912 data: certData,
913 extraExtension: c.config.Bugs.SendExtensionOnCertificate,
914 })
915 }
David Benjamin8d343b42016-07-09 14:26:01 -0700916 }
917 hs.writeClientHash(certMsg.marshal())
918 c.writeRecord(recordTypeHandshake, certMsg.marshal())
919
920 if chainToSend != nil {
921 certVerify := &certificateVerifyMsg{
922 hasSignatureAlgorithm: true,
923 }
924
925 // Determine the hash to sign.
926 privKey := chainToSend.PrivateKey
927
928 var err error
929 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
930 if err != nil {
931 c.sendAlert(alertInternalError)
932 return err
933 }
934
935 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
936 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
937 if err != nil {
938 c.sendAlert(alertInternalError)
939 return err
940 }
Steven Valdez0ee2e112016-07-15 06:51:15 -0400941 if c.config.Bugs.SendSignatureAlgorithm != 0 {
942 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
943 }
David Benjamin8d343b42016-07-09 14:26:01 -0700944
945 hs.writeClientHash(certVerify.marshal())
946 c.writeRecord(recordTypeHandshake, certVerify.marshal())
947 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400948 }
949
Nick Harper60a85cb2016-09-23 16:25:11 -0700950 if encryptedExtensions.extensions.channelIDRequested {
951 channelIDHash := crypto.SHA256.New()
952 channelIDHash.Write(hs.finishedHash.certificateVerifyInput(channelIDContextTLS13))
953 channelIDMsgBytes, err := hs.writeChannelIDMessage(channelIDHash.Sum(nil))
954 if err != nil {
955 return err
956 }
957 hs.writeClientHash(channelIDMsgBytes)
958 c.writeRecord(recordTypeHandshake, channelIDMsgBytes)
959 }
960
Nick Harperb41d2e42016-07-01 17:50:32 -0400961 // Send a client Finished message.
962 finished := new(finishedMsg)
Steven Valdezc4aa7272016-10-03 12:25:56 -0400963 finished.verifyData = hs.finishedHash.clientSum(clientHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400964 if c.config.Bugs.BadFinished {
965 finished.verifyData[0]++
966 }
David Benjamin97a0a082016-07-13 17:57:35 -0400967 hs.writeClientHash(finished.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400968 if c.config.Bugs.PartialClientFinishedWithClientHello {
969 // The first byte has already been sent.
970 c.writeRecord(recordTypeHandshake, finished.marshal()[1:])
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500971 } else if c.config.Bugs.InterleaveEarlyData {
972 finishedBytes := finished.marshal()
973 c.sendFakeEarlyData(4)
974 c.writeRecord(recordTypeHandshake, finishedBytes[:1])
975 c.sendFakeEarlyData(4)
976 c.writeRecord(recordTypeHandshake, finishedBytes[1:])
David Benjamin7964b182016-07-14 23:36:30 -0400977 } else {
978 c.writeRecord(recordTypeHandshake, finished.marshal())
979 }
David Benjamin02edcd02016-07-27 17:40:37 -0400980 if c.config.Bugs.SendExtraFinished {
981 c.writeRecord(recordTypeHandshake, finished.marshal())
982 }
David Benjaminee51a222016-07-07 18:34:12 -0700983 c.flushHandshake()
Nick Harperb41d2e42016-07-01 17:50:32 -0400984
985 // Switch to application data keys.
Steven Valdeza833c352016-11-01 13:39:36 -0400986 c.out.useTrafficSecret(c.vers, hs.suite, clientTrafficSecret, clientWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -0400987
David Benjamin48891ad2016-12-04 00:02:43 -0500988 c.resumptionSecret = hs.finishedHash.deriveSecret(resumptionLabel)
Nick Harperb41d2e42016-07-01 17:50:32 -0400989 return nil
990}
991
Adam Langley95c29f32014-06-20 12:00:00 -0700992func (hs *clientHandshakeState) doFullHandshake() error {
993 c := hs.c
994
David Benjamin48cae082014-10-27 01:06:24 -0400995 var leaf *x509.Certificate
996 if hs.suite.flags&suitePSK == 0 {
997 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700998 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700999 return err
1000 }
Adam Langley95c29f32014-06-20 12:00:00 -07001001
David Benjamin48cae082014-10-27 01:06:24 -04001002 certMsg, ok := msg.(*certificateMsg)
David Benjamin75051442016-07-01 18:58:51 -04001003 if !ok {
David Benjamin48cae082014-10-27 01:06:24 -04001004 c.sendAlert(alertUnexpectedMessage)
1005 return unexpectedMessageError(certMsg, msg)
1006 }
1007 hs.writeServerHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001008
David Benjamin75051442016-07-01 18:58:51 -04001009 if err := hs.verifyCertificates(certMsg); err != nil {
1010 return err
David Benjamin48cae082014-10-27 01:06:24 -04001011 }
David Benjamin75051442016-07-01 18:58:51 -04001012 leaf = c.peerCertificates[0]
David Benjamin48cae082014-10-27 01:06:24 -04001013 }
Adam Langley95c29f32014-06-20 12:00:00 -07001014
Nick Harperb3d51be2016-07-01 11:43:18 -04001015 if hs.serverHello.extensions.ocspStapling {
David Benjamin48cae082014-10-27 01:06:24 -04001016 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001017 if err != nil {
1018 return err
1019 }
1020 cs, ok := msg.(*certificateStatusMsg)
1021 if !ok {
1022 c.sendAlert(alertUnexpectedMessage)
1023 return unexpectedMessageError(cs, msg)
1024 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001025 hs.writeServerHash(cs.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001026
1027 if cs.statusType == statusTypeOCSP {
1028 c.ocspResponse = cs.response
1029 }
1030 }
1031
David Benjamin48cae082014-10-27 01:06:24 -04001032 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001033 if err != nil {
1034 return err
1035 }
1036
1037 keyAgreement := hs.suite.ka(c.vers)
1038
1039 skx, ok := msg.(*serverKeyExchangeMsg)
1040 if ok {
David Benjamin83c0bc92014-08-04 01:23:53 -04001041 hs.writeServerHash(skx.marshal())
David Benjamin48cae082014-10-27 01:06:24 -04001042 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx)
Adam Langley95c29f32014-06-20 12:00:00 -07001043 if err != nil {
1044 c.sendAlert(alertUnexpectedMessage)
1045 return err
1046 }
Steven Valdez5440fe02016-07-18 12:40:30 -04001047 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1048 c.curveID = ecdhe.curveID
1049 }
Adam Langley95c29f32014-06-20 12:00:00 -07001050
Nick Harper60edffd2016-06-21 15:19:24 -07001051 c.peerSignatureAlgorithm = keyAgreement.peerSignatureAlgorithm()
1052
Adam Langley95c29f32014-06-20 12:00:00 -07001053 msg, err = c.readHandshake()
1054 if err != nil {
1055 return err
1056 }
1057 }
1058
1059 var chainToSend *Certificate
1060 var certRequested bool
1061 certReq, ok := msg.(*certificateRequestMsg)
1062 if ok {
1063 certRequested = true
David Benjamin7a41d372016-07-09 11:21:54 -07001064 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
1065 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
1066 }
Adam Langley95c29f32014-06-20 12:00:00 -07001067
David Benjamin83c0bc92014-08-04 01:23:53 -04001068 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001069
David Benjamina6f82632016-07-01 18:44:02 -04001070 chainToSend, err = selectClientCertificate(c, certReq)
1071 if err != nil {
1072 return err
Adam Langley95c29f32014-06-20 12:00:00 -07001073 }
1074
1075 msg, err = c.readHandshake()
1076 if err != nil {
1077 return err
1078 }
1079 }
1080
1081 shd, ok := msg.(*serverHelloDoneMsg)
1082 if !ok {
1083 c.sendAlert(alertUnexpectedMessage)
1084 return unexpectedMessageError(shd, msg)
1085 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001086 hs.writeServerHash(shd.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001087
1088 // If the server requested a certificate then we have to send a
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001089 // Certificate message in TLS, even if it's empty because we don't have
1090 // a certificate to send. In SSL 3.0, skip the message and send a
1091 // no_certificate warning alert.
Adam Langley95c29f32014-06-20 12:00:00 -07001092 if certRequested {
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001093 if c.vers == VersionSSL30 && chainToSend == nil {
David Benjamin053fee92017-01-02 08:30:36 -05001094 c.sendAlert(alertNoCertificate)
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001095 } else if !c.config.Bugs.SkipClientCertificate {
1096 certMsg := new(certificateMsg)
1097 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -04001098 for _, certData := range chainToSend.Certificate {
1099 certMsg.certificates = append(certMsg.certificates, certificateEntry{
1100 data: certData,
1101 })
1102 }
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001103 }
1104 hs.writeClientHash(certMsg.marshal())
1105 c.writeRecord(recordTypeHandshake, certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001106 }
Adam Langley95c29f32014-06-20 12:00:00 -07001107 }
1108
David Benjamin48cae082014-10-27 01:06:24 -04001109 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf)
Adam Langley95c29f32014-06-20 12:00:00 -07001110 if err != nil {
1111 c.sendAlert(alertInternalError)
1112 return err
1113 }
1114 if ckx != nil {
David Benjaminf3ec83d2014-07-21 22:42:34 -04001115 if c.config.Bugs.EarlyChangeCipherSpec < 2 {
David Benjamin83c0bc92014-08-04 01:23:53 -04001116 hs.writeClientHash(ckx.marshal())
David Benjaminf3ec83d2014-07-21 22:42:34 -04001117 }
Adam Langley95c29f32014-06-20 12:00:00 -07001118 c.writeRecord(recordTypeHandshake, ckx.marshal())
1119 }
1120
Nick Harperb3d51be2016-07-01 11:43:18 -04001121 if hs.serverHello.extensions.extendedMasterSecret && c.vers >= VersionTLS10 {
Adam Langley75712922014-10-10 16:23:43 -07001122 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1123 c.extendedMasterSecret = true
1124 } else {
1125 if c.config.Bugs.RequireExtendedMasterSecret {
1126 return errors.New("tls: extended master secret required but not supported by peer")
1127 }
1128 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
1129 }
David Benjamine098ec22014-08-27 23:13:20 -04001130
Adam Langley95c29f32014-06-20 12:00:00 -07001131 if chainToSend != nil {
Adam Langley95c29f32014-06-20 12:00:00 -07001132 certVerify := &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001133 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001134 }
1135
David Benjamin72dc7832015-03-16 17:49:43 -04001136 // Determine the hash to sign.
Nick Harper60edffd2016-06-21 15:19:24 -07001137 privKey := c.config.Certificates[0].PrivateKey
David Benjamin72dc7832015-03-16 17:49:43 -04001138
Nick Harper60edffd2016-06-21 15:19:24 -07001139 if certVerify.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001140 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
Nick Harper60edffd2016-06-21 15:19:24 -07001141 if err != nil {
1142 c.sendAlert(alertInternalError)
1143 return err
Adam Langley95c29f32014-06-20 12:00:00 -07001144 }
Nick Harper60edffd2016-06-21 15:19:24 -07001145 }
1146
1147 if c.vers > VersionSSL30 {
David Benjamin5208fd42016-07-13 21:43:25 -04001148 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, hs.finishedHash.buffer)
David Benjamina95e9f32016-07-08 16:28:04 -07001149 if err == nil && c.config.Bugs.SendSignatureAlgorithm != 0 {
1150 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
1151 }
Nick Harper60edffd2016-06-21 15:19:24 -07001152 } else {
1153 // SSL 3.0's client certificate construction is
1154 // incompatible with signatureAlgorithm.
1155 rsaKey, ok := privKey.(*rsa.PrivateKey)
1156 if !ok {
1157 err = errors.New("unsupported signature type for client certificate")
1158 } else {
1159 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
David Benjamin5208fd42016-07-13 21:43:25 -04001160 if c.config.Bugs.InvalidSignature {
Nick Harper60edffd2016-06-21 15:19:24 -07001161 digest[0] ^= 0x80
1162 }
1163 certVerify.signature, err = rsa.SignPKCS1v15(c.config.rand(), rsaKey, crypto.MD5SHA1, digest)
1164 }
Adam Langley95c29f32014-06-20 12:00:00 -07001165 }
1166 if err != nil {
1167 c.sendAlert(alertInternalError)
1168 return errors.New("tls: failed to sign handshake with client certificate: " + err.Error())
1169 }
Adam Langley95c29f32014-06-20 12:00:00 -07001170
David Benjamin83c0bc92014-08-04 01:23:53 -04001171 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001172 c.writeRecord(recordTypeHandshake, certVerify.marshal())
1173 }
David Benjamin82261be2016-07-07 14:32:50 -07001174 // flushHandshake will be called in sendFinished.
Adam Langley95c29f32014-06-20 12:00:00 -07001175
David Benjamine098ec22014-08-27 23:13:20 -04001176 hs.finishedHash.discardHandshakeBuffer()
1177
Adam Langley95c29f32014-06-20 12:00:00 -07001178 return nil
1179}
1180
David Benjamin75051442016-07-01 18:58:51 -04001181func (hs *clientHandshakeState) verifyCertificates(certMsg *certificateMsg) error {
1182 c := hs.c
1183
1184 if len(certMsg.certificates) == 0 {
1185 c.sendAlert(alertIllegalParameter)
1186 return errors.New("tls: no certificates sent")
1187 }
1188
1189 certs := make([]*x509.Certificate, len(certMsg.certificates))
Steven Valdeza833c352016-11-01 13:39:36 -04001190 for i, certEntry := range certMsg.certificates {
1191 cert, err := x509.ParseCertificate(certEntry.data)
David Benjamin75051442016-07-01 18:58:51 -04001192 if err != nil {
1193 c.sendAlert(alertBadCertificate)
1194 return errors.New("tls: failed to parse certificate from server: " + err.Error())
1195 }
1196 certs[i] = cert
1197 }
1198
1199 if !c.config.InsecureSkipVerify {
1200 opts := x509.VerifyOptions{
1201 Roots: c.config.RootCAs,
1202 CurrentTime: c.config.time(),
1203 DNSName: c.config.ServerName,
1204 Intermediates: x509.NewCertPool(),
1205 }
1206
1207 for i, cert := range certs {
1208 if i == 0 {
1209 continue
1210 }
1211 opts.Intermediates.AddCert(cert)
1212 }
1213 var err error
1214 c.verifiedChains, err = certs[0].Verify(opts)
1215 if err != nil {
1216 c.sendAlert(alertBadCertificate)
1217 return err
1218 }
1219 }
1220
David Benjamind768c5d2017-03-28 18:28:44 -05001221 publicKey := getCertificatePublicKey(certs[0])
1222 switch publicKey.(type) {
1223 case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
David Benjamin75051442016-07-01 18:58:51 -04001224 break
1225 default:
1226 c.sendAlert(alertUnsupportedCertificate)
David Benjamind768c5d2017-03-28 18:28:44 -05001227 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", publicKey)
David Benjamin75051442016-07-01 18:58:51 -04001228 }
1229
1230 c.peerCertificates = certs
1231 return nil
1232}
1233
Adam Langley95c29f32014-06-20 12:00:00 -07001234func (hs *clientHandshakeState) establishKeys() error {
1235 c := hs.c
1236
1237 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001238 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 -07001239 var clientCipher, serverCipher interface{}
1240 var clientHash, serverHash macFunction
1241 if hs.suite.cipher != nil {
1242 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
1243 clientHash = hs.suite.mac(c.vers, clientMAC)
1244 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
1245 serverHash = hs.suite.mac(c.vers, serverMAC)
1246 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001247 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1248 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001249 }
1250
1251 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
1252 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
1253 return nil
1254}
1255
David Benjamin75101402016-07-01 13:40:23 -04001256func (hs *clientHandshakeState) processServerExtensions(serverExtensions *serverExtensions) error {
1257 c := hs.c
1258
David Benjamin8d315d72016-07-18 01:03:18 +02001259 if c.vers < VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001260 if c.config.Bugs.RequireRenegotiationInfo && serverExtensions.secureRenegotiation == nil {
1261 return errors.New("tls: renegotiation extension missing")
1262 }
David Benjamin75101402016-07-01 13:40:23 -04001263
Nick Harperb41d2e42016-07-01 17:50:32 -04001264 if len(c.clientVerify) > 0 && !c.noRenegotiationInfo() {
1265 var expectedRenegInfo []byte
1266 expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...)
1267 expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...)
1268 if !bytes.Equal(serverExtensions.secureRenegotiation, expectedRenegInfo) {
1269 c.sendAlert(alertHandshakeFailure)
1270 return fmt.Errorf("tls: renegotiation mismatch")
1271 }
David Benjamin75101402016-07-01 13:40:23 -04001272 }
David Benjamincea0ab42016-07-14 12:33:14 -04001273 } else if serverExtensions.secureRenegotiation != nil {
1274 return errors.New("tls: renegotiation info sent in TLS 1.3")
David Benjamin75101402016-07-01 13:40:23 -04001275 }
1276
1277 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
1278 if serverExtensions.customExtension != *expected {
1279 return fmt.Errorf("tls: bad custom extension contents %q", serverExtensions.customExtension)
1280 }
1281 }
1282
1283 clientDidNPN := hs.hello.nextProtoNeg
1284 clientDidALPN := len(hs.hello.alpnProtocols) > 0
1285 serverHasNPN := serverExtensions.nextProtoNeg
1286 serverHasALPN := len(serverExtensions.alpnProtocol) > 0
1287
1288 if !clientDidNPN && serverHasNPN {
1289 c.sendAlert(alertHandshakeFailure)
1290 return errors.New("server advertised unrequested NPN extension")
1291 }
1292
1293 if !clientDidALPN && serverHasALPN {
1294 c.sendAlert(alertHandshakeFailure)
1295 return errors.New("server advertised unrequested ALPN extension")
1296 }
1297
1298 if serverHasNPN && serverHasALPN {
1299 c.sendAlert(alertHandshakeFailure)
1300 return errors.New("server advertised both NPN and ALPN extensions")
1301 }
1302
1303 if serverHasALPN {
1304 c.clientProtocol = serverExtensions.alpnProtocol
1305 c.clientProtocolFallback = false
1306 c.usedALPN = true
1307 }
1308
David Benjamin8d315d72016-07-18 01:03:18 +02001309 if serverHasNPN && c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001310 c.sendAlert(alertHandshakeFailure)
1311 return errors.New("server advertised NPN over TLS 1.3")
1312 }
1313
David Benjamin75101402016-07-01 13:40:23 -04001314 if !hs.hello.channelIDSupported && serverExtensions.channelIDRequested {
1315 c.sendAlert(alertHandshakeFailure)
1316 return errors.New("server advertised unrequested Channel ID extension")
1317 }
1318
David Benjamin8d315d72016-07-18 01:03:18 +02001319 if serverExtensions.extendedMasterSecret && c.vers >= VersionTLS13 {
David Benjamine9077652016-07-13 21:02:08 -04001320 return errors.New("tls: server advertised extended master secret over TLS 1.3")
1321 }
1322
David Benjamin8d315d72016-07-18 01:03:18 +02001323 if serverExtensions.ticketSupported && c.vers >= VersionTLS13 {
Steven Valdez143e8b32016-07-11 13:19:03 -04001324 return errors.New("tls: server advertised ticket extension over TLS 1.3")
1325 }
1326
Steven Valdeza833c352016-11-01 13:39:36 -04001327 if serverExtensions.ocspStapling && c.vers >= VersionTLS13 {
1328 return errors.New("tls: server advertised OCSP in ServerHello over TLS 1.3")
1329 }
1330
David Benjamin53210cb2016-11-16 09:01:48 +09001331 if serverExtensions.ocspStapling && c.config.Bugs.NoOCSPStapling {
1332 return errors.New("tls: server advertised unrequested OCSP extension")
1333 }
1334
Steven Valdeza833c352016-11-01 13:39:36 -04001335 if len(serverExtensions.sctList) > 0 && c.vers >= VersionTLS13 {
1336 return errors.New("tls: server advertised SCTs in ServerHello over TLS 1.3")
1337 }
1338
David Benjamin53210cb2016-11-16 09:01:48 +09001339 if len(serverExtensions.sctList) > 0 && c.config.Bugs.NoSignedCertificateTimestamps {
1340 return errors.New("tls: server advertised unrequested SCTs")
1341 }
1342
David Benjamin75101402016-07-01 13:40:23 -04001343 if serverExtensions.srtpProtectionProfile != 0 {
1344 if serverExtensions.srtpMasterKeyIdentifier != "" {
1345 return errors.New("tls: server selected SRTP MKI value")
1346 }
1347
1348 found := false
1349 for _, p := range c.config.SRTPProtectionProfiles {
1350 if p == serverExtensions.srtpProtectionProfile {
1351 found = true
1352 break
1353 }
1354 }
1355 if !found {
1356 return errors.New("tls: server advertised unsupported SRTP profile")
1357 }
1358
1359 c.srtpProtectionProfile = serverExtensions.srtpProtectionProfile
1360 }
1361
Steven Valdez2d850622017-01-11 11:34:52 -05001362 if c.vers >= VersionTLS13 && c.didResume {
1363 if c.config.Bugs.ExpectEarlyDataAccepted && !serverExtensions.hasEarlyData {
1364 c.sendAlert(alertHandshakeFailure)
1365 return errors.New("tls: server did not accept early data when expected")
1366 }
1367
1368 if !c.config.Bugs.ExpectEarlyDataAccepted && serverExtensions.hasEarlyData {
1369 c.sendAlert(alertHandshakeFailure)
1370 return errors.New("tls: server accepted early data when not expected")
1371 }
1372 }
1373
David Benjamin75101402016-07-01 13:40:23 -04001374 return nil
1375}
1376
Adam Langley95c29f32014-06-20 12:00:00 -07001377func (hs *clientHandshakeState) serverResumedSession() bool {
1378 // If the server responded with the same sessionId then it means the
1379 // sessionTicket is being used to resume a TLS session.
David Benjamind4c349b2017-02-09 14:07:17 -05001380 //
1381 // Note that, if hs.hello.sessionId is a non-nil empty array, this will
1382 // accept an empty session ID from the server as resumption. See
1383 // EmptyTicketSessionID.
Adam Langley95c29f32014-06-20 12:00:00 -07001384 return hs.session != nil && hs.hello.sessionId != nil &&
1385 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
1386}
1387
1388func (hs *clientHandshakeState) processServerHello() (bool, error) {
1389 c := hs.c
1390
Adam Langley95c29f32014-06-20 12:00:00 -07001391 if hs.serverResumedSession() {
David Benjamin4b27d9f2015-05-12 22:42:52 -04001392 // For test purposes, assert that the server never accepts the
1393 // resumption offer on renegotiation.
1394 if c.cipherSuite != nil && c.config.Bugs.FailIfResumeOnRenego {
1395 return false, errors.New("tls: server resumed session on renegotiation")
1396 }
1397
Nick Harperb3d51be2016-07-01 11:43:18 -04001398 if hs.serverHello.extensions.sctList != nil {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001399 return false, errors.New("tls: server sent SCT extension on session resumption")
1400 }
1401
Nick Harperb3d51be2016-07-01 11:43:18 -04001402 if hs.serverHello.extensions.ocspStapling {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001403 return false, errors.New("tls: server sent OCSP extension on session resumption")
1404 }
1405
Adam Langley95c29f32014-06-20 12:00:00 -07001406 // Restore masterSecret and peerCerts from previous state
1407 hs.masterSecret = hs.session.masterSecret
1408 c.peerCertificates = hs.session.serverCertificates
Adam Langley75712922014-10-10 16:23:43 -07001409 c.extendedMasterSecret = hs.session.extendedMasterSecret
Paul Lietar62be8ac2015-09-16 10:03:30 +01001410 c.sctList = hs.session.sctList
1411 c.ocspResponse = hs.session.ocspResponse
David Benjamine098ec22014-08-27 23:13:20 -04001412 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001413 return true, nil
1414 }
Paul Lietar62be8ac2015-09-16 10:03:30 +01001415
Nick Harperb3d51be2016-07-01 11:43:18 -04001416 if hs.serverHello.extensions.sctList != nil {
1417 c.sctList = hs.serverHello.extensions.sctList
Paul Lietar62be8ac2015-09-16 10:03:30 +01001418 }
1419
Adam Langley95c29f32014-06-20 12:00:00 -07001420 return false, nil
1421}
1422
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001423func (hs *clientHandshakeState) readFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001424 c := hs.c
1425
1426 c.readRecord(recordTypeChangeCipherSpec)
1427 if err := c.in.error(); err != nil {
1428 return err
1429 }
1430
1431 msg, err := c.readHandshake()
1432 if err != nil {
1433 return err
1434 }
1435 serverFinished, ok := msg.(*finishedMsg)
1436 if !ok {
1437 c.sendAlert(alertUnexpectedMessage)
1438 return unexpectedMessageError(serverFinished, msg)
1439 }
1440
David Benjaminf3ec83d2014-07-21 22:42:34 -04001441 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
1442 verify := hs.finishedHash.serverSum(hs.masterSecret)
1443 if len(verify) != len(serverFinished.verifyData) ||
1444 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
1445 c.sendAlert(alertHandshakeFailure)
1446 return errors.New("tls: server's Finished message was incorrect")
1447 }
Adam Langley95c29f32014-06-20 12:00:00 -07001448 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001449 c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001450 copy(out, serverFinished.verifyData)
David Benjamin83c0bc92014-08-04 01:23:53 -04001451 hs.writeServerHash(serverFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001452 return nil
1453}
1454
1455func (hs *clientHandshakeState) readSessionTicket() error {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001456 c := hs.c
1457
1458 // Create a session with no server identifier. Either a
1459 // session ID or session ticket will be attached.
1460 session := &ClientSessionState{
1461 vers: c.vers,
1462 cipherSuite: hs.suite.id,
1463 masterSecret: hs.masterSecret,
Nick Harperc9846112016-10-17 15:05:35 -07001464 handshakeHash: hs.finishedHash.Sum(),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001465 serverCertificates: c.peerCertificates,
Paul Lietar62be8ac2015-09-16 10:03:30 +01001466 sctList: c.sctList,
1467 ocspResponse: c.ocspResponse,
Nick Harper0b3625b2016-07-25 16:16:28 -07001468 ticketExpiration: c.config.time().Add(time.Duration(7 * 24 * time.Hour)),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001469 }
1470
Nick Harperb3d51be2016-07-01 11:43:18 -04001471 if !hs.serverHello.extensions.ticketSupported {
David Benjamind98452d2015-06-16 14:16:23 -04001472 if c.config.Bugs.ExpectNewTicket {
1473 return errors.New("tls: expected new ticket")
1474 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001475 if hs.session == nil && len(hs.serverHello.sessionId) > 0 {
1476 session.sessionId = hs.serverHello.sessionId
1477 hs.session = session
1478 }
Adam Langley95c29f32014-06-20 12:00:00 -07001479 return nil
1480 }
1481
David Benjaminc7ce9772015-10-09 19:32:41 -04001482 if c.vers == VersionSSL30 {
1483 return errors.New("tls: negotiated session tickets in SSL 3.0")
1484 }
1485
Adam Langley95c29f32014-06-20 12:00:00 -07001486 msg, err := c.readHandshake()
1487 if err != nil {
1488 return err
1489 }
1490 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
1491 if !ok {
1492 c.sendAlert(alertUnexpectedMessage)
1493 return unexpectedMessageError(sessionTicketMsg, msg)
1494 }
Adam Langley95c29f32014-06-20 12:00:00 -07001495
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001496 session.sessionTicket = sessionTicketMsg.ticket
1497 hs.session = session
Adam Langley95c29f32014-06-20 12:00:00 -07001498
David Benjamind30a9902014-08-24 01:44:23 -04001499 hs.writeServerHash(sessionTicketMsg.marshal())
1500
Adam Langley95c29f32014-06-20 12:00:00 -07001501 return nil
1502}
1503
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001504func (hs *clientHandshakeState) sendFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001505 c := hs.c
1506
David Benjamin0b8d5da2016-07-15 00:39:56 -04001507 var postCCSMsgs [][]byte
David Benjamin83c0bc92014-08-04 01:23:53 -04001508 seqno := hs.c.sendHandshakeSeq
Nick Harperb3d51be2016-07-01 11:43:18 -04001509 if hs.serverHello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001510 nextProto := new(nextProtoMsg)
Nick Harperb3d51be2016-07-01 11:43:18 -04001511 proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.extensions.nextProtos)
Adam Langley95c29f32014-06-20 12:00:00 -07001512 nextProto.proto = proto
1513 c.clientProtocol = proto
1514 c.clientProtocolFallback = fallback
1515
David Benjamin86271ee2014-07-21 16:14:03 -04001516 nextProtoBytes := nextProto.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -04001517 hs.writeHash(nextProtoBytes, seqno)
1518 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001519 postCCSMsgs = append(postCCSMsgs, nextProtoBytes)
Adam Langley95c29f32014-06-20 12:00:00 -07001520 }
1521
Nick Harperb3d51be2016-07-01 11:43:18 -04001522 if hs.serverHello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001523 var resumeHash []byte
1524 if isResume {
1525 resumeHash = hs.session.handshakeHash
1526 }
Nick Harper60a85cb2016-09-23 16:25:11 -07001527 channelIDMsgBytes, err := hs.writeChannelIDMessage(hs.finishedHash.hashForChannelID(resumeHash))
David Benjamind30a9902014-08-24 01:44:23 -04001528 if err != nil {
1529 return err
1530 }
David Benjamin24599a82016-06-30 18:56:53 -04001531 hs.writeHash(channelIDMsgBytes, seqno)
David Benjamind30a9902014-08-24 01:44:23 -04001532 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001533 postCCSMsgs = append(postCCSMsgs, channelIDMsgBytes)
David Benjamind30a9902014-08-24 01:44:23 -04001534 }
1535
Adam Langley95c29f32014-06-20 12:00:00 -07001536 finished := new(finishedMsg)
David Benjaminf3ec83d2014-07-21 22:42:34 -04001537 if c.config.Bugs.EarlyChangeCipherSpec == 2 {
1538 finished.verifyData = hs.finishedHash.clientSum(nil)
1539 } else {
1540 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
1541 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001542 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001543 if c.config.Bugs.BadFinished {
1544 finished.verifyData[0]++
1545 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001546 c.clientVerify = append(c.clientVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001547 hs.finishedBytes = finished.marshal()
1548 hs.writeHash(hs.finishedBytes, seqno)
David Benjamin0b8d5da2016-07-15 00:39:56 -04001549 postCCSMsgs = append(postCCSMsgs, hs.finishedBytes)
David Benjamin86271ee2014-07-21 16:14:03 -04001550
1551 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001552 c.writeRecord(recordTypeHandshake, postCCSMsgs[0][:5])
1553 postCCSMsgs[0] = postCCSMsgs[0][5:]
David Benjamin61672812016-07-14 23:10:43 -04001554 } else if c.config.Bugs.SendUnencryptedFinished {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001555 c.writeRecord(recordTypeHandshake, postCCSMsgs[0])
1556 postCCSMsgs = postCCSMsgs[1:]
David Benjamin86271ee2014-07-21 16:14:03 -04001557 }
David Benjamin582ba042016-07-07 12:33:25 -07001558 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001559
1560 if !c.config.Bugs.SkipChangeCipherSpec &&
1561 c.config.Bugs.EarlyChangeCipherSpec == 0 {
David Benjamin8411b242015-11-26 12:07:28 -05001562 ccs := []byte{1}
1563 if c.config.Bugs.BadChangeCipherSpec != nil {
1564 ccs = c.config.Bugs.BadChangeCipherSpec
1565 }
1566 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamin86271ee2014-07-21 16:14:03 -04001567 }
1568
David Benjamin4189bd92015-01-25 23:52:39 -05001569 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1570 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1571 }
David Benjamindc3da932015-03-12 15:09:02 -04001572 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1573 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1574 return errors.New("tls: simulating post-CCS alert")
1575 }
David Benjamin4189bd92015-01-25 23:52:39 -05001576
David Benjamin0b8d5da2016-07-15 00:39:56 -04001577 if !c.config.Bugs.SkipFinished {
1578 for _, msg := range postCCSMsgs {
1579 c.writeRecord(recordTypeHandshake, msg)
1580 }
David Benjamin02edcd02016-07-27 17:40:37 -04001581
1582 if c.config.Bugs.SendExtraFinished {
1583 c.writeRecord(recordTypeHandshake, finished.marshal())
1584 }
1585
David Benjamin582ba042016-07-07 12:33:25 -07001586 c.flushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -05001587 }
Adam Langley95c29f32014-06-20 12:00:00 -07001588 return nil
1589}
1590
Nick Harper60a85cb2016-09-23 16:25:11 -07001591func (hs *clientHandshakeState) writeChannelIDMessage(channelIDHash []byte) ([]byte, error) {
1592 c := hs.c
1593 channelIDMsg := new(channelIDMsg)
1594 if c.config.ChannelID.Curve != elliptic.P256() {
1595 return nil, fmt.Errorf("tls: Channel ID is not on P-256.")
1596 }
1597 r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, channelIDHash)
1598 if err != nil {
1599 return nil, err
1600 }
1601 channelID := make([]byte, 128)
1602 writeIntPadded(channelID[0:32], c.config.ChannelID.X)
1603 writeIntPadded(channelID[32:64], c.config.ChannelID.Y)
1604 writeIntPadded(channelID[64:96], r)
1605 writeIntPadded(channelID[96:128], s)
1606 if c.config.Bugs.InvalidChannelIDSignature {
1607 channelID[64] ^= 1
1608 }
1609 channelIDMsg.channelID = channelID
1610
1611 c.channelID = &c.config.ChannelID.PublicKey
1612
1613 return channelIDMsg.marshal(), nil
1614}
1615
David Benjamin83c0bc92014-08-04 01:23:53 -04001616func (hs *clientHandshakeState) writeClientHash(msg []byte) {
1617 // writeClientHash is called before writeRecord.
1618 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1619}
1620
1621func (hs *clientHandshakeState) writeServerHash(msg []byte) {
1622 // writeServerHash is called after readHandshake.
1623 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1624}
1625
1626func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) {
1627 if hs.c.isDTLS {
1628 // This is somewhat hacky. DTLS hashes a slightly different format.
1629 // First, the TLS header.
1630 hs.finishedHash.Write(msg[:4])
1631 // Then the sequence number and reassembled fragment offset (always 0).
1632 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1633 // Then the reassembled fragment (always equal to the message length).
1634 hs.finishedHash.Write(msg[1:4])
1635 // And then the message body.
1636 hs.finishedHash.Write(msg[4:])
1637 } else {
1638 hs.finishedHash.Write(msg)
1639 }
1640}
1641
David Benjamina6f82632016-07-01 18:44:02 -04001642// selectClientCertificate selects a certificate for use with the given
1643// certificate, or none if none match. It may return a particular certificate or
1644// nil on success, or an error on internal error.
1645func selectClientCertificate(c *Conn, certReq *certificateRequestMsg) (*Certificate, error) {
1646 // RFC 4346 on the certificateAuthorities field:
1647 // A list of the distinguished names of acceptable certificate
1648 // authorities. These distinguished names may specify a desired
1649 // distinguished name for a root CA or for a subordinate CA; thus, this
1650 // message can be used to describe both known roots and a desired
1651 // authorization space. If the certificate_authorities list is empty
1652 // then the client MAY send any certificate of the appropriate
1653 // ClientCertificateType, unless there is some external arrangement to
1654 // the contrary.
1655
1656 var rsaAvail, ecdsaAvail bool
Nick Harperb41d2e42016-07-01 17:50:32 -04001657 if !certReq.hasRequestContext {
1658 for _, certType := range certReq.certificateTypes {
1659 switch certType {
1660 case CertTypeRSASign:
1661 rsaAvail = true
1662 case CertTypeECDSASign:
1663 ecdsaAvail = true
1664 }
David Benjamina6f82632016-07-01 18:44:02 -04001665 }
1666 }
1667
1668 // We need to search our list of client certs for one
1669 // where SignatureAlgorithm is RSA and the Issuer is in
1670 // certReq.certificateAuthorities
1671findCert:
1672 for i, chain := range c.config.Certificates {
Nick Harperb41d2e42016-07-01 17:50:32 -04001673 if !certReq.hasRequestContext && !rsaAvail && !ecdsaAvail {
David Benjamina6f82632016-07-01 18:44:02 -04001674 continue
1675 }
1676
1677 // Ensure the private key supports one of the advertised
1678 // signature algorithms.
1679 if certReq.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001680 if _, err := selectSignatureAlgorithm(c.vers, chain.PrivateKey, c.config, certReq.signatureAlgorithms); err != nil {
David Benjamina6f82632016-07-01 18:44:02 -04001681 continue
1682 }
1683 }
1684
1685 for j, cert := range chain.Certificate {
1686 x509Cert := chain.Leaf
1687 // parse the certificate if this isn't the leaf
1688 // node, or if chain.Leaf was nil
1689 if j != 0 || x509Cert == nil {
1690 var err error
1691 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
1692 c.sendAlert(alertInternalError)
1693 return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
1694 }
1695 }
1696
Nick Harperb41d2e42016-07-01 17:50:32 -04001697 if !certReq.hasRequestContext {
1698 switch {
1699 case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
1700 case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
David Benjamind768c5d2017-03-28 18:28:44 -05001701 case ecdsaAvail && isEd25519Certificate(x509Cert):
Nick Harperb41d2e42016-07-01 17:50:32 -04001702 default:
1703 continue findCert
1704 }
David Benjamina6f82632016-07-01 18:44:02 -04001705 }
1706
Adam Langley2ff79332017-02-28 13:45:39 -08001707 if expected := c.config.Bugs.ExpectCertificateReqNames; expected != nil {
1708 if !eqByteSlices(expected, certReq.certificateAuthorities) {
1709 return nil, fmt.Errorf("tls: CertificateRequest names differed, got %#v but expected %#v", certReq.certificateAuthorities, expected)
David Benjamina6f82632016-07-01 18:44:02 -04001710 }
1711 }
Adam Langley2ff79332017-02-28 13:45:39 -08001712
1713 return &chain, nil
David Benjamina6f82632016-07-01 18:44:02 -04001714 }
1715 }
1716
1717 return nil, nil
1718}
1719
Adam Langley95c29f32014-06-20 12:00:00 -07001720// clientSessionCacheKey returns a key used to cache sessionTickets that could
1721// be used to resume previously negotiated TLS sessions with a server.
1722func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
1723 if len(config.ServerName) > 0 {
1724 return config.ServerName
1725 }
1726 return serverAddr.String()
1727}
1728
David Benjaminfa055a22014-09-15 16:51:51 -04001729// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
1730// given list of possible protocols and a list of the preference order. The
1731// first list must not be empty. It returns the resulting protocol and flag
Adam Langley95c29f32014-06-20 12:00:00 -07001732// indicating if the fallback case was reached.
David Benjaminfa055a22014-09-15 16:51:51 -04001733func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
1734 for _, s := range preferenceProtos {
1735 for _, c := range protos {
Adam Langley95c29f32014-06-20 12:00:00 -07001736 if s == c {
1737 return s, false
1738 }
1739 }
1740 }
1741
David Benjaminfa055a22014-09-15 16:51:51 -04001742 return protos[0], true
Adam Langley95c29f32014-06-20 12:00:00 -07001743}
David Benjamind30a9902014-08-24 01:44:23 -04001744
1745// writeIntPadded writes x into b, padded up with leading zeros as
1746// needed.
1747func writeIntPadded(b []byte, x *big.Int) {
1748 for i := range b {
1749 b[i] = 0
1750 }
1751 xb := x.Bytes()
1752 copy(b[len(b)-len(xb):], xb)
1753}
Steven Valdeza833c352016-11-01 13:39:36 -04001754
1755func generatePSKBinders(hello *clientHelloMsg, pskCipherSuite *cipherSuite, psk, transcript []byte, config *Config) {
1756 if config.Bugs.SendNoPSKBinder {
1757 return
1758 }
1759
1760 binderLen := pskCipherSuite.hash().Size()
1761 if config.Bugs.SendShortPSKBinder {
1762 binderLen--
1763 }
1764
David Benjaminaedf3032016-12-01 16:47:56 -05001765 numBinders := 1
1766 if config.Bugs.SendExtraPSKBinder {
1767 numBinders++
1768 }
1769
Steven Valdeza833c352016-11-01 13:39:36 -04001770 // Fill hello.pskBinders with appropriate length arrays of zeros so the
1771 // length prefixes are correct when computing the binder over the truncated
1772 // ClientHello message.
David Benjaminaedf3032016-12-01 16:47:56 -05001773 hello.pskBinders = make([][]byte, numBinders)
1774 for i := range hello.pskBinders {
Steven Valdeza833c352016-11-01 13:39:36 -04001775 hello.pskBinders[i] = make([]byte, binderLen)
1776 }
1777
1778 helloBytes := hello.marshal()
1779 binderSize := len(hello.pskBinders)*(binderLen+1) + 2
1780 truncatedHello := helloBytes[:len(helloBytes)-binderSize]
1781 binder := computePSKBinder(psk, resumptionPSKBinderLabel, pskCipherSuite, transcript, truncatedHello)
1782 if config.Bugs.SendShortPSKBinder {
1783 binder = binder[:binderLen]
1784 }
1785 if config.Bugs.SendInvalidPSKBinder {
1786 binder[0] ^= 1
1787 }
1788
1789 for i := range hello.pskBinders {
1790 hello.pskBinders[i] = binder
1791 }
1792
1793 hello.raw = nil
1794}