blob: 12a4a26c984e59d285187d8f81af9982206274cf [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)
414 c.out.useTrafficSecret(session.vers, 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
Adam Langley95c29f32014-06-20 12:00:00 -0700582 hs := &clientHandshakeState{
583 c: c,
584 serverHello: serverHello,
585 hello: hello,
586 suite: suite,
587 finishedHash: newFinishedHash(c.vers, suite),
Nick Harperb41d2e42016-07-01 17:50:32 -0400588 keyShares: keyShares,
Adam Langley95c29f32014-06-20 12:00:00 -0700589 session: session,
590 }
591
David Benjamin83c0bc92014-08-04 01:23:53 -0400592 hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1)
Nick Harperdcfbc672016-07-16 17:47:31 +0200593 if haveHelloRetryRequest {
594 hs.writeServerHash(helloRetryRequest.marshal())
595 hs.writeClientHash(secondHelloBytes)
596 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400597 hs.writeServerHash(hs.serverHello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700598
David Benjamin8d315d72016-07-18 01:03:18 +0200599 if c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -0400600 if err := hs.doTLS13Handshake(); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700601 return err
602 }
603 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400604 if c.config.Bugs.EarlyChangeCipherSpec > 0 {
605 hs.establishKeys()
606 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
607 }
608
609 if hs.serverHello.compressionMethod != compressionNone {
610 c.sendAlert(alertUnexpectedMessage)
611 return errors.New("tls: server selected unsupported compression format")
612 }
613
614 err = hs.processServerExtensions(&serverHello.extensions)
615 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700616 return err
617 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400618
619 isResume, err := hs.processServerHello()
620 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700621 return err
622 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400623
624 if isResume {
625 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
626 if err := hs.establishKeys(); err != nil {
627 return err
628 }
629 }
630 if err := hs.readSessionTicket(); err != nil {
631 return err
632 }
633 if err := hs.readFinished(c.firstFinished[:]); err != nil {
634 return err
635 }
636 if err := hs.sendFinished(nil, isResume); err != nil {
637 return err
638 }
639 } else {
640 if err := hs.doFullHandshake(); err != nil {
641 return err
642 }
643 if err := hs.establishKeys(); err != nil {
644 return err
645 }
646 if err := hs.sendFinished(c.firstFinished[:], isResume); err != nil {
647 return err
648 }
649 // Most retransmits are triggered by a timeout, but the final
650 // leg of the handshake is retransmited upon re-receiving a
651 // Finished.
652 if err := c.simulatePacketLoss(func() {
David Benjamin02edcd02016-07-27 17:40:37 -0400653 c.sendHandshakeSeq--
Nick Harperb41d2e42016-07-01 17:50:32 -0400654 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
655 c.flushHandshake()
656 }); err != nil {
657 return err
658 }
659 if err := hs.readSessionTicket(); err != nil {
660 return err
661 }
662 if err := hs.readFinished(nil); err != nil {
663 return err
664 }
Adam Langley95c29f32014-06-20 12:00:00 -0700665 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400666
667 if sessionCache != nil && hs.session != nil && session != hs.session {
668 if c.config.Bugs.RequireSessionTickets && len(hs.session.sessionTicket) == 0 {
669 return errors.New("tls: new session used session IDs instead of tickets")
670 }
671 sessionCache.Put(cacheKey, hs.session)
David Benjamin83f90402015-01-27 01:09:43 -0500672 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400673
674 c.didResume = isResume
David Benjamin97a0a082016-07-13 17:57:35 -0400675 c.exporterSecret = hs.masterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700676 }
677
Adam Langley95c29f32014-06-20 12:00:00 -0700678 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400679 c.cipherSuite = suite
680 copy(c.clientRandom[:], hs.hello.random)
681 copy(c.serverRandom[:], hs.serverHello.random)
Paul Lietar4fac72e2015-09-09 13:44:55 +0100682
Adam Langley95c29f32014-06-20 12:00:00 -0700683 return nil
684}
685
Nick Harperb41d2e42016-07-01 17:50:32 -0400686func (hs *clientHandshakeState) doTLS13Handshake() error {
687 c := hs.c
688
Steven Valdez0e4a4482017-07-17 11:12:34 -0400689 if c.wireVersion == tls13ExperimentVersion && !bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) {
690 return errors.New("tls: session IDs did not match.")
691 }
692
Nick Harperb41d2e42016-07-01 17:50:32 -0400693 // Once the PRF hash is known, TLS 1.3 does not require a handshake
694 // buffer.
695 hs.finishedHash.discardHandshakeBuffer()
696
697 zeroSecret := hs.finishedHash.zeroSecret()
698
699 // Resolve PSK and compute the early secret.
700 //
701 // TODO(davidben): This will need to be handled slightly earlier once
702 // 0-RTT is implemented.
Steven Valdez803c77a2016-09-06 14:13:43 -0400703 if hs.serverHello.hasPSKIdentity {
Nick Harper0b3625b2016-07-25 16:16:28 -0700704 // We send at most one PSK identity.
705 if hs.session == nil || hs.serverHello.pskIdentity != 0 {
706 c.sendAlert(alertUnknownPSKIdentity)
707 return errors.New("tls: server sent unknown PSK identity")
708 }
David Benjamin2b02f4b2016-11-16 16:11:47 +0900709 sessionCipher := cipherSuiteFromID(hs.session.cipherSuite)
710 if sessionCipher == nil || sessionCipher.hash() != hs.suite.hash() {
Nick Harper0b3625b2016-07-25 16:16:28 -0700711 c.sendAlert(alertHandshakeFailure)
David Benjamin2b02f4b2016-11-16 16:11:47 +0900712 return errors.New("tls: server resumed an invalid session for the cipher suite")
Nick Harper0b3625b2016-07-25 16:16:28 -0700713 }
David Benjamin48891ad2016-12-04 00:02:43 -0500714 hs.finishedHash.addEntropy(hs.session.masterSecret)
Nick Harper0b3625b2016-07-25 16:16:28 -0700715 c.didResume = true
Nick Harperb41d2e42016-07-01 17:50:32 -0400716 } else {
David Benjamin48891ad2016-12-04 00:02:43 -0500717 hs.finishedHash.addEntropy(zeroSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400718 }
719
Steven Valdeza833c352016-11-01 13:39:36 -0400720 if !hs.serverHello.hasKeyShare {
721 c.sendAlert(alertUnsupportedExtension)
722 return errors.New("tls: server omitted KeyShare on resumption.")
723 }
724
Nick Harperb41d2e42016-07-01 17:50:32 -0400725 // Resolve ECDHE and compute the handshake secret.
Steven Valdez803c77a2016-09-06 14:13:43 -0400726 if !c.config.Bugs.MissingKeyShare && !c.config.Bugs.SecondClientHelloMissingKeyShare {
Nick Harperb41d2e42016-07-01 17:50:32 -0400727 curve, ok := hs.keyShares[hs.serverHello.keyShare.group]
728 if !ok {
729 c.sendAlert(alertHandshakeFailure)
730 return errors.New("tls: server selected an unsupported group")
731 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400732 c.curveID = hs.serverHello.keyShare.group
Nick Harperb41d2e42016-07-01 17:50:32 -0400733
David Benjamin48891ad2016-12-04 00:02:43 -0500734 ecdheSecret, err := curve.finish(hs.serverHello.keyShare.keyExchange)
Nick Harperb41d2e42016-07-01 17:50:32 -0400735 if err != nil {
736 return err
737 }
David Benjamin48891ad2016-12-04 00:02:43 -0500738 hs.finishedHash.addEntropy(ecdheSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400739 } else {
David Benjamin48891ad2016-12-04 00:02:43 -0500740 hs.finishedHash.addEntropy(zeroSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400741 }
742
Steven Valdez520e1222017-06-13 12:45:25 -0400743 if c.wireVersion == tls13ExperimentVersion {
744 if err := c.readRecord(recordTypeChangeCipherSpec); err != nil {
745 return err
746 }
747 }
748
Nick Harperf2511f12016-12-06 16:02:31 -0800749 // Derive handshake traffic keys and switch read key to handshake
750 // traffic key.
David Benjamin48891ad2016-12-04 00:02:43 -0500751 clientHandshakeTrafficSecret := hs.finishedHash.deriveSecret(clientHandshakeTrafficLabel)
David Benjamin48891ad2016-12-04 00:02:43 -0500752 serverHandshakeTrafficSecret := hs.finishedHash.deriveSecret(serverHandshakeTrafficLabel)
Steven Valdeza833c352016-11-01 13:39:36 -0400753 c.in.useTrafficSecret(c.vers, hs.suite, serverHandshakeTrafficSecret, serverWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -0400754
755 msg, err := c.readHandshake()
756 if err != nil {
757 return err
758 }
759
760 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
761 if !ok {
762 c.sendAlert(alertUnexpectedMessage)
763 return unexpectedMessageError(encryptedExtensions, msg)
764 }
765 hs.writeServerHash(encryptedExtensions.marshal())
766
767 err = hs.processServerExtensions(&encryptedExtensions.extensions)
768 if err != nil {
769 return err
770 }
771
772 var chainToSend *Certificate
David Benjamin8d343b42016-07-09 14:26:01 -0700773 var certReq *certificateRequestMsg
Steven Valdeza833c352016-11-01 13:39:36 -0400774 if c.didResume {
Nick Harper0b3625b2016-07-25 16:16:28 -0700775 // Copy over authentication from the session.
776 c.peerCertificates = hs.session.serverCertificates
777 c.sctList = hs.session.sctList
778 c.ocspResponse = hs.session.ocspResponse
David Benjamin44b33bc2016-07-01 22:40:23 -0400779 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400780 msg, err := c.readHandshake()
781 if err != nil {
782 return err
783 }
784
David Benjamin8d343b42016-07-09 14:26:01 -0700785 var ok bool
786 certReq, ok = msg.(*certificateRequestMsg)
Nick Harperb41d2e42016-07-01 17:50:32 -0400787 if ok {
David Benjamin8a8349b2016-08-18 02:32:23 -0400788 if len(certReq.requestContext) != 0 {
789 return errors.New("tls: non-empty certificate request context sent in handshake")
790 }
791
David Benjaminb62d2872016-07-18 14:55:02 +0200792 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
793 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
794 }
795
Nick Harperb41d2e42016-07-01 17:50:32 -0400796 hs.writeServerHash(certReq.marshal())
Nick Harperb41d2e42016-07-01 17:50:32 -0400797
798 chainToSend, err = selectClientCertificate(c, certReq)
799 if err != nil {
800 return err
801 }
802
803 msg, err = c.readHandshake()
804 if err != nil {
805 return err
806 }
807 }
808
809 certMsg, ok := msg.(*certificateMsg)
810 if !ok {
811 c.sendAlert(alertUnexpectedMessage)
812 return unexpectedMessageError(certMsg, msg)
813 }
814 hs.writeServerHash(certMsg.marshal())
815
David Benjamin53210cb2016-11-16 09:01:48 +0900816 // Check for unsolicited extensions.
817 for i, cert := range certMsg.certificates {
818 if c.config.Bugs.NoOCSPStapling && cert.ocspResponse != nil {
819 c.sendAlert(alertUnsupportedExtension)
820 return errors.New("tls: unexpected OCSP response in the server certificate")
821 }
822 if c.config.Bugs.NoSignedCertificateTimestamps && cert.sctList != nil {
823 c.sendAlert(alertUnsupportedExtension)
824 return errors.New("tls: unexpected SCT list in the server certificate")
825 }
826 if i > 0 && c.config.Bugs.ExpectNoExtensionsOnIntermediate && (cert.ocspResponse != nil || cert.sctList != nil) {
827 c.sendAlert(alertUnsupportedExtension)
828 return errors.New("tls: unexpected extensions in the server certificate")
829 }
830 }
831
Nick Harperb41d2e42016-07-01 17:50:32 -0400832 if err := hs.verifyCertificates(certMsg); err != nil {
833 return err
834 }
835 leaf := c.peerCertificates[0]
Steven Valdeza833c352016-11-01 13:39:36 -0400836 c.ocspResponse = certMsg.certificates[0].ocspResponse
837 c.sctList = certMsg.certificates[0].sctList
838
Nick Harperb41d2e42016-07-01 17:50:32 -0400839 msg, err = c.readHandshake()
840 if err != nil {
841 return err
842 }
843 certVerifyMsg, ok := msg.(*certificateVerifyMsg)
844 if !ok {
845 c.sendAlert(alertUnexpectedMessage)
846 return unexpectedMessageError(certVerifyMsg, msg)
847 }
848
David Benjaminf74ec792016-07-13 21:18:49 -0400849 c.peerSignatureAlgorithm = certVerifyMsg.signatureAlgorithm
Nick Harperb41d2e42016-07-01 17:50:32 -0400850 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
David Benjamind768c5d2017-03-28 18:28:44 -0500851 err = verifyMessage(c.vers, getCertificatePublicKey(leaf), c.config, certVerifyMsg.signatureAlgorithm, input, certVerifyMsg.signature)
Nick Harperb41d2e42016-07-01 17:50:32 -0400852 if err != nil {
853 return err
854 }
855
856 hs.writeServerHash(certVerifyMsg.marshal())
857 }
858
859 msg, err = c.readHandshake()
860 if err != nil {
861 return err
862 }
863 serverFinished, ok := msg.(*finishedMsg)
864 if !ok {
865 c.sendAlert(alertUnexpectedMessage)
866 return unexpectedMessageError(serverFinished, msg)
867 }
868
Steven Valdezc4aa7272016-10-03 12:25:56 -0400869 verify := hs.finishedHash.serverSum(serverHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400870 if len(verify) != len(serverFinished.verifyData) ||
871 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
872 c.sendAlert(alertHandshakeFailure)
873 return errors.New("tls: server's Finished message was incorrect")
874 }
875
876 hs.writeServerHash(serverFinished.marshal())
877
878 // The various secrets do not incorporate the client's final leg, so
879 // derive them now before updating the handshake context.
David Benjamin48891ad2016-12-04 00:02:43 -0500880 hs.finishedHash.addEntropy(zeroSecret)
881 clientTrafficSecret := hs.finishedHash.deriveSecret(clientApplicationTrafficLabel)
882 serverTrafficSecret := hs.finishedHash.deriveSecret(serverApplicationTrafficLabel)
David Benjamincdb6fe92017-02-07 16:06:48 -0500883 c.exporterSecret = hs.finishedHash.deriveSecret(exporterLabel)
884
885 // Switch to application data keys on read. In particular, any alerts
886 // from the client certificate are read over these keys.
Nick Harper7cd0a972016-12-02 11:08:40 -0800887 c.in.useTrafficSecret(c.vers, hs.suite, serverTrafficSecret, serverWrite)
888
889 // If we're expecting 0.5-RTT messages from the server, read them
890 // now.
David Benjamin794cc592017-03-25 22:24:23 -0500891 if encryptedExtensions.extensions.hasEarlyData {
892 // BoringSSL will always send two tickets half-RTT when
893 // negotiating 0-RTT.
894 for i := 0; i < shimConfig.HalfRTTTickets; i++ {
895 msg, err := c.readHandshake()
896 if err != nil {
897 return fmt.Errorf("tls: error reading half-RTT ticket: %s", err)
898 }
899 newSessionTicket, ok := msg.(*newSessionTicketMsg)
900 if !ok {
901 return errors.New("tls: expected half-RTT ticket")
902 }
903 if err := c.processTLS13NewSessionTicket(newSessionTicket, hs.suite); err != nil {
904 return err
905 }
Nick Harper7cd0a972016-12-02 11:08:40 -0800906 }
David Benjamin794cc592017-03-25 22:24:23 -0500907 for _, expectedMsg := range c.config.Bugs.ExpectHalfRTTData {
908 if err := c.readRecord(recordTypeApplicationData); err != nil {
909 return err
910 }
911 if !bytes.Equal(c.input.data[c.input.off:], expectedMsg) {
912 return errors.New("ExpectHalfRTTData: did not get expected message")
913 }
914 c.in.freeBlock(c.input)
915 c.input = nil
Nick Harper7cd0a972016-12-02 11:08:40 -0800916 }
Nick Harper7cd0a972016-12-02 11:08:40 -0800917 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400918
Nick Harperf2511f12016-12-06 16:02:31 -0800919 // Send EndOfEarlyData and then switch write key to handshake
920 // traffic key.
David Benjamin32c89272017-03-26 13:54:21 -0500921 if c.out.cipher != nil && !c.config.Bugs.SkipEndOfEarlyData {
Steven Valdez681eb6a2016-12-19 13:19:29 -0500922 if c.config.Bugs.SendStrayEarlyHandshake {
923 helloRequest := new(helloRequestMsg)
924 c.writeRecord(recordTypeHandshake, helloRequest.marshal())
925 }
Nick Harperf2511f12016-12-06 16:02:31 -0800926 c.sendAlert(alertEndOfEarlyData)
927 }
Steven Valdez520e1222017-06-13 12:45:25 -0400928
929 if c.wireVersion == tls13ExperimentVersion {
930 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
931 }
932
Nick Harperf2511f12016-12-06 16:02:31 -0800933 c.out.useTrafficSecret(c.vers, hs.suite, clientHandshakeTrafficSecret, clientWrite)
934
Steven Valdez0ee2e112016-07-15 06:51:15 -0400935 if certReq != nil && !c.config.Bugs.SkipClientCertificate {
David Benjamin8d343b42016-07-09 14:26:01 -0700936 certMsg := &certificateMsg{
937 hasRequestContext: true,
938 requestContext: certReq.requestContext,
939 }
940 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -0400941 for _, certData := range chainToSend.Certificate {
942 certMsg.certificates = append(certMsg.certificates, certificateEntry{
943 data: certData,
944 extraExtension: c.config.Bugs.SendExtensionOnCertificate,
945 })
946 }
David Benjamin8d343b42016-07-09 14:26:01 -0700947 }
948 hs.writeClientHash(certMsg.marshal())
949 c.writeRecord(recordTypeHandshake, certMsg.marshal())
950
951 if chainToSend != nil {
952 certVerify := &certificateVerifyMsg{
953 hasSignatureAlgorithm: true,
954 }
955
956 // Determine the hash to sign.
957 privKey := chainToSend.PrivateKey
958
959 var err error
960 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
961 if err != nil {
962 c.sendAlert(alertInternalError)
963 return err
964 }
965
966 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
967 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
968 if err != nil {
969 c.sendAlert(alertInternalError)
970 return err
971 }
Steven Valdez0ee2e112016-07-15 06:51:15 -0400972 if c.config.Bugs.SendSignatureAlgorithm != 0 {
973 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
974 }
David Benjamin8d343b42016-07-09 14:26:01 -0700975
Dimitar Vlahovskibd708452017-08-10 18:01:06 +0200976 if !c.config.Bugs.SkipCertificateVerify {
977 hs.writeClientHash(certVerify.marshal())
978 c.writeRecord(recordTypeHandshake, certVerify.marshal())
979 }
David Benjamin8d343b42016-07-09 14:26:01 -0700980 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400981 }
982
Nick Harper60a85cb2016-09-23 16:25:11 -0700983 if encryptedExtensions.extensions.channelIDRequested {
984 channelIDHash := crypto.SHA256.New()
985 channelIDHash.Write(hs.finishedHash.certificateVerifyInput(channelIDContextTLS13))
986 channelIDMsgBytes, err := hs.writeChannelIDMessage(channelIDHash.Sum(nil))
987 if err != nil {
988 return err
989 }
990 hs.writeClientHash(channelIDMsgBytes)
991 c.writeRecord(recordTypeHandshake, channelIDMsgBytes)
992 }
993
Nick Harperb41d2e42016-07-01 17:50:32 -0400994 // Send a client Finished message.
995 finished := new(finishedMsg)
Steven Valdezc4aa7272016-10-03 12:25:56 -0400996 finished.verifyData = hs.finishedHash.clientSum(clientHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400997 if c.config.Bugs.BadFinished {
998 finished.verifyData[0]++
999 }
David Benjamin97a0a082016-07-13 17:57:35 -04001000 hs.writeClientHash(finished.marshal())
David Benjamin7964b182016-07-14 23:36:30 -04001001 if c.config.Bugs.PartialClientFinishedWithClientHello {
1002 // The first byte has already been sent.
1003 c.writeRecord(recordTypeHandshake, finished.marshal()[1:])
Steven Valdeza4ee74d2016-11-29 13:36:45 -05001004 } else if c.config.Bugs.InterleaveEarlyData {
1005 finishedBytes := finished.marshal()
1006 c.sendFakeEarlyData(4)
1007 c.writeRecord(recordTypeHandshake, finishedBytes[:1])
1008 c.sendFakeEarlyData(4)
1009 c.writeRecord(recordTypeHandshake, finishedBytes[1:])
David Benjamin7964b182016-07-14 23:36:30 -04001010 } else {
1011 c.writeRecord(recordTypeHandshake, finished.marshal())
1012 }
David Benjamin02edcd02016-07-27 17:40:37 -04001013 if c.config.Bugs.SendExtraFinished {
1014 c.writeRecord(recordTypeHandshake, finished.marshal())
1015 }
David Benjaminee51a222016-07-07 18:34:12 -07001016 c.flushHandshake()
Nick Harperb41d2e42016-07-01 17:50:32 -04001017
1018 // Switch to application data keys.
Steven Valdeza833c352016-11-01 13:39:36 -04001019 c.out.useTrafficSecret(c.vers, hs.suite, clientTrafficSecret, clientWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -04001020
David Benjamin48891ad2016-12-04 00:02:43 -05001021 c.resumptionSecret = hs.finishedHash.deriveSecret(resumptionLabel)
Nick Harperb41d2e42016-07-01 17:50:32 -04001022 return nil
1023}
1024
Adam Langley95c29f32014-06-20 12:00:00 -07001025func (hs *clientHandshakeState) doFullHandshake() error {
1026 c := hs.c
1027
David Benjamin48cae082014-10-27 01:06:24 -04001028 var leaf *x509.Certificate
1029 if hs.suite.flags&suitePSK == 0 {
1030 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001031 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -07001032 return err
1033 }
Adam Langley95c29f32014-06-20 12:00:00 -07001034
David Benjamin48cae082014-10-27 01:06:24 -04001035 certMsg, ok := msg.(*certificateMsg)
David Benjamin75051442016-07-01 18:58:51 -04001036 if !ok {
David Benjamin48cae082014-10-27 01:06:24 -04001037 c.sendAlert(alertUnexpectedMessage)
1038 return unexpectedMessageError(certMsg, msg)
1039 }
1040 hs.writeServerHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001041
David Benjamin75051442016-07-01 18:58:51 -04001042 if err := hs.verifyCertificates(certMsg); err != nil {
1043 return err
David Benjamin48cae082014-10-27 01:06:24 -04001044 }
David Benjamin75051442016-07-01 18:58:51 -04001045 leaf = c.peerCertificates[0]
David Benjamin48cae082014-10-27 01:06:24 -04001046 }
Adam Langley95c29f32014-06-20 12:00:00 -07001047
Nick Harperb3d51be2016-07-01 11:43:18 -04001048 if hs.serverHello.extensions.ocspStapling {
David Benjamin48cae082014-10-27 01:06:24 -04001049 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001050 if err != nil {
1051 return err
1052 }
1053 cs, ok := msg.(*certificateStatusMsg)
1054 if !ok {
1055 c.sendAlert(alertUnexpectedMessage)
1056 return unexpectedMessageError(cs, msg)
1057 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001058 hs.writeServerHash(cs.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001059
1060 if cs.statusType == statusTypeOCSP {
1061 c.ocspResponse = cs.response
1062 }
1063 }
1064
David Benjamin48cae082014-10-27 01:06:24 -04001065 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001066 if err != nil {
1067 return err
1068 }
1069
1070 keyAgreement := hs.suite.ka(c.vers)
1071
1072 skx, ok := msg.(*serverKeyExchangeMsg)
1073 if ok {
David Benjamin83c0bc92014-08-04 01:23:53 -04001074 hs.writeServerHash(skx.marshal())
David Benjamin48cae082014-10-27 01:06:24 -04001075 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx)
Adam Langley95c29f32014-06-20 12:00:00 -07001076 if err != nil {
1077 c.sendAlert(alertUnexpectedMessage)
1078 return err
1079 }
Steven Valdez5440fe02016-07-18 12:40:30 -04001080 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1081 c.curveID = ecdhe.curveID
1082 }
Adam Langley95c29f32014-06-20 12:00:00 -07001083
Nick Harper60edffd2016-06-21 15:19:24 -07001084 c.peerSignatureAlgorithm = keyAgreement.peerSignatureAlgorithm()
1085
Adam Langley95c29f32014-06-20 12:00:00 -07001086 msg, err = c.readHandshake()
1087 if err != nil {
1088 return err
1089 }
1090 }
1091
1092 var chainToSend *Certificate
1093 var certRequested bool
1094 certReq, ok := msg.(*certificateRequestMsg)
1095 if ok {
1096 certRequested = true
David Benjamin7a41d372016-07-09 11:21:54 -07001097 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
1098 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
1099 }
Adam Langley95c29f32014-06-20 12:00:00 -07001100
David Benjamin83c0bc92014-08-04 01:23:53 -04001101 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001102
David Benjamina6f82632016-07-01 18:44:02 -04001103 chainToSend, err = selectClientCertificate(c, certReq)
1104 if err != nil {
1105 return err
Adam Langley95c29f32014-06-20 12:00:00 -07001106 }
1107
1108 msg, err = c.readHandshake()
1109 if err != nil {
1110 return err
1111 }
1112 }
1113
1114 shd, ok := msg.(*serverHelloDoneMsg)
1115 if !ok {
1116 c.sendAlert(alertUnexpectedMessage)
1117 return unexpectedMessageError(shd, msg)
1118 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001119 hs.writeServerHash(shd.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001120
1121 // If the server requested a certificate then we have to send a
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001122 // Certificate message in TLS, even if it's empty because we don't have
1123 // a certificate to send. In SSL 3.0, skip the message and send a
1124 // no_certificate warning alert.
Adam Langley95c29f32014-06-20 12:00:00 -07001125 if certRequested {
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001126 if c.vers == VersionSSL30 && chainToSend == nil {
David Benjamin053fee92017-01-02 08:30:36 -05001127 c.sendAlert(alertNoCertificate)
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001128 } else if !c.config.Bugs.SkipClientCertificate {
1129 certMsg := new(certificateMsg)
1130 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -04001131 for _, certData := range chainToSend.Certificate {
1132 certMsg.certificates = append(certMsg.certificates, certificateEntry{
1133 data: certData,
1134 })
1135 }
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001136 }
1137 hs.writeClientHash(certMsg.marshal())
1138 c.writeRecord(recordTypeHandshake, certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001139 }
Adam Langley95c29f32014-06-20 12:00:00 -07001140 }
1141
David Benjamin48cae082014-10-27 01:06:24 -04001142 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf)
Adam Langley95c29f32014-06-20 12:00:00 -07001143 if err != nil {
1144 c.sendAlert(alertInternalError)
1145 return err
1146 }
1147 if ckx != nil {
David Benjaminf3ec83d2014-07-21 22:42:34 -04001148 if c.config.Bugs.EarlyChangeCipherSpec < 2 {
David Benjamin83c0bc92014-08-04 01:23:53 -04001149 hs.writeClientHash(ckx.marshal())
David Benjaminf3ec83d2014-07-21 22:42:34 -04001150 }
Adam Langley95c29f32014-06-20 12:00:00 -07001151 c.writeRecord(recordTypeHandshake, ckx.marshal())
1152 }
1153
Nick Harperb3d51be2016-07-01 11:43:18 -04001154 if hs.serverHello.extensions.extendedMasterSecret && c.vers >= VersionTLS10 {
Adam Langley75712922014-10-10 16:23:43 -07001155 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1156 c.extendedMasterSecret = true
1157 } else {
1158 if c.config.Bugs.RequireExtendedMasterSecret {
1159 return errors.New("tls: extended master secret required but not supported by peer")
1160 }
1161 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
1162 }
David Benjamine098ec22014-08-27 23:13:20 -04001163
Adam Langley95c29f32014-06-20 12:00:00 -07001164 if chainToSend != nil {
Adam Langley95c29f32014-06-20 12:00:00 -07001165 certVerify := &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001166 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001167 }
1168
David Benjamin72dc7832015-03-16 17:49:43 -04001169 // Determine the hash to sign.
Nick Harper60edffd2016-06-21 15:19:24 -07001170 privKey := c.config.Certificates[0].PrivateKey
David Benjamin72dc7832015-03-16 17:49:43 -04001171
Nick Harper60edffd2016-06-21 15:19:24 -07001172 if certVerify.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001173 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
Nick Harper60edffd2016-06-21 15:19:24 -07001174 if err != nil {
1175 c.sendAlert(alertInternalError)
1176 return err
Adam Langley95c29f32014-06-20 12:00:00 -07001177 }
Nick Harper60edffd2016-06-21 15:19:24 -07001178 }
1179
1180 if c.vers > VersionSSL30 {
David Benjamin5208fd42016-07-13 21:43:25 -04001181 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, hs.finishedHash.buffer)
David Benjamina95e9f32016-07-08 16:28:04 -07001182 if err == nil && c.config.Bugs.SendSignatureAlgorithm != 0 {
1183 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
1184 }
Nick Harper60edffd2016-06-21 15:19:24 -07001185 } else {
1186 // SSL 3.0's client certificate construction is
1187 // incompatible with signatureAlgorithm.
1188 rsaKey, ok := privKey.(*rsa.PrivateKey)
1189 if !ok {
1190 err = errors.New("unsupported signature type for client certificate")
1191 } else {
1192 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
David Benjamin5208fd42016-07-13 21:43:25 -04001193 if c.config.Bugs.InvalidSignature {
Nick Harper60edffd2016-06-21 15:19:24 -07001194 digest[0] ^= 0x80
1195 }
1196 certVerify.signature, err = rsa.SignPKCS1v15(c.config.rand(), rsaKey, crypto.MD5SHA1, digest)
1197 }
Adam Langley95c29f32014-06-20 12:00:00 -07001198 }
1199 if err != nil {
1200 c.sendAlert(alertInternalError)
1201 return errors.New("tls: failed to sign handshake with client certificate: " + err.Error())
1202 }
Adam Langley95c29f32014-06-20 12:00:00 -07001203
Dimitar Vlahovskibd708452017-08-10 18:01:06 +02001204 if !c.config.Bugs.SkipCertificateVerify {
1205 hs.writeClientHash(certVerify.marshal())
1206 c.writeRecord(recordTypeHandshake, certVerify.marshal())
1207 }
Adam Langley95c29f32014-06-20 12:00:00 -07001208 }
David Benjamin82261be2016-07-07 14:32:50 -07001209 // flushHandshake will be called in sendFinished.
Adam Langley95c29f32014-06-20 12:00:00 -07001210
David Benjamine098ec22014-08-27 23:13:20 -04001211 hs.finishedHash.discardHandshakeBuffer()
1212
Adam Langley95c29f32014-06-20 12:00:00 -07001213 return nil
1214}
1215
David Benjamin75051442016-07-01 18:58:51 -04001216func (hs *clientHandshakeState) verifyCertificates(certMsg *certificateMsg) error {
1217 c := hs.c
1218
1219 if len(certMsg.certificates) == 0 {
1220 c.sendAlert(alertIllegalParameter)
1221 return errors.New("tls: no certificates sent")
1222 }
1223
1224 certs := make([]*x509.Certificate, len(certMsg.certificates))
Steven Valdeza833c352016-11-01 13:39:36 -04001225 for i, certEntry := range certMsg.certificates {
1226 cert, err := x509.ParseCertificate(certEntry.data)
David Benjamin75051442016-07-01 18:58:51 -04001227 if err != nil {
1228 c.sendAlert(alertBadCertificate)
1229 return errors.New("tls: failed to parse certificate from server: " + err.Error())
1230 }
1231 certs[i] = cert
1232 }
1233
1234 if !c.config.InsecureSkipVerify {
1235 opts := x509.VerifyOptions{
1236 Roots: c.config.RootCAs,
1237 CurrentTime: c.config.time(),
1238 DNSName: c.config.ServerName,
1239 Intermediates: x509.NewCertPool(),
1240 }
1241
1242 for i, cert := range certs {
1243 if i == 0 {
1244 continue
1245 }
1246 opts.Intermediates.AddCert(cert)
1247 }
1248 var err error
1249 c.verifiedChains, err = certs[0].Verify(opts)
1250 if err != nil {
1251 c.sendAlert(alertBadCertificate)
1252 return err
1253 }
1254 }
1255
David Benjamind768c5d2017-03-28 18:28:44 -05001256 publicKey := getCertificatePublicKey(certs[0])
1257 switch publicKey.(type) {
1258 case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
David Benjamin75051442016-07-01 18:58:51 -04001259 break
1260 default:
1261 c.sendAlert(alertUnsupportedCertificate)
David Benjamind768c5d2017-03-28 18:28:44 -05001262 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", publicKey)
David Benjamin75051442016-07-01 18:58:51 -04001263 }
1264
1265 c.peerCertificates = certs
1266 return nil
1267}
1268
Adam Langley95c29f32014-06-20 12:00:00 -07001269func (hs *clientHandshakeState) establishKeys() error {
1270 c := hs.c
1271
1272 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001273 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 -07001274 var clientCipher, serverCipher interface{}
1275 var clientHash, serverHash macFunction
1276 if hs.suite.cipher != nil {
1277 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
1278 clientHash = hs.suite.mac(c.vers, clientMAC)
1279 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
1280 serverHash = hs.suite.mac(c.vers, serverMAC)
1281 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001282 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1283 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001284 }
1285
1286 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
1287 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
1288 return nil
1289}
1290
David Benjamin75101402016-07-01 13:40:23 -04001291func (hs *clientHandshakeState) processServerExtensions(serverExtensions *serverExtensions) error {
1292 c := hs.c
1293
David Benjamin8d315d72016-07-18 01:03:18 +02001294 if c.vers < VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001295 if c.config.Bugs.RequireRenegotiationInfo && serverExtensions.secureRenegotiation == nil {
1296 return errors.New("tls: renegotiation extension missing")
1297 }
David Benjamin75101402016-07-01 13:40:23 -04001298
Nick Harperb41d2e42016-07-01 17:50:32 -04001299 if len(c.clientVerify) > 0 && !c.noRenegotiationInfo() {
1300 var expectedRenegInfo []byte
1301 expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...)
1302 expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...)
1303 if !bytes.Equal(serverExtensions.secureRenegotiation, expectedRenegInfo) {
1304 c.sendAlert(alertHandshakeFailure)
1305 return fmt.Errorf("tls: renegotiation mismatch")
1306 }
David Benjamin75101402016-07-01 13:40:23 -04001307 }
David Benjamincea0ab42016-07-14 12:33:14 -04001308 } else if serverExtensions.secureRenegotiation != nil {
1309 return errors.New("tls: renegotiation info sent in TLS 1.3")
David Benjamin75101402016-07-01 13:40:23 -04001310 }
1311
1312 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
1313 if serverExtensions.customExtension != *expected {
1314 return fmt.Errorf("tls: bad custom extension contents %q", serverExtensions.customExtension)
1315 }
1316 }
1317
1318 clientDidNPN := hs.hello.nextProtoNeg
1319 clientDidALPN := len(hs.hello.alpnProtocols) > 0
1320 serverHasNPN := serverExtensions.nextProtoNeg
1321 serverHasALPN := len(serverExtensions.alpnProtocol) > 0
1322
1323 if !clientDidNPN && serverHasNPN {
1324 c.sendAlert(alertHandshakeFailure)
1325 return errors.New("server advertised unrequested NPN extension")
1326 }
1327
1328 if !clientDidALPN && serverHasALPN {
1329 c.sendAlert(alertHandshakeFailure)
1330 return errors.New("server advertised unrequested ALPN extension")
1331 }
1332
1333 if serverHasNPN && serverHasALPN {
1334 c.sendAlert(alertHandshakeFailure)
1335 return errors.New("server advertised both NPN and ALPN extensions")
1336 }
1337
1338 if serverHasALPN {
1339 c.clientProtocol = serverExtensions.alpnProtocol
1340 c.clientProtocolFallback = false
1341 c.usedALPN = true
1342 }
1343
David Benjamin8d315d72016-07-18 01:03:18 +02001344 if serverHasNPN && c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001345 c.sendAlert(alertHandshakeFailure)
1346 return errors.New("server advertised NPN over TLS 1.3")
1347 }
1348
David Benjamin75101402016-07-01 13:40:23 -04001349 if !hs.hello.channelIDSupported && serverExtensions.channelIDRequested {
1350 c.sendAlert(alertHandshakeFailure)
1351 return errors.New("server advertised unrequested Channel ID extension")
1352 }
1353
David Benjamin8d315d72016-07-18 01:03:18 +02001354 if serverExtensions.extendedMasterSecret && c.vers >= VersionTLS13 {
David Benjamine9077652016-07-13 21:02:08 -04001355 return errors.New("tls: server advertised extended master secret over TLS 1.3")
1356 }
1357
David Benjamin8d315d72016-07-18 01:03:18 +02001358 if serverExtensions.ticketSupported && c.vers >= VersionTLS13 {
Steven Valdez143e8b32016-07-11 13:19:03 -04001359 return errors.New("tls: server advertised ticket extension over TLS 1.3")
1360 }
1361
Steven Valdeza833c352016-11-01 13:39:36 -04001362 if serverExtensions.ocspStapling && c.vers >= VersionTLS13 {
1363 return errors.New("tls: server advertised OCSP in ServerHello over TLS 1.3")
1364 }
1365
David Benjamin53210cb2016-11-16 09:01:48 +09001366 if serverExtensions.ocspStapling && c.config.Bugs.NoOCSPStapling {
1367 return errors.New("tls: server advertised unrequested OCSP extension")
1368 }
1369
Steven Valdeza833c352016-11-01 13:39:36 -04001370 if len(serverExtensions.sctList) > 0 && c.vers >= VersionTLS13 {
1371 return errors.New("tls: server advertised SCTs in ServerHello over TLS 1.3")
1372 }
1373
David Benjamin53210cb2016-11-16 09:01:48 +09001374 if len(serverExtensions.sctList) > 0 && c.config.Bugs.NoSignedCertificateTimestamps {
1375 return errors.New("tls: server advertised unrequested SCTs")
1376 }
1377
David Benjamin75101402016-07-01 13:40:23 -04001378 if serverExtensions.srtpProtectionProfile != 0 {
1379 if serverExtensions.srtpMasterKeyIdentifier != "" {
1380 return errors.New("tls: server selected SRTP MKI value")
1381 }
1382
1383 found := false
1384 for _, p := range c.config.SRTPProtectionProfiles {
1385 if p == serverExtensions.srtpProtectionProfile {
1386 found = true
1387 break
1388 }
1389 }
1390 if !found {
1391 return errors.New("tls: server advertised unsupported SRTP profile")
1392 }
1393
1394 c.srtpProtectionProfile = serverExtensions.srtpProtectionProfile
1395 }
1396
Steven Valdez2d850622017-01-11 11:34:52 -05001397 if c.vers >= VersionTLS13 && c.didResume {
1398 if c.config.Bugs.ExpectEarlyDataAccepted && !serverExtensions.hasEarlyData {
1399 c.sendAlert(alertHandshakeFailure)
1400 return errors.New("tls: server did not accept early data when expected")
1401 }
1402
1403 if !c.config.Bugs.ExpectEarlyDataAccepted && serverExtensions.hasEarlyData {
1404 c.sendAlert(alertHandshakeFailure)
1405 return errors.New("tls: server accepted early data when not expected")
1406 }
1407 }
1408
David Benjamin75101402016-07-01 13:40:23 -04001409 return nil
1410}
1411
Adam Langley95c29f32014-06-20 12:00:00 -07001412func (hs *clientHandshakeState) serverResumedSession() bool {
1413 // If the server responded with the same sessionId then it means the
1414 // sessionTicket is being used to resume a TLS session.
David Benjamind4c349b2017-02-09 14:07:17 -05001415 //
1416 // Note that, if hs.hello.sessionId is a non-nil empty array, this will
1417 // accept an empty session ID from the server as resumption. See
1418 // EmptyTicketSessionID.
Adam Langley95c29f32014-06-20 12:00:00 -07001419 return hs.session != nil && hs.hello.sessionId != nil &&
1420 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
1421}
1422
1423func (hs *clientHandshakeState) processServerHello() (bool, error) {
1424 c := hs.c
1425
Adam Langley95c29f32014-06-20 12:00:00 -07001426 if hs.serverResumedSession() {
David Benjamin4b27d9f2015-05-12 22:42:52 -04001427 // For test purposes, assert that the server never accepts the
1428 // resumption offer on renegotiation.
1429 if c.cipherSuite != nil && c.config.Bugs.FailIfResumeOnRenego {
1430 return false, errors.New("tls: server resumed session on renegotiation")
1431 }
1432
Nick Harperb3d51be2016-07-01 11:43:18 -04001433 if hs.serverHello.extensions.sctList != nil {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001434 return false, errors.New("tls: server sent SCT extension on session resumption")
1435 }
1436
Nick Harperb3d51be2016-07-01 11:43:18 -04001437 if hs.serverHello.extensions.ocspStapling {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001438 return false, errors.New("tls: server sent OCSP extension on session resumption")
1439 }
1440
Adam Langley95c29f32014-06-20 12:00:00 -07001441 // Restore masterSecret and peerCerts from previous state
1442 hs.masterSecret = hs.session.masterSecret
1443 c.peerCertificates = hs.session.serverCertificates
Adam Langley75712922014-10-10 16:23:43 -07001444 c.extendedMasterSecret = hs.session.extendedMasterSecret
Paul Lietar62be8ac2015-09-16 10:03:30 +01001445 c.sctList = hs.session.sctList
1446 c.ocspResponse = hs.session.ocspResponse
David Benjamine098ec22014-08-27 23:13:20 -04001447 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001448 return true, nil
1449 }
Paul Lietar62be8ac2015-09-16 10:03:30 +01001450
Nick Harperb3d51be2016-07-01 11:43:18 -04001451 if hs.serverHello.extensions.sctList != nil {
1452 c.sctList = hs.serverHello.extensions.sctList
Paul Lietar62be8ac2015-09-16 10:03:30 +01001453 }
1454
Adam Langley95c29f32014-06-20 12:00:00 -07001455 return false, nil
1456}
1457
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001458func (hs *clientHandshakeState) readFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001459 c := hs.c
1460
1461 c.readRecord(recordTypeChangeCipherSpec)
1462 if err := c.in.error(); err != nil {
1463 return err
1464 }
1465
1466 msg, err := c.readHandshake()
1467 if err != nil {
1468 return err
1469 }
1470 serverFinished, ok := msg.(*finishedMsg)
1471 if !ok {
1472 c.sendAlert(alertUnexpectedMessage)
1473 return unexpectedMessageError(serverFinished, msg)
1474 }
1475
David Benjaminf3ec83d2014-07-21 22:42:34 -04001476 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
1477 verify := hs.finishedHash.serverSum(hs.masterSecret)
1478 if len(verify) != len(serverFinished.verifyData) ||
1479 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
1480 c.sendAlert(alertHandshakeFailure)
1481 return errors.New("tls: server's Finished message was incorrect")
1482 }
Adam Langley95c29f32014-06-20 12:00:00 -07001483 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001484 c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001485 copy(out, serverFinished.verifyData)
David Benjamin83c0bc92014-08-04 01:23:53 -04001486 hs.writeServerHash(serverFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001487 return nil
1488}
1489
1490func (hs *clientHandshakeState) readSessionTicket() error {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001491 c := hs.c
1492
1493 // Create a session with no server identifier. Either a
1494 // session ID or session ticket will be attached.
1495 session := &ClientSessionState{
1496 vers: c.vers,
1497 cipherSuite: hs.suite.id,
1498 masterSecret: hs.masterSecret,
Nick Harperc9846112016-10-17 15:05:35 -07001499 handshakeHash: hs.finishedHash.Sum(),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001500 serverCertificates: c.peerCertificates,
Paul Lietar62be8ac2015-09-16 10:03:30 +01001501 sctList: c.sctList,
1502 ocspResponse: c.ocspResponse,
Nick Harper0b3625b2016-07-25 16:16:28 -07001503 ticketExpiration: c.config.time().Add(time.Duration(7 * 24 * time.Hour)),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001504 }
1505
Nick Harperb3d51be2016-07-01 11:43:18 -04001506 if !hs.serverHello.extensions.ticketSupported {
David Benjamind98452d2015-06-16 14:16:23 -04001507 if c.config.Bugs.ExpectNewTicket {
1508 return errors.New("tls: expected new ticket")
1509 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001510 if hs.session == nil && len(hs.serverHello.sessionId) > 0 {
1511 session.sessionId = hs.serverHello.sessionId
1512 hs.session = session
1513 }
Adam Langley95c29f32014-06-20 12:00:00 -07001514 return nil
1515 }
1516
David Benjaminc7ce9772015-10-09 19:32:41 -04001517 if c.vers == VersionSSL30 {
1518 return errors.New("tls: negotiated session tickets in SSL 3.0")
1519 }
1520
Adam Langley95c29f32014-06-20 12:00:00 -07001521 msg, err := c.readHandshake()
1522 if err != nil {
1523 return err
1524 }
1525 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
1526 if !ok {
1527 c.sendAlert(alertUnexpectedMessage)
1528 return unexpectedMessageError(sessionTicketMsg, msg)
1529 }
Adam Langley95c29f32014-06-20 12:00:00 -07001530
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001531 session.sessionTicket = sessionTicketMsg.ticket
1532 hs.session = session
Adam Langley95c29f32014-06-20 12:00:00 -07001533
David Benjamind30a9902014-08-24 01:44:23 -04001534 hs.writeServerHash(sessionTicketMsg.marshal())
1535
Adam Langley95c29f32014-06-20 12:00:00 -07001536 return nil
1537}
1538
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001539func (hs *clientHandshakeState) sendFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001540 c := hs.c
1541
David Benjamin0b8d5da2016-07-15 00:39:56 -04001542 var postCCSMsgs [][]byte
David Benjamin83c0bc92014-08-04 01:23:53 -04001543 seqno := hs.c.sendHandshakeSeq
Nick Harperb3d51be2016-07-01 11:43:18 -04001544 if hs.serverHello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001545 nextProto := new(nextProtoMsg)
Nick Harperb3d51be2016-07-01 11:43:18 -04001546 proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.extensions.nextProtos)
Adam Langley95c29f32014-06-20 12:00:00 -07001547 nextProto.proto = proto
1548 c.clientProtocol = proto
1549 c.clientProtocolFallback = fallback
1550
David Benjamin86271ee2014-07-21 16:14:03 -04001551 nextProtoBytes := nextProto.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -04001552 hs.writeHash(nextProtoBytes, seqno)
1553 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001554 postCCSMsgs = append(postCCSMsgs, nextProtoBytes)
Adam Langley95c29f32014-06-20 12:00:00 -07001555 }
1556
Nick Harperb3d51be2016-07-01 11:43:18 -04001557 if hs.serverHello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001558 var resumeHash []byte
1559 if isResume {
1560 resumeHash = hs.session.handshakeHash
1561 }
Nick Harper60a85cb2016-09-23 16:25:11 -07001562 channelIDMsgBytes, err := hs.writeChannelIDMessage(hs.finishedHash.hashForChannelID(resumeHash))
David Benjamind30a9902014-08-24 01:44:23 -04001563 if err != nil {
1564 return err
1565 }
David Benjamin24599a82016-06-30 18:56:53 -04001566 hs.writeHash(channelIDMsgBytes, seqno)
David Benjamind30a9902014-08-24 01:44:23 -04001567 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001568 postCCSMsgs = append(postCCSMsgs, channelIDMsgBytes)
David Benjamind30a9902014-08-24 01:44:23 -04001569 }
1570
Adam Langley95c29f32014-06-20 12:00:00 -07001571 finished := new(finishedMsg)
David Benjaminf3ec83d2014-07-21 22:42:34 -04001572 if c.config.Bugs.EarlyChangeCipherSpec == 2 {
1573 finished.verifyData = hs.finishedHash.clientSum(nil)
1574 } else {
1575 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
1576 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001577 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001578 if c.config.Bugs.BadFinished {
1579 finished.verifyData[0]++
1580 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001581 c.clientVerify = append(c.clientVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001582 hs.finishedBytes = finished.marshal()
1583 hs.writeHash(hs.finishedBytes, seqno)
David Benjamin0b8d5da2016-07-15 00:39:56 -04001584 postCCSMsgs = append(postCCSMsgs, hs.finishedBytes)
David Benjamin86271ee2014-07-21 16:14:03 -04001585
1586 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001587 c.writeRecord(recordTypeHandshake, postCCSMsgs[0][:5])
1588 postCCSMsgs[0] = postCCSMsgs[0][5:]
David Benjamin61672812016-07-14 23:10:43 -04001589 } else if c.config.Bugs.SendUnencryptedFinished {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001590 c.writeRecord(recordTypeHandshake, postCCSMsgs[0])
1591 postCCSMsgs = postCCSMsgs[1:]
David Benjamin86271ee2014-07-21 16:14:03 -04001592 }
1593
1594 if !c.config.Bugs.SkipChangeCipherSpec &&
1595 c.config.Bugs.EarlyChangeCipherSpec == 0 {
David Benjamin8411b242015-11-26 12:07:28 -05001596 ccs := []byte{1}
1597 if c.config.Bugs.BadChangeCipherSpec != nil {
1598 ccs = c.config.Bugs.BadChangeCipherSpec
1599 }
1600 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamin86271ee2014-07-21 16:14:03 -04001601 }
1602
David Benjamin4189bd92015-01-25 23:52:39 -05001603 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1604 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1605 }
David Benjamindc3da932015-03-12 15:09:02 -04001606 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1607 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1608 return errors.New("tls: simulating post-CCS alert")
1609 }
David Benjamin4189bd92015-01-25 23:52:39 -05001610
David Benjamin0b8d5da2016-07-15 00:39:56 -04001611 if !c.config.Bugs.SkipFinished {
1612 for _, msg := range postCCSMsgs {
1613 c.writeRecord(recordTypeHandshake, msg)
1614 }
David Benjamin02edcd02016-07-27 17:40:37 -04001615
1616 if c.config.Bugs.SendExtraFinished {
1617 c.writeRecord(recordTypeHandshake, finished.marshal())
1618 }
David Benjaminb3774b92015-01-31 17:16:01 -05001619 }
David Benjaminb0c761e2017-06-25 22:42:55 -04001620
1621 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001622 return nil
1623}
1624
Nick Harper60a85cb2016-09-23 16:25:11 -07001625func (hs *clientHandshakeState) writeChannelIDMessage(channelIDHash []byte) ([]byte, error) {
1626 c := hs.c
1627 channelIDMsg := new(channelIDMsg)
1628 if c.config.ChannelID.Curve != elliptic.P256() {
1629 return nil, fmt.Errorf("tls: Channel ID is not on P-256.")
1630 }
1631 r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, channelIDHash)
1632 if err != nil {
1633 return nil, err
1634 }
1635 channelID := make([]byte, 128)
1636 writeIntPadded(channelID[0:32], c.config.ChannelID.X)
1637 writeIntPadded(channelID[32:64], c.config.ChannelID.Y)
1638 writeIntPadded(channelID[64:96], r)
1639 writeIntPadded(channelID[96:128], s)
1640 if c.config.Bugs.InvalidChannelIDSignature {
1641 channelID[64] ^= 1
1642 }
1643 channelIDMsg.channelID = channelID
1644
1645 c.channelID = &c.config.ChannelID.PublicKey
1646
1647 return channelIDMsg.marshal(), nil
1648}
1649
David Benjamin83c0bc92014-08-04 01:23:53 -04001650func (hs *clientHandshakeState) writeClientHash(msg []byte) {
1651 // writeClientHash is called before writeRecord.
1652 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1653}
1654
1655func (hs *clientHandshakeState) writeServerHash(msg []byte) {
1656 // writeServerHash is called after readHandshake.
1657 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1658}
1659
1660func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) {
1661 if hs.c.isDTLS {
1662 // This is somewhat hacky. DTLS hashes a slightly different format.
1663 // First, the TLS header.
1664 hs.finishedHash.Write(msg[:4])
1665 // Then the sequence number and reassembled fragment offset (always 0).
1666 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1667 // Then the reassembled fragment (always equal to the message length).
1668 hs.finishedHash.Write(msg[1:4])
1669 // And then the message body.
1670 hs.finishedHash.Write(msg[4:])
1671 } else {
1672 hs.finishedHash.Write(msg)
1673 }
1674}
1675
David Benjamina6f82632016-07-01 18:44:02 -04001676// selectClientCertificate selects a certificate for use with the given
1677// certificate, or none if none match. It may return a particular certificate or
1678// nil on success, or an error on internal error.
1679func selectClientCertificate(c *Conn, certReq *certificateRequestMsg) (*Certificate, error) {
David Benjamin3969fdf2017-08-29 15:50:58 -04001680 if len(c.config.Certificates) == 0 {
1681 return nil, nil
David Benjamina6f82632016-07-01 18:44:02 -04001682 }
1683
David Benjamin3969fdf2017-08-29 15:50:58 -04001684 // The test is assumed to have configured the certificate it meant to
1685 // send.
1686 if len(c.config.Certificates) > 1 {
1687 return nil, errors.New("tls: multiple certificates configured")
David Benjamina6f82632016-07-01 18:44:02 -04001688 }
1689
David Benjamin3969fdf2017-08-29 15:50:58 -04001690 return &c.config.Certificates[0], nil
David Benjamina6f82632016-07-01 18:44:02 -04001691}
1692
Adam Langley95c29f32014-06-20 12:00:00 -07001693// clientSessionCacheKey returns a key used to cache sessionTickets that could
1694// be used to resume previously negotiated TLS sessions with a server.
1695func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
1696 if len(config.ServerName) > 0 {
1697 return config.ServerName
1698 }
1699 return serverAddr.String()
1700}
1701
David Benjaminfa055a22014-09-15 16:51:51 -04001702// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
1703// given list of possible protocols and a list of the preference order. The
1704// first list must not be empty. It returns the resulting protocol and flag
Adam Langley95c29f32014-06-20 12:00:00 -07001705// indicating if the fallback case was reached.
David Benjaminfa055a22014-09-15 16:51:51 -04001706func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
1707 for _, s := range preferenceProtos {
1708 for _, c := range protos {
Adam Langley95c29f32014-06-20 12:00:00 -07001709 if s == c {
1710 return s, false
1711 }
1712 }
1713 }
1714
David Benjaminfa055a22014-09-15 16:51:51 -04001715 return protos[0], true
Adam Langley95c29f32014-06-20 12:00:00 -07001716}
David Benjamind30a9902014-08-24 01:44:23 -04001717
1718// writeIntPadded writes x into b, padded up with leading zeros as
1719// needed.
1720func writeIntPadded(b []byte, x *big.Int) {
1721 for i := range b {
1722 b[i] = 0
1723 }
1724 xb := x.Bytes()
1725 copy(b[len(b)-len(xb):], xb)
1726}
Steven Valdeza833c352016-11-01 13:39:36 -04001727
1728func generatePSKBinders(hello *clientHelloMsg, pskCipherSuite *cipherSuite, psk, transcript []byte, config *Config) {
1729 if config.Bugs.SendNoPSKBinder {
1730 return
1731 }
1732
1733 binderLen := pskCipherSuite.hash().Size()
1734 if config.Bugs.SendShortPSKBinder {
1735 binderLen--
1736 }
1737
David Benjaminaedf3032016-12-01 16:47:56 -05001738 numBinders := 1
1739 if config.Bugs.SendExtraPSKBinder {
1740 numBinders++
1741 }
1742
Steven Valdeza833c352016-11-01 13:39:36 -04001743 // Fill hello.pskBinders with appropriate length arrays of zeros so the
1744 // length prefixes are correct when computing the binder over the truncated
1745 // ClientHello message.
David Benjaminaedf3032016-12-01 16:47:56 -05001746 hello.pskBinders = make([][]byte, numBinders)
1747 for i := range hello.pskBinders {
Steven Valdeza833c352016-11-01 13:39:36 -04001748 hello.pskBinders[i] = make([]byte, binderLen)
1749 }
1750
1751 helloBytes := hello.marshal()
1752 binderSize := len(hello.pskBinders)*(binderLen+1) + 2
1753 truncatedHello := helloBytes[:len(helloBytes)-binderSize]
1754 binder := computePSKBinder(psk, resumptionPSKBinderLabel, pskCipherSuite, transcript, truncatedHello)
1755 if config.Bugs.SendShortPSKBinder {
1756 binder = binder[:binderLen]
1757 }
1758 if config.Bugs.SendInvalidPSKBinder {
1759 binder[0] ^= 1
1760 }
1761
1762 for i := range hello.pskBinders {
1763 hello.pskBinders[i] = binder
1764 }
1765
1766 hello.raw = nil
1767}