blob: ba7b91ef3bc7b5c0a63f68b9e236988fd2320b82 [file] [log] [blame]
Adam Langley95c29f32014-06-20 12:00:00 -07001// Copyright 2009 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
Adam Langleydc7e9c42015-09-29 15:21:04 -07005package runner
Adam Langley95c29f32014-06-20 12:00:00 -07006
7import (
8 "bytes"
Nick Harper60edffd2016-06-21 15:19:24 -07009 "crypto"
Adam Langley95c29f32014-06-20 12:00:00 -070010 "crypto/ecdsa"
David Benjamind30a9902014-08-24 01:44:23 -040011 "crypto/elliptic"
Adam Langley95c29f32014-06-20 12:00:00 -070012 "crypto/rsa"
13 "crypto/subtle"
14 "crypto/x509"
Adam Langley95c29f32014-06-20 12:00:00 -070015 "errors"
16 "fmt"
17 "io"
David Benjaminde620d92014-07-18 15:03:41 -040018 "math/big"
Adam Langley95c29f32014-06-20 12:00:00 -070019 "net"
20 "strconv"
Nick Harper0b3625b2016-07-25 16:16:28 -070021 "time"
Adam Langley95c29f32014-06-20 12:00:00 -070022)
23
24type clientHandshakeState struct {
David Benjamin83f90402015-01-27 01:09:43 -050025 c *Conn
26 serverHello *serverHelloMsg
27 hello *clientHelloMsg
28 suite *cipherSuite
29 finishedHash finishedHash
Nick Harperb41d2e42016-07-01 17:50:32 -040030 keyShares map[CurveID]ecdhCurve
David Benjamin83f90402015-01-27 01:09:43 -050031 masterSecret []byte
32 session *ClientSessionState
33 finishedBytes []byte
Adam Langley95c29f32014-06-20 12:00:00 -070034}
35
36func (c *Conn) clientHandshake() error {
37 if c.config == nil {
38 c.config = defaultConfig()
39 }
40
41 if len(c.config.ServerName) == 0 && !c.config.InsecureSkipVerify {
42 return errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
43 }
44
David Benjamin83c0bc92014-08-04 01:23:53 -040045 c.sendHandshakeSeq = 0
46 c.recvHandshakeSeq = 0
47
David Benjaminfa055a22014-09-15 16:51:51 -040048 nextProtosLength := 0
49 for _, proto := range c.config.NextProtos {
Adam Langleyefb0e162015-07-09 11:35:04 -070050 if l := len(proto); l > 255 {
David Benjaminfa055a22014-09-15 16:51:51 -040051 return errors.New("tls: invalid NextProtos value")
52 } else {
53 nextProtosLength += 1 + l
54 }
55 }
56 if nextProtosLength > 0xffff {
57 return errors.New("tls: NextProtos values too large")
58 }
59
Steven Valdezfdd10992016-09-15 16:27:05 -040060 minVersion := c.config.minVersion(c.isDTLS)
David Benjamin3c6a1ea2016-09-26 18:30:05 -040061 maxVersion := c.config.maxVersion(c.isDTLS)
Adam Langley95c29f32014-06-20 12:00:00 -070062 hello := &clientHelloMsg{
David Benjaminca6c8262014-11-15 19:06:08 -050063 isDTLS: c.isDTLS,
David Benjamin3c6a1ea2016-09-26 18:30:05 -040064 vers: versionToWire(maxVersion, c.isDTLS),
David Benjaminca6c8262014-11-15 19:06:08 -050065 compressionMethods: []uint8{compressionNone},
66 random: make([]byte, 32),
David Benjamin53210cb2016-11-16 09:01:48 +090067 ocspStapling: !c.config.Bugs.NoOCSPStapling,
68 sctListSupported: !c.config.Bugs.NoSignedCertificateTimestamps,
David Benjaminca6c8262014-11-15 19:06:08 -050069 serverName: c.config.ServerName,
70 supportedCurves: c.config.curvePreferences(),
Steven Valdeza833c352016-11-01 13:39:36 -040071 pskKEModes: []byte{pskDHEKEMode},
David Benjaminca6c8262014-11-15 19:06:08 -050072 supportedPoints: []uint8{pointFormatUncompressed},
73 nextProtoNeg: len(c.config.NextProtos) > 0,
74 secureRenegotiation: []byte{},
75 alpnProtocols: c.config.NextProtos,
76 duplicateExtension: c.config.Bugs.DuplicateExtension,
77 channelIDSupported: c.config.ChannelID != nil,
Steven Valdeza833c352016-11-01 13:39:36 -040078 npnAfterAlpn: c.config.Bugs.SwapNPNAndALPN,
Steven Valdezfdd10992016-09-15 16:27:05 -040079 extendedMasterSecret: maxVersion >= VersionTLS10,
David Benjaminca6c8262014-11-15 19:06:08 -050080 srtpProtectionProfiles: c.config.SRTPProtectionProfiles,
81 srtpMasterKeyIdentifier: c.config.Bugs.SRTPMasterKeyIdentifer,
Adam Langley09505632015-07-30 18:10:13 -070082 customExtension: c.config.Bugs.CustomExtension,
Steven Valdeza833c352016-11-01 13:39:36 -040083 pskBinderFirst: c.config.Bugs.PSKBinderFirst,
David Benjamin6f600d62016-12-21 16:06:54 -050084 shortHeaderSupported: c.config.Bugs.EnableShortHeader,
Adam Langley95c29f32014-06-20 12:00:00 -070085 }
86
David Benjamin163c9562016-08-29 23:14:17 -040087 disableEMS := c.config.Bugs.NoExtendedMasterSecret
88 if c.cipherSuite != nil {
89 disableEMS = c.config.Bugs.NoExtendedMasterSecretOnRenegotiation
90 }
91
92 if disableEMS {
Adam Langley75712922014-10-10 16:23:43 -070093 hello.extendedMasterSecret = false
94 }
95
David Benjamin55a43642015-04-20 14:45:55 -040096 if c.config.Bugs.NoSupportedCurves {
97 hello.supportedCurves = nil
98 }
99
Steven Valdeza833c352016-11-01 13:39:36 -0400100 if len(c.config.Bugs.SendPSKKeyExchangeModes) != 0 {
101 hello.pskKEModes = c.config.Bugs.SendPSKKeyExchangeModes
102 }
103
David Benjaminc241d792016-09-09 10:34:20 -0400104 if c.config.Bugs.SendCompressionMethods != nil {
105 hello.compressionMethods = c.config.Bugs.SendCompressionMethods
106 }
107
David Benjamina81967b2016-12-22 09:16:57 -0500108 if c.config.Bugs.SendSupportedPointFormats != nil {
109 hello.supportedPoints = c.config.Bugs.SendSupportedPointFormats
110 }
111
Adam Langley2ae77d22014-10-28 17:29:33 -0700112 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
113 if c.config.Bugs.BadRenegotiationInfo {
114 hello.secureRenegotiation = append(hello.secureRenegotiation, c.clientVerify...)
115 hello.secureRenegotiation[0] ^= 0x80
116 } else {
117 hello.secureRenegotiation = c.clientVerify
118 }
119 }
120
David Benjamin3e052de2015-11-25 20:10:31 -0500121 if c.noRenegotiationInfo() {
David Benjaminca6554b2014-11-08 12:31:52 -0500122 hello.secureRenegotiation = nil
123 }
124
Nick Harperb41d2e42016-07-01 17:50:32 -0400125 var keyShares map[CurveID]ecdhCurve
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400126 if maxVersion >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -0400127 keyShares = make(map[CurveID]ecdhCurve)
Nick Harperdcfbc672016-07-16 17:47:31 +0200128 hello.hasKeyShares = true
David Benjamin7e1f9842016-09-20 19:24:40 -0400129 hello.trailingKeyShareData = c.config.Bugs.TrailingKeyShareData
Nick Harperdcfbc672016-07-16 17:47:31 +0200130 curvesToSend := c.config.defaultCurves()
Nick Harperb41d2e42016-07-01 17:50:32 -0400131 for _, curveID := range hello.supportedCurves {
Nick Harperdcfbc672016-07-16 17:47:31 +0200132 if !curvesToSend[curveID] {
133 continue
134 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400135 curve, ok := curveForCurveID(curveID)
136 if !ok {
137 continue
138 }
139 publicKey, err := curve.offer(c.config.rand())
140 if err != nil {
141 return err
142 }
Steven Valdez0ee2e112016-07-15 06:51:15 -0400143
144 if c.config.Bugs.SendCurve != 0 {
145 curveID = c.config.Bugs.SendCurve
146 }
147 if c.config.Bugs.InvalidECDHPoint {
148 publicKey[0] ^= 0xff
149 }
150
Nick Harperb41d2e42016-07-01 17:50:32 -0400151 hello.keyShares = append(hello.keyShares, keyShareEntry{
152 group: curveID,
153 keyExchange: publicKey,
154 })
155 keyShares[curveID] = curve
Steven Valdez143e8b32016-07-11 13:19:03 -0400156
157 if c.config.Bugs.DuplicateKeyShares {
158 hello.keyShares = append(hello.keyShares, hello.keyShares[len(hello.keyShares)-1])
159 }
160 }
161
162 if c.config.Bugs.MissingKeyShare {
Steven Valdez5440fe02016-07-18 12:40:30 -0400163 hello.hasKeyShares = false
Nick Harperb41d2e42016-07-01 17:50:32 -0400164 }
165 }
166
Adam Langley95c29f32014-06-20 12:00:00 -0700167 possibleCipherSuites := c.config.cipherSuites()
168 hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
169
170NextCipherSuite:
171 for _, suiteId := range possibleCipherSuites {
172 for _, suite := range cipherSuites {
173 if suite.id != suiteId {
174 continue
175 }
David Benjamin5ecb88b2016-10-04 17:51:35 -0400176 // Don't advertise TLS 1.2-only cipher suites unless
177 // we're attempting TLS 1.2.
178 if maxVersion < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
179 continue
180 }
181 // Don't advertise non-DTLS cipher suites in DTLS.
182 if c.isDTLS && suite.flags&suiteNoDTLS != 0 {
183 continue
David Benjamin83c0bc92014-08-04 01:23:53 -0400184 }
Adam Langley95c29f32014-06-20 12:00:00 -0700185 hello.cipherSuites = append(hello.cipherSuites, suiteId)
186 continue NextCipherSuite
187 }
188 }
189
David Benjamin5ecb88b2016-10-04 17:51:35 -0400190 if c.config.Bugs.AdvertiseAllConfiguredCiphers {
191 hello.cipherSuites = possibleCipherSuites
192 }
193
Adam Langley5021b222015-06-12 18:27:58 -0700194 if c.config.Bugs.SendRenegotiationSCSV {
195 hello.cipherSuites = append(hello.cipherSuites, renegotiationSCSV)
196 }
197
David Benjaminbef270a2014-08-02 04:22:02 -0400198 if c.config.Bugs.SendFallbackSCSV {
199 hello.cipherSuites = append(hello.cipherSuites, fallbackSCSV)
200 }
201
Adam Langley95c29f32014-06-20 12:00:00 -0700202 _, err := io.ReadFull(c.config.rand(), hello.random)
203 if err != nil {
204 c.sendAlert(alertInternalError)
205 return errors.New("tls: short read from Rand: " + err.Error())
206 }
207
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400208 if maxVersion >= VersionTLS12 && !c.config.Bugs.NoSignatureAlgorithms {
David Benjamin7a41d372016-07-09 11:21:54 -0700209 hello.signatureAlgorithms = c.config.verifySignatureAlgorithms()
Adam Langley95c29f32014-06-20 12:00:00 -0700210 }
211
212 var session *ClientSessionState
213 var cacheKey string
214 sessionCache := c.config.ClientSessionCache
Adam Langley95c29f32014-06-20 12:00:00 -0700215
216 if sessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500217 hello.ticketSupported = !c.config.SessionTicketsDisabled
Adam Langley95c29f32014-06-20 12:00:00 -0700218
219 // Try to resume a previously negotiated TLS session, if
220 // available.
221 cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
Nick Harper0b3625b2016-07-25 16:16:28 -0700222 // TODO(nharper): Support storing more than one session
223 // ticket for TLS 1.3.
Adam Langley95c29f32014-06-20 12:00:00 -0700224 candidateSession, ok := sessionCache.Get(cacheKey)
225 if ok {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500226 ticketOk := !c.config.SessionTicketsDisabled || candidateSession.sessionTicket == nil
227
Adam Langley95c29f32014-06-20 12:00:00 -0700228 // Check that the ciphersuite/version used for the
229 // previous session are still valid.
230 cipherSuiteOk := false
David Benjamin2b02f4b2016-11-16 16:11:47 +0900231 if candidateSession.vers <= VersionTLS12 {
232 for _, id := range hello.cipherSuites {
233 if id == candidateSession.cipherSuite {
234 cipherSuiteOk = true
235 break
236 }
Adam Langley95c29f32014-06-20 12:00:00 -0700237 }
David Benjamin2b02f4b2016-11-16 16:11:47 +0900238 } else {
239 // TLS 1.3 allows the cipher to change on
240 // resumption.
241 cipherSuiteOk = true
Adam Langley95c29f32014-06-20 12:00:00 -0700242 }
243
Steven Valdezfdd10992016-09-15 16:27:05 -0400244 versOk := candidateSession.vers >= minVersion &&
245 candidateSession.vers <= maxVersion
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500246 if ticketOk && versOk && cipherSuiteOk {
Adam Langley95c29f32014-06-20 12:00:00 -0700247 session = candidateSession
248 }
249 }
250 }
251
Steven Valdeza833c352016-11-01 13:39:36 -0400252 var pskCipherSuite *cipherSuite
Nick Harper0b3625b2016-07-25 16:16:28 -0700253 if session != nil && c.config.time().Before(session.ticketExpiration) {
David Benjamind5a4ecb2016-07-18 01:17:13 +0200254 ticket := session.sessionTicket
David Benjamin4199b0d2016-11-01 13:58:25 -0400255 if c.config.Bugs.FilterTicket != nil && len(ticket) > 0 {
256 // Copy the ticket so FilterTicket may act in-place.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200257 ticket = make([]byte, len(session.sessionTicket))
258 copy(ticket, session.sessionTicket)
David Benjamin4199b0d2016-11-01 13:58:25 -0400259
260 ticket, err = c.config.Bugs.FilterTicket(ticket)
261 if err != nil {
262 return err
Adam Langley38311732014-10-16 19:04:35 -0700263 }
David Benjamind5a4ecb2016-07-18 01:17:13 +0200264 }
265
David Benjamin405da482016-08-08 17:25:07 -0400266 if session.vers >= VersionTLS13 || c.config.Bugs.SendBothTickets {
Steven Valdeza833c352016-11-01 13:39:36 -0400267 pskCipherSuite = cipherSuiteFromID(session.cipherSuite)
268 if pskCipherSuite == nil {
269 return errors.New("tls: client session cache has invalid cipher suite")
270 }
Nick Harper0b3625b2016-07-25 16:16:28 -0700271 // TODO(nharper): Support sending more
272 // than one PSK identity.
Steven Valdeza833c352016-11-01 13:39:36 -0400273 ticketAge := uint32(c.config.time().Sub(session.ticketCreationTime) / time.Millisecond)
Steven Valdez5b986082016-09-01 12:29:49 -0400274 psk := pskIdentity{
Steven Valdeza833c352016-11-01 13:39:36 -0400275 ticket: ticket,
276 obfuscatedTicketAge: session.ticketAgeAdd + ticketAge,
Nick Harper0b3625b2016-07-25 16:16:28 -0700277 }
Steven Valdez5b986082016-09-01 12:29:49 -0400278 hello.pskIdentities = []pskIdentity{psk}
Steven Valdezaf3b8a92016-11-01 12:49:22 -0400279
280 if c.config.Bugs.ExtraPSKIdentity {
281 hello.pskIdentities = append(hello.pskIdentities, psk)
282 }
David Benjamin405da482016-08-08 17:25:07 -0400283 }
284
285 if session.vers < VersionTLS13 || c.config.Bugs.SendBothTickets {
286 if ticket != nil {
287 hello.sessionTicket = ticket
288 // A random session ID is used to detect when the
289 // server accepted the ticket and is resuming a session
290 // (see RFC 5077).
291 sessionIdLen := 16
David Benjamind4c349b2017-02-09 14:07:17 -0500292 if c.config.Bugs.TicketSessionIDLength != 0 {
293 sessionIdLen = c.config.Bugs.TicketSessionIDLength
294 }
295 if c.config.Bugs.EmptyTicketSessionID {
296 sessionIdLen = 0
David Benjamin405da482016-08-08 17:25:07 -0400297 }
298 hello.sessionId = make([]byte, sessionIdLen)
299 if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
300 c.sendAlert(alertInternalError)
301 return errors.New("tls: short read from Rand: " + err.Error())
302 }
303 } else {
304 hello.sessionId = session.sessionId
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500305 }
Adam Langley95c29f32014-06-20 12:00:00 -0700306 }
307 }
308
Steven Valdezfdd10992016-09-15 16:27:05 -0400309 if maxVersion == VersionTLS13 && !c.config.Bugs.OmitSupportedVersions {
310 if hello.vers >= VersionTLS13 {
311 hello.vers = VersionTLS12
312 }
313 for version := maxVersion; version >= minVersion; version-- {
314 hello.supportedVersions = append(hello.supportedVersions, versionToWire(version, c.isDTLS))
315 }
316 }
317
318 if len(c.config.Bugs.SendSupportedVersions) > 0 {
319 hello.supportedVersions = c.config.Bugs.SendSupportedVersions
320 }
321
David Benjamineed24012016-08-13 19:26:00 -0400322 if c.config.Bugs.SendClientVersion != 0 {
323 hello.vers = c.config.Bugs.SendClientVersion
324 }
325
David Benjamin75f99142016-11-12 12:36:06 +0900326 if c.config.Bugs.SendCipherSuites != nil {
327 hello.cipherSuites = c.config.Bugs.SendCipherSuites
328 }
329
Nick Harperf2511f12016-12-06 16:02:31 -0800330 var sendEarlyData bool
331 if len(hello.pskIdentities) > 0 && session.maxEarlyDataSize > 0 && c.config.Bugs.SendEarlyData != nil {
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500332 hello.hasEarlyData = true
Nick Harperf2511f12016-12-06 16:02:31 -0800333 sendEarlyData = true
334 }
335 if c.config.Bugs.SendFakeEarlyDataLength > 0 {
336 hello.hasEarlyData = true
337 }
338 if c.config.Bugs.OmitEarlyDataExtension {
339 hello.hasEarlyData = false
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500340 }
341
David Benjamind86c7672014-08-02 04:07:12 -0400342 var helloBytes []byte
343 if c.config.Bugs.SendV2ClientHello {
David Benjamin94d701b2014-11-30 13:54:41 -0500344 // Test that the peer left-pads random.
345 hello.random[0] = 0
David Benjamind86c7672014-08-02 04:07:12 -0400346 v2Hello := &v2ClientHelloMsg{
347 vers: hello.vers,
348 cipherSuites: hello.cipherSuites,
349 // No session resumption for V2ClientHello.
350 sessionId: nil,
David Benjamin94d701b2014-11-30 13:54:41 -0500351 challenge: hello.random[1:],
David Benjamind86c7672014-08-02 04:07:12 -0400352 }
353 helloBytes = v2Hello.marshal()
354 c.writeV2Record(helloBytes)
355 } else {
Steven Valdeza833c352016-11-01 13:39:36 -0400356 if len(hello.pskIdentities) > 0 {
357 generatePSKBinders(hello, pskCipherSuite, session.masterSecret, []byte{}, c.config)
358 }
David Benjamind86c7672014-08-02 04:07:12 -0400359 helloBytes = hello.marshal()
Steven Valdeza833c352016-11-01 13:39:36 -0400360
David Benjamin7964b182016-07-14 23:36:30 -0400361 if c.config.Bugs.PartialClientFinishedWithClientHello {
362 // Include one byte of Finished. We can compute it
363 // without completing the handshake. This assumes we
364 // negotiate TLS 1.3 with no HelloRetryRequest or
365 // CertificateRequest.
366 toWrite := make([]byte, 0, len(helloBytes)+1)
367 toWrite = append(toWrite, helloBytes...)
368 toWrite = append(toWrite, typeFinished)
369 c.writeRecord(recordTypeHandshake, toWrite)
370 } else {
371 c.writeRecord(recordTypeHandshake, helloBytes)
372 }
David Benjamind86c7672014-08-02 04:07:12 -0400373 }
David Benjamin582ba042016-07-07 12:33:25 -0700374 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700375
David Benjamin83f90402015-01-27 01:09:43 -0500376 if err := c.simulatePacketLoss(nil); err != nil {
377 return err
378 }
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500379 if c.config.Bugs.SendEarlyAlert {
380 c.sendAlert(alertHandshakeFailure)
381 }
Nick Harperf2511f12016-12-06 16:02:31 -0800382 if c.config.Bugs.SendFakeEarlyDataLength > 0 {
383 c.sendFakeEarlyData(c.config.Bugs.SendFakeEarlyDataLength)
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500384 }
Nick Harperf2511f12016-12-06 16:02:31 -0800385
386 // Derive early write keys and set Conn state to allow early writes.
387 if sendEarlyData {
388 finishedHash := newFinishedHash(session.vers, pskCipherSuite)
389 finishedHash.addEntropy(session.masterSecret)
390 finishedHash.Write(helloBytes)
391 earlyTrafficSecret := finishedHash.deriveSecret(earlyTrafficLabel)
392 c.out.useTrafficSecret(session.vers, pskCipherSuite, earlyTrafficSecret, clientWrite)
393
394 for _, earlyData := range c.config.Bugs.SendEarlyData {
395 if _, err := c.writeRecord(recordTypeApplicationData, earlyData); err != nil {
396 return err
397 }
398 }
399 }
400
Adam Langley95c29f32014-06-20 12:00:00 -0700401 msg, err := c.readHandshake()
402 if err != nil {
403 return err
404 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400405
406 if c.isDTLS {
407 helloVerifyRequest, ok := msg.(*helloVerifyRequestMsg)
408 if ok {
David Benjaminda4789e2016-10-31 19:23:34 -0400409 if helloVerifyRequest.vers != versionToWire(VersionTLS10, c.isDTLS) {
David Benjamin8bc38f52014-08-16 12:07:27 -0400410 // Per RFC 6347, the version field in
411 // HelloVerifyRequest SHOULD be always DTLS
412 // 1.0. Enforce this for testing purposes.
413 return errors.New("dtls: bad HelloVerifyRequest version")
414 }
415
David Benjamin83c0bc92014-08-04 01:23:53 -0400416 hello.raw = nil
417 hello.cookie = helloVerifyRequest.cookie
418 helloBytes = hello.marshal()
419 c.writeRecord(recordTypeHandshake, helloBytes)
David Benjamin582ba042016-07-07 12:33:25 -0700420 c.flushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400421
David Benjamin83f90402015-01-27 01:09:43 -0500422 if err := c.simulatePacketLoss(nil); err != nil {
423 return err
424 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400425 msg, err = c.readHandshake()
426 if err != nil {
427 return err
428 }
429 }
430 }
431
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400432 var serverWireVersion uint16
Nick Harperdcfbc672016-07-16 17:47:31 +0200433 switch m := msg.(type) {
434 case *helloRetryRequestMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400435 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200436 case *serverHelloMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400437 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200438 default:
439 c.sendAlert(alertUnexpectedMessage)
440 return fmt.Errorf("tls: received unexpected message of type %T when waiting for HelloRetryRequest or ServerHello", msg)
441 }
442
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400443 serverVersion, ok := wireToVersion(serverWireVersion, c.isDTLS)
444 if ok {
Steven Valdezfdd10992016-09-15 16:27:05 -0400445 ok = c.config.isSupportedVersion(serverVersion, c.isDTLS)
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400446 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200447 if !ok {
448 c.sendAlert(alertProtocolVersion)
449 return fmt.Errorf("tls: server selected unsupported protocol version %x", c.vers)
450 }
Steven Valdezfdd10992016-09-15 16:27:05 -0400451 c.vers = serverVersion
Nick Harperdcfbc672016-07-16 17:47:31 +0200452 c.haveVers = true
453
454 helloRetryRequest, haveHelloRetryRequest := msg.(*helloRetryRequestMsg)
455 var secondHelloBytes []byte
456 if haveHelloRetryRequest {
Nick Harperf2511f12016-12-06 16:02:31 -0800457 c.out.resetCipher()
David Benjamin3baa6e12016-10-07 21:10:38 -0400458 if len(helloRetryRequest.cookie) > 0 {
459 hello.tls13Cookie = helloRetryRequest.cookie
460 }
461
Steven Valdez5440fe02016-07-18 12:40:30 -0400462 if c.config.Bugs.MisinterpretHelloRetryRequestCurve != 0 {
David Benjamin3baa6e12016-10-07 21:10:38 -0400463 helloRetryRequest.hasSelectedGroup = true
Steven Valdez5440fe02016-07-18 12:40:30 -0400464 helloRetryRequest.selectedGroup = c.config.Bugs.MisinterpretHelloRetryRequestCurve
465 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400466 if helloRetryRequest.hasSelectedGroup {
467 var hrrCurveFound bool
468 group := helloRetryRequest.selectedGroup
469 for _, curveID := range hello.supportedCurves {
470 if group == curveID {
471 hrrCurveFound = true
472 break
473 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200474 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400475 if !hrrCurveFound || keyShares[group] != nil {
476 c.sendAlert(alertHandshakeFailure)
477 return errors.New("tls: received invalid HelloRetryRequest")
478 }
479 curve, ok := curveForCurveID(group)
480 if !ok {
481 return errors.New("tls: Unable to get curve requested in HelloRetryRequest")
482 }
483 publicKey, err := curve.offer(c.config.rand())
484 if err != nil {
485 return err
486 }
487 keyShares[group] = curve
Steven Valdeza833c352016-11-01 13:39:36 -0400488 hello.keyShares = []keyShareEntry{{
David Benjamin3baa6e12016-10-07 21:10:38 -0400489 group: group,
490 keyExchange: publicKey,
Steven Valdeza833c352016-11-01 13:39:36 -0400491 }}
Nick Harperdcfbc672016-07-16 17:47:31 +0200492 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200493
Steven Valdez5440fe02016-07-18 12:40:30 -0400494 if c.config.Bugs.SecondClientHelloMissingKeyShare {
495 hello.hasKeyShares = false
496 }
497
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500498 hello.hasEarlyData = c.config.Bugs.SendEarlyDataOnSecondClientHello
Nick Harperdcfbc672016-07-16 17:47:31 +0200499 hello.raw = nil
500
Steven Valdeza833c352016-11-01 13:39:36 -0400501 if len(hello.pskIdentities) > 0 {
502 generatePSKBinders(hello, pskCipherSuite, session.masterSecret, append(helloBytes, helloRetryRequest.marshal()...), c.config)
503 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200504 secondHelloBytes = hello.marshal()
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500505
506 if c.config.Bugs.InterleaveEarlyData {
507 c.sendFakeEarlyData(4)
508 c.writeRecord(recordTypeHandshake, secondHelloBytes[:16])
509 c.sendFakeEarlyData(4)
510 c.writeRecord(recordTypeHandshake, secondHelloBytes[16:])
511 } else {
512 c.writeRecord(recordTypeHandshake, secondHelloBytes)
513 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200514 c.flushHandshake()
515
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500516 if c.config.Bugs.SendEarlyDataOnSecondClientHello {
517 c.sendFakeEarlyData(4)
518 }
519
Nick Harperdcfbc672016-07-16 17:47:31 +0200520 msg, err = c.readHandshake()
521 if err != nil {
522 return err
523 }
524 }
525
Adam Langley95c29f32014-06-20 12:00:00 -0700526 serverHello, ok := msg.(*serverHelloMsg)
527 if !ok {
528 c.sendAlert(alertUnexpectedMessage)
529 return unexpectedMessageError(serverHello, msg)
530 }
531
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400532 if serverWireVersion != serverHello.vers {
Adam Langley95c29f32014-06-20 12:00:00 -0700533 c.sendAlert(alertProtocolVersion)
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400534 return fmt.Errorf("tls: server sent non-matching version %x vs %x", serverWireVersion, serverHello.vers)
Adam Langley95c29f32014-06-20 12:00:00 -0700535 }
Adam Langley95c29f32014-06-20 12:00:00 -0700536
Nick Harper85f20c22016-07-04 10:11:59 -0700537 // Check for downgrade signals in the server random, per
David Benjamina128a552016-10-13 14:26:33 -0400538 // draft-ietf-tls-tls13-16, section 4.1.3.
Nick Harper85f20c22016-07-04 10:11:59 -0700539 if c.vers <= VersionTLS12 && c.config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400540 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS13) {
Nick Harper85f20c22016-07-04 10:11:59 -0700541 c.sendAlert(alertProtocolVersion)
542 return errors.New("tls: downgrade from TLS 1.3 detected")
543 }
544 }
545 if c.vers <= VersionTLS11 && c.config.maxVersion(c.isDTLS) >= VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400546 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS12) {
Nick Harper85f20c22016-07-04 10:11:59 -0700547 c.sendAlert(alertProtocolVersion)
548 return errors.New("tls: downgrade from TLS 1.2 detected")
549 }
550 }
551
Nick Harper0b3625b2016-07-25 16:16:28 -0700552 suite := mutualCipherSuite(hello.cipherSuites, serverHello.cipherSuite)
Adam Langley95c29f32014-06-20 12:00:00 -0700553 if suite == nil {
554 c.sendAlert(alertHandshakeFailure)
555 return fmt.Errorf("tls: server selected an unsupported cipher suite")
556 }
557
David Benjamin3baa6e12016-10-07 21:10:38 -0400558 if haveHelloRetryRequest && helloRetryRequest.hasSelectedGroup && helloRetryRequest.selectedGroup != serverHello.keyShare.group {
Nick Harperdcfbc672016-07-16 17:47:31 +0200559 c.sendAlert(alertHandshakeFailure)
560 return errors.New("tls: ServerHello parameters did not match HelloRetryRequest")
561 }
562
Adam Langley95c29f32014-06-20 12:00:00 -0700563 hs := &clientHandshakeState{
564 c: c,
565 serverHello: serverHello,
566 hello: hello,
567 suite: suite,
568 finishedHash: newFinishedHash(c.vers, suite),
Nick Harperb41d2e42016-07-01 17:50:32 -0400569 keyShares: keyShares,
Adam Langley95c29f32014-06-20 12:00:00 -0700570 session: session,
571 }
572
David Benjamin83c0bc92014-08-04 01:23:53 -0400573 hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1)
Nick Harperdcfbc672016-07-16 17:47:31 +0200574 if haveHelloRetryRequest {
575 hs.writeServerHash(helloRetryRequest.marshal())
576 hs.writeClientHash(secondHelloBytes)
577 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400578 hs.writeServerHash(hs.serverHello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700579
David Benjamin8d315d72016-07-18 01:03:18 +0200580 if c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -0400581 if err := hs.doTLS13Handshake(); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700582 return err
583 }
584 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400585 if c.config.Bugs.EarlyChangeCipherSpec > 0 {
586 hs.establishKeys()
587 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
588 }
589
590 if hs.serverHello.compressionMethod != compressionNone {
591 c.sendAlert(alertUnexpectedMessage)
592 return errors.New("tls: server selected unsupported compression format")
593 }
594
595 err = hs.processServerExtensions(&serverHello.extensions)
596 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700597 return err
598 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400599
600 isResume, err := hs.processServerHello()
601 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700602 return err
603 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400604
605 if isResume {
606 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
607 if err := hs.establishKeys(); err != nil {
608 return err
609 }
610 }
611 if err := hs.readSessionTicket(); err != nil {
612 return err
613 }
614 if err := hs.readFinished(c.firstFinished[:]); err != nil {
615 return err
616 }
617 if err := hs.sendFinished(nil, isResume); err != nil {
618 return err
619 }
620 } else {
621 if err := hs.doFullHandshake(); err != nil {
622 return err
623 }
624 if err := hs.establishKeys(); err != nil {
625 return err
626 }
627 if err := hs.sendFinished(c.firstFinished[:], isResume); err != nil {
628 return err
629 }
630 // Most retransmits are triggered by a timeout, but the final
631 // leg of the handshake is retransmited upon re-receiving a
632 // Finished.
633 if err := c.simulatePacketLoss(func() {
David Benjamin02edcd02016-07-27 17:40:37 -0400634 c.sendHandshakeSeq--
Nick Harperb41d2e42016-07-01 17:50:32 -0400635 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
636 c.flushHandshake()
637 }); err != nil {
638 return err
639 }
640 if err := hs.readSessionTicket(); err != nil {
641 return err
642 }
643 if err := hs.readFinished(nil); err != nil {
644 return err
645 }
Adam Langley95c29f32014-06-20 12:00:00 -0700646 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400647
648 if sessionCache != nil && hs.session != nil && session != hs.session {
649 if c.config.Bugs.RequireSessionTickets && len(hs.session.sessionTicket) == 0 {
650 return errors.New("tls: new session used session IDs instead of tickets")
651 }
652 sessionCache.Put(cacheKey, hs.session)
David Benjamin83f90402015-01-27 01:09:43 -0500653 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400654
655 c.didResume = isResume
David Benjamin97a0a082016-07-13 17:57:35 -0400656 c.exporterSecret = hs.masterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700657 }
658
Adam Langley95c29f32014-06-20 12:00:00 -0700659 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400660 c.cipherSuite = suite
661 copy(c.clientRandom[:], hs.hello.random)
662 copy(c.serverRandom[:], hs.serverHello.random)
Paul Lietar4fac72e2015-09-09 13:44:55 +0100663
Adam Langley95c29f32014-06-20 12:00:00 -0700664 return nil
665}
666
Nick Harperb41d2e42016-07-01 17:50:32 -0400667func (hs *clientHandshakeState) doTLS13Handshake() error {
668 c := hs.c
669
670 // Once the PRF hash is known, TLS 1.3 does not require a handshake
671 // buffer.
672 hs.finishedHash.discardHandshakeBuffer()
673
674 zeroSecret := hs.finishedHash.zeroSecret()
675
676 // Resolve PSK and compute the early secret.
677 //
678 // TODO(davidben): This will need to be handled slightly earlier once
679 // 0-RTT is implemented.
Steven Valdez803c77a2016-09-06 14:13:43 -0400680 if hs.serverHello.hasPSKIdentity {
Nick Harper0b3625b2016-07-25 16:16:28 -0700681 // We send at most one PSK identity.
682 if hs.session == nil || hs.serverHello.pskIdentity != 0 {
683 c.sendAlert(alertUnknownPSKIdentity)
684 return errors.New("tls: server sent unknown PSK identity")
685 }
David Benjamin2b02f4b2016-11-16 16:11:47 +0900686 sessionCipher := cipherSuiteFromID(hs.session.cipherSuite)
687 if sessionCipher == nil || sessionCipher.hash() != hs.suite.hash() {
Nick Harper0b3625b2016-07-25 16:16:28 -0700688 c.sendAlert(alertHandshakeFailure)
David Benjamin2b02f4b2016-11-16 16:11:47 +0900689 return errors.New("tls: server resumed an invalid session for the cipher suite")
Nick Harper0b3625b2016-07-25 16:16:28 -0700690 }
David Benjamin48891ad2016-12-04 00:02:43 -0500691 hs.finishedHash.addEntropy(hs.session.masterSecret)
Nick Harper0b3625b2016-07-25 16:16:28 -0700692 c.didResume = true
Nick Harperb41d2e42016-07-01 17:50:32 -0400693 } else {
David Benjamin48891ad2016-12-04 00:02:43 -0500694 hs.finishedHash.addEntropy(zeroSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400695 }
696
Steven Valdeza833c352016-11-01 13:39:36 -0400697 if !hs.serverHello.hasKeyShare {
698 c.sendAlert(alertUnsupportedExtension)
699 return errors.New("tls: server omitted KeyShare on resumption.")
700 }
701
Nick Harperb41d2e42016-07-01 17:50:32 -0400702 // Resolve ECDHE and compute the handshake secret.
Steven Valdez803c77a2016-09-06 14:13:43 -0400703 if !c.config.Bugs.MissingKeyShare && !c.config.Bugs.SecondClientHelloMissingKeyShare {
Nick Harperb41d2e42016-07-01 17:50:32 -0400704 curve, ok := hs.keyShares[hs.serverHello.keyShare.group]
705 if !ok {
706 c.sendAlert(alertHandshakeFailure)
707 return errors.New("tls: server selected an unsupported group")
708 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400709 c.curveID = hs.serverHello.keyShare.group
Nick Harperb41d2e42016-07-01 17:50:32 -0400710
David Benjamin48891ad2016-12-04 00:02:43 -0500711 ecdheSecret, err := curve.finish(hs.serverHello.keyShare.keyExchange)
Nick Harperb41d2e42016-07-01 17:50:32 -0400712 if err != nil {
713 return err
714 }
David Benjamin48891ad2016-12-04 00:02:43 -0500715 hs.finishedHash.addEntropy(ecdheSecret)
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
David Benjamin6f600d62016-12-21 16:06:54 -0500720 if hs.serverHello.shortHeader && !hs.hello.shortHeaderSupported {
721 return errors.New("tls: server sent unsolicited short header extension")
722 }
723
724 if hs.serverHello.shortHeader && hs.hello.hasEarlyData {
725 return errors.New("tls: server sent short header extension in response to early data")
726 }
727
728 if hs.serverHello.shortHeader {
729 c.setShortHeader()
730 }
731
Nick Harperf2511f12016-12-06 16:02:31 -0800732 // Derive handshake traffic keys and switch read key to handshake
733 // traffic key.
David Benjamin48891ad2016-12-04 00:02:43 -0500734 clientHandshakeTrafficSecret := hs.finishedHash.deriveSecret(clientHandshakeTrafficLabel)
David Benjamin48891ad2016-12-04 00:02:43 -0500735 serverHandshakeTrafficSecret := hs.finishedHash.deriveSecret(serverHandshakeTrafficLabel)
Steven Valdeza833c352016-11-01 13:39:36 -0400736 c.in.useTrafficSecret(c.vers, hs.suite, serverHandshakeTrafficSecret, serverWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -0400737
738 msg, err := c.readHandshake()
739 if err != nil {
740 return err
741 }
742
743 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
744 if !ok {
745 c.sendAlert(alertUnexpectedMessage)
746 return unexpectedMessageError(encryptedExtensions, msg)
747 }
748 hs.writeServerHash(encryptedExtensions.marshal())
749
750 err = hs.processServerExtensions(&encryptedExtensions.extensions)
751 if err != nil {
752 return err
753 }
754
755 var chainToSend *Certificate
David Benjamin8d343b42016-07-09 14:26:01 -0700756 var certReq *certificateRequestMsg
Steven Valdeza833c352016-11-01 13:39:36 -0400757 if c.didResume {
Nick Harper0b3625b2016-07-25 16:16:28 -0700758 // Copy over authentication from the session.
759 c.peerCertificates = hs.session.serverCertificates
760 c.sctList = hs.session.sctList
761 c.ocspResponse = hs.session.ocspResponse
David Benjamin44b33bc2016-07-01 22:40:23 -0400762 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400763 msg, err := c.readHandshake()
764 if err != nil {
765 return err
766 }
767
David Benjamin8d343b42016-07-09 14:26:01 -0700768 var ok bool
769 certReq, ok = msg.(*certificateRequestMsg)
Nick Harperb41d2e42016-07-01 17:50:32 -0400770 if ok {
David Benjamin8a8349b2016-08-18 02:32:23 -0400771 if len(certReq.requestContext) != 0 {
772 return errors.New("tls: non-empty certificate request context sent in handshake")
773 }
774
David Benjaminb62d2872016-07-18 14:55:02 +0200775 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
776 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
777 }
778
Nick Harperb41d2e42016-07-01 17:50:32 -0400779 hs.writeServerHash(certReq.marshal())
Nick Harperb41d2e42016-07-01 17:50:32 -0400780
781 chainToSend, err = selectClientCertificate(c, certReq)
782 if err != nil {
783 return err
784 }
785
786 msg, err = c.readHandshake()
787 if err != nil {
788 return err
789 }
790 }
791
792 certMsg, ok := msg.(*certificateMsg)
793 if !ok {
794 c.sendAlert(alertUnexpectedMessage)
795 return unexpectedMessageError(certMsg, msg)
796 }
797 hs.writeServerHash(certMsg.marshal())
798
David Benjamin53210cb2016-11-16 09:01:48 +0900799 // Check for unsolicited extensions.
800 for i, cert := range certMsg.certificates {
801 if c.config.Bugs.NoOCSPStapling && cert.ocspResponse != nil {
802 c.sendAlert(alertUnsupportedExtension)
803 return errors.New("tls: unexpected OCSP response in the server certificate")
804 }
805 if c.config.Bugs.NoSignedCertificateTimestamps && cert.sctList != nil {
806 c.sendAlert(alertUnsupportedExtension)
807 return errors.New("tls: unexpected SCT list in the server certificate")
808 }
809 if i > 0 && c.config.Bugs.ExpectNoExtensionsOnIntermediate && (cert.ocspResponse != nil || cert.sctList != nil) {
810 c.sendAlert(alertUnsupportedExtension)
811 return errors.New("tls: unexpected extensions in the server certificate")
812 }
813 }
814
Nick Harperb41d2e42016-07-01 17:50:32 -0400815 if err := hs.verifyCertificates(certMsg); err != nil {
816 return err
817 }
818 leaf := c.peerCertificates[0]
Steven Valdeza833c352016-11-01 13:39:36 -0400819 c.ocspResponse = certMsg.certificates[0].ocspResponse
820 c.sctList = certMsg.certificates[0].sctList
821
Nick Harperb41d2e42016-07-01 17:50:32 -0400822 msg, err = c.readHandshake()
823 if err != nil {
824 return err
825 }
826 certVerifyMsg, ok := msg.(*certificateVerifyMsg)
827 if !ok {
828 c.sendAlert(alertUnexpectedMessage)
829 return unexpectedMessageError(certVerifyMsg, msg)
830 }
831
David Benjaminf74ec792016-07-13 21:18:49 -0400832 c.peerSignatureAlgorithm = certVerifyMsg.signatureAlgorithm
Nick Harperb41d2e42016-07-01 17:50:32 -0400833 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
David Benjamin1fb125c2016-07-08 18:52:12 -0700834 err = verifyMessage(c.vers, leaf.PublicKey, c.config, certVerifyMsg.signatureAlgorithm, input, certVerifyMsg.signature)
Nick Harperb41d2e42016-07-01 17:50:32 -0400835 if err != nil {
836 return err
837 }
838
839 hs.writeServerHash(certVerifyMsg.marshal())
840 }
841
842 msg, err = c.readHandshake()
843 if err != nil {
844 return err
845 }
846 serverFinished, ok := msg.(*finishedMsg)
847 if !ok {
848 c.sendAlert(alertUnexpectedMessage)
849 return unexpectedMessageError(serverFinished, msg)
850 }
851
Steven Valdezc4aa7272016-10-03 12:25:56 -0400852 verify := hs.finishedHash.serverSum(serverHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400853 if len(verify) != len(serverFinished.verifyData) ||
854 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
855 c.sendAlert(alertHandshakeFailure)
856 return errors.New("tls: server's Finished message was incorrect")
857 }
858
859 hs.writeServerHash(serverFinished.marshal())
860
861 // The various secrets do not incorporate the client's final leg, so
862 // derive them now before updating the handshake context.
David Benjamin48891ad2016-12-04 00:02:43 -0500863 hs.finishedHash.addEntropy(zeroSecret)
864 clientTrafficSecret := hs.finishedHash.deriveSecret(clientApplicationTrafficLabel)
865 serverTrafficSecret := hs.finishedHash.deriveSecret(serverApplicationTrafficLabel)
David Benjamincdb6fe92017-02-07 16:06:48 -0500866 c.exporterSecret = hs.finishedHash.deriveSecret(exporterLabel)
867
868 // Switch to application data keys on read. In particular, any alerts
869 // from the client certificate are read over these keys.
Nick Harper7cd0a972016-12-02 11:08:40 -0800870 c.in.useTrafficSecret(c.vers, hs.suite, serverTrafficSecret, serverWrite)
871
872 // If we're expecting 0.5-RTT messages from the server, read them
873 // now.
874 for _, expectedMsg := range c.config.Bugs.ExpectHalfRTTData {
875 if err := c.readRecord(recordTypeApplicationData); err != nil {
876 return err
877 }
878 if !bytes.Equal(c.input.data[c.input.off:], expectedMsg) {
879 return errors.New("ExpectHalfRTTData: did not get expected message")
880 }
881 c.in.freeBlock(c.input)
882 c.input = nil
883 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400884
Nick Harperf2511f12016-12-06 16:02:31 -0800885 // Send EndOfEarlyData and then switch write key to handshake
886 // traffic key.
887 if c.out.cipher != nil {
888 c.sendAlert(alertEndOfEarlyData)
889 }
890 c.out.useTrafficSecret(c.vers, hs.suite, clientHandshakeTrafficSecret, clientWrite)
891
Steven Valdez0ee2e112016-07-15 06:51:15 -0400892 if certReq != nil && !c.config.Bugs.SkipClientCertificate {
David Benjamin8d343b42016-07-09 14:26:01 -0700893 certMsg := &certificateMsg{
894 hasRequestContext: true,
895 requestContext: certReq.requestContext,
896 }
897 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -0400898 for _, certData := range chainToSend.Certificate {
899 certMsg.certificates = append(certMsg.certificates, certificateEntry{
900 data: certData,
901 extraExtension: c.config.Bugs.SendExtensionOnCertificate,
902 })
903 }
David Benjamin8d343b42016-07-09 14:26:01 -0700904 }
905 hs.writeClientHash(certMsg.marshal())
906 c.writeRecord(recordTypeHandshake, certMsg.marshal())
907
908 if chainToSend != nil {
909 certVerify := &certificateVerifyMsg{
910 hasSignatureAlgorithm: true,
911 }
912
913 // Determine the hash to sign.
914 privKey := chainToSend.PrivateKey
915
916 var err error
917 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
918 if err != nil {
919 c.sendAlert(alertInternalError)
920 return err
921 }
922
923 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
924 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
925 if err != nil {
926 c.sendAlert(alertInternalError)
927 return err
928 }
Steven Valdez0ee2e112016-07-15 06:51:15 -0400929 if c.config.Bugs.SendSignatureAlgorithm != 0 {
930 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
931 }
David Benjamin8d343b42016-07-09 14:26:01 -0700932
933 hs.writeClientHash(certVerify.marshal())
934 c.writeRecord(recordTypeHandshake, certVerify.marshal())
935 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400936 }
937
Nick Harper60a85cb2016-09-23 16:25:11 -0700938 if encryptedExtensions.extensions.channelIDRequested {
939 channelIDHash := crypto.SHA256.New()
940 channelIDHash.Write(hs.finishedHash.certificateVerifyInput(channelIDContextTLS13))
941 channelIDMsgBytes, err := hs.writeChannelIDMessage(channelIDHash.Sum(nil))
942 if err != nil {
943 return err
944 }
945 hs.writeClientHash(channelIDMsgBytes)
946 c.writeRecord(recordTypeHandshake, channelIDMsgBytes)
947 }
948
Nick Harperb41d2e42016-07-01 17:50:32 -0400949 // Send a client Finished message.
950 finished := new(finishedMsg)
Steven Valdezc4aa7272016-10-03 12:25:56 -0400951 finished.verifyData = hs.finishedHash.clientSum(clientHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400952 if c.config.Bugs.BadFinished {
953 finished.verifyData[0]++
954 }
David Benjamin97a0a082016-07-13 17:57:35 -0400955 hs.writeClientHash(finished.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400956 if c.config.Bugs.PartialClientFinishedWithClientHello {
957 // The first byte has already been sent.
958 c.writeRecord(recordTypeHandshake, finished.marshal()[1:])
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500959 } else if c.config.Bugs.InterleaveEarlyData {
960 finishedBytes := finished.marshal()
961 c.sendFakeEarlyData(4)
962 c.writeRecord(recordTypeHandshake, finishedBytes[:1])
963 c.sendFakeEarlyData(4)
964 c.writeRecord(recordTypeHandshake, finishedBytes[1:])
David Benjamin7964b182016-07-14 23:36:30 -0400965 } else {
966 c.writeRecord(recordTypeHandshake, finished.marshal())
967 }
David Benjamin02edcd02016-07-27 17:40:37 -0400968 if c.config.Bugs.SendExtraFinished {
969 c.writeRecord(recordTypeHandshake, finished.marshal())
970 }
David Benjaminee51a222016-07-07 18:34:12 -0700971 c.flushHandshake()
Nick Harperb41d2e42016-07-01 17:50:32 -0400972
973 // Switch to application data keys.
Steven Valdeza833c352016-11-01 13:39:36 -0400974 c.out.useTrafficSecret(c.vers, hs.suite, clientTrafficSecret, clientWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -0400975
David Benjamin48891ad2016-12-04 00:02:43 -0500976 c.resumptionSecret = hs.finishedHash.deriveSecret(resumptionLabel)
Nick Harperb41d2e42016-07-01 17:50:32 -0400977 return nil
978}
979
Adam Langley95c29f32014-06-20 12:00:00 -0700980func (hs *clientHandshakeState) doFullHandshake() error {
981 c := hs.c
982
David Benjamin48cae082014-10-27 01:06:24 -0400983 var leaf *x509.Certificate
984 if hs.suite.flags&suitePSK == 0 {
985 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700986 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700987 return err
988 }
Adam Langley95c29f32014-06-20 12:00:00 -0700989
David Benjamin48cae082014-10-27 01:06:24 -0400990 certMsg, ok := msg.(*certificateMsg)
David Benjamin75051442016-07-01 18:58:51 -0400991 if !ok {
David Benjamin48cae082014-10-27 01:06:24 -0400992 c.sendAlert(alertUnexpectedMessage)
993 return unexpectedMessageError(certMsg, msg)
994 }
995 hs.writeServerHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700996
David Benjamin75051442016-07-01 18:58:51 -0400997 if err := hs.verifyCertificates(certMsg); err != nil {
998 return err
David Benjamin48cae082014-10-27 01:06:24 -0400999 }
David Benjamin75051442016-07-01 18:58:51 -04001000 leaf = c.peerCertificates[0]
David Benjamin48cae082014-10-27 01:06:24 -04001001 }
Adam Langley95c29f32014-06-20 12:00:00 -07001002
Nick Harperb3d51be2016-07-01 11:43:18 -04001003 if hs.serverHello.extensions.ocspStapling {
David Benjamin48cae082014-10-27 01:06:24 -04001004 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001005 if err != nil {
1006 return err
1007 }
1008 cs, ok := msg.(*certificateStatusMsg)
1009 if !ok {
1010 c.sendAlert(alertUnexpectedMessage)
1011 return unexpectedMessageError(cs, msg)
1012 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001013 hs.writeServerHash(cs.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001014
1015 if cs.statusType == statusTypeOCSP {
1016 c.ocspResponse = cs.response
1017 }
1018 }
1019
David Benjamin48cae082014-10-27 01:06:24 -04001020 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001021 if err != nil {
1022 return err
1023 }
1024
1025 keyAgreement := hs.suite.ka(c.vers)
1026
1027 skx, ok := msg.(*serverKeyExchangeMsg)
1028 if ok {
David Benjamin83c0bc92014-08-04 01:23:53 -04001029 hs.writeServerHash(skx.marshal())
David Benjamin48cae082014-10-27 01:06:24 -04001030 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx)
Adam Langley95c29f32014-06-20 12:00:00 -07001031 if err != nil {
1032 c.sendAlert(alertUnexpectedMessage)
1033 return err
1034 }
Steven Valdez5440fe02016-07-18 12:40:30 -04001035 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1036 c.curveID = ecdhe.curveID
1037 }
Adam Langley95c29f32014-06-20 12:00:00 -07001038
Nick Harper60edffd2016-06-21 15:19:24 -07001039 c.peerSignatureAlgorithm = keyAgreement.peerSignatureAlgorithm()
1040
Adam Langley95c29f32014-06-20 12:00:00 -07001041 msg, err = c.readHandshake()
1042 if err != nil {
1043 return err
1044 }
1045 }
1046
1047 var chainToSend *Certificate
1048 var certRequested bool
1049 certReq, ok := msg.(*certificateRequestMsg)
1050 if ok {
1051 certRequested = true
David Benjamin7a41d372016-07-09 11:21:54 -07001052 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
1053 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
1054 }
Adam Langley95c29f32014-06-20 12:00:00 -07001055
David Benjamin83c0bc92014-08-04 01:23:53 -04001056 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001057
David Benjamina6f82632016-07-01 18:44:02 -04001058 chainToSend, err = selectClientCertificate(c, certReq)
1059 if err != nil {
1060 return err
Adam Langley95c29f32014-06-20 12:00:00 -07001061 }
1062
1063 msg, err = c.readHandshake()
1064 if err != nil {
1065 return err
1066 }
1067 }
1068
1069 shd, ok := msg.(*serverHelloDoneMsg)
1070 if !ok {
1071 c.sendAlert(alertUnexpectedMessage)
1072 return unexpectedMessageError(shd, msg)
1073 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001074 hs.writeServerHash(shd.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001075
1076 // If the server requested a certificate then we have to send a
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001077 // Certificate message in TLS, even if it's empty because we don't have
1078 // a certificate to send. In SSL 3.0, skip the message and send a
1079 // no_certificate warning alert.
Adam Langley95c29f32014-06-20 12:00:00 -07001080 if certRequested {
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001081 if c.vers == VersionSSL30 && chainToSend == nil {
David Benjamin053fee92017-01-02 08:30:36 -05001082 c.sendAlert(alertNoCertificate)
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001083 } else if !c.config.Bugs.SkipClientCertificate {
1084 certMsg := new(certificateMsg)
1085 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -04001086 for _, certData := range chainToSend.Certificate {
1087 certMsg.certificates = append(certMsg.certificates, certificateEntry{
1088 data: certData,
1089 })
1090 }
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001091 }
1092 hs.writeClientHash(certMsg.marshal())
1093 c.writeRecord(recordTypeHandshake, certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001094 }
Adam Langley95c29f32014-06-20 12:00:00 -07001095 }
1096
David Benjamin48cae082014-10-27 01:06:24 -04001097 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf)
Adam Langley95c29f32014-06-20 12:00:00 -07001098 if err != nil {
1099 c.sendAlert(alertInternalError)
1100 return err
1101 }
1102 if ckx != nil {
David Benjaminf3ec83d2014-07-21 22:42:34 -04001103 if c.config.Bugs.EarlyChangeCipherSpec < 2 {
David Benjamin83c0bc92014-08-04 01:23:53 -04001104 hs.writeClientHash(ckx.marshal())
David Benjaminf3ec83d2014-07-21 22:42:34 -04001105 }
Adam Langley95c29f32014-06-20 12:00:00 -07001106 c.writeRecord(recordTypeHandshake, ckx.marshal())
1107 }
1108
Nick Harperb3d51be2016-07-01 11:43:18 -04001109 if hs.serverHello.extensions.extendedMasterSecret && c.vers >= VersionTLS10 {
Adam Langley75712922014-10-10 16:23:43 -07001110 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1111 c.extendedMasterSecret = true
1112 } else {
1113 if c.config.Bugs.RequireExtendedMasterSecret {
1114 return errors.New("tls: extended master secret required but not supported by peer")
1115 }
1116 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
1117 }
David Benjamine098ec22014-08-27 23:13:20 -04001118
Adam Langley95c29f32014-06-20 12:00:00 -07001119 if chainToSend != nil {
Adam Langley95c29f32014-06-20 12:00:00 -07001120 certVerify := &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001121 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001122 }
1123
David Benjamin72dc7832015-03-16 17:49:43 -04001124 // Determine the hash to sign.
Nick Harper60edffd2016-06-21 15:19:24 -07001125 privKey := c.config.Certificates[0].PrivateKey
David Benjamin72dc7832015-03-16 17:49:43 -04001126
Nick Harper60edffd2016-06-21 15:19:24 -07001127 if certVerify.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001128 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
Nick Harper60edffd2016-06-21 15:19:24 -07001129 if err != nil {
1130 c.sendAlert(alertInternalError)
1131 return err
Adam Langley95c29f32014-06-20 12:00:00 -07001132 }
Nick Harper60edffd2016-06-21 15:19:24 -07001133 }
1134
1135 if c.vers > VersionSSL30 {
David Benjamin5208fd42016-07-13 21:43:25 -04001136 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, hs.finishedHash.buffer)
David Benjamina95e9f32016-07-08 16:28:04 -07001137 if err == nil && c.config.Bugs.SendSignatureAlgorithm != 0 {
1138 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
1139 }
Nick Harper60edffd2016-06-21 15:19:24 -07001140 } else {
1141 // SSL 3.0's client certificate construction is
1142 // incompatible with signatureAlgorithm.
1143 rsaKey, ok := privKey.(*rsa.PrivateKey)
1144 if !ok {
1145 err = errors.New("unsupported signature type for client certificate")
1146 } else {
1147 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
David Benjamin5208fd42016-07-13 21:43:25 -04001148 if c.config.Bugs.InvalidSignature {
Nick Harper60edffd2016-06-21 15:19:24 -07001149 digest[0] ^= 0x80
1150 }
1151 certVerify.signature, err = rsa.SignPKCS1v15(c.config.rand(), rsaKey, crypto.MD5SHA1, digest)
1152 }
Adam Langley95c29f32014-06-20 12:00:00 -07001153 }
1154 if err != nil {
1155 c.sendAlert(alertInternalError)
1156 return errors.New("tls: failed to sign handshake with client certificate: " + err.Error())
1157 }
Adam Langley95c29f32014-06-20 12:00:00 -07001158
David Benjamin83c0bc92014-08-04 01:23:53 -04001159 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001160 c.writeRecord(recordTypeHandshake, certVerify.marshal())
1161 }
David Benjamin82261be2016-07-07 14:32:50 -07001162 // flushHandshake will be called in sendFinished.
Adam Langley95c29f32014-06-20 12:00:00 -07001163
David Benjamine098ec22014-08-27 23:13:20 -04001164 hs.finishedHash.discardHandshakeBuffer()
1165
Adam Langley95c29f32014-06-20 12:00:00 -07001166 return nil
1167}
1168
David Benjamin75051442016-07-01 18:58:51 -04001169func (hs *clientHandshakeState) verifyCertificates(certMsg *certificateMsg) error {
1170 c := hs.c
1171
1172 if len(certMsg.certificates) == 0 {
1173 c.sendAlert(alertIllegalParameter)
1174 return errors.New("tls: no certificates sent")
1175 }
1176
1177 certs := make([]*x509.Certificate, len(certMsg.certificates))
Steven Valdeza833c352016-11-01 13:39:36 -04001178 for i, certEntry := range certMsg.certificates {
1179 cert, err := x509.ParseCertificate(certEntry.data)
David Benjamin75051442016-07-01 18:58:51 -04001180 if err != nil {
1181 c.sendAlert(alertBadCertificate)
1182 return errors.New("tls: failed to parse certificate from server: " + err.Error())
1183 }
1184 certs[i] = cert
1185 }
1186
1187 if !c.config.InsecureSkipVerify {
1188 opts := x509.VerifyOptions{
1189 Roots: c.config.RootCAs,
1190 CurrentTime: c.config.time(),
1191 DNSName: c.config.ServerName,
1192 Intermediates: x509.NewCertPool(),
1193 }
1194
1195 for i, cert := range certs {
1196 if i == 0 {
1197 continue
1198 }
1199 opts.Intermediates.AddCert(cert)
1200 }
1201 var err error
1202 c.verifiedChains, err = certs[0].Verify(opts)
1203 if err != nil {
1204 c.sendAlert(alertBadCertificate)
1205 return err
1206 }
1207 }
1208
1209 switch certs[0].PublicKey.(type) {
1210 case *rsa.PublicKey, *ecdsa.PublicKey:
1211 break
1212 default:
1213 c.sendAlert(alertUnsupportedCertificate)
1214 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
1215 }
1216
1217 c.peerCertificates = certs
1218 return nil
1219}
1220
Adam Langley95c29f32014-06-20 12:00:00 -07001221func (hs *clientHandshakeState) establishKeys() error {
1222 c := hs.c
1223
1224 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001225 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 -07001226 var clientCipher, serverCipher interface{}
1227 var clientHash, serverHash macFunction
1228 if hs.suite.cipher != nil {
1229 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
1230 clientHash = hs.suite.mac(c.vers, clientMAC)
1231 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
1232 serverHash = hs.suite.mac(c.vers, serverMAC)
1233 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001234 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1235 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001236 }
1237
1238 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
1239 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
1240 return nil
1241}
1242
David Benjamin75101402016-07-01 13:40:23 -04001243func (hs *clientHandshakeState) processServerExtensions(serverExtensions *serverExtensions) error {
1244 c := hs.c
1245
David Benjamin8d315d72016-07-18 01:03:18 +02001246 if c.vers < VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001247 if c.config.Bugs.RequireRenegotiationInfo && serverExtensions.secureRenegotiation == nil {
1248 return errors.New("tls: renegotiation extension missing")
1249 }
David Benjamin75101402016-07-01 13:40:23 -04001250
Nick Harperb41d2e42016-07-01 17:50:32 -04001251 if len(c.clientVerify) > 0 && !c.noRenegotiationInfo() {
1252 var expectedRenegInfo []byte
1253 expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...)
1254 expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...)
1255 if !bytes.Equal(serverExtensions.secureRenegotiation, expectedRenegInfo) {
1256 c.sendAlert(alertHandshakeFailure)
1257 return fmt.Errorf("tls: renegotiation mismatch")
1258 }
David Benjamin75101402016-07-01 13:40:23 -04001259 }
David Benjamincea0ab42016-07-14 12:33:14 -04001260 } else if serverExtensions.secureRenegotiation != nil {
1261 return errors.New("tls: renegotiation info sent in TLS 1.3")
David Benjamin75101402016-07-01 13:40:23 -04001262 }
1263
1264 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
1265 if serverExtensions.customExtension != *expected {
1266 return fmt.Errorf("tls: bad custom extension contents %q", serverExtensions.customExtension)
1267 }
1268 }
1269
1270 clientDidNPN := hs.hello.nextProtoNeg
1271 clientDidALPN := len(hs.hello.alpnProtocols) > 0
1272 serverHasNPN := serverExtensions.nextProtoNeg
1273 serverHasALPN := len(serverExtensions.alpnProtocol) > 0
1274
1275 if !clientDidNPN && serverHasNPN {
1276 c.sendAlert(alertHandshakeFailure)
1277 return errors.New("server advertised unrequested NPN extension")
1278 }
1279
1280 if !clientDidALPN && serverHasALPN {
1281 c.sendAlert(alertHandshakeFailure)
1282 return errors.New("server advertised unrequested ALPN extension")
1283 }
1284
1285 if serverHasNPN && serverHasALPN {
1286 c.sendAlert(alertHandshakeFailure)
1287 return errors.New("server advertised both NPN and ALPN extensions")
1288 }
1289
1290 if serverHasALPN {
1291 c.clientProtocol = serverExtensions.alpnProtocol
1292 c.clientProtocolFallback = false
1293 c.usedALPN = true
1294 }
1295
David Benjamin8d315d72016-07-18 01:03:18 +02001296 if serverHasNPN && c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001297 c.sendAlert(alertHandshakeFailure)
1298 return errors.New("server advertised NPN over TLS 1.3")
1299 }
1300
David Benjamin75101402016-07-01 13:40:23 -04001301 if !hs.hello.channelIDSupported && serverExtensions.channelIDRequested {
1302 c.sendAlert(alertHandshakeFailure)
1303 return errors.New("server advertised unrequested Channel ID extension")
1304 }
1305
David Benjamin8d315d72016-07-18 01:03:18 +02001306 if serverExtensions.extendedMasterSecret && c.vers >= VersionTLS13 {
David Benjamine9077652016-07-13 21:02:08 -04001307 return errors.New("tls: server advertised extended master secret over TLS 1.3")
1308 }
1309
David Benjamin8d315d72016-07-18 01:03:18 +02001310 if serverExtensions.ticketSupported && c.vers >= VersionTLS13 {
Steven Valdez143e8b32016-07-11 13:19:03 -04001311 return errors.New("tls: server advertised ticket extension over TLS 1.3")
1312 }
1313
Steven Valdeza833c352016-11-01 13:39:36 -04001314 if serverExtensions.ocspStapling && c.vers >= VersionTLS13 {
1315 return errors.New("tls: server advertised OCSP in ServerHello over TLS 1.3")
1316 }
1317
David Benjamin53210cb2016-11-16 09:01:48 +09001318 if serverExtensions.ocspStapling && c.config.Bugs.NoOCSPStapling {
1319 return errors.New("tls: server advertised unrequested OCSP extension")
1320 }
1321
Steven Valdeza833c352016-11-01 13:39:36 -04001322 if len(serverExtensions.sctList) > 0 && c.vers >= VersionTLS13 {
1323 return errors.New("tls: server advertised SCTs in ServerHello over TLS 1.3")
1324 }
1325
David Benjamin53210cb2016-11-16 09:01:48 +09001326 if len(serverExtensions.sctList) > 0 && c.config.Bugs.NoSignedCertificateTimestamps {
1327 return errors.New("tls: server advertised unrequested SCTs")
1328 }
1329
David Benjamin75101402016-07-01 13:40:23 -04001330 if serverExtensions.srtpProtectionProfile != 0 {
1331 if serverExtensions.srtpMasterKeyIdentifier != "" {
1332 return errors.New("tls: server selected SRTP MKI value")
1333 }
1334
1335 found := false
1336 for _, p := range c.config.SRTPProtectionProfiles {
1337 if p == serverExtensions.srtpProtectionProfile {
1338 found = true
1339 break
1340 }
1341 }
1342 if !found {
1343 return errors.New("tls: server advertised unsupported SRTP profile")
1344 }
1345
1346 c.srtpProtectionProfile = serverExtensions.srtpProtectionProfile
1347 }
1348
1349 return nil
1350}
1351
Adam Langley95c29f32014-06-20 12:00:00 -07001352func (hs *clientHandshakeState) serverResumedSession() bool {
1353 // If the server responded with the same sessionId then it means the
1354 // sessionTicket is being used to resume a TLS session.
David Benjamind4c349b2017-02-09 14:07:17 -05001355 //
1356 // Note that, if hs.hello.sessionId is a non-nil empty array, this will
1357 // accept an empty session ID from the server as resumption. See
1358 // EmptyTicketSessionID.
Adam Langley95c29f32014-06-20 12:00:00 -07001359 return hs.session != nil && hs.hello.sessionId != nil &&
1360 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
1361}
1362
1363func (hs *clientHandshakeState) processServerHello() (bool, error) {
1364 c := hs.c
1365
David Benjamin6f600d62016-12-21 16:06:54 -05001366 if hs.serverHello.shortHeader {
1367 return false, errors.New("tls: short header extension sent before TLS 1.3")
1368 }
1369
Adam Langley95c29f32014-06-20 12:00:00 -07001370 if hs.serverResumedSession() {
David Benjamin4b27d9f2015-05-12 22:42:52 -04001371 // For test purposes, assert that the server never accepts the
1372 // resumption offer on renegotiation.
1373 if c.cipherSuite != nil && c.config.Bugs.FailIfResumeOnRenego {
1374 return false, errors.New("tls: server resumed session on renegotiation")
1375 }
1376
Nick Harperb3d51be2016-07-01 11:43:18 -04001377 if hs.serverHello.extensions.sctList != nil {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001378 return false, errors.New("tls: server sent SCT extension on session resumption")
1379 }
1380
Nick Harperb3d51be2016-07-01 11:43:18 -04001381 if hs.serverHello.extensions.ocspStapling {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001382 return false, errors.New("tls: server sent OCSP extension on session resumption")
1383 }
1384
Adam Langley95c29f32014-06-20 12:00:00 -07001385 // Restore masterSecret and peerCerts from previous state
1386 hs.masterSecret = hs.session.masterSecret
1387 c.peerCertificates = hs.session.serverCertificates
Adam Langley75712922014-10-10 16:23:43 -07001388 c.extendedMasterSecret = hs.session.extendedMasterSecret
Paul Lietar62be8ac2015-09-16 10:03:30 +01001389 c.sctList = hs.session.sctList
1390 c.ocspResponse = hs.session.ocspResponse
David Benjamine098ec22014-08-27 23:13:20 -04001391 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001392 return true, nil
1393 }
Paul Lietar62be8ac2015-09-16 10:03:30 +01001394
Nick Harperb3d51be2016-07-01 11:43:18 -04001395 if hs.serverHello.extensions.sctList != nil {
1396 c.sctList = hs.serverHello.extensions.sctList
Paul Lietar62be8ac2015-09-16 10:03:30 +01001397 }
1398
Adam Langley95c29f32014-06-20 12:00:00 -07001399 return false, nil
1400}
1401
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001402func (hs *clientHandshakeState) readFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001403 c := hs.c
1404
1405 c.readRecord(recordTypeChangeCipherSpec)
1406 if err := c.in.error(); err != nil {
1407 return err
1408 }
1409
1410 msg, err := c.readHandshake()
1411 if err != nil {
1412 return err
1413 }
1414 serverFinished, ok := msg.(*finishedMsg)
1415 if !ok {
1416 c.sendAlert(alertUnexpectedMessage)
1417 return unexpectedMessageError(serverFinished, msg)
1418 }
1419
David Benjaminf3ec83d2014-07-21 22:42:34 -04001420 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
1421 verify := hs.finishedHash.serverSum(hs.masterSecret)
1422 if len(verify) != len(serverFinished.verifyData) ||
1423 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
1424 c.sendAlert(alertHandshakeFailure)
1425 return errors.New("tls: server's Finished message was incorrect")
1426 }
Adam Langley95c29f32014-06-20 12:00:00 -07001427 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001428 c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001429 copy(out, serverFinished.verifyData)
David Benjamin83c0bc92014-08-04 01:23:53 -04001430 hs.writeServerHash(serverFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001431 return nil
1432}
1433
1434func (hs *clientHandshakeState) readSessionTicket() error {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001435 c := hs.c
1436
1437 // Create a session with no server identifier. Either a
1438 // session ID or session ticket will be attached.
1439 session := &ClientSessionState{
1440 vers: c.vers,
1441 cipherSuite: hs.suite.id,
1442 masterSecret: hs.masterSecret,
Nick Harperc9846112016-10-17 15:05:35 -07001443 handshakeHash: hs.finishedHash.Sum(),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001444 serverCertificates: c.peerCertificates,
Paul Lietar62be8ac2015-09-16 10:03:30 +01001445 sctList: c.sctList,
1446 ocspResponse: c.ocspResponse,
Nick Harper0b3625b2016-07-25 16:16:28 -07001447 ticketExpiration: c.config.time().Add(time.Duration(7 * 24 * time.Hour)),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001448 }
1449
Nick Harperb3d51be2016-07-01 11:43:18 -04001450 if !hs.serverHello.extensions.ticketSupported {
David Benjamind98452d2015-06-16 14:16:23 -04001451 if c.config.Bugs.ExpectNewTicket {
1452 return errors.New("tls: expected new ticket")
1453 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001454 if hs.session == nil && len(hs.serverHello.sessionId) > 0 {
1455 session.sessionId = hs.serverHello.sessionId
1456 hs.session = session
1457 }
Adam Langley95c29f32014-06-20 12:00:00 -07001458 return nil
1459 }
1460
David Benjaminc7ce9772015-10-09 19:32:41 -04001461 if c.vers == VersionSSL30 {
1462 return errors.New("tls: negotiated session tickets in SSL 3.0")
1463 }
1464
Adam Langley95c29f32014-06-20 12:00:00 -07001465 msg, err := c.readHandshake()
1466 if err != nil {
1467 return err
1468 }
1469 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
1470 if !ok {
1471 c.sendAlert(alertUnexpectedMessage)
1472 return unexpectedMessageError(sessionTicketMsg, msg)
1473 }
Adam Langley95c29f32014-06-20 12:00:00 -07001474
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001475 session.sessionTicket = sessionTicketMsg.ticket
1476 hs.session = session
Adam Langley95c29f32014-06-20 12:00:00 -07001477
David Benjamind30a9902014-08-24 01:44:23 -04001478 hs.writeServerHash(sessionTicketMsg.marshal())
1479
Adam Langley95c29f32014-06-20 12:00:00 -07001480 return nil
1481}
1482
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001483func (hs *clientHandshakeState) sendFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001484 c := hs.c
1485
David Benjamin0b8d5da2016-07-15 00:39:56 -04001486 var postCCSMsgs [][]byte
David Benjamin83c0bc92014-08-04 01:23:53 -04001487 seqno := hs.c.sendHandshakeSeq
Nick Harperb3d51be2016-07-01 11:43:18 -04001488 if hs.serverHello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001489 nextProto := new(nextProtoMsg)
Nick Harperb3d51be2016-07-01 11:43:18 -04001490 proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.extensions.nextProtos)
Adam Langley95c29f32014-06-20 12:00:00 -07001491 nextProto.proto = proto
1492 c.clientProtocol = proto
1493 c.clientProtocolFallback = fallback
1494
David Benjamin86271ee2014-07-21 16:14:03 -04001495 nextProtoBytes := nextProto.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -04001496 hs.writeHash(nextProtoBytes, seqno)
1497 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001498 postCCSMsgs = append(postCCSMsgs, nextProtoBytes)
Adam Langley95c29f32014-06-20 12:00:00 -07001499 }
1500
Nick Harperb3d51be2016-07-01 11:43:18 -04001501 if hs.serverHello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001502 var resumeHash []byte
1503 if isResume {
1504 resumeHash = hs.session.handshakeHash
1505 }
Nick Harper60a85cb2016-09-23 16:25:11 -07001506 channelIDMsgBytes, err := hs.writeChannelIDMessage(hs.finishedHash.hashForChannelID(resumeHash))
David Benjamind30a9902014-08-24 01:44:23 -04001507 if err != nil {
1508 return err
1509 }
David Benjamin24599a82016-06-30 18:56:53 -04001510 hs.writeHash(channelIDMsgBytes, seqno)
David Benjamind30a9902014-08-24 01:44:23 -04001511 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001512 postCCSMsgs = append(postCCSMsgs, channelIDMsgBytes)
David Benjamind30a9902014-08-24 01:44:23 -04001513 }
1514
Adam Langley95c29f32014-06-20 12:00:00 -07001515 finished := new(finishedMsg)
David Benjaminf3ec83d2014-07-21 22:42:34 -04001516 if c.config.Bugs.EarlyChangeCipherSpec == 2 {
1517 finished.verifyData = hs.finishedHash.clientSum(nil)
1518 } else {
1519 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
1520 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001521 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001522 if c.config.Bugs.BadFinished {
1523 finished.verifyData[0]++
1524 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001525 c.clientVerify = append(c.clientVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001526 hs.finishedBytes = finished.marshal()
1527 hs.writeHash(hs.finishedBytes, seqno)
David Benjamin0b8d5da2016-07-15 00:39:56 -04001528 postCCSMsgs = append(postCCSMsgs, hs.finishedBytes)
David Benjamin86271ee2014-07-21 16:14:03 -04001529
1530 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001531 c.writeRecord(recordTypeHandshake, postCCSMsgs[0][:5])
1532 postCCSMsgs[0] = postCCSMsgs[0][5:]
David Benjamin61672812016-07-14 23:10:43 -04001533 } else if c.config.Bugs.SendUnencryptedFinished {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001534 c.writeRecord(recordTypeHandshake, postCCSMsgs[0])
1535 postCCSMsgs = postCCSMsgs[1:]
David Benjamin86271ee2014-07-21 16:14:03 -04001536 }
David Benjamin582ba042016-07-07 12:33:25 -07001537 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001538
1539 if !c.config.Bugs.SkipChangeCipherSpec &&
1540 c.config.Bugs.EarlyChangeCipherSpec == 0 {
David Benjamin8411b242015-11-26 12:07:28 -05001541 ccs := []byte{1}
1542 if c.config.Bugs.BadChangeCipherSpec != nil {
1543 ccs = c.config.Bugs.BadChangeCipherSpec
1544 }
1545 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamin86271ee2014-07-21 16:14:03 -04001546 }
1547
David Benjamin4189bd92015-01-25 23:52:39 -05001548 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1549 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1550 }
David Benjamindc3da932015-03-12 15:09:02 -04001551 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1552 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1553 return errors.New("tls: simulating post-CCS alert")
1554 }
David Benjamin4189bd92015-01-25 23:52:39 -05001555
David Benjamin0b8d5da2016-07-15 00:39:56 -04001556 if !c.config.Bugs.SkipFinished {
1557 for _, msg := range postCCSMsgs {
1558 c.writeRecord(recordTypeHandshake, msg)
1559 }
David Benjamin02edcd02016-07-27 17:40:37 -04001560
1561 if c.config.Bugs.SendExtraFinished {
1562 c.writeRecord(recordTypeHandshake, finished.marshal())
1563 }
1564
David Benjamin582ba042016-07-07 12:33:25 -07001565 c.flushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -05001566 }
Adam Langley95c29f32014-06-20 12:00:00 -07001567 return nil
1568}
1569
Nick Harper60a85cb2016-09-23 16:25:11 -07001570func (hs *clientHandshakeState) writeChannelIDMessage(channelIDHash []byte) ([]byte, error) {
1571 c := hs.c
1572 channelIDMsg := new(channelIDMsg)
1573 if c.config.ChannelID.Curve != elliptic.P256() {
1574 return nil, fmt.Errorf("tls: Channel ID is not on P-256.")
1575 }
1576 r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, channelIDHash)
1577 if err != nil {
1578 return nil, err
1579 }
1580 channelID := make([]byte, 128)
1581 writeIntPadded(channelID[0:32], c.config.ChannelID.X)
1582 writeIntPadded(channelID[32:64], c.config.ChannelID.Y)
1583 writeIntPadded(channelID[64:96], r)
1584 writeIntPadded(channelID[96:128], s)
1585 if c.config.Bugs.InvalidChannelIDSignature {
1586 channelID[64] ^= 1
1587 }
1588 channelIDMsg.channelID = channelID
1589
1590 c.channelID = &c.config.ChannelID.PublicKey
1591
1592 return channelIDMsg.marshal(), nil
1593}
1594
David Benjamin83c0bc92014-08-04 01:23:53 -04001595func (hs *clientHandshakeState) writeClientHash(msg []byte) {
1596 // writeClientHash is called before writeRecord.
1597 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1598}
1599
1600func (hs *clientHandshakeState) writeServerHash(msg []byte) {
1601 // writeServerHash is called after readHandshake.
1602 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1603}
1604
1605func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) {
1606 if hs.c.isDTLS {
1607 // This is somewhat hacky. DTLS hashes a slightly different format.
1608 // First, the TLS header.
1609 hs.finishedHash.Write(msg[:4])
1610 // Then the sequence number and reassembled fragment offset (always 0).
1611 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1612 // Then the reassembled fragment (always equal to the message length).
1613 hs.finishedHash.Write(msg[1:4])
1614 // And then the message body.
1615 hs.finishedHash.Write(msg[4:])
1616 } else {
1617 hs.finishedHash.Write(msg)
1618 }
1619}
1620
David Benjamina6f82632016-07-01 18:44:02 -04001621// selectClientCertificate selects a certificate for use with the given
1622// certificate, or none if none match. It may return a particular certificate or
1623// nil on success, or an error on internal error.
1624func selectClientCertificate(c *Conn, certReq *certificateRequestMsg) (*Certificate, error) {
1625 // RFC 4346 on the certificateAuthorities field:
1626 // A list of the distinguished names of acceptable certificate
1627 // authorities. These distinguished names may specify a desired
1628 // distinguished name for a root CA or for a subordinate CA; thus, this
1629 // message can be used to describe both known roots and a desired
1630 // authorization space. If the certificate_authorities list is empty
1631 // then the client MAY send any certificate of the appropriate
1632 // ClientCertificateType, unless there is some external arrangement to
1633 // the contrary.
1634
1635 var rsaAvail, ecdsaAvail bool
Nick Harperb41d2e42016-07-01 17:50:32 -04001636 if !certReq.hasRequestContext {
1637 for _, certType := range certReq.certificateTypes {
1638 switch certType {
1639 case CertTypeRSASign:
1640 rsaAvail = true
1641 case CertTypeECDSASign:
1642 ecdsaAvail = true
1643 }
David Benjamina6f82632016-07-01 18:44:02 -04001644 }
1645 }
1646
1647 // We need to search our list of client certs for one
1648 // where SignatureAlgorithm is RSA and the Issuer is in
1649 // certReq.certificateAuthorities
1650findCert:
1651 for i, chain := range c.config.Certificates {
Nick Harperb41d2e42016-07-01 17:50:32 -04001652 if !certReq.hasRequestContext && !rsaAvail && !ecdsaAvail {
David Benjamina6f82632016-07-01 18:44:02 -04001653 continue
1654 }
1655
1656 // Ensure the private key supports one of the advertised
1657 // signature algorithms.
1658 if certReq.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001659 if _, err := selectSignatureAlgorithm(c.vers, chain.PrivateKey, c.config, certReq.signatureAlgorithms); err != nil {
David Benjamina6f82632016-07-01 18:44:02 -04001660 continue
1661 }
1662 }
1663
1664 for j, cert := range chain.Certificate {
1665 x509Cert := chain.Leaf
1666 // parse the certificate if this isn't the leaf
1667 // node, or if chain.Leaf was nil
1668 if j != 0 || x509Cert == nil {
1669 var err error
1670 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
1671 c.sendAlert(alertInternalError)
1672 return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
1673 }
1674 }
1675
Nick Harperb41d2e42016-07-01 17:50:32 -04001676 if !certReq.hasRequestContext {
1677 switch {
1678 case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
1679 case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
1680 default:
1681 continue findCert
1682 }
David Benjamina6f82632016-07-01 18:44:02 -04001683 }
1684
Adam Langley2ff79332017-02-28 13:45:39 -08001685 if expected := c.config.Bugs.ExpectCertificateReqNames; expected != nil {
1686 if !eqByteSlices(expected, certReq.certificateAuthorities) {
1687 return nil, fmt.Errorf("tls: CertificateRequest names differed, got %#v but expected %#v", certReq.certificateAuthorities, expected)
David Benjamina6f82632016-07-01 18:44:02 -04001688 }
1689 }
Adam Langley2ff79332017-02-28 13:45:39 -08001690
1691 return &chain, nil
David Benjamina6f82632016-07-01 18:44:02 -04001692 }
1693 }
1694
1695 return nil, nil
1696}
1697
Adam Langley95c29f32014-06-20 12:00:00 -07001698// clientSessionCacheKey returns a key used to cache sessionTickets that could
1699// be used to resume previously negotiated TLS sessions with a server.
1700func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
1701 if len(config.ServerName) > 0 {
1702 return config.ServerName
1703 }
1704 return serverAddr.String()
1705}
1706
David Benjaminfa055a22014-09-15 16:51:51 -04001707// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
1708// given list of possible protocols and a list of the preference order. The
1709// first list must not be empty. It returns the resulting protocol and flag
Adam Langley95c29f32014-06-20 12:00:00 -07001710// indicating if the fallback case was reached.
David Benjaminfa055a22014-09-15 16:51:51 -04001711func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
1712 for _, s := range preferenceProtos {
1713 for _, c := range protos {
Adam Langley95c29f32014-06-20 12:00:00 -07001714 if s == c {
1715 return s, false
1716 }
1717 }
1718 }
1719
David Benjaminfa055a22014-09-15 16:51:51 -04001720 return protos[0], true
Adam Langley95c29f32014-06-20 12:00:00 -07001721}
David Benjamind30a9902014-08-24 01:44:23 -04001722
1723// writeIntPadded writes x into b, padded up with leading zeros as
1724// needed.
1725func writeIntPadded(b []byte, x *big.Int) {
1726 for i := range b {
1727 b[i] = 0
1728 }
1729 xb := x.Bytes()
1730 copy(b[len(b)-len(xb):], xb)
1731}
Steven Valdeza833c352016-11-01 13:39:36 -04001732
1733func generatePSKBinders(hello *clientHelloMsg, pskCipherSuite *cipherSuite, psk, transcript []byte, config *Config) {
1734 if config.Bugs.SendNoPSKBinder {
1735 return
1736 }
1737
1738 binderLen := pskCipherSuite.hash().Size()
1739 if config.Bugs.SendShortPSKBinder {
1740 binderLen--
1741 }
1742
David Benjaminaedf3032016-12-01 16:47:56 -05001743 numBinders := 1
1744 if config.Bugs.SendExtraPSKBinder {
1745 numBinders++
1746 }
1747
Steven Valdeza833c352016-11-01 13:39:36 -04001748 // Fill hello.pskBinders with appropriate length arrays of zeros so the
1749 // length prefixes are correct when computing the binder over the truncated
1750 // ClientHello message.
David Benjaminaedf3032016-12-01 16:47:56 -05001751 hello.pskBinders = make([][]byte, numBinders)
1752 for i := range hello.pskBinders {
Steven Valdeza833c352016-11-01 13:39:36 -04001753 hello.pskBinders[i] = make([]byte, binderLen)
1754 }
1755
1756 helloBytes := hello.marshal()
1757 binderSize := len(hello.pskBinders)*(binderLen+1) + 2
1758 truncatedHello := helloBytes[:len(helloBytes)-binderSize]
1759 binder := computePSKBinder(psk, resumptionPSKBinderLabel, pskCipherSuite, transcript, truncatedHello)
1760 if config.Bugs.SendShortPSKBinder {
1761 binder = binder[:binderLen]
1762 }
1763 if config.Bugs.SendInvalidPSKBinder {
1764 binder[0] ^= 1
1765 }
1766
1767 for i := range hello.pskBinders {
1768 hello.pskBinders[i] = binder
1769 }
1770
1771 hello.raw = nil
1772}