blob: 0c237931dee1d552cd6db740c5be2aa5affacde9 [file] [log] [blame]
Adam Langley95c29f32014-06-20 12:00:00 -07001// Copyright 2009 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
Adam Langleydc7e9c42015-09-29 15:21:04 -07005package runner
Adam Langley95c29f32014-06-20 12:00:00 -07006
7import (
8 "bytes"
Nick Harper60edffd2016-06-21 15:19:24 -07009 "crypto"
Adam Langley95c29f32014-06-20 12:00:00 -070010 "crypto/ecdsa"
David Benjamind30a9902014-08-24 01:44:23 -040011 "crypto/elliptic"
Adam Langley95c29f32014-06-20 12:00:00 -070012 "crypto/rsa"
13 "crypto/subtle"
14 "crypto/x509"
Adam Langley95c29f32014-06-20 12:00:00 -070015 "errors"
16 "fmt"
17 "io"
David Benjaminde620d92014-07-18 15:03:41 -040018 "math/big"
Adam Langley95c29f32014-06-20 12:00:00 -070019 "net"
Nick Harper0b3625b2016-07-25 16:16:28 -070020 "time"
David Benjamind768c5d2017-03-28 18:28:44 -050021
22 "./ed25519"
Adam Langley95c29f32014-06-20 12:00:00 -070023)
24
25type clientHandshakeState struct {
David Benjamin83f90402015-01-27 01:09:43 -050026 c *Conn
27 serverHello *serverHelloMsg
28 hello *clientHelloMsg
29 suite *cipherSuite
30 finishedHash finishedHash
Nick Harperb41d2e42016-07-01 17:50:32 -040031 keyShares map[CurveID]ecdhCurve
David Benjamin83f90402015-01-27 01:09:43 -050032 masterSecret []byte
33 session *ClientSessionState
34 finishedBytes []byte
Adam Langley95c29f32014-06-20 12:00:00 -070035}
36
Steven Valdezc94998a2017-06-20 10:55:02 -040037func mapClientHelloVersion(vers uint16, isDTLS bool) uint16 {
38 if !isDTLS {
39 return vers
40 }
41
42 switch vers {
43 case VersionTLS12:
44 return VersionDTLS12
45 case VersionTLS10:
46 return VersionDTLS10
47 }
48
49 panic("Unknown ClientHello version.")
50}
51
Adam Langley95c29f32014-06-20 12:00:00 -070052func (c *Conn) clientHandshake() error {
53 if c.config == nil {
54 c.config = defaultConfig()
55 }
56
57 if len(c.config.ServerName) == 0 && !c.config.InsecureSkipVerify {
58 return errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
59 }
60
David Benjamin83c0bc92014-08-04 01:23:53 -040061 c.sendHandshakeSeq = 0
62 c.recvHandshakeSeq = 0
63
David Benjaminfa055a22014-09-15 16:51:51 -040064 nextProtosLength := 0
65 for _, proto := range c.config.NextProtos {
Adam Langleyefb0e162015-07-09 11:35:04 -070066 if l := len(proto); l > 255 {
David Benjaminfa055a22014-09-15 16:51:51 -040067 return errors.New("tls: invalid NextProtos value")
68 } else {
69 nextProtosLength += 1 + l
70 }
71 }
72 if nextProtosLength > 0xffff {
73 return errors.New("tls: NextProtos values too large")
74 }
75
Steven Valdezfdd10992016-09-15 16:27:05 -040076 minVersion := c.config.minVersion(c.isDTLS)
David Benjamin3c6a1ea2016-09-26 18:30:05 -040077 maxVersion := c.config.maxVersion(c.isDTLS)
Adam Langley95c29f32014-06-20 12:00:00 -070078 hello := &clientHelloMsg{
David Benjaminca6c8262014-11-15 19:06:08 -050079 isDTLS: c.isDTLS,
David Benjaminca6c8262014-11-15 19:06:08 -050080 compressionMethods: []uint8{compressionNone},
81 random: make([]byte, 32),
David Benjamin53210cb2016-11-16 09:01:48 +090082 ocspStapling: !c.config.Bugs.NoOCSPStapling,
83 sctListSupported: !c.config.Bugs.NoSignedCertificateTimestamps,
David Benjaminca6c8262014-11-15 19:06:08 -050084 serverName: c.config.ServerName,
85 supportedCurves: c.config.curvePreferences(),
86 supportedPoints: []uint8{pointFormatUncompressed},
87 nextProtoNeg: len(c.config.NextProtos) > 0,
88 secureRenegotiation: []byte{},
89 alpnProtocols: c.config.NextProtos,
90 duplicateExtension: c.config.Bugs.DuplicateExtension,
91 channelIDSupported: c.config.ChannelID != nil,
Steven Valdeza833c352016-11-01 13:39:36 -040092 npnAfterAlpn: c.config.Bugs.SwapNPNAndALPN,
Steven Valdezfdd10992016-09-15 16:27:05 -040093 extendedMasterSecret: maxVersion >= VersionTLS10,
David Benjaminca6c8262014-11-15 19:06:08 -050094 srtpProtectionProfiles: c.config.SRTPProtectionProfiles,
95 srtpMasterKeyIdentifier: c.config.Bugs.SRTPMasterKeyIdentifer,
Adam Langley09505632015-07-30 18:10:13 -070096 customExtension: c.config.Bugs.CustomExtension,
Steven Valdeza833c352016-11-01 13:39:36 -040097 pskBinderFirst: c.config.Bugs.PSKBinderFirst,
David Benjaminb853f312017-07-14 18:40:34 -040098 omitExtensions: c.config.Bugs.OmitExtensions,
99 emptyExtensions: c.config.Bugs.EmptyExtensions,
Adam Langley95c29f32014-06-20 12:00:00 -0700100 }
101
Steven Valdezc94998a2017-06-20 10:55:02 -0400102 if maxVersion >= VersionTLS13 {
103 hello.vers = mapClientHelloVersion(VersionTLS12, c.isDTLS)
104 if !c.config.Bugs.OmitSupportedVersions {
105 hello.supportedVersions = c.config.supportedVersions(c.isDTLS)
106 }
David Benjaminb853f312017-07-14 18:40:34 -0400107 hello.pskKEModes = []byte{pskDHEKEMode}
Steven Valdezc94998a2017-06-20 10:55:02 -0400108 } else {
109 hello.vers = mapClientHelloVersion(maxVersion, c.isDTLS)
110 }
111
112 if c.config.Bugs.SendClientVersion != 0 {
113 hello.vers = c.config.Bugs.SendClientVersion
114 }
115
116 if len(c.config.Bugs.SendSupportedVersions) > 0 {
117 hello.supportedVersions = c.config.Bugs.SendSupportedVersions
118 }
119
David Benjamin163c9562016-08-29 23:14:17 -0400120 disableEMS := c.config.Bugs.NoExtendedMasterSecret
121 if c.cipherSuite != nil {
122 disableEMS = c.config.Bugs.NoExtendedMasterSecretOnRenegotiation
123 }
124
125 if disableEMS {
Adam Langley75712922014-10-10 16:23:43 -0700126 hello.extendedMasterSecret = false
127 }
128
David Benjamin55a43642015-04-20 14:45:55 -0400129 if c.config.Bugs.NoSupportedCurves {
130 hello.supportedCurves = nil
131 }
132
Steven Valdeza833c352016-11-01 13:39:36 -0400133 if len(c.config.Bugs.SendPSKKeyExchangeModes) != 0 {
134 hello.pskKEModes = c.config.Bugs.SendPSKKeyExchangeModes
135 }
136
David Benjaminc241d792016-09-09 10:34:20 -0400137 if c.config.Bugs.SendCompressionMethods != nil {
138 hello.compressionMethods = c.config.Bugs.SendCompressionMethods
139 }
140
David Benjamina81967b2016-12-22 09:16:57 -0500141 if c.config.Bugs.SendSupportedPointFormats != nil {
142 hello.supportedPoints = c.config.Bugs.SendSupportedPointFormats
143 }
144
Adam Langley2ae77d22014-10-28 17:29:33 -0700145 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
146 if c.config.Bugs.BadRenegotiationInfo {
147 hello.secureRenegotiation = append(hello.secureRenegotiation, c.clientVerify...)
148 hello.secureRenegotiation[0] ^= 0x80
149 } else {
150 hello.secureRenegotiation = c.clientVerify
151 }
152 }
153
David Benjamin3e052de2015-11-25 20:10:31 -0500154 if c.noRenegotiationInfo() {
David Benjaminca6554b2014-11-08 12:31:52 -0500155 hello.secureRenegotiation = nil
156 }
157
Nick Harperb41d2e42016-07-01 17:50:32 -0400158 var keyShares map[CurveID]ecdhCurve
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400159 if maxVersion >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -0400160 keyShares = make(map[CurveID]ecdhCurve)
Nick Harperdcfbc672016-07-16 17:47:31 +0200161 hello.hasKeyShares = true
David Benjamin7e1f9842016-09-20 19:24:40 -0400162 hello.trailingKeyShareData = c.config.Bugs.TrailingKeyShareData
Nick Harperdcfbc672016-07-16 17:47:31 +0200163 curvesToSend := c.config.defaultCurves()
Nick Harperb41d2e42016-07-01 17:50:32 -0400164 for _, curveID := range hello.supportedCurves {
Nick Harperdcfbc672016-07-16 17:47:31 +0200165 if !curvesToSend[curveID] {
166 continue
167 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400168 curve, ok := curveForCurveID(curveID)
169 if !ok {
170 continue
171 }
172 publicKey, err := curve.offer(c.config.rand())
173 if err != nil {
174 return err
175 }
Steven Valdez0ee2e112016-07-15 06:51:15 -0400176
177 if c.config.Bugs.SendCurve != 0 {
178 curveID = c.config.Bugs.SendCurve
179 }
180 if c.config.Bugs.InvalidECDHPoint {
181 publicKey[0] ^= 0xff
182 }
183
Nick Harperb41d2e42016-07-01 17:50:32 -0400184 hello.keyShares = append(hello.keyShares, keyShareEntry{
185 group: curveID,
186 keyExchange: publicKey,
187 })
188 keyShares[curveID] = curve
Steven Valdez143e8b32016-07-11 13:19:03 -0400189
190 if c.config.Bugs.DuplicateKeyShares {
191 hello.keyShares = append(hello.keyShares, hello.keyShares[len(hello.keyShares)-1])
192 }
193 }
194
195 if c.config.Bugs.MissingKeyShare {
Steven Valdez5440fe02016-07-18 12:40:30 -0400196 hello.hasKeyShares = false
Nick Harperb41d2e42016-07-01 17:50:32 -0400197 }
198 }
199
Adam Langley95c29f32014-06-20 12:00:00 -0700200 possibleCipherSuites := c.config.cipherSuites()
201 hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
202
203NextCipherSuite:
204 for _, suiteId := range possibleCipherSuites {
205 for _, suite := range cipherSuites {
206 if suite.id != suiteId {
207 continue
208 }
David Benjamin5ecb88b2016-10-04 17:51:35 -0400209 // Don't advertise TLS 1.2-only cipher suites unless
210 // we're attempting TLS 1.2.
211 if maxVersion < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
212 continue
213 }
214 // Don't advertise non-DTLS cipher suites in DTLS.
215 if c.isDTLS && suite.flags&suiteNoDTLS != 0 {
216 continue
David Benjamin83c0bc92014-08-04 01:23:53 -0400217 }
Adam Langley95c29f32014-06-20 12:00:00 -0700218 hello.cipherSuites = append(hello.cipherSuites, suiteId)
219 continue NextCipherSuite
220 }
221 }
222
David Benjamin5ecb88b2016-10-04 17:51:35 -0400223 if c.config.Bugs.AdvertiseAllConfiguredCiphers {
224 hello.cipherSuites = possibleCipherSuites
225 }
226
Adam Langley5021b222015-06-12 18:27:58 -0700227 if c.config.Bugs.SendRenegotiationSCSV {
228 hello.cipherSuites = append(hello.cipherSuites, renegotiationSCSV)
229 }
230
David Benjaminbef270a2014-08-02 04:22:02 -0400231 if c.config.Bugs.SendFallbackSCSV {
232 hello.cipherSuites = append(hello.cipherSuites, fallbackSCSV)
233 }
234
Adam Langley95c29f32014-06-20 12:00:00 -0700235 _, err := io.ReadFull(c.config.rand(), hello.random)
236 if err != nil {
237 c.sendAlert(alertInternalError)
238 return errors.New("tls: short read from Rand: " + err.Error())
239 }
240
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400241 if maxVersion >= VersionTLS12 && !c.config.Bugs.NoSignatureAlgorithms {
David Benjamin7a41d372016-07-09 11:21:54 -0700242 hello.signatureAlgorithms = c.config.verifySignatureAlgorithms()
Adam Langley95c29f32014-06-20 12:00:00 -0700243 }
244
245 var session *ClientSessionState
246 var cacheKey string
247 sessionCache := c.config.ClientSessionCache
Adam Langley95c29f32014-06-20 12:00:00 -0700248
249 if sessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500250 hello.ticketSupported = !c.config.SessionTicketsDisabled
Adam Langley95c29f32014-06-20 12:00:00 -0700251
252 // Try to resume a previously negotiated TLS session, if
253 // available.
254 cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
Nick Harper0b3625b2016-07-25 16:16:28 -0700255 // TODO(nharper): Support storing more than one session
256 // ticket for TLS 1.3.
Adam Langley95c29f32014-06-20 12:00:00 -0700257 candidateSession, ok := sessionCache.Get(cacheKey)
258 if ok {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500259 ticketOk := !c.config.SessionTicketsDisabled || candidateSession.sessionTicket == nil
260
Adam Langley95c29f32014-06-20 12:00:00 -0700261 // Check that the ciphersuite/version used for the
262 // previous session are still valid.
263 cipherSuiteOk := false
David Benjamin2b02f4b2016-11-16 16:11:47 +0900264 if candidateSession.vers <= VersionTLS12 {
265 for _, id := range hello.cipherSuites {
266 if id == candidateSession.cipherSuite {
267 cipherSuiteOk = true
268 break
269 }
Adam Langley95c29f32014-06-20 12:00:00 -0700270 }
David Benjamin2b02f4b2016-11-16 16:11:47 +0900271 } else {
272 // TLS 1.3 allows the cipher to change on
273 // resumption.
274 cipherSuiteOk = true
Adam Langley95c29f32014-06-20 12:00:00 -0700275 }
276
Steven Valdezfdd10992016-09-15 16:27:05 -0400277 versOk := candidateSession.vers >= minVersion &&
278 candidateSession.vers <= maxVersion
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500279 if ticketOk && versOk && cipherSuiteOk {
Adam Langley95c29f32014-06-20 12:00:00 -0700280 session = candidateSession
281 }
282 }
283 }
284
Steven Valdeza833c352016-11-01 13:39:36 -0400285 var pskCipherSuite *cipherSuite
Nick Harper0b3625b2016-07-25 16:16:28 -0700286 if session != nil && c.config.time().Before(session.ticketExpiration) {
David Benjamind5a4ecb2016-07-18 01:17:13 +0200287 ticket := session.sessionTicket
David Benjamin4199b0d2016-11-01 13:58:25 -0400288 if c.config.Bugs.FilterTicket != nil && len(ticket) > 0 {
289 // Copy the ticket so FilterTicket may act in-place.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200290 ticket = make([]byte, len(session.sessionTicket))
291 copy(ticket, session.sessionTicket)
David Benjamin4199b0d2016-11-01 13:58:25 -0400292
293 ticket, err = c.config.Bugs.FilterTicket(ticket)
294 if err != nil {
295 return err
Adam Langley38311732014-10-16 19:04:35 -0700296 }
David Benjamind5a4ecb2016-07-18 01:17:13 +0200297 }
298
David Benjamin405da482016-08-08 17:25:07 -0400299 if session.vers >= VersionTLS13 || c.config.Bugs.SendBothTickets {
Steven Valdeza833c352016-11-01 13:39:36 -0400300 pskCipherSuite = cipherSuiteFromID(session.cipherSuite)
301 if pskCipherSuite == nil {
302 return errors.New("tls: client session cache has invalid cipher suite")
303 }
Nick Harper0b3625b2016-07-25 16:16:28 -0700304 // TODO(nharper): Support sending more
305 // than one PSK identity.
Steven Valdeza833c352016-11-01 13:39:36 -0400306 ticketAge := uint32(c.config.time().Sub(session.ticketCreationTime) / time.Millisecond)
David Benjamin35ac5b72017-03-03 15:05:56 -0500307 if c.config.Bugs.SendTicketAge != 0 {
308 ticketAge = uint32(c.config.Bugs.SendTicketAge / time.Millisecond)
309 }
Steven Valdez5b986082016-09-01 12:29:49 -0400310 psk := pskIdentity{
Steven Valdeza833c352016-11-01 13:39:36 -0400311 ticket: ticket,
312 obfuscatedTicketAge: session.ticketAgeAdd + ticketAge,
Nick Harper0b3625b2016-07-25 16:16:28 -0700313 }
Steven Valdez5b986082016-09-01 12:29:49 -0400314 hello.pskIdentities = []pskIdentity{psk}
Steven Valdezaf3b8a92016-11-01 12:49:22 -0400315
316 if c.config.Bugs.ExtraPSKIdentity {
317 hello.pskIdentities = append(hello.pskIdentities, psk)
318 }
David Benjamin405da482016-08-08 17:25:07 -0400319 }
320
321 if session.vers < VersionTLS13 || c.config.Bugs.SendBothTickets {
322 if ticket != nil {
323 hello.sessionTicket = ticket
324 // A random session ID is used to detect when the
325 // server accepted the ticket and is resuming a session
326 // (see RFC 5077).
327 sessionIdLen := 16
David Benjamind4c349b2017-02-09 14:07:17 -0500328 if c.config.Bugs.TicketSessionIDLength != 0 {
329 sessionIdLen = c.config.Bugs.TicketSessionIDLength
330 }
331 if c.config.Bugs.EmptyTicketSessionID {
332 sessionIdLen = 0
David Benjamin405da482016-08-08 17:25:07 -0400333 }
334 hello.sessionId = make([]byte, sessionIdLen)
335 if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
336 c.sendAlert(alertInternalError)
337 return errors.New("tls: short read from Rand: " + err.Error())
338 }
339 } else {
340 hello.sessionId = session.sessionId
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500341 }
Adam Langley95c29f32014-06-20 12:00:00 -0700342 }
343 }
344
David Benjamin75f99142016-11-12 12:36:06 +0900345 if c.config.Bugs.SendCipherSuites != nil {
346 hello.cipherSuites = c.config.Bugs.SendCipherSuites
347 }
348
Nick Harperf2511f12016-12-06 16:02:31 -0800349 var sendEarlyData bool
Steven Valdez2d850622017-01-11 11:34:52 -0500350 if len(hello.pskIdentities) > 0 && c.config.Bugs.SendEarlyData != nil {
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500351 hello.hasEarlyData = true
Nick Harperf2511f12016-12-06 16:02:31 -0800352 sendEarlyData = true
353 }
354 if c.config.Bugs.SendFakeEarlyDataLength > 0 {
355 hello.hasEarlyData = true
356 }
357 if c.config.Bugs.OmitEarlyDataExtension {
358 hello.hasEarlyData = false
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500359 }
Steven Valdez0e4a4482017-07-17 11:12:34 -0400360 if c.config.Bugs.SendClientHelloSessionID != nil {
361 hello.sessionId = c.config.Bugs.SendClientHelloSessionID
362 }
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500363
David Benjamind86c7672014-08-02 04:07:12 -0400364 var helloBytes []byte
365 if c.config.Bugs.SendV2ClientHello {
David Benjamin94d701b2014-11-30 13:54:41 -0500366 // Test that the peer left-pads random.
367 hello.random[0] = 0
David Benjamind86c7672014-08-02 04:07:12 -0400368 v2Hello := &v2ClientHelloMsg{
369 vers: hello.vers,
370 cipherSuites: hello.cipherSuites,
371 // No session resumption for V2ClientHello.
372 sessionId: nil,
David Benjamin94d701b2014-11-30 13:54:41 -0500373 challenge: hello.random[1:],
David Benjamind86c7672014-08-02 04:07:12 -0400374 }
375 helloBytes = v2Hello.marshal()
376 c.writeV2Record(helloBytes)
377 } else {
Steven Valdeza833c352016-11-01 13:39:36 -0400378 if len(hello.pskIdentities) > 0 {
379 generatePSKBinders(hello, pskCipherSuite, session.masterSecret, []byte{}, c.config)
380 }
David Benjamind86c7672014-08-02 04:07:12 -0400381 helloBytes = hello.marshal()
Steven Valdeza833c352016-11-01 13:39:36 -0400382
David Benjamin7964b182016-07-14 23:36:30 -0400383 if c.config.Bugs.PartialClientFinishedWithClientHello {
384 // Include one byte of Finished. We can compute it
385 // without completing the handshake. This assumes we
386 // negotiate TLS 1.3 with no HelloRetryRequest or
387 // CertificateRequest.
388 toWrite := make([]byte, 0, len(helloBytes)+1)
389 toWrite = append(toWrite, helloBytes...)
390 toWrite = append(toWrite, typeFinished)
391 c.writeRecord(recordTypeHandshake, toWrite)
392 } else {
393 c.writeRecord(recordTypeHandshake, helloBytes)
394 }
David Benjamind86c7672014-08-02 04:07:12 -0400395 }
David Benjamin582ba042016-07-07 12:33:25 -0700396 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700397
David Benjamin83f90402015-01-27 01:09:43 -0500398 if err := c.simulatePacketLoss(nil); err != nil {
399 return err
400 }
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500401 if c.config.Bugs.SendEarlyAlert {
402 c.sendAlert(alertHandshakeFailure)
403 }
Nick Harperf2511f12016-12-06 16:02:31 -0800404 if c.config.Bugs.SendFakeEarlyDataLength > 0 {
405 c.sendFakeEarlyData(c.config.Bugs.SendFakeEarlyDataLength)
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500406 }
Nick Harperf2511f12016-12-06 16:02:31 -0800407
408 // Derive early write keys and set Conn state to allow early writes.
409 if sendEarlyData {
410 finishedHash := newFinishedHash(session.vers, pskCipherSuite)
411 finishedHash.addEntropy(session.masterSecret)
412 finishedHash.Write(helloBytes)
413 earlyTrafficSecret := finishedHash.deriveSecret(earlyTrafficLabel)
Steven Valdezc7d4d212017-09-11 13:53:08 -0400414 c.out.useTrafficSecret(session.wireVersion, pskCipherSuite, earlyTrafficSecret, clientWrite)
Nick Harperf2511f12016-12-06 16:02:31 -0800415 for _, earlyData := range c.config.Bugs.SendEarlyData {
416 if _, err := c.writeRecord(recordTypeApplicationData, earlyData); err != nil {
417 return err
418 }
419 }
420 }
421
Adam Langley95c29f32014-06-20 12:00:00 -0700422 msg, err := c.readHandshake()
423 if err != nil {
424 return err
425 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400426
427 if c.isDTLS {
428 helloVerifyRequest, ok := msg.(*helloVerifyRequestMsg)
429 if ok {
Steven Valdezc94998a2017-06-20 10:55:02 -0400430 if helloVerifyRequest.vers != VersionDTLS10 {
David Benjamin8bc38f52014-08-16 12:07:27 -0400431 // Per RFC 6347, the version field in
432 // HelloVerifyRequest SHOULD be always DTLS
433 // 1.0. Enforce this for testing purposes.
434 return errors.New("dtls: bad HelloVerifyRequest version")
435 }
436
David Benjamin83c0bc92014-08-04 01:23:53 -0400437 hello.raw = nil
438 hello.cookie = helloVerifyRequest.cookie
439 helloBytes = hello.marshal()
440 c.writeRecord(recordTypeHandshake, helloBytes)
David Benjamin582ba042016-07-07 12:33:25 -0700441 c.flushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400442
David Benjamin83f90402015-01-27 01:09:43 -0500443 if err := c.simulatePacketLoss(nil); err != nil {
444 return err
445 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400446 msg, err = c.readHandshake()
447 if err != nil {
448 return err
449 }
450 }
451 }
452
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400453 var serverWireVersion uint16
Nick Harperdcfbc672016-07-16 17:47:31 +0200454 switch m := msg.(type) {
455 case *helloRetryRequestMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400456 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200457 case *serverHelloMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400458 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200459 default:
460 c.sendAlert(alertUnexpectedMessage)
461 return fmt.Errorf("tls: received unexpected message of type %T when waiting for HelloRetryRequest or ServerHello", msg)
462 }
463
Steven Valdezc94998a2017-06-20 10:55:02 -0400464 serverVersion, ok := c.config.isSupportedVersion(serverWireVersion, c.isDTLS)
Nick Harperdcfbc672016-07-16 17:47:31 +0200465 if !ok {
466 c.sendAlert(alertProtocolVersion)
467 return fmt.Errorf("tls: server selected unsupported protocol version %x", c.vers)
468 }
Steven Valdezc94998a2017-06-20 10:55:02 -0400469 c.wireVersion = serverWireVersion
Steven Valdezfdd10992016-09-15 16:27:05 -0400470 c.vers = serverVersion
Nick Harperdcfbc672016-07-16 17:47:31 +0200471 c.haveVers = true
472
473 helloRetryRequest, haveHelloRetryRequest := msg.(*helloRetryRequestMsg)
474 var secondHelloBytes []byte
475 if haveHelloRetryRequest {
Nick Harperf2511f12016-12-06 16:02:31 -0800476 c.out.resetCipher()
David Benjamin3baa6e12016-10-07 21:10:38 -0400477 if len(helloRetryRequest.cookie) > 0 {
478 hello.tls13Cookie = helloRetryRequest.cookie
479 }
480
Steven Valdez5440fe02016-07-18 12:40:30 -0400481 if c.config.Bugs.MisinterpretHelloRetryRequestCurve != 0 {
David Benjamin3baa6e12016-10-07 21:10:38 -0400482 helloRetryRequest.hasSelectedGroup = true
Steven Valdez5440fe02016-07-18 12:40:30 -0400483 helloRetryRequest.selectedGroup = c.config.Bugs.MisinterpretHelloRetryRequestCurve
484 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400485 if helloRetryRequest.hasSelectedGroup {
486 var hrrCurveFound bool
487 group := helloRetryRequest.selectedGroup
488 for _, curveID := range hello.supportedCurves {
489 if group == curveID {
490 hrrCurveFound = true
491 break
492 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200493 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400494 if !hrrCurveFound || keyShares[group] != nil {
495 c.sendAlert(alertHandshakeFailure)
496 return errors.New("tls: received invalid HelloRetryRequest")
497 }
498 curve, ok := curveForCurveID(group)
499 if !ok {
500 return errors.New("tls: Unable to get curve requested in HelloRetryRequest")
501 }
502 publicKey, err := curve.offer(c.config.rand())
503 if err != nil {
504 return err
505 }
506 keyShares[group] = curve
Steven Valdeza833c352016-11-01 13:39:36 -0400507 hello.keyShares = []keyShareEntry{{
David Benjamin3baa6e12016-10-07 21:10:38 -0400508 group: group,
509 keyExchange: publicKey,
Steven Valdeza833c352016-11-01 13:39:36 -0400510 }}
Nick Harperdcfbc672016-07-16 17:47:31 +0200511 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200512
Steven Valdez5440fe02016-07-18 12:40:30 -0400513 if c.config.Bugs.SecondClientHelloMissingKeyShare {
514 hello.hasKeyShares = false
515 }
516
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500517 hello.hasEarlyData = c.config.Bugs.SendEarlyDataOnSecondClientHello
Nick Harperdcfbc672016-07-16 17:47:31 +0200518 hello.raw = nil
519
Steven Valdeza833c352016-11-01 13:39:36 -0400520 if len(hello.pskIdentities) > 0 {
521 generatePSKBinders(hello, pskCipherSuite, session.masterSecret, append(helloBytes, helloRetryRequest.marshal()...), c.config)
522 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200523 secondHelloBytes = hello.marshal()
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500524
525 if c.config.Bugs.InterleaveEarlyData {
526 c.sendFakeEarlyData(4)
527 c.writeRecord(recordTypeHandshake, secondHelloBytes[:16])
528 c.sendFakeEarlyData(4)
529 c.writeRecord(recordTypeHandshake, secondHelloBytes[16:])
530 } else {
531 c.writeRecord(recordTypeHandshake, secondHelloBytes)
532 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200533 c.flushHandshake()
534
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500535 if c.config.Bugs.SendEarlyDataOnSecondClientHello {
536 c.sendFakeEarlyData(4)
537 }
538
Nick Harperdcfbc672016-07-16 17:47:31 +0200539 msg, err = c.readHandshake()
540 if err != nil {
541 return err
542 }
543 }
544
Adam Langley95c29f32014-06-20 12:00:00 -0700545 serverHello, ok := msg.(*serverHelloMsg)
546 if !ok {
547 c.sendAlert(alertUnexpectedMessage)
548 return unexpectedMessageError(serverHello, msg)
549 }
550
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400551 if serverWireVersion != serverHello.vers {
Adam Langley95c29f32014-06-20 12:00:00 -0700552 c.sendAlert(alertProtocolVersion)
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400553 return fmt.Errorf("tls: server sent non-matching version %x vs %x", serverWireVersion, serverHello.vers)
Adam Langley95c29f32014-06-20 12:00:00 -0700554 }
Adam Langley95c29f32014-06-20 12:00:00 -0700555
Nick Harper85f20c22016-07-04 10:11:59 -0700556 // Check for downgrade signals in the server random, per
David Benjamina128a552016-10-13 14:26:33 -0400557 // draft-ietf-tls-tls13-16, section 4.1.3.
Nick Harper85f20c22016-07-04 10:11:59 -0700558 if c.vers <= VersionTLS12 && c.config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400559 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS13) {
Nick Harper85f20c22016-07-04 10:11:59 -0700560 c.sendAlert(alertProtocolVersion)
561 return errors.New("tls: downgrade from TLS 1.3 detected")
562 }
563 }
564 if c.vers <= VersionTLS11 && c.config.maxVersion(c.isDTLS) >= VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400565 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS12) {
Nick Harper85f20c22016-07-04 10:11:59 -0700566 c.sendAlert(alertProtocolVersion)
567 return errors.New("tls: downgrade from TLS 1.2 detected")
568 }
569 }
570
Nick Harper0b3625b2016-07-25 16:16:28 -0700571 suite := mutualCipherSuite(hello.cipherSuites, serverHello.cipherSuite)
Adam Langley95c29f32014-06-20 12:00:00 -0700572 if suite == nil {
573 c.sendAlert(alertHandshakeFailure)
574 return fmt.Errorf("tls: server selected an unsupported cipher suite")
575 }
576
David Benjamin3baa6e12016-10-07 21:10:38 -0400577 if haveHelloRetryRequest && helloRetryRequest.hasSelectedGroup && helloRetryRequest.selectedGroup != serverHello.keyShare.group {
Nick Harperdcfbc672016-07-16 17:47:31 +0200578 c.sendAlert(alertHandshakeFailure)
579 return errors.New("tls: ServerHello parameters did not match HelloRetryRequest")
580 }
581
David Benjamin0a471912017-08-31 00:19:57 -0400582 if c.config.Bugs.ExpectOmitExtensions && !serverHello.omitExtensions {
583 return errors.New("tls: ServerHello did not omit extensions")
584 }
585
Adam Langley95c29f32014-06-20 12:00:00 -0700586 hs := &clientHandshakeState{
587 c: c,
588 serverHello: serverHello,
589 hello: hello,
590 suite: suite,
591 finishedHash: newFinishedHash(c.vers, suite),
Nick Harperb41d2e42016-07-01 17:50:32 -0400592 keyShares: keyShares,
Adam Langley95c29f32014-06-20 12:00:00 -0700593 session: session,
594 }
595
David Benjamin83c0bc92014-08-04 01:23:53 -0400596 hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1)
Nick Harperdcfbc672016-07-16 17:47:31 +0200597 if haveHelloRetryRequest {
598 hs.writeServerHash(helloRetryRequest.marshal())
599 hs.writeClientHash(secondHelloBytes)
600 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400601 hs.writeServerHash(hs.serverHello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700602
David Benjamin8d315d72016-07-18 01:03:18 +0200603 if c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -0400604 if err := hs.doTLS13Handshake(); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700605 return err
606 }
607 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400608 if c.config.Bugs.EarlyChangeCipherSpec > 0 {
609 hs.establishKeys()
610 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
611 }
612
613 if hs.serverHello.compressionMethod != compressionNone {
614 c.sendAlert(alertUnexpectedMessage)
615 return errors.New("tls: server selected unsupported compression format")
616 }
617
618 err = hs.processServerExtensions(&serverHello.extensions)
619 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700620 return err
621 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400622
623 isResume, err := hs.processServerHello()
624 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700625 return err
626 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400627
628 if isResume {
629 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
630 if err := hs.establishKeys(); err != nil {
631 return err
632 }
633 }
634 if err := hs.readSessionTicket(); err != nil {
635 return err
636 }
637 if err := hs.readFinished(c.firstFinished[:]); err != nil {
638 return err
639 }
640 if err := hs.sendFinished(nil, isResume); err != nil {
641 return err
642 }
643 } else {
644 if err := hs.doFullHandshake(); err != nil {
645 return err
646 }
647 if err := hs.establishKeys(); err != nil {
648 return err
649 }
650 if err := hs.sendFinished(c.firstFinished[:], isResume); err != nil {
651 return err
652 }
653 // Most retransmits are triggered by a timeout, but the final
654 // leg of the handshake is retransmited upon re-receiving a
655 // Finished.
656 if err := c.simulatePacketLoss(func() {
David Benjamin02edcd02016-07-27 17:40:37 -0400657 c.sendHandshakeSeq--
Nick Harperb41d2e42016-07-01 17:50:32 -0400658 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
659 c.flushHandshake()
660 }); err != nil {
661 return err
662 }
663 if err := hs.readSessionTicket(); err != nil {
664 return err
665 }
666 if err := hs.readFinished(nil); err != nil {
667 return err
668 }
Adam Langley95c29f32014-06-20 12:00:00 -0700669 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400670
671 if sessionCache != nil && hs.session != nil && session != hs.session {
672 if c.config.Bugs.RequireSessionTickets && len(hs.session.sessionTicket) == 0 {
673 return errors.New("tls: new session used session IDs instead of tickets")
674 }
675 sessionCache.Put(cacheKey, hs.session)
David Benjamin83f90402015-01-27 01:09:43 -0500676 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400677
678 c.didResume = isResume
David Benjamin97a0a082016-07-13 17:57:35 -0400679 c.exporterSecret = hs.masterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700680 }
681
Adam Langley95c29f32014-06-20 12:00:00 -0700682 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400683 c.cipherSuite = suite
684 copy(c.clientRandom[:], hs.hello.random)
685 copy(c.serverRandom[:], hs.serverHello.random)
Paul Lietar4fac72e2015-09-09 13:44:55 +0100686
Adam Langley95c29f32014-06-20 12:00:00 -0700687 return nil
688}
689
Nick Harperb41d2e42016-07-01 17:50:32 -0400690func (hs *clientHandshakeState) doTLS13Handshake() error {
691 c := hs.c
692
Steven Valdez16821262017-09-08 17:03:42 -0400693 if isResumptionExperiment(c.wireVersion) && !bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) {
Steven Valdez0e4a4482017-07-17 11:12:34 -0400694 return errors.New("tls: session IDs did not match.")
695 }
696
Nick Harperb41d2e42016-07-01 17:50:32 -0400697 // Once the PRF hash is known, TLS 1.3 does not require a handshake
698 // buffer.
699 hs.finishedHash.discardHandshakeBuffer()
700
701 zeroSecret := hs.finishedHash.zeroSecret()
702
703 // Resolve PSK and compute the early secret.
704 //
705 // TODO(davidben): This will need to be handled slightly earlier once
706 // 0-RTT is implemented.
Steven Valdez803c77a2016-09-06 14:13:43 -0400707 if hs.serverHello.hasPSKIdentity {
Nick Harper0b3625b2016-07-25 16:16:28 -0700708 // We send at most one PSK identity.
709 if hs.session == nil || hs.serverHello.pskIdentity != 0 {
710 c.sendAlert(alertUnknownPSKIdentity)
711 return errors.New("tls: server sent unknown PSK identity")
712 }
David Benjamin2b02f4b2016-11-16 16:11:47 +0900713 sessionCipher := cipherSuiteFromID(hs.session.cipherSuite)
714 if sessionCipher == nil || sessionCipher.hash() != hs.suite.hash() {
Nick Harper0b3625b2016-07-25 16:16:28 -0700715 c.sendAlert(alertHandshakeFailure)
David Benjamin2b02f4b2016-11-16 16:11:47 +0900716 return errors.New("tls: server resumed an invalid session for the cipher suite")
Nick Harper0b3625b2016-07-25 16:16:28 -0700717 }
David Benjamin48891ad2016-12-04 00:02:43 -0500718 hs.finishedHash.addEntropy(hs.session.masterSecret)
Nick Harper0b3625b2016-07-25 16:16:28 -0700719 c.didResume = true
Nick Harperb41d2e42016-07-01 17:50:32 -0400720 } else {
David Benjamin48891ad2016-12-04 00:02:43 -0500721 hs.finishedHash.addEntropy(zeroSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400722 }
723
Steven Valdeza833c352016-11-01 13:39:36 -0400724 if !hs.serverHello.hasKeyShare {
725 c.sendAlert(alertUnsupportedExtension)
726 return errors.New("tls: server omitted KeyShare on resumption.")
727 }
728
Nick Harperb41d2e42016-07-01 17:50:32 -0400729 // Resolve ECDHE and compute the handshake secret.
Steven Valdez803c77a2016-09-06 14:13:43 -0400730 if !c.config.Bugs.MissingKeyShare && !c.config.Bugs.SecondClientHelloMissingKeyShare {
Nick Harperb41d2e42016-07-01 17:50:32 -0400731 curve, ok := hs.keyShares[hs.serverHello.keyShare.group]
732 if !ok {
733 c.sendAlert(alertHandshakeFailure)
734 return errors.New("tls: server selected an unsupported group")
735 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400736 c.curveID = hs.serverHello.keyShare.group
Nick Harperb41d2e42016-07-01 17:50:32 -0400737
David Benjamin48891ad2016-12-04 00:02:43 -0500738 ecdheSecret, err := curve.finish(hs.serverHello.keyShare.keyExchange)
Nick Harperb41d2e42016-07-01 17:50:32 -0400739 if err != nil {
740 return err
741 }
David Benjamin48891ad2016-12-04 00:02:43 -0500742 hs.finishedHash.addEntropy(ecdheSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400743 } else {
David Benjamin48891ad2016-12-04 00:02:43 -0500744 hs.finishedHash.addEntropy(zeroSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400745 }
746
Steven Valdez16821262017-09-08 17:03:42 -0400747 if isResumptionExperiment(c.wireVersion) {
Steven Valdez520e1222017-06-13 12:45:25 -0400748 if err := c.readRecord(recordTypeChangeCipherSpec); err != nil {
749 return err
750 }
751 }
752
Nick Harperf2511f12016-12-06 16:02:31 -0800753 // Derive handshake traffic keys and switch read key to handshake
754 // traffic key.
David Benjamin48891ad2016-12-04 00:02:43 -0500755 clientHandshakeTrafficSecret := hs.finishedHash.deriveSecret(clientHandshakeTrafficLabel)
David Benjamin48891ad2016-12-04 00:02:43 -0500756 serverHandshakeTrafficSecret := hs.finishedHash.deriveSecret(serverHandshakeTrafficLabel)
Steven Valdezc7d4d212017-09-11 13:53:08 -0400757 c.in.useTrafficSecret(c.wireVersion, hs.suite, serverHandshakeTrafficSecret, serverWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -0400758
759 msg, err := c.readHandshake()
760 if err != nil {
761 return err
762 }
763
764 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
765 if !ok {
766 c.sendAlert(alertUnexpectedMessage)
767 return unexpectedMessageError(encryptedExtensions, msg)
768 }
769 hs.writeServerHash(encryptedExtensions.marshal())
770
771 err = hs.processServerExtensions(&encryptedExtensions.extensions)
772 if err != nil {
773 return err
774 }
775
776 var chainToSend *Certificate
David Benjamin8d343b42016-07-09 14:26:01 -0700777 var certReq *certificateRequestMsg
Steven Valdeza833c352016-11-01 13:39:36 -0400778 if c.didResume {
Nick Harper0b3625b2016-07-25 16:16:28 -0700779 // Copy over authentication from the session.
780 c.peerCertificates = hs.session.serverCertificates
781 c.sctList = hs.session.sctList
782 c.ocspResponse = hs.session.ocspResponse
David Benjamin44b33bc2016-07-01 22:40:23 -0400783 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400784 msg, err := c.readHandshake()
785 if err != nil {
786 return err
787 }
788
David Benjamin8d343b42016-07-09 14:26:01 -0700789 var ok bool
790 certReq, ok = msg.(*certificateRequestMsg)
Nick Harperb41d2e42016-07-01 17:50:32 -0400791 if ok {
David Benjamin8a8349b2016-08-18 02:32:23 -0400792 if len(certReq.requestContext) != 0 {
793 return errors.New("tls: non-empty certificate request context sent in handshake")
794 }
795
David Benjaminb62d2872016-07-18 14:55:02 +0200796 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
797 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
798 }
799
Nick Harperb41d2e42016-07-01 17:50:32 -0400800 hs.writeServerHash(certReq.marshal())
Nick Harperb41d2e42016-07-01 17:50:32 -0400801
802 chainToSend, err = selectClientCertificate(c, certReq)
803 if err != nil {
804 return err
805 }
806
807 msg, err = c.readHandshake()
808 if err != nil {
809 return err
810 }
811 }
812
813 certMsg, ok := msg.(*certificateMsg)
814 if !ok {
815 c.sendAlert(alertUnexpectedMessage)
816 return unexpectedMessageError(certMsg, msg)
817 }
818 hs.writeServerHash(certMsg.marshal())
819
David Benjamin53210cb2016-11-16 09:01:48 +0900820 // Check for unsolicited extensions.
821 for i, cert := range certMsg.certificates {
822 if c.config.Bugs.NoOCSPStapling && cert.ocspResponse != nil {
823 c.sendAlert(alertUnsupportedExtension)
824 return errors.New("tls: unexpected OCSP response in the server certificate")
825 }
826 if c.config.Bugs.NoSignedCertificateTimestamps && cert.sctList != nil {
827 c.sendAlert(alertUnsupportedExtension)
828 return errors.New("tls: unexpected SCT list in the server certificate")
829 }
830 if i > 0 && c.config.Bugs.ExpectNoExtensionsOnIntermediate && (cert.ocspResponse != nil || cert.sctList != nil) {
831 c.sendAlert(alertUnsupportedExtension)
832 return errors.New("tls: unexpected extensions in the server certificate")
833 }
834 }
835
Nick Harperb41d2e42016-07-01 17:50:32 -0400836 if err := hs.verifyCertificates(certMsg); err != nil {
837 return err
838 }
839 leaf := c.peerCertificates[0]
Steven Valdeza833c352016-11-01 13:39:36 -0400840 c.ocspResponse = certMsg.certificates[0].ocspResponse
841 c.sctList = certMsg.certificates[0].sctList
842
Nick Harperb41d2e42016-07-01 17:50:32 -0400843 msg, err = c.readHandshake()
844 if err != nil {
845 return err
846 }
847 certVerifyMsg, ok := msg.(*certificateVerifyMsg)
848 if !ok {
849 c.sendAlert(alertUnexpectedMessage)
850 return unexpectedMessageError(certVerifyMsg, msg)
851 }
852
David Benjaminf74ec792016-07-13 21:18:49 -0400853 c.peerSignatureAlgorithm = certVerifyMsg.signatureAlgorithm
Nick Harperb41d2e42016-07-01 17:50:32 -0400854 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
David Benjamind768c5d2017-03-28 18:28:44 -0500855 err = verifyMessage(c.vers, getCertificatePublicKey(leaf), c.config, certVerifyMsg.signatureAlgorithm, input, certVerifyMsg.signature)
Nick Harperb41d2e42016-07-01 17:50:32 -0400856 if err != nil {
857 return err
858 }
859
860 hs.writeServerHash(certVerifyMsg.marshal())
861 }
862
863 msg, err = c.readHandshake()
864 if err != nil {
865 return err
866 }
867 serverFinished, ok := msg.(*finishedMsg)
868 if !ok {
869 c.sendAlert(alertUnexpectedMessage)
870 return unexpectedMessageError(serverFinished, msg)
871 }
872
Steven Valdezc4aa7272016-10-03 12:25:56 -0400873 verify := hs.finishedHash.serverSum(serverHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400874 if len(verify) != len(serverFinished.verifyData) ||
875 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
876 c.sendAlert(alertHandshakeFailure)
877 return errors.New("tls: server's Finished message was incorrect")
878 }
879
880 hs.writeServerHash(serverFinished.marshal())
881
882 // The various secrets do not incorporate the client's final leg, so
883 // derive them now before updating the handshake context.
David Benjamin48891ad2016-12-04 00:02:43 -0500884 hs.finishedHash.addEntropy(zeroSecret)
885 clientTrafficSecret := hs.finishedHash.deriveSecret(clientApplicationTrafficLabel)
886 serverTrafficSecret := hs.finishedHash.deriveSecret(serverApplicationTrafficLabel)
David Benjamincdb6fe92017-02-07 16:06:48 -0500887 c.exporterSecret = hs.finishedHash.deriveSecret(exporterLabel)
888
889 // Switch to application data keys on read. In particular, any alerts
890 // from the client certificate are read over these keys.
Steven Valdezc7d4d212017-09-11 13:53:08 -0400891 c.in.useTrafficSecret(c.wireVersion, hs.suite, serverTrafficSecret, serverWrite)
Nick Harper7cd0a972016-12-02 11:08:40 -0800892
893 // If we're expecting 0.5-RTT messages from the server, read them
894 // now.
David Benjamin794cc592017-03-25 22:24:23 -0500895 if encryptedExtensions.extensions.hasEarlyData {
896 // BoringSSL will always send two tickets half-RTT when
897 // negotiating 0-RTT.
898 for i := 0; i < shimConfig.HalfRTTTickets; i++ {
899 msg, err := c.readHandshake()
900 if err != nil {
901 return fmt.Errorf("tls: error reading half-RTT ticket: %s", err)
902 }
903 newSessionTicket, ok := msg.(*newSessionTicketMsg)
904 if !ok {
905 return errors.New("tls: expected half-RTT ticket")
906 }
907 if err := c.processTLS13NewSessionTicket(newSessionTicket, hs.suite); err != nil {
908 return err
909 }
Nick Harper7cd0a972016-12-02 11:08:40 -0800910 }
David Benjamin794cc592017-03-25 22:24:23 -0500911 for _, expectedMsg := range c.config.Bugs.ExpectHalfRTTData {
912 if err := c.readRecord(recordTypeApplicationData); err != nil {
913 return err
914 }
915 if !bytes.Equal(c.input.data[c.input.off:], expectedMsg) {
916 return errors.New("ExpectHalfRTTData: did not get expected message")
917 }
918 c.in.freeBlock(c.input)
919 c.input = nil
Nick Harper7cd0a972016-12-02 11:08:40 -0800920 }
Nick Harper7cd0a972016-12-02 11:08:40 -0800921 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400922
Nick Harperf2511f12016-12-06 16:02:31 -0800923 // Send EndOfEarlyData and then switch write key to handshake
924 // traffic key.
David Benjamin32c89272017-03-26 13:54:21 -0500925 if c.out.cipher != nil && !c.config.Bugs.SkipEndOfEarlyData {
Steven Valdez681eb6a2016-12-19 13:19:29 -0500926 if c.config.Bugs.SendStrayEarlyHandshake {
927 helloRequest := new(helloRequestMsg)
928 c.writeRecord(recordTypeHandshake, helloRequest.marshal())
929 }
Nick Harperf2511f12016-12-06 16:02:31 -0800930 c.sendAlert(alertEndOfEarlyData)
931 }
Steven Valdez520e1222017-06-13 12:45:25 -0400932
Steven Valdezc7d4d212017-09-11 13:53:08 -0400933 if isResumptionClientCCSExperiment(c.wireVersion) {
Steven Valdez520e1222017-06-13 12:45:25 -0400934 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
935 }
936
Steven Valdezc7d4d212017-09-11 13:53:08 -0400937 c.out.useTrafficSecret(c.wireVersion, hs.suite, clientHandshakeTrafficSecret, clientWrite)
Nick Harperf2511f12016-12-06 16:02:31 -0800938
Steven Valdez0ee2e112016-07-15 06:51:15 -0400939 if certReq != nil && !c.config.Bugs.SkipClientCertificate {
David Benjamin8d343b42016-07-09 14:26:01 -0700940 certMsg := &certificateMsg{
941 hasRequestContext: true,
942 requestContext: certReq.requestContext,
943 }
944 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -0400945 for _, certData := range chainToSend.Certificate {
946 certMsg.certificates = append(certMsg.certificates, certificateEntry{
947 data: certData,
948 extraExtension: c.config.Bugs.SendExtensionOnCertificate,
949 })
950 }
David Benjamin8d343b42016-07-09 14:26:01 -0700951 }
952 hs.writeClientHash(certMsg.marshal())
953 c.writeRecord(recordTypeHandshake, certMsg.marshal())
954
955 if chainToSend != nil {
956 certVerify := &certificateVerifyMsg{
957 hasSignatureAlgorithm: true,
958 }
959
960 // Determine the hash to sign.
961 privKey := chainToSend.PrivateKey
962
963 var err error
964 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
965 if err != nil {
966 c.sendAlert(alertInternalError)
967 return err
968 }
969
970 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
971 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
972 if err != nil {
973 c.sendAlert(alertInternalError)
974 return err
975 }
Steven Valdez0ee2e112016-07-15 06:51:15 -0400976 if c.config.Bugs.SendSignatureAlgorithm != 0 {
977 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
978 }
David Benjamin8d343b42016-07-09 14:26:01 -0700979
Dimitar Vlahovskibd708452017-08-10 18:01:06 +0200980 if !c.config.Bugs.SkipCertificateVerify {
981 hs.writeClientHash(certVerify.marshal())
982 c.writeRecord(recordTypeHandshake, certVerify.marshal())
983 }
David Benjamin8d343b42016-07-09 14:26:01 -0700984 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400985 }
986
Nick Harper60a85cb2016-09-23 16:25:11 -0700987 if encryptedExtensions.extensions.channelIDRequested {
988 channelIDHash := crypto.SHA256.New()
989 channelIDHash.Write(hs.finishedHash.certificateVerifyInput(channelIDContextTLS13))
990 channelIDMsgBytes, err := hs.writeChannelIDMessage(channelIDHash.Sum(nil))
991 if err != nil {
992 return err
993 }
994 hs.writeClientHash(channelIDMsgBytes)
995 c.writeRecord(recordTypeHandshake, channelIDMsgBytes)
996 }
997
Nick Harperb41d2e42016-07-01 17:50:32 -0400998 // Send a client Finished message.
999 finished := new(finishedMsg)
Steven Valdezc4aa7272016-10-03 12:25:56 -04001000 finished.verifyData = hs.finishedHash.clientSum(clientHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -04001001 if c.config.Bugs.BadFinished {
1002 finished.verifyData[0]++
1003 }
David Benjamin97a0a082016-07-13 17:57:35 -04001004 hs.writeClientHash(finished.marshal())
David Benjamin7964b182016-07-14 23:36:30 -04001005 if c.config.Bugs.PartialClientFinishedWithClientHello {
1006 // The first byte has already been sent.
1007 c.writeRecord(recordTypeHandshake, finished.marshal()[1:])
Steven Valdeza4ee74d2016-11-29 13:36:45 -05001008 } else if c.config.Bugs.InterleaveEarlyData {
1009 finishedBytes := finished.marshal()
1010 c.sendFakeEarlyData(4)
1011 c.writeRecord(recordTypeHandshake, finishedBytes[:1])
1012 c.sendFakeEarlyData(4)
1013 c.writeRecord(recordTypeHandshake, finishedBytes[1:])
David Benjamin7964b182016-07-14 23:36:30 -04001014 } else {
1015 c.writeRecord(recordTypeHandshake, finished.marshal())
1016 }
David Benjamin02edcd02016-07-27 17:40:37 -04001017 if c.config.Bugs.SendExtraFinished {
1018 c.writeRecord(recordTypeHandshake, finished.marshal())
1019 }
David Benjaminee51a222016-07-07 18:34:12 -07001020 c.flushHandshake()
Nick Harperb41d2e42016-07-01 17:50:32 -04001021
1022 // Switch to application data keys.
Steven Valdezc7d4d212017-09-11 13:53:08 -04001023 c.out.useTrafficSecret(c.wireVersion, hs.suite, clientTrafficSecret, clientWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -04001024
David Benjamin48891ad2016-12-04 00:02:43 -05001025 c.resumptionSecret = hs.finishedHash.deriveSecret(resumptionLabel)
Nick Harperb41d2e42016-07-01 17:50:32 -04001026 return nil
1027}
1028
Adam Langley95c29f32014-06-20 12:00:00 -07001029func (hs *clientHandshakeState) doFullHandshake() error {
1030 c := hs.c
1031
David Benjamin48cae082014-10-27 01:06:24 -04001032 var leaf *x509.Certificate
1033 if hs.suite.flags&suitePSK == 0 {
1034 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001035 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -07001036 return err
1037 }
Adam Langley95c29f32014-06-20 12:00:00 -07001038
David Benjamin48cae082014-10-27 01:06:24 -04001039 certMsg, ok := msg.(*certificateMsg)
David Benjamin75051442016-07-01 18:58:51 -04001040 if !ok {
David Benjamin48cae082014-10-27 01:06:24 -04001041 c.sendAlert(alertUnexpectedMessage)
1042 return unexpectedMessageError(certMsg, msg)
1043 }
1044 hs.writeServerHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001045
David Benjamin75051442016-07-01 18:58:51 -04001046 if err := hs.verifyCertificates(certMsg); err != nil {
1047 return err
David Benjamin48cae082014-10-27 01:06:24 -04001048 }
David Benjamin75051442016-07-01 18:58:51 -04001049 leaf = c.peerCertificates[0]
David Benjamin48cae082014-10-27 01:06:24 -04001050 }
Adam Langley95c29f32014-06-20 12:00:00 -07001051
Nick Harperb3d51be2016-07-01 11:43:18 -04001052 if hs.serverHello.extensions.ocspStapling {
David Benjamin48cae082014-10-27 01:06:24 -04001053 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001054 if err != nil {
1055 return err
1056 }
1057 cs, ok := msg.(*certificateStatusMsg)
1058 if !ok {
1059 c.sendAlert(alertUnexpectedMessage)
1060 return unexpectedMessageError(cs, msg)
1061 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001062 hs.writeServerHash(cs.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001063
1064 if cs.statusType == statusTypeOCSP {
1065 c.ocspResponse = cs.response
1066 }
1067 }
1068
David Benjamin48cae082014-10-27 01:06:24 -04001069 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001070 if err != nil {
1071 return err
1072 }
1073
1074 keyAgreement := hs.suite.ka(c.vers)
1075
1076 skx, ok := msg.(*serverKeyExchangeMsg)
1077 if ok {
David Benjamin83c0bc92014-08-04 01:23:53 -04001078 hs.writeServerHash(skx.marshal())
David Benjamin48cae082014-10-27 01:06:24 -04001079 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx)
Adam Langley95c29f32014-06-20 12:00:00 -07001080 if err != nil {
1081 c.sendAlert(alertUnexpectedMessage)
1082 return err
1083 }
Steven Valdez5440fe02016-07-18 12:40:30 -04001084 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1085 c.curveID = ecdhe.curveID
1086 }
Adam Langley95c29f32014-06-20 12:00:00 -07001087
Nick Harper60edffd2016-06-21 15:19:24 -07001088 c.peerSignatureAlgorithm = keyAgreement.peerSignatureAlgorithm()
1089
Adam Langley95c29f32014-06-20 12:00:00 -07001090 msg, err = c.readHandshake()
1091 if err != nil {
1092 return err
1093 }
1094 }
1095
1096 var chainToSend *Certificate
1097 var certRequested bool
1098 certReq, ok := msg.(*certificateRequestMsg)
1099 if ok {
1100 certRequested = true
David Benjamin7a41d372016-07-09 11:21:54 -07001101 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
1102 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
1103 }
Adam Langley95c29f32014-06-20 12:00:00 -07001104
David Benjamin83c0bc92014-08-04 01:23:53 -04001105 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001106
David Benjamina6f82632016-07-01 18:44:02 -04001107 chainToSend, err = selectClientCertificate(c, certReq)
1108 if err != nil {
1109 return err
Adam Langley95c29f32014-06-20 12:00:00 -07001110 }
1111
1112 msg, err = c.readHandshake()
1113 if err != nil {
1114 return err
1115 }
1116 }
1117
1118 shd, ok := msg.(*serverHelloDoneMsg)
1119 if !ok {
1120 c.sendAlert(alertUnexpectedMessage)
1121 return unexpectedMessageError(shd, msg)
1122 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001123 hs.writeServerHash(shd.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001124
1125 // If the server requested a certificate then we have to send a
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001126 // Certificate message in TLS, even if it's empty because we don't have
1127 // a certificate to send. In SSL 3.0, skip the message and send a
1128 // no_certificate warning alert.
Adam Langley95c29f32014-06-20 12:00:00 -07001129 if certRequested {
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001130 if c.vers == VersionSSL30 && chainToSend == nil {
David Benjamin053fee92017-01-02 08:30:36 -05001131 c.sendAlert(alertNoCertificate)
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001132 } else if !c.config.Bugs.SkipClientCertificate {
1133 certMsg := new(certificateMsg)
1134 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -04001135 for _, certData := range chainToSend.Certificate {
1136 certMsg.certificates = append(certMsg.certificates, certificateEntry{
1137 data: certData,
1138 })
1139 }
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001140 }
1141 hs.writeClientHash(certMsg.marshal())
1142 c.writeRecord(recordTypeHandshake, certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001143 }
Adam Langley95c29f32014-06-20 12:00:00 -07001144 }
1145
David Benjamin48cae082014-10-27 01:06:24 -04001146 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf)
Adam Langley95c29f32014-06-20 12:00:00 -07001147 if err != nil {
1148 c.sendAlert(alertInternalError)
1149 return err
1150 }
1151 if ckx != nil {
David Benjaminf3ec83d2014-07-21 22:42:34 -04001152 if c.config.Bugs.EarlyChangeCipherSpec < 2 {
David Benjamin83c0bc92014-08-04 01:23:53 -04001153 hs.writeClientHash(ckx.marshal())
David Benjaminf3ec83d2014-07-21 22:42:34 -04001154 }
Adam Langley95c29f32014-06-20 12:00:00 -07001155 c.writeRecord(recordTypeHandshake, ckx.marshal())
1156 }
1157
Nick Harperb3d51be2016-07-01 11:43:18 -04001158 if hs.serverHello.extensions.extendedMasterSecret && c.vers >= VersionTLS10 {
Adam Langley75712922014-10-10 16:23:43 -07001159 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1160 c.extendedMasterSecret = true
1161 } else {
1162 if c.config.Bugs.RequireExtendedMasterSecret {
1163 return errors.New("tls: extended master secret required but not supported by peer")
1164 }
1165 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
1166 }
David Benjamine098ec22014-08-27 23:13:20 -04001167
Adam Langley95c29f32014-06-20 12:00:00 -07001168 if chainToSend != nil {
Adam Langley95c29f32014-06-20 12:00:00 -07001169 certVerify := &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001170 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001171 }
1172
David Benjamin72dc7832015-03-16 17:49:43 -04001173 // Determine the hash to sign.
Nick Harper60edffd2016-06-21 15:19:24 -07001174 privKey := c.config.Certificates[0].PrivateKey
David Benjamin72dc7832015-03-16 17:49:43 -04001175
Nick Harper60edffd2016-06-21 15:19:24 -07001176 if certVerify.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001177 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
Nick Harper60edffd2016-06-21 15:19:24 -07001178 if err != nil {
1179 c.sendAlert(alertInternalError)
1180 return err
Adam Langley95c29f32014-06-20 12:00:00 -07001181 }
Nick Harper60edffd2016-06-21 15:19:24 -07001182 }
1183
1184 if c.vers > VersionSSL30 {
David Benjamin5208fd42016-07-13 21:43:25 -04001185 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, hs.finishedHash.buffer)
David Benjamina95e9f32016-07-08 16:28:04 -07001186 if err == nil && c.config.Bugs.SendSignatureAlgorithm != 0 {
1187 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
1188 }
Nick Harper60edffd2016-06-21 15:19:24 -07001189 } else {
1190 // SSL 3.0's client certificate construction is
1191 // incompatible with signatureAlgorithm.
1192 rsaKey, ok := privKey.(*rsa.PrivateKey)
1193 if !ok {
1194 err = errors.New("unsupported signature type for client certificate")
1195 } else {
1196 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
David Benjamin5208fd42016-07-13 21:43:25 -04001197 if c.config.Bugs.InvalidSignature {
Nick Harper60edffd2016-06-21 15:19:24 -07001198 digest[0] ^= 0x80
1199 }
1200 certVerify.signature, err = rsa.SignPKCS1v15(c.config.rand(), rsaKey, crypto.MD5SHA1, digest)
1201 }
Adam Langley95c29f32014-06-20 12:00:00 -07001202 }
1203 if err != nil {
1204 c.sendAlert(alertInternalError)
1205 return errors.New("tls: failed to sign handshake with client certificate: " + err.Error())
1206 }
Adam Langley95c29f32014-06-20 12:00:00 -07001207
Dimitar Vlahovskibd708452017-08-10 18:01:06 +02001208 if !c.config.Bugs.SkipCertificateVerify {
1209 hs.writeClientHash(certVerify.marshal())
1210 c.writeRecord(recordTypeHandshake, certVerify.marshal())
1211 }
Adam Langley95c29f32014-06-20 12:00:00 -07001212 }
David Benjamin82261be2016-07-07 14:32:50 -07001213 // flushHandshake will be called in sendFinished.
Adam Langley95c29f32014-06-20 12:00:00 -07001214
David Benjamine098ec22014-08-27 23:13:20 -04001215 hs.finishedHash.discardHandshakeBuffer()
1216
Adam Langley95c29f32014-06-20 12:00:00 -07001217 return nil
1218}
1219
David Benjamin75051442016-07-01 18:58:51 -04001220func (hs *clientHandshakeState) verifyCertificates(certMsg *certificateMsg) error {
1221 c := hs.c
1222
1223 if len(certMsg.certificates) == 0 {
1224 c.sendAlert(alertIllegalParameter)
1225 return errors.New("tls: no certificates sent")
1226 }
1227
1228 certs := make([]*x509.Certificate, len(certMsg.certificates))
Steven Valdeza833c352016-11-01 13:39:36 -04001229 for i, certEntry := range certMsg.certificates {
1230 cert, err := x509.ParseCertificate(certEntry.data)
David Benjamin75051442016-07-01 18:58:51 -04001231 if err != nil {
1232 c.sendAlert(alertBadCertificate)
1233 return errors.New("tls: failed to parse certificate from server: " + err.Error())
1234 }
1235 certs[i] = cert
1236 }
1237
1238 if !c.config.InsecureSkipVerify {
1239 opts := x509.VerifyOptions{
1240 Roots: c.config.RootCAs,
1241 CurrentTime: c.config.time(),
1242 DNSName: c.config.ServerName,
1243 Intermediates: x509.NewCertPool(),
1244 }
1245
1246 for i, cert := range certs {
1247 if i == 0 {
1248 continue
1249 }
1250 opts.Intermediates.AddCert(cert)
1251 }
1252 var err error
1253 c.verifiedChains, err = certs[0].Verify(opts)
1254 if err != nil {
1255 c.sendAlert(alertBadCertificate)
1256 return err
1257 }
1258 }
1259
David Benjamind768c5d2017-03-28 18:28:44 -05001260 publicKey := getCertificatePublicKey(certs[0])
1261 switch publicKey.(type) {
1262 case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
David Benjamin75051442016-07-01 18:58:51 -04001263 break
1264 default:
1265 c.sendAlert(alertUnsupportedCertificate)
David Benjamind768c5d2017-03-28 18:28:44 -05001266 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", publicKey)
David Benjamin75051442016-07-01 18:58:51 -04001267 }
1268
1269 c.peerCertificates = certs
1270 return nil
1271}
1272
Adam Langley95c29f32014-06-20 12:00:00 -07001273func (hs *clientHandshakeState) establishKeys() error {
1274 c := hs.c
1275
1276 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001277 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 -07001278 var clientCipher, serverCipher interface{}
1279 var clientHash, serverHash macFunction
1280 if hs.suite.cipher != nil {
1281 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
1282 clientHash = hs.suite.mac(c.vers, clientMAC)
1283 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
1284 serverHash = hs.suite.mac(c.vers, serverMAC)
1285 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001286 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1287 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001288 }
1289
Steven Valdezc7d4d212017-09-11 13:53:08 -04001290 c.in.prepareCipherSpec(c.wireVersion, serverCipher, serverHash)
1291 c.out.prepareCipherSpec(c.wireVersion, clientCipher, clientHash)
Adam Langley95c29f32014-06-20 12:00:00 -07001292 return nil
1293}
1294
David Benjamin75101402016-07-01 13:40:23 -04001295func (hs *clientHandshakeState) processServerExtensions(serverExtensions *serverExtensions) error {
1296 c := hs.c
1297
David Benjamin8d315d72016-07-18 01:03:18 +02001298 if c.vers < VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001299 if c.config.Bugs.RequireRenegotiationInfo && serverExtensions.secureRenegotiation == nil {
1300 return errors.New("tls: renegotiation extension missing")
1301 }
David Benjamin75101402016-07-01 13:40:23 -04001302
Nick Harperb41d2e42016-07-01 17:50:32 -04001303 if len(c.clientVerify) > 0 && !c.noRenegotiationInfo() {
1304 var expectedRenegInfo []byte
1305 expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...)
1306 expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...)
1307 if !bytes.Equal(serverExtensions.secureRenegotiation, expectedRenegInfo) {
1308 c.sendAlert(alertHandshakeFailure)
1309 return fmt.Errorf("tls: renegotiation mismatch")
1310 }
David Benjamin75101402016-07-01 13:40:23 -04001311 }
David Benjamincea0ab42016-07-14 12:33:14 -04001312 } else if serverExtensions.secureRenegotiation != nil {
1313 return errors.New("tls: renegotiation info sent in TLS 1.3")
David Benjamin75101402016-07-01 13:40:23 -04001314 }
1315
1316 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
1317 if serverExtensions.customExtension != *expected {
1318 return fmt.Errorf("tls: bad custom extension contents %q", serverExtensions.customExtension)
1319 }
1320 }
1321
1322 clientDidNPN := hs.hello.nextProtoNeg
1323 clientDidALPN := len(hs.hello.alpnProtocols) > 0
1324 serverHasNPN := serverExtensions.nextProtoNeg
1325 serverHasALPN := len(serverExtensions.alpnProtocol) > 0
1326
1327 if !clientDidNPN && serverHasNPN {
1328 c.sendAlert(alertHandshakeFailure)
1329 return errors.New("server advertised unrequested NPN extension")
1330 }
1331
1332 if !clientDidALPN && serverHasALPN {
1333 c.sendAlert(alertHandshakeFailure)
1334 return errors.New("server advertised unrequested ALPN extension")
1335 }
1336
1337 if serverHasNPN && serverHasALPN {
1338 c.sendAlert(alertHandshakeFailure)
1339 return errors.New("server advertised both NPN and ALPN extensions")
1340 }
1341
1342 if serverHasALPN {
1343 c.clientProtocol = serverExtensions.alpnProtocol
1344 c.clientProtocolFallback = false
1345 c.usedALPN = true
1346 }
1347
David Benjamin8d315d72016-07-18 01:03:18 +02001348 if serverHasNPN && c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001349 c.sendAlert(alertHandshakeFailure)
1350 return errors.New("server advertised NPN over TLS 1.3")
1351 }
1352
David Benjamin75101402016-07-01 13:40:23 -04001353 if !hs.hello.channelIDSupported && serverExtensions.channelIDRequested {
1354 c.sendAlert(alertHandshakeFailure)
1355 return errors.New("server advertised unrequested Channel ID extension")
1356 }
1357
David Benjamin8d315d72016-07-18 01:03:18 +02001358 if serverExtensions.extendedMasterSecret && c.vers >= VersionTLS13 {
David Benjamine9077652016-07-13 21:02:08 -04001359 return errors.New("tls: server advertised extended master secret over TLS 1.3")
1360 }
1361
David Benjamin8d315d72016-07-18 01:03:18 +02001362 if serverExtensions.ticketSupported && c.vers >= VersionTLS13 {
Steven Valdez143e8b32016-07-11 13:19:03 -04001363 return errors.New("tls: server advertised ticket extension over TLS 1.3")
1364 }
1365
Steven Valdeza833c352016-11-01 13:39:36 -04001366 if serverExtensions.ocspStapling && c.vers >= VersionTLS13 {
1367 return errors.New("tls: server advertised OCSP in ServerHello over TLS 1.3")
1368 }
1369
David Benjamin53210cb2016-11-16 09:01:48 +09001370 if serverExtensions.ocspStapling && c.config.Bugs.NoOCSPStapling {
1371 return errors.New("tls: server advertised unrequested OCSP extension")
1372 }
1373
Steven Valdeza833c352016-11-01 13:39:36 -04001374 if len(serverExtensions.sctList) > 0 && c.vers >= VersionTLS13 {
1375 return errors.New("tls: server advertised SCTs in ServerHello over TLS 1.3")
1376 }
1377
David Benjamin53210cb2016-11-16 09:01:48 +09001378 if len(serverExtensions.sctList) > 0 && c.config.Bugs.NoSignedCertificateTimestamps {
1379 return errors.New("tls: server advertised unrequested SCTs")
1380 }
1381
David Benjamin75101402016-07-01 13:40:23 -04001382 if serverExtensions.srtpProtectionProfile != 0 {
1383 if serverExtensions.srtpMasterKeyIdentifier != "" {
1384 return errors.New("tls: server selected SRTP MKI value")
1385 }
1386
1387 found := false
1388 for _, p := range c.config.SRTPProtectionProfiles {
1389 if p == serverExtensions.srtpProtectionProfile {
1390 found = true
1391 break
1392 }
1393 }
1394 if !found {
1395 return errors.New("tls: server advertised unsupported SRTP profile")
1396 }
1397
1398 c.srtpProtectionProfile = serverExtensions.srtpProtectionProfile
1399 }
1400
Steven Valdez2d850622017-01-11 11:34:52 -05001401 if c.vers >= VersionTLS13 && c.didResume {
1402 if c.config.Bugs.ExpectEarlyDataAccepted && !serverExtensions.hasEarlyData {
1403 c.sendAlert(alertHandshakeFailure)
1404 return errors.New("tls: server did not accept early data when expected")
1405 }
1406
1407 if !c.config.Bugs.ExpectEarlyDataAccepted && serverExtensions.hasEarlyData {
1408 c.sendAlert(alertHandshakeFailure)
1409 return errors.New("tls: server accepted early data when not expected")
1410 }
1411 }
1412
David Benjamin75101402016-07-01 13:40:23 -04001413 return nil
1414}
1415
Adam Langley95c29f32014-06-20 12:00:00 -07001416func (hs *clientHandshakeState) serverResumedSession() bool {
1417 // If the server responded with the same sessionId then it means the
1418 // sessionTicket is being used to resume a TLS session.
David Benjamind4c349b2017-02-09 14:07:17 -05001419 //
1420 // Note that, if hs.hello.sessionId is a non-nil empty array, this will
1421 // accept an empty session ID from the server as resumption. See
1422 // EmptyTicketSessionID.
Adam Langley95c29f32014-06-20 12:00:00 -07001423 return hs.session != nil && hs.hello.sessionId != nil &&
1424 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
1425}
1426
1427func (hs *clientHandshakeState) processServerHello() (bool, error) {
1428 c := hs.c
1429
Adam Langley95c29f32014-06-20 12:00:00 -07001430 if hs.serverResumedSession() {
David Benjamin4b27d9f2015-05-12 22:42:52 -04001431 // For test purposes, assert that the server never accepts the
1432 // resumption offer on renegotiation.
1433 if c.cipherSuite != nil && c.config.Bugs.FailIfResumeOnRenego {
1434 return false, errors.New("tls: server resumed session on renegotiation")
1435 }
1436
Nick Harperb3d51be2016-07-01 11:43:18 -04001437 if hs.serverHello.extensions.sctList != nil {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001438 return false, errors.New("tls: server sent SCT extension on session resumption")
1439 }
1440
Nick Harperb3d51be2016-07-01 11:43:18 -04001441 if hs.serverHello.extensions.ocspStapling {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001442 return false, errors.New("tls: server sent OCSP extension on session resumption")
1443 }
1444
Adam Langley95c29f32014-06-20 12:00:00 -07001445 // Restore masterSecret and peerCerts from previous state
1446 hs.masterSecret = hs.session.masterSecret
1447 c.peerCertificates = hs.session.serverCertificates
Adam Langley75712922014-10-10 16:23:43 -07001448 c.extendedMasterSecret = hs.session.extendedMasterSecret
Paul Lietar62be8ac2015-09-16 10:03:30 +01001449 c.sctList = hs.session.sctList
1450 c.ocspResponse = hs.session.ocspResponse
David Benjamine098ec22014-08-27 23:13:20 -04001451 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001452 return true, nil
1453 }
Paul Lietar62be8ac2015-09-16 10:03:30 +01001454
Nick Harperb3d51be2016-07-01 11:43:18 -04001455 if hs.serverHello.extensions.sctList != nil {
1456 c.sctList = hs.serverHello.extensions.sctList
Paul Lietar62be8ac2015-09-16 10:03:30 +01001457 }
1458
Adam Langley95c29f32014-06-20 12:00:00 -07001459 return false, nil
1460}
1461
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001462func (hs *clientHandshakeState) readFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001463 c := hs.c
1464
1465 c.readRecord(recordTypeChangeCipherSpec)
1466 if err := c.in.error(); err != nil {
1467 return err
1468 }
1469
1470 msg, err := c.readHandshake()
1471 if err != nil {
1472 return err
1473 }
1474 serverFinished, ok := msg.(*finishedMsg)
1475 if !ok {
1476 c.sendAlert(alertUnexpectedMessage)
1477 return unexpectedMessageError(serverFinished, msg)
1478 }
1479
David Benjaminf3ec83d2014-07-21 22:42:34 -04001480 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
1481 verify := hs.finishedHash.serverSum(hs.masterSecret)
1482 if len(verify) != len(serverFinished.verifyData) ||
1483 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
1484 c.sendAlert(alertHandshakeFailure)
1485 return errors.New("tls: server's Finished message was incorrect")
1486 }
Adam Langley95c29f32014-06-20 12:00:00 -07001487 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001488 c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001489 copy(out, serverFinished.verifyData)
David Benjamin83c0bc92014-08-04 01:23:53 -04001490 hs.writeServerHash(serverFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001491 return nil
1492}
1493
1494func (hs *clientHandshakeState) readSessionTicket() error {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001495 c := hs.c
1496
1497 // Create a session with no server identifier. Either a
1498 // session ID or session ticket will be attached.
1499 session := &ClientSessionState{
1500 vers: c.vers,
1501 cipherSuite: hs.suite.id,
1502 masterSecret: hs.masterSecret,
Nick Harperc9846112016-10-17 15:05:35 -07001503 handshakeHash: hs.finishedHash.Sum(),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001504 serverCertificates: c.peerCertificates,
Paul Lietar62be8ac2015-09-16 10:03:30 +01001505 sctList: c.sctList,
1506 ocspResponse: c.ocspResponse,
Nick Harper0b3625b2016-07-25 16:16:28 -07001507 ticketExpiration: c.config.time().Add(time.Duration(7 * 24 * time.Hour)),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001508 }
1509
Nick Harperb3d51be2016-07-01 11:43:18 -04001510 if !hs.serverHello.extensions.ticketSupported {
David Benjamind98452d2015-06-16 14:16:23 -04001511 if c.config.Bugs.ExpectNewTicket {
1512 return errors.New("tls: expected new ticket")
1513 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001514 if hs.session == nil && len(hs.serverHello.sessionId) > 0 {
1515 session.sessionId = hs.serverHello.sessionId
1516 hs.session = session
1517 }
Adam Langley95c29f32014-06-20 12:00:00 -07001518 return nil
1519 }
1520
David Benjaminc7ce9772015-10-09 19:32:41 -04001521 if c.vers == VersionSSL30 {
1522 return errors.New("tls: negotiated session tickets in SSL 3.0")
1523 }
1524
Adam Langley95c29f32014-06-20 12:00:00 -07001525 msg, err := c.readHandshake()
1526 if err != nil {
1527 return err
1528 }
1529 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
1530 if !ok {
1531 c.sendAlert(alertUnexpectedMessage)
1532 return unexpectedMessageError(sessionTicketMsg, msg)
1533 }
Adam Langley95c29f32014-06-20 12:00:00 -07001534
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001535 session.sessionTicket = sessionTicketMsg.ticket
1536 hs.session = session
Adam Langley95c29f32014-06-20 12:00:00 -07001537
David Benjamind30a9902014-08-24 01:44:23 -04001538 hs.writeServerHash(sessionTicketMsg.marshal())
1539
Adam Langley95c29f32014-06-20 12:00:00 -07001540 return nil
1541}
1542
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001543func (hs *clientHandshakeState) sendFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001544 c := hs.c
1545
David Benjamin0b8d5da2016-07-15 00:39:56 -04001546 var postCCSMsgs [][]byte
David Benjamin83c0bc92014-08-04 01:23:53 -04001547 seqno := hs.c.sendHandshakeSeq
Nick Harperb3d51be2016-07-01 11:43:18 -04001548 if hs.serverHello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001549 nextProto := new(nextProtoMsg)
Nick Harperb3d51be2016-07-01 11:43:18 -04001550 proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.extensions.nextProtos)
Adam Langley95c29f32014-06-20 12:00:00 -07001551 nextProto.proto = proto
1552 c.clientProtocol = proto
1553 c.clientProtocolFallback = fallback
1554
David Benjamin86271ee2014-07-21 16:14:03 -04001555 nextProtoBytes := nextProto.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -04001556 hs.writeHash(nextProtoBytes, seqno)
1557 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001558 postCCSMsgs = append(postCCSMsgs, nextProtoBytes)
Adam Langley95c29f32014-06-20 12:00:00 -07001559 }
1560
Nick Harperb3d51be2016-07-01 11:43:18 -04001561 if hs.serverHello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001562 var resumeHash []byte
1563 if isResume {
1564 resumeHash = hs.session.handshakeHash
1565 }
Nick Harper60a85cb2016-09-23 16:25:11 -07001566 channelIDMsgBytes, err := hs.writeChannelIDMessage(hs.finishedHash.hashForChannelID(resumeHash))
David Benjamind30a9902014-08-24 01:44:23 -04001567 if err != nil {
1568 return err
1569 }
David Benjamin24599a82016-06-30 18:56:53 -04001570 hs.writeHash(channelIDMsgBytes, seqno)
David Benjamind30a9902014-08-24 01:44:23 -04001571 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001572 postCCSMsgs = append(postCCSMsgs, channelIDMsgBytes)
David Benjamind30a9902014-08-24 01:44:23 -04001573 }
1574
Adam Langley95c29f32014-06-20 12:00:00 -07001575 finished := new(finishedMsg)
David Benjaminf3ec83d2014-07-21 22:42:34 -04001576 if c.config.Bugs.EarlyChangeCipherSpec == 2 {
1577 finished.verifyData = hs.finishedHash.clientSum(nil)
1578 } else {
1579 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
1580 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001581 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001582 if c.config.Bugs.BadFinished {
1583 finished.verifyData[0]++
1584 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001585 c.clientVerify = append(c.clientVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001586 hs.finishedBytes = finished.marshal()
1587 hs.writeHash(hs.finishedBytes, seqno)
David Benjamin0b8d5da2016-07-15 00:39:56 -04001588 postCCSMsgs = append(postCCSMsgs, hs.finishedBytes)
David Benjamin86271ee2014-07-21 16:14:03 -04001589
1590 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001591 c.writeRecord(recordTypeHandshake, postCCSMsgs[0][:5])
1592 postCCSMsgs[0] = postCCSMsgs[0][5:]
David Benjamin61672812016-07-14 23:10:43 -04001593 } else if c.config.Bugs.SendUnencryptedFinished {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001594 c.writeRecord(recordTypeHandshake, postCCSMsgs[0])
1595 postCCSMsgs = postCCSMsgs[1:]
David Benjamin86271ee2014-07-21 16:14:03 -04001596 }
1597
1598 if !c.config.Bugs.SkipChangeCipherSpec &&
1599 c.config.Bugs.EarlyChangeCipherSpec == 0 {
David Benjamin8411b242015-11-26 12:07:28 -05001600 ccs := []byte{1}
1601 if c.config.Bugs.BadChangeCipherSpec != nil {
1602 ccs = c.config.Bugs.BadChangeCipherSpec
1603 }
1604 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamin86271ee2014-07-21 16:14:03 -04001605 }
1606
David Benjamin4189bd92015-01-25 23:52:39 -05001607 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1608 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1609 }
David Benjamindc3da932015-03-12 15:09:02 -04001610 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1611 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1612 return errors.New("tls: simulating post-CCS alert")
1613 }
David Benjamin4189bd92015-01-25 23:52:39 -05001614
David Benjamin0b8d5da2016-07-15 00:39:56 -04001615 if !c.config.Bugs.SkipFinished {
1616 for _, msg := range postCCSMsgs {
1617 c.writeRecord(recordTypeHandshake, msg)
1618 }
David Benjamin02edcd02016-07-27 17:40:37 -04001619
1620 if c.config.Bugs.SendExtraFinished {
1621 c.writeRecord(recordTypeHandshake, finished.marshal())
1622 }
David Benjaminb3774b92015-01-31 17:16:01 -05001623 }
David Benjaminb0c761e2017-06-25 22:42:55 -04001624
1625 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001626 return nil
1627}
1628
Nick Harper60a85cb2016-09-23 16:25:11 -07001629func (hs *clientHandshakeState) writeChannelIDMessage(channelIDHash []byte) ([]byte, error) {
1630 c := hs.c
1631 channelIDMsg := new(channelIDMsg)
1632 if c.config.ChannelID.Curve != elliptic.P256() {
1633 return nil, fmt.Errorf("tls: Channel ID is not on P-256.")
1634 }
1635 r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, channelIDHash)
1636 if err != nil {
1637 return nil, err
1638 }
1639 channelID := make([]byte, 128)
1640 writeIntPadded(channelID[0:32], c.config.ChannelID.X)
1641 writeIntPadded(channelID[32:64], c.config.ChannelID.Y)
1642 writeIntPadded(channelID[64:96], r)
1643 writeIntPadded(channelID[96:128], s)
1644 if c.config.Bugs.InvalidChannelIDSignature {
1645 channelID[64] ^= 1
1646 }
1647 channelIDMsg.channelID = channelID
1648
1649 c.channelID = &c.config.ChannelID.PublicKey
1650
1651 return channelIDMsg.marshal(), nil
1652}
1653
David Benjamin83c0bc92014-08-04 01:23:53 -04001654func (hs *clientHandshakeState) writeClientHash(msg []byte) {
1655 // writeClientHash is called before writeRecord.
1656 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1657}
1658
1659func (hs *clientHandshakeState) writeServerHash(msg []byte) {
1660 // writeServerHash is called after readHandshake.
1661 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1662}
1663
1664func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) {
1665 if hs.c.isDTLS {
1666 // This is somewhat hacky. DTLS hashes a slightly different format.
1667 // First, the TLS header.
1668 hs.finishedHash.Write(msg[:4])
1669 // Then the sequence number and reassembled fragment offset (always 0).
1670 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1671 // Then the reassembled fragment (always equal to the message length).
1672 hs.finishedHash.Write(msg[1:4])
1673 // And then the message body.
1674 hs.finishedHash.Write(msg[4:])
1675 } else {
1676 hs.finishedHash.Write(msg)
1677 }
1678}
1679
David Benjamina6f82632016-07-01 18:44:02 -04001680// selectClientCertificate selects a certificate for use with the given
1681// certificate, or none if none match. It may return a particular certificate or
1682// nil on success, or an error on internal error.
1683func selectClientCertificate(c *Conn, certReq *certificateRequestMsg) (*Certificate, error) {
David Benjamin3969fdf2017-08-29 15:50:58 -04001684 if len(c.config.Certificates) == 0 {
1685 return nil, nil
David Benjamina6f82632016-07-01 18:44:02 -04001686 }
1687
David Benjamin3969fdf2017-08-29 15:50:58 -04001688 // The test is assumed to have configured the certificate it meant to
1689 // send.
1690 if len(c.config.Certificates) > 1 {
1691 return nil, errors.New("tls: multiple certificates configured")
David Benjamina6f82632016-07-01 18:44:02 -04001692 }
1693
David Benjamin3969fdf2017-08-29 15:50:58 -04001694 return &c.config.Certificates[0], nil
David Benjamina6f82632016-07-01 18:44:02 -04001695}
1696
Adam Langley95c29f32014-06-20 12:00:00 -07001697// clientSessionCacheKey returns a key used to cache sessionTickets that could
1698// be used to resume previously negotiated TLS sessions with a server.
1699func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
1700 if len(config.ServerName) > 0 {
1701 return config.ServerName
1702 }
1703 return serverAddr.String()
1704}
1705
David Benjaminfa055a22014-09-15 16:51:51 -04001706// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
1707// given list of possible protocols and a list of the preference order. The
1708// first list must not be empty. It returns the resulting protocol and flag
Adam Langley95c29f32014-06-20 12:00:00 -07001709// indicating if the fallback case was reached.
David Benjaminfa055a22014-09-15 16:51:51 -04001710func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
1711 for _, s := range preferenceProtos {
1712 for _, c := range protos {
Adam Langley95c29f32014-06-20 12:00:00 -07001713 if s == c {
1714 return s, false
1715 }
1716 }
1717 }
1718
David Benjaminfa055a22014-09-15 16:51:51 -04001719 return protos[0], true
Adam Langley95c29f32014-06-20 12:00:00 -07001720}
David Benjamind30a9902014-08-24 01:44:23 -04001721
1722// writeIntPadded writes x into b, padded up with leading zeros as
1723// needed.
1724func writeIntPadded(b []byte, x *big.Int) {
1725 for i := range b {
1726 b[i] = 0
1727 }
1728 xb := x.Bytes()
1729 copy(b[len(b)-len(xb):], xb)
1730}
Steven Valdeza833c352016-11-01 13:39:36 -04001731
1732func generatePSKBinders(hello *clientHelloMsg, pskCipherSuite *cipherSuite, psk, transcript []byte, config *Config) {
1733 if config.Bugs.SendNoPSKBinder {
1734 return
1735 }
1736
1737 binderLen := pskCipherSuite.hash().Size()
1738 if config.Bugs.SendShortPSKBinder {
1739 binderLen--
1740 }
1741
David Benjaminaedf3032016-12-01 16:47:56 -05001742 numBinders := 1
1743 if config.Bugs.SendExtraPSKBinder {
1744 numBinders++
1745 }
1746
Steven Valdeza833c352016-11-01 13:39:36 -04001747 // Fill hello.pskBinders with appropriate length arrays of zeros so the
1748 // length prefixes are correct when computing the binder over the truncated
1749 // ClientHello message.
David Benjaminaedf3032016-12-01 16:47:56 -05001750 hello.pskBinders = make([][]byte, numBinders)
1751 for i := range hello.pskBinders {
Steven Valdeza833c352016-11-01 13:39:36 -04001752 hello.pskBinders[i] = make([]byte, binderLen)
1753 }
1754
1755 helloBytes := hello.marshal()
1756 binderSize := len(hello.pskBinders)*(binderLen+1) + 2
1757 truncatedHello := helloBytes[:len(helloBytes)-binderSize]
1758 binder := computePSKBinder(psk, resumptionPSKBinderLabel, pskCipherSuite, transcript, truncatedHello)
1759 if config.Bugs.SendShortPSKBinder {
1760 binder = binder[:binderLen]
1761 }
1762 if config.Bugs.SendInvalidPSKBinder {
1763 binder[0] ^= 1
1764 }
1765
1766 for i := range hello.pskBinders {
1767 hello.pskBinders[i] = binder
1768 }
1769
1770 hello.raw = nil
1771}