blob: d73722c5b2dd12317407681a85f9e7469589a4e9 [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,
Adam Langley95c29f32014-06-20 12:00:00 -070084 }
85
David Benjamin163c9562016-08-29 23:14:17 -040086 disableEMS := c.config.Bugs.NoExtendedMasterSecret
87 if c.cipherSuite != nil {
88 disableEMS = c.config.Bugs.NoExtendedMasterSecretOnRenegotiation
89 }
90
91 if disableEMS {
Adam Langley75712922014-10-10 16:23:43 -070092 hello.extendedMasterSecret = false
93 }
94
David Benjamin55a43642015-04-20 14:45:55 -040095 if c.config.Bugs.NoSupportedCurves {
96 hello.supportedCurves = nil
97 }
98
Steven Valdeza833c352016-11-01 13:39:36 -040099 if len(c.config.Bugs.SendPSKKeyExchangeModes) != 0 {
100 hello.pskKEModes = c.config.Bugs.SendPSKKeyExchangeModes
101 }
102
David Benjaminc241d792016-09-09 10:34:20 -0400103 if c.config.Bugs.SendCompressionMethods != nil {
104 hello.compressionMethods = c.config.Bugs.SendCompressionMethods
105 }
106
David Benjamina81967b2016-12-22 09:16:57 -0500107 if c.config.Bugs.SendSupportedPointFormats != nil {
108 hello.supportedPoints = c.config.Bugs.SendSupportedPointFormats
109 }
110
Adam Langley2ae77d22014-10-28 17:29:33 -0700111 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
112 if c.config.Bugs.BadRenegotiationInfo {
113 hello.secureRenegotiation = append(hello.secureRenegotiation, c.clientVerify...)
114 hello.secureRenegotiation[0] ^= 0x80
115 } else {
116 hello.secureRenegotiation = c.clientVerify
117 }
118 }
119
David Benjamin3e052de2015-11-25 20:10:31 -0500120 if c.noRenegotiationInfo() {
David Benjaminca6554b2014-11-08 12:31:52 -0500121 hello.secureRenegotiation = nil
122 }
123
Nick Harperb41d2e42016-07-01 17:50:32 -0400124 var keyShares map[CurveID]ecdhCurve
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400125 if maxVersion >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -0400126 keyShares = make(map[CurveID]ecdhCurve)
Nick Harperdcfbc672016-07-16 17:47:31 +0200127 hello.hasKeyShares = true
David Benjamin7e1f9842016-09-20 19:24:40 -0400128 hello.trailingKeyShareData = c.config.Bugs.TrailingKeyShareData
Nick Harperdcfbc672016-07-16 17:47:31 +0200129 curvesToSend := c.config.defaultCurves()
Nick Harperb41d2e42016-07-01 17:50:32 -0400130 for _, curveID := range hello.supportedCurves {
Nick Harperdcfbc672016-07-16 17:47:31 +0200131 if !curvesToSend[curveID] {
132 continue
133 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400134 curve, ok := curveForCurveID(curveID)
135 if !ok {
136 continue
137 }
138 publicKey, err := curve.offer(c.config.rand())
139 if err != nil {
140 return err
141 }
Steven Valdez0ee2e112016-07-15 06:51:15 -0400142
143 if c.config.Bugs.SendCurve != 0 {
144 curveID = c.config.Bugs.SendCurve
145 }
146 if c.config.Bugs.InvalidECDHPoint {
147 publicKey[0] ^= 0xff
148 }
149
Nick Harperb41d2e42016-07-01 17:50:32 -0400150 hello.keyShares = append(hello.keyShares, keyShareEntry{
151 group: curveID,
152 keyExchange: publicKey,
153 })
154 keyShares[curveID] = curve
Steven Valdez143e8b32016-07-11 13:19:03 -0400155
156 if c.config.Bugs.DuplicateKeyShares {
157 hello.keyShares = append(hello.keyShares, hello.keyShares[len(hello.keyShares)-1])
158 }
159 }
160
161 if c.config.Bugs.MissingKeyShare {
Steven Valdez5440fe02016-07-18 12:40:30 -0400162 hello.hasKeyShares = false
Nick Harperb41d2e42016-07-01 17:50:32 -0400163 }
164 }
165
Adam Langley95c29f32014-06-20 12:00:00 -0700166 possibleCipherSuites := c.config.cipherSuites()
167 hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
168
169NextCipherSuite:
170 for _, suiteId := range possibleCipherSuites {
171 for _, suite := range cipherSuites {
172 if suite.id != suiteId {
173 continue
174 }
David Benjamin5ecb88b2016-10-04 17:51:35 -0400175 // Don't advertise TLS 1.2-only cipher suites unless
176 // we're attempting TLS 1.2.
177 if maxVersion < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
178 continue
179 }
180 // Don't advertise non-DTLS cipher suites in DTLS.
181 if c.isDTLS && suite.flags&suiteNoDTLS != 0 {
182 continue
David Benjamin83c0bc92014-08-04 01:23:53 -0400183 }
Adam Langley95c29f32014-06-20 12:00:00 -0700184 hello.cipherSuites = append(hello.cipherSuites, suiteId)
185 continue NextCipherSuite
186 }
187 }
188
David Benjamin5ecb88b2016-10-04 17:51:35 -0400189 if c.config.Bugs.AdvertiseAllConfiguredCiphers {
190 hello.cipherSuites = possibleCipherSuites
191 }
192
Adam Langley5021b222015-06-12 18:27:58 -0700193 if c.config.Bugs.SendRenegotiationSCSV {
194 hello.cipherSuites = append(hello.cipherSuites, renegotiationSCSV)
195 }
196
David Benjaminbef270a2014-08-02 04:22:02 -0400197 if c.config.Bugs.SendFallbackSCSV {
198 hello.cipherSuites = append(hello.cipherSuites, fallbackSCSV)
199 }
200
Adam Langley95c29f32014-06-20 12:00:00 -0700201 _, err := io.ReadFull(c.config.rand(), hello.random)
202 if err != nil {
203 c.sendAlert(alertInternalError)
204 return errors.New("tls: short read from Rand: " + err.Error())
205 }
206
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400207 if maxVersion >= VersionTLS12 && !c.config.Bugs.NoSignatureAlgorithms {
David Benjamin7a41d372016-07-09 11:21:54 -0700208 hello.signatureAlgorithms = c.config.verifySignatureAlgorithms()
Adam Langley95c29f32014-06-20 12:00:00 -0700209 }
210
211 var session *ClientSessionState
212 var cacheKey string
213 sessionCache := c.config.ClientSessionCache
Adam Langley95c29f32014-06-20 12:00:00 -0700214
215 if sessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500216 hello.ticketSupported = !c.config.SessionTicketsDisabled
Adam Langley95c29f32014-06-20 12:00:00 -0700217
218 // Try to resume a previously negotiated TLS session, if
219 // available.
220 cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
Nick Harper0b3625b2016-07-25 16:16:28 -0700221 // TODO(nharper): Support storing more than one session
222 // ticket for TLS 1.3.
Adam Langley95c29f32014-06-20 12:00:00 -0700223 candidateSession, ok := sessionCache.Get(cacheKey)
224 if ok {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500225 ticketOk := !c.config.SessionTicketsDisabled || candidateSession.sessionTicket == nil
226
Adam Langley95c29f32014-06-20 12:00:00 -0700227 // Check that the ciphersuite/version used for the
228 // previous session are still valid.
229 cipherSuiteOk := false
David Benjamin2b02f4b2016-11-16 16:11:47 +0900230 if candidateSession.vers <= VersionTLS12 {
231 for _, id := range hello.cipherSuites {
232 if id == candidateSession.cipherSuite {
233 cipherSuiteOk = true
234 break
235 }
Adam Langley95c29f32014-06-20 12:00:00 -0700236 }
David Benjamin2b02f4b2016-11-16 16:11:47 +0900237 } else {
238 // TLS 1.3 allows the cipher to change on
239 // resumption.
240 cipherSuiteOk = true
Adam Langley95c29f32014-06-20 12:00:00 -0700241 }
242
Steven Valdezfdd10992016-09-15 16:27:05 -0400243 versOk := candidateSession.vers >= minVersion &&
244 candidateSession.vers <= maxVersion
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500245 if ticketOk && versOk && cipherSuiteOk {
Adam Langley95c29f32014-06-20 12:00:00 -0700246 session = candidateSession
247 }
248 }
249 }
250
Steven Valdeza833c352016-11-01 13:39:36 -0400251 var pskCipherSuite *cipherSuite
Nick Harper0b3625b2016-07-25 16:16:28 -0700252 if session != nil && c.config.time().Before(session.ticketExpiration) {
David Benjamind5a4ecb2016-07-18 01:17:13 +0200253 ticket := session.sessionTicket
David Benjamin4199b0d2016-11-01 13:58:25 -0400254 if c.config.Bugs.FilterTicket != nil && len(ticket) > 0 {
255 // Copy the ticket so FilterTicket may act in-place.
David Benjamind5a4ecb2016-07-18 01:17:13 +0200256 ticket = make([]byte, len(session.sessionTicket))
257 copy(ticket, session.sessionTicket)
David Benjamin4199b0d2016-11-01 13:58:25 -0400258
259 ticket, err = c.config.Bugs.FilterTicket(ticket)
260 if err != nil {
261 return err
Adam Langley38311732014-10-16 19:04:35 -0700262 }
David Benjamind5a4ecb2016-07-18 01:17:13 +0200263 }
264
David Benjamin405da482016-08-08 17:25:07 -0400265 if session.vers >= VersionTLS13 || c.config.Bugs.SendBothTickets {
Steven Valdeza833c352016-11-01 13:39:36 -0400266 pskCipherSuite = cipherSuiteFromID(session.cipherSuite)
267 if pskCipherSuite == nil {
268 return errors.New("tls: client session cache has invalid cipher suite")
269 }
Nick Harper0b3625b2016-07-25 16:16:28 -0700270 // TODO(nharper): Support sending more
271 // than one PSK identity.
Steven Valdeza833c352016-11-01 13:39:36 -0400272 ticketAge := uint32(c.config.time().Sub(session.ticketCreationTime) / time.Millisecond)
David Benjamin35ac5b72017-03-03 15:05:56 -0500273 if c.config.Bugs.SendTicketAge != 0 {
274 ticketAge = uint32(c.config.Bugs.SendTicketAge / time.Millisecond)
275 }
Steven Valdez5b986082016-09-01 12:29:49 -0400276 psk := pskIdentity{
Steven Valdeza833c352016-11-01 13:39:36 -0400277 ticket: ticket,
278 obfuscatedTicketAge: session.ticketAgeAdd + ticketAge,
Nick Harper0b3625b2016-07-25 16:16:28 -0700279 }
Steven Valdez5b986082016-09-01 12:29:49 -0400280 hello.pskIdentities = []pskIdentity{psk}
Steven Valdezaf3b8a92016-11-01 12:49:22 -0400281
282 if c.config.Bugs.ExtraPSKIdentity {
283 hello.pskIdentities = append(hello.pskIdentities, psk)
284 }
David Benjamin405da482016-08-08 17:25:07 -0400285 }
286
287 if session.vers < VersionTLS13 || c.config.Bugs.SendBothTickets {
288 if ticket != nil {
289 hello.sessionTicket = ticket
290 // A random session ID is used to detect when the
291 // server accepted the ticket and is resuming a session
292 // (see RFC 5077).
293 sessionIdLen := 16
David Benjamind4c349b2017-02-09 14:07:17 -0500294 if c.config.Bugs.TicketSessionIDLength != 0 {
295 sessionIdLen = c.config.Bugs.TicketSessionIDLength
296 }
297 if c.config.Bugs.EmptyTicketSessionID {
298 sessionIdLen = 0
David Benjamin405da482016-08-08 17:25:07 -0400299 }
300 hello.sessionId = make([]byte, sessionIdLen)
301 if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
302 c.sendAlert(alertInternalError)
303 return errors.New("tls: short read from Rand: " + err.Error())
304 }
305 } else {
306 hello.sessionId = session.sessionId
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500307 }
Adam Langley95c29f32014-06-20 12:00:00 -0700308 }
309 }
310
Steven Valdezfdd10992016-09-15 16:27:05 -0400311 if maxVersion == VersionTLS13 && !c.config.Bugs.OmitSupportedVersions {
312 if hello.vers >= VersionTLS13 {
313 hello.vers = VersionTLS12
314 }
315 for version := maxVersion; version >= minVersion; version-- {
316 hello.supportedVersions = append(hello.supportedVersions, versionToWire(version, c.isDTLS))
317 }
318 }
319
320 if len(c.config.Bugs.SendSupportedVersions) > 0 {
321 hello.supportedVersions = c.config.Bugs.SendSupportedVersions
322 }
323
David Benjamineed24012016-08-13 19:26:00 -0400324 if c.config.Bugs.SendClientVersion != 0 {
325 hello.vers = c.config.Bugs.SendClientVersion
326 }
327
David Benjamin75f99142016-11-12 12:36:06 +0900328 if c.config.Bugs.SendCipherSuites != nil {
329 hello.cipherSuites = c.config.Bugs.SendCipherSuites
330 }
331
Nick Harperf2511f12016-12-06 16:02:31 -0800332 var sendEarlyData bool
Steven Valdez2d850622017-01-11 11:34:52 -0500333 if len(hello.pskIdentities) > 0 && c.config.Bugs.SendEarlyData != nil {
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500334 hello.hasEarlyData = true
Nick Harperf2511f12016-12-06 16:02:31 -0800335 sendEarlyData = true
336 }
337 if c.config.Bugs.SendFakeEarlyDataLength > 0 {
338 hello.hasEarlyData = true
339 }
340 if c.config.Bugs.OmitEarlyDataExtension {
341 hello.hasEarlyData = false
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500342 }
343
David Benjamind86c7672014-08-02 04:07:12 -0400344 var helloBytes []byte
345 if c.config.Bugs.SendV2ClientHello {
David Benjamin94d701b2014-11-30 13:54:41 -0500346 // Test that the peer left-pads random.
347 hello.random[0] = 0
David Benjamind86c7672014-08-02 04:07:12 -0400348 v2Hello := &v2ClientHelloMsg{
349 vers: hello.vers,
350 cipherSuites: hello.cipherSuites,
351 // No session resumption for V2ClientHello.
352 sessionId: nil,
David Benjamin94d701b2014-11-30 13:54:41 -0500353 challenge: hello.random[1:],
David Benjamind86c7672014-08-02 04:07:12 -0400354 }
355 helloBytes = v2Hello.marshal()
356 c.writeV2Record(helloBytes)
357 } else {
Steven Valdeza833c352016-11-01 13:39:36 -0400358 if len(hello.pskIdentities) > 0 {
359 generatePSKBinders(hello, pskCipherSuite, session.masterSecret, []byte{}, c.config)
360 }
David Benjamind86c7672014-08-02 04:07:12 -0400361 helloBytes = hello.marshal()
Steven Valdeza833c352016-11-01 13:39:36 -0400362
David Benjamin7964b182016-07-14 23:36:30 -0400363 if c.config.Bugs.PartialClientFinishedWithClientHello {
364 // Include one byte of Finished. We can compute it
365 // without completing the handshake. This assumes we
366 // negotiate TLS 1.3 with no HelloRetryRequest or
367 // CertificateRequest.
368 toWrite := make([]byte, 0, len(helloBytes)+1)
369 toWrite = append(toWrite, helloBytes...)
370 toWrite = append(toWrite, typeFinished)
371 c.writeRecord(recordTypeHandshake, toWrite)
372 } else {
373 c.writeRecord(recordTypeHandshake, helloBytes)
374 }
David Benjamind86c7672014-08-02 04:07:12 -0400375 }
David Benjamin582ba042016-07-07 12:33:25 -0700376 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700377
David Benjamin83f90402015-01-27 01:09:43 -0500378 if err := c.simulatePacketLoss(nil); err != nil {
379 return err
380 }
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500381 if c.config.Bugs.SendEarlyAlert {
382 c.sendAlert(alertHandshakeFailure)
383 }
Nick Harperf2511f12016-12-06 16:02:31 -0800384 if c.config.Bugs.SendFakeEarlyDataLength > 0 {
385 c.sendFakeEarlyData(c.config.Bugs.SendFakeEarlyDataLength)
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500386 }
Nick Harperf2511f12016-12-06 16:02:31 -0800387
388 // Derive early write keys and set Conn state to allow early writes.
389 if sendEarlyData {
390 finishedHash := newFinishedHash(session.vers, pskCipherSuite)
391 finishedHash.addEntropy(session.masterSecret)
392 finishedHash.Write(helloBytes)
393 earlyTrafficSecret := finishedHash.deriveSecret(earlyTrafficLabel)
394 c.out.useTrafficSecret(session.vers, pskCipherSuite, earlyTrafficSecret, clientWrite)
Nick Harperf2511f12016-12-06 16:02:31 -0800395 for _, earlyData := range c.config.Bugs.SendEarlyData {
396 if _, err := c.writeRecord(recordTypeApplicationData, earlyData); err != nil {
397 return err
398 }
399 }
400 }
401
Adam Langley95c29f32014-06-20 12:00:00 -0700402 msg, err := c.readHandshake()
403 if err != nil {
404 return err
405 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400406
407 if c.isDTLS {
408 helloVerifyRequest, ok := msg.(*helloVerifyRequestMsg)
409 if ok {
David Benjaminda4789e2016-10-31 19:23:34 -0400410 if helloVerifyRequest.vers != versionToWire(VersionTLS10, c.isDTLS) {
David Benjamin8bc38f52014-08-16 12:07:27 -0400411 // Per RFC 6347, the version field in
412 // HelloVerifyRequest SHOULD be always DTLS
413 // 1.0. Enforce this for testing purposes.
414 return errors.New("dtls: bad HelloVerifyRequest version")
415 }
416
David Benjamin83c0bc92014-08-04 01:23:53 -0400417 hello.raw = nil
418 hello.cookie = helloVerifyRequest.cookie
419 helloBytes = hello.marshal()
420 c.writeRecord(recordTypeHandshake, helloBytes)
David Benjamin582ba042016-07-07 12:33:25 -0700421 c.flushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400422
David Benjamin83f90402015-01-27 01:09:43 -0500423 if err := c.simulatePacketLoss(nil); err != nil {
424 return err
425 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400426 msg, err = c.readHandshake()
427 if err != nil {
428 return err
429 }
430 }
431 }
432
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400433 var serverWireVersion uint16
Nick Harperdcfbc672016-07-16 17:47:31 +0200434 switch m := msg.(type) {
435 case *helloRetryRequestMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400436 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200437 case *serverHelloMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400438 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200439 default:
440 c.sendAlert(alertUnexpectedMessage)
441 return fmt.Errorf("tls: received unexpected message of type %T when waiting for HelloRetryRequest or ServerHello", msg)
442 }
443
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400444 serverVersion, ok := wireToVersion(serverWireVersion, c.isDTLS)
445 if ok {
Steven Valdezfdd10992016-09-15 16:27:05 -0400446 ok = c.config.isSupportedVersion(serverVersion, c.isDTLS)
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400447 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200448 if !ok {
449 c.sendAlert(alertProtocolVersion)
450 return fmt.Errorf("tls: server selected unsupported protocol version %x", c.vers)
451 }
Steven Valdezfdd10992016-09-15 16:27:05 -0400452 c.vers = serverVersion
Nick Harperdcfbc672016-07-16 17:47:31 +0200453 c.haveVers = true
454
455 helloRetryRequest, haveHelloRetryRequest := msg.(*helloRetryRequestMsg)
456 var secondHelloBytes []byte
457 if haveHelloRetryRequest {
Nick Harperf2511f12016-12-06 16:02:31 -0800458 c.out.resetCipher()
David Benjamin3baa6e12016-10-07 21:10:38 -0400459 if len(helloRetryRequest.cookie) > 0 {
460 hello.tls13Cookie = helloRetryRequest.cookie
461 }
462
Steven Valdez5440fe02016-07-18 12:40:30 -0400463 if c.config.Bugs.MisinterpretHelloRetryRequestCurve != 0 {
David Benjamin3baa6e12016-10-07 21:10:38 -0400464 helloRetryRequest.hasSelectedGroup = true
Steven Valdez5440fe02016-07-18 12:40:30 -0400465 helloRetryRequest.selectedGroup = c.config.Bugs.MisinterpretHelloRetryRequestCurve
466 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400467 if helloRetryRequest.hasSelectedGroup {
468 var hrrCurveFound bool
469 group := helloRetryRequest.selectedGroup
470 for _, curveID := range hello.supportedCurves {
471 if group == curveID {
472 hrrCurveFound = true
473 break
474 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200475 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400476 if !hrrCurveFound || keyShares[group] != nil {
477 c.sendAlert(alertHandshakeFailure)
478 return errors.New("tls: received invalid HelloRetryRequest")
479 }
480 curve, ok := curveForCurveID(group)
481 if !ok {
482 return errors.New("tls: Unable to get curve requested in HelloRetryRequest")
483 }
484 publicKey, err := curve.offer(c.config.rand())
485 if err != nil {
486 return err
487 }
488 keyShares[group] = curve
Steven Valdeza833c352016-11-01 13:39:36 -0400489 hello.keyShares = []keyShareEntry{{
David Benjamin3baa6e12016-10-07 21:10:38 -0400490 group: group,
491 keyExchange: publicKey,
Steven Valdeza833c352016-11-01 13:39:36 -0400492 }}
Nick Harperdcfbc672016-07-16 17:47:31 +0200493 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200494
Steven Valdez5440fe02016-07-18 12:40:30 -0400495 if c.config.Bugs.SecondClientHelloMissingKeyShare {
496 hello.hasKeyShares = false
497 }
498
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500499 hello.hasEarlyData = c.config.Bugs.SendEarlyDataOnSecondClientHello
Nick Harperdcfbc672016-07-16 17:47:31 +0200500 hello.raw = nil
501
Steven Valdeza833c352016-11-01 13:39:36 -0400502 if len(hello.pskIdentities) > 0 {
503 generatePSKBinders(hello, pskCipherSuite, session.masterSecret, append(helloBytes, helloRetryRequest.marshal()...), c.config)
504 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200505 secondHelloBytes = hello.marshal()
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500506
507 if c.config.Bugs.InterleaveEarlyData {
508 c.sendFakeEarlyData(4)
509 c.writeRecord(recordTypeHandshake, secondHelloBytes[:16])
510 c.sendFakeEarlyData(4)
511 c.writeRecord(recordTypeHandshake, secondHelloBytes[16:])
512 } else {
513 c.writeRecord(recordTypeHandshake, secondHelloBytes)
514 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200515 c.flushHandshake()
516
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500517 if c.config.Bugs.SendEarlyDataOnSecondClientHello {
518 c.sendFakeEarlyData(4)
519 }
520
Nick Harperdcfbc672016-07-16 17:47:31 +0200521 msg, err = c.readHandshake()
522 if err != nil {
523 return err
524 }
525 }
526
Adam Langley95c29f32014-06-20 12:00:00 -0700527 serverHello, ok := msg.(*serverHelloMsg)
528 if !ok {
529 c.sendAlert(alertUnexpectedMessage)
530 return unexpectedMessageError(serverHello, msg)
531 }
532
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400533 if serverWireVersion != serverHello.vers {
Adam Langley95c29f32014-06-20 12:00:00 -0700534 c.sendAlert(alertProtocolVersion)
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400535 return fmt.Errorf("tls: server sent non-matching version %x vs %x", serverWireVersion, serverHello.vers)
Adam Langley95c29f32014-06-20 12:00:00 -0700536 }
Adam Langley95c29f32014-06-20 12:00:00 -0700537
Nick Harper85f20c22016-07-04 10:11:59 -0700538 // Check for downgrade signals in the server random, per
David Benjamina128a552016-10-13 14:26:33 -0400539 // draft-ietf-tls-tls13-16, section 4.1.3.
Nick Harper85f20c22016-07-04 10:11:59 -0700540 if c.vers <= VersionTLS12 && c.config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400541 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS13) {
Nick Harper85f20c22016-07-04 10:11:59 -0700542 c.sendAlert(alertProtocolVersion)
543 return errors.New("tls: downgrade from TLS 1.3 detected")
544 }
545 }
546 if c.vers <= VersionTLS11 && c.config.maxVersion(c.isDTLS) >= VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400547 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS12) {
Nick Harper85f20c22016-07-04 10:11:59 -0700548 c.sendAlert(alertProtocolVersion)
549 return errors.New("tls: downgrade from TLS 1.2 detected")
550 }
551 }
552
Nick Harper0b3625b2016-07-25 16:16:28 -0700553 suite := mutualCipherSuite(hello.cipherSuites, serverHello.cipherSuite)
Adam Langley95c29f32014-06-20 12:00:00 -0700554 if suite == nil {
555 c.sendAlert(alertHandshakeFailure)
556 return fmt.Errorf("tls: server selected an unsupported cipher suite")
557 }
558
David Benjamin3baa6e12016-10-07 21:10:38 -0400559 if haveHelloRetryRequest && helloRetryRequest.hasSelectedGroup && helloRetryRequest.selectedGroup != serverHello.keyShare.group {
Nick Harperdcfbc672016-07-16 17:47:31 +0200560 c.sendAlert(alertHandshakeFailure)
561 return errors.New("tls: ServerHello parameters did not match HelloRetryRequest")
562 }
563
Adam Langley95c29f32014-06-20 12:00:00 -0700564 hs := &clientHandshakeState{
565 c: c,
566 serverHello: serverHello,
567 hello: hello,
568 suite: suite,
569 finishedHash: newFinishedHash(c.vers, suite),
Nick Harperb41d2e42016-07-01 17:50:32 -0400570 keyShares: keyShares,
Adam Langley95c29f32014-06-20 12:00:00 -0700571 session: session,
572 }
573
David Benjamin83c0bc92014-08-04 01:23:53 -0400574 hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1)
Nick Harperdcfbc672016-07-16 17:47:31 +0200575 if haveHelloRetryRequest {
576 hs.writeServerHash(helloRetryRequest.marshal())
577 hs.writeClientHash(secondHelloBytes)
578 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400579 hs.writeServerHash(hs.serverHello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700580
David Benjamin8d315d72016-07-18 01:03:18 +0200581 if c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -0400582 if err := hs.doTLS13Handshake(); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700583 return err
584 }
585 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400586 if c.config.Bugs.EarlyChangeCipherSpec > 0 {
587 hs.establishKeys()
588 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
589 }
590
591 if hs.serverHello.compressionMethod != compressionNone {
592 c.sendAlert(alertUnexpectedMessage)
593 return errors.New("tls: server selected unsupported compression format")
594 }
595
596 err = hs.processServerExtensions(&serverHello.extensions)
597 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700598 return err
599 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400600
601 isResume, err := hs.processServerHello()
602 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700603 return err
604 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400605
606 if isResume {
607 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
608 if err := hs.establishKeys(); err != nil {
609 return err
610 }
611 }
612 if err := hs.readSessionTicket(); err != nil {
613 return err
614 }
615 if err := hs.readFinished(c.firstFinished[:]); err != nil {
616 return err
617 }
618 if err := hs.sendFinished(nil, isResume); err != nil {
619 return err
620 }
621 } else {
622 if err := hs.doFullHandshake(); err != nil {
623 return err
624 }
625 if err := hs.establishKeys(); err != nil {
626 return err
627 }
628 if err := hs.sendFinished(c.firstFinished[:], isResume); err != nil {
629 return err
630 }
631 // Most retransmits are triggered by a timeout, but the final
632 // leg of the handshake is retransmited upon re-receiving a
633 // Finished.
634 if err := c.simulatePacketLoss(func() {
David Benjamin02edcd02016-07-27 17:40:37 -0400635 c.sendHandshakeSeq--
Nick Harperb41d2e42016-07-01 17:50:32 -0400636 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
637 c.flushHandshake()
638 }); err != nil {
639 return err
640 }
641 if err := hs.readSessionTicket(); err != nil {
642 return err
643 }
644 if err := hs.readFinished(nil); err != nil {
645 return err
646 }
Adam Langley95c29f32014-06-20 12:00:00 -0700647 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400648
649 if sessionCache != nil && hs.session != nil && session != hs.session {
650 if c.config.Bugs.RequireSessionTickets && len(hs.session.sessionTicket) == 0 {
651 return errors.New("tls: new session used session IDs instead of tickets")
652 }
653 sessionCache.Put(cacheKey, hs.session)
David Benjamin83f90402015-01-27 01:09:43 -0500654 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400655
656 c.didResume = isResume
David Benjamin97a0a082016-07-13 17:57:35 -0400657 c.exporterSecret = hs.masterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700658 }
659
Adam Langley95c29f32014-06-20 12:00:00 -0700660 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400661 c.cipherSuite = suite
662 copy(c.clientRandom[:], hs.hello.random)
663 copy(c.serverRandom[:], hs.serverHello.random)
Paul Lietar4fac72e2015-09-09 13:44:55 +0100664
Adam Langley95c29f32014-06-20 12:00:00 -0700665 return nil
666}
667
Nick Harperb41d2e42016-07-01 17:50:32 -0400668func (hs *clientHandshakeState) doTLS13Handshake() error {
669 c := hs.c
670
671 // Once the PRF hash is known, TLS 1.3 does not require a handshake
672 // buffer.
673 hs.finishedHash.discardHandshakeBuffer()
674
675 zeroSecret := hs.finishedHash.zeroSecret()
676
677 // Resolve PSK and compute the early secret.
678 //
679 // TODO(davidben): This will need to be handled slightly earlier once
680 // 0-RTT is implemented.
Steven Valdez803c77a2016-09-06 14:13:43 -0400681 if hs.serverHello.hasPSKIdentity {
Nick Harper0b3625b2016-07-25 16:16:28 -0700682 // We send at most one PSK identity.
683 if hs.session == nil || hs.serverHello.pskIdentity != 0 {
684 c.sendAlert(alertUnknownPSKIdentity)
685 return errors.New("tls: server sent unknown PSK identity")
686 }
David Benjamin2b02f4b2016-11-16 16:11:47 +0900687 sessionCipher := cipherSuiteFromID(hs.session.cipherSuite)
688 if sessionCipher == nil || sessionCipher.hash() != hs.suite.hash() {
Nick Harper0b3625b2016-07-25 16:16:28 -0700689 c.sendAlert(alertHandshakeFailure)
David Benjamin2b02f4b2016-11-16 16:11:47 +0900690 return errors.New("tls: server resumed an invalid session for the cipher suite")
Nick Harper0b3625b2016-07-25 16:16:28 -0700691 }
David Benjamin48891ad2016-12-04 00:02:43 -0500692 hs.finishedHash.addEntropy(hs.session.masterSecret)
Nick Harper0b3625b2016-07-25 16:16:28 -0700693 c.didResume = true
Nick Harperb41d2e42016-07-01 17:50:32 -0400694 } else {
David Benjamin48891ad2016-12-04 00:02:43 -0500695 hs.finishedHash.addEntropy(zeroSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400696 }
697
Steven Valdeza833c352016-11-01 13:39:36 -0400698 if !hs.serverHello.hasKeyShare {
699 c.sendAlert(alertUnsupportedExtension)
700 return errors.New("tls: server omitted KeyShare on resumption.")
701 }
702
Nick Harperb41d2e42016-07-01 17:50:32 -0400703 // Resolve ECDHE and compute the handshake secret.
Steven Valdez803c77a2016-09-06 14:13:43 -0400704 if !c.config.Bugs.MissingKeyShare && !c.config.Bugs.SecondClientHelloMissingKeyShare {
Nick Harperb41d2e42016-07-01 17:50:32 -0400705 curve, ok := hs.keyShares[hs.serverHello.keyShare.group]
706 if !ok {
707 c.sendAlert(alertHandshakeFailure)
708 return errors.New("tls: server selected an unsupported group")
709 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400710 c.curveID = hs.serverHello.keyShare.group
Nick Harperb41d2e42016-07-01 17:50:32 -0400711
David Benjamin48891ad2016-12-04 00:02:43 -0500712 ecdheSecret, err := curve.finish(hs.serverHello.keyShare.keyExchange)
Nick Harperb41d2e42016-07-01 17:50:32 -0400713 if err != nil {
714 return err
715 }
David Benjamin48891ad2016-12-04 00:02:43 -0500716 hs.finishedHash.addEntropy(ecdheSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400717 } else {
David Benjamin48891ad2016-12-04 00:02:43 -0500718 hs.finishedHash.addEntropy(zeroSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400719 }
720
Nick Harperf2511f12016-12-06 16:02:31 -0800721 // Derive handshake traffic keys and switch read key to handshake
722 // traffic key.
David Benjamin48891ad2016-12-04 00:02:43 -0500723 clientHandshakeTrafficSecret := hs.finishedHash.deriveSecret(clientHandshakeTrafficLabel)
David Benjamin48891ad2016-12-04 00:02:43 -0500724 serverHandshakeTrafficSecret := hs.finishedHash.deriveSecret(serverHandshakeTrafficLabel)
Steven Valdeza833c352016-11-01 13:39:36 -0400725 c.in.useTrafficSecret(c.vers, hs.suite, serverHandshakeTrafficSecret, serverWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -0400726
727 msg, err := c.readHandshake()
728 if err != nil {
729 return err
730 }
731
732 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
733 if !ok {
734 c.sendAlert(alertUnexpectedMessage)
735 return unexpectedMessageError(encryptedExtensions, msg)
736 }
737 hs.writeServerHash(encryptedExtensions.marshal())
738
739 err = hs.processServerExtensions(&encryptedExtensions.extensions)
740 if err != nil {
741 return err
742 }
743
744 var chainToSend *Certificate
David Benjamin8d343b42016-07-09 14:26:01 -0700745 var certReq *certificateRequestMsg
Steven Valdeza833c352016-11-01 13:39:36 -0400746 if c.didResume {
Nick Harper0b3625b2016-07-25 16:16:28 -0700747 // Copy over authentication from the session.
748 c.peerCertificates = hs.session.serverCertificates
749 c.sctList = hs.session.sctList
750 c.ocspResponse = hs.session.ocspResponse
David Benjamin44b33bc2016-07-01 22:40:23 -0400751 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400752 msg, err := c.readHandshake()
753 if err != nil {
754 return err
755 }
756
David Benjamin8d343b42016-07-09 14:26:01 -0700757 var ok bool
758 certReq, ok = msg.(*certificateRequestMsg)
Nick Harperb41d2e42016-07-01 17:50:32 -0400759 if ok {
David Benjamin8a8349b2016-08-18 02:32:23 -0400760 if len(certReq.requestContext) != 0 {
761 return errors.New("tls: non-empty certificate request context sent in handshake")
762 }
763
David Benjaminb62d2872016-07-18 14:55:02 +0200764 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
765 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
766 }
767
Nick Harperb41d2e42016-07-01 17:50:32 -0400768 hs.writeServerHash(certReq.marshal())
Nick Harperb41d2e42016-07-01 17:50:32 -0400769
770 chainToSend, err = selectClientCertificate(c, certReq)
771 if err != nil {
772 return err
773 }
774
775 msg, err = c.readHandshake()
776 if err != nil {
777 return err
778 }
779 }
780
781 certMsg, ok := msg.(*certificateMsg)
782 if !ok {
783 c.sendAlert(alertUnexpectedMessage)
784 return unexpectedMessageError(certMsg, msg)
785 }
786 hs.writeServerHash(certMsg.marshal())
787
David Benjamin53210cb2016-11-16 09:01:48 +0900788 // Check for unsolicited extensions.
789 for i, cert := range certMsg.certificates {
790 if c.config.Bugs.NoOCSPStapling && cert.ocspResponse != nil {
791 c.sendAlert(alertUnsupportedExtension)
792 return errors.New("tls: unexpected OCSP response in the server certificate")
793 }
794 if c.config.Bugs.NoSignedCertificateTimestamps && cert.sctList != nil {
795 c.sendAlert(alertUnsupportedExtension)
796 return errors.New("tls: unexpected SCT list in the server certificate")
797 }
798 if i > 0 && c.config.Bugs.ExpectNoExtensionsOnIntermediate && (cert.ocspResponse != nil || cert.sctList != nil) {
799 c.sendAlert(alertUnsupportedExtension)
800 return errors.New("tls: unexpected extensions in the server certificate")
801 }
802 }
803
Nick Harperb41d2e42016-07-01 17:50:32 -0400804 if err := hs.verifyCertificates(certMsg); err != nil {
805 return err
806 }
807 leaf := c.peerCertificates[0]
Steven Valdeza833c352016-11-01 13:39:36 -0400808 c.ocspResponse = certMsg.certificates[0].ocspResponse
809 c.sctList = certMsg.certificates[0].sctList
810
Nick Harperb41d2e42016-07-01 17:50:32 -0400811 msg, err = c.readHandshake()
812 if err != nil {
813 return err
814 }
815 certVerifyMsg, ok := msg.(*certificateVerifyMsg)
816 if !ok {
817 c.sendAlert(alertUnexpectedMessage)
818 return unexpectedMessageError(certVerifyMsg, msg)
819 }
820
David Benjaminf74ec792016-07-13 21:18:49 -0400821 c.peerSignatureAlgorithm = certVerifyMsg.signatureAlgorithm
Nick Harperb41d2e42016-07-01 17:50:32 -0400822 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
David Benjamin1fb125c2016-07-08 18:52:12 -0700823 err = verifyMessage(c.vers, leaf.PublicKey, c.config, certVerifyMsg.signatureAlgorithm, input, certVerifyMsg.signature)
Nick Harperb41d2e42016-07-01 17:50:32 -0400824 if err != nil {
825 return err
826 }
827
828 hs.writeServerHash(certVerifyMsg.marshal())
829 }
830
831 msg, err = c.readHandshake()
832 if err != nil {
833 return err
834 }
835 serverFinished, ok := msg.(*finishedMsg)
836 if !ok {
837 c.sendAlert(alertUnexpectedMessage)
838 return unexpectedMessageError(serverFinished, msg)
839 }
840
Steven Valdezc4aa7272016-10-03 12:25:56 -0400841 verify := hs.finishedHash.serverSum(serverHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400842 if len(verify) != len(serverFinished.verifyData) ||
843 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
844 c.sendAlert(alertHandshakeFailure)
845 return errors.New("tls: server's Finished message was incorrect")
846 }
847
848 hs.writeServerHash(serverFinished.marshal())
849
850 // The various secrets do not incorporate the client's final leg, so
851 // derive them now before updating the handshake context.
David Benjamin48891ad2016-12-04 00:02:43 -0500852 hs.finishedHash.addEntropy(zeroSecret)
853 clientTrafficSecret := hs.finishedHash.deriveSecret(clientApplicationTrafficLabel)
854 serverTrafficSecret := hs.finishedHash.deriveSecret(serverApplicationTrafficLabel)
David Benjamincdb6fe92017-02-07 16:06:48 -0500855 c.exporterSecret = hs.finishedHash.deriveSecret(exporterLabel)
856
857 // Switch to application data keys on read. In particular, any alerts
858 // from the client certificate are read over these keys.
Nick Harper7cd0a972016-12-02 11:08:40 -0800859 c.in.useTrafficSecret(c.vers, hs.suite, serverTrafficSecret, serverWrite)
860
861 // If we're expecting 0.5-RTT messages from the server, read them
862 // now.
David Benjamin794cc592017-03-25 22:24:23 -0500863 if encryptedExtensions.extensions.hasEarlyData {
864 // BoringSSL will always send two tickets half-RTT when
865 // negotiating 0-RTT.
866 for i := 0; i < shimConfig.HalfRTTTickets; i++ {
867 msg, err := c.readHandshake()
868 if err != nil {
869 return fmt.Errorf("tls: error reading half-RTT ticket: %s", err)
870 }
871 newSessionTicket, ok := msg.(*newSessionTicketMsg)
872 if !ok {
873 return errors.New("tls: expected half-RTT ticket")
874 }
875 if err := c.processTLS13NewSessionTicket(newSessionTicket, hs.suite); err != nil {
876 return err
877 }
Nick Harper7cd0a972016-12-02 11:08:40 -0800878 }
David Benjamin794cc592017-03-25 22:24:23 -0500879 for _, expectedMsg := range c.config.Bugs.ExpectHalfRTTData {
880 if err := c.readRecord(recordTypeApplicationData); err != nil {
881 return err
882 }
883 if !bytes.Equal(c.input.data[c.input.off:], expectedMsg) {
884 return errors.New("ExpectHalfRTTData: did not get expected message")
885 }
886 c.in.freeBlock(c.input)
887 c.input = nil
Nick Harper7cd0a972016-12-02 11:08:40 -0800888 }
Nick Harper7cd0a972016-12-02 11:08:40 -0800889 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400890
Nick Harperf2511f12016-12-06 16:02:31 -0800891 // Send EndOfEarlyData and then switch write key to handshake
892 // traffic key.
David Benjamin32c89272017-03-26 13:54:21 -0500893 if c.out.cipher != nil && !c.config.Bugs.SkipEndOfEarlyData {
Steven Valdez681eb6a2016-12-19 13:19:29 -0500894 if c.config.Bugs.SendStrayEarlyHandshake {
895 helloRequest := new(helloRequestMsg)
896 c.writeRecord(recordTypeHandshake, helloRequest.marshal())
897 }
Nick Harperf2511f12016-12-06 16:02:31 -0800898 c.sendAlert(alertEndOfEarlyData)
899 }
900 c.out.useTrafficSecret(c.vers, hs.suite, clientHandshakeTrafficSecret, clientWrite)
901
Steven Valdez0ee2e112016-07-15 06:51:15 -0400902 if certReq != nil && !c.config.Bugs.SkipClientCertificate {
David Benjamin8d343b42016-07-09 14:26:01 -0700903 certMsg := &certificateMsg{
904 hasRequestContext: true,
905 requestContext: certReq.requestContext,
906 }
907 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -0400908 for _, certData := range chainToSend.Certificate {
909 certMsg.certificates = append(certMsg.certificates, certificateEntry{
910 data: certData,
911 extraExtension: c.config.Bugs.SendExtensionOnCertificate,
912 })
913 }
David Benjamin8d343b42016-07-09 14:26:01 -0700914 }
915 hs.writeClientHash(certMsg.marshal())
916 c.writeRecord(recordTypeHandshake, certMsg.marshal())
917
918 if chainToSend != nil {
919 certVerify := &certificateVerifyMsg{
920 hasSignatureAlgorithm: true,
921 }
922
923 // Determine the hash to sign.
924 privKey := chainToSend.PrivateKey
925
926 var err error
927 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
928 if err != nil {
929 c.sendAlert(alertInternalError)
930 return err
931 }
932
933 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
934 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
935 if err != nil {
936 c.sendAlert(alertInternalError)
937 return err
938 }
Steven Valdez0ee2e112016-07-15 06:51:15 -0400939 if c.config.Bugs.SendSignatureAlgorithm != 0 {
940 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
941 }
David Benjamin8d343b42016-07-09 14:26:01 -0700942
943 hs.writeClientHash(certVerify.marshal())
944 c.writeRecord(recordTypeHandshake, certVerify.marshal())
945 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400946 }
947
Nick Harper60a85cb2016-09-23 16:25:11 -0700948 if encryptedExtensions.extensions.channelIDRequested {
949 channelIDHash := crypto.SHA256.New()
950 channelIDHash.Write(hs.finishedHash.certificateVerifyInput(channelIDContextTLS13))
951 channelIDMsgBytes, err := hs.writeChannelIDMessage(channelIDHash.Sum(nil))
952 if err != nil {
953 return err
954 }
955 hs.writeClientHash(channelIDMsgBytes)
956 c.writeRecord(recordTypeHandshake, channelIDMsgBytes)
957 }
958
Nick Harperb41d2e42016-07-01 17:50:32 -0400959 // Send a client Finished message.
960 finished := new(finishedMsg)
Steven Valdezc4aa7272016-10-03 12:25:56 -0400961 finished.verifyData = hs.finishedHash.clientSum(clientHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400962 if c.config.Bugs.BadFinished {
963 finished.verifyData[0]++
964 }
David Benjamin97a0a082016-07-13 17:57:35 -0400965 hs.writeClientHash(finished.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400966 if c.config.Bugs.PartialClientFinishedWithClientHello {
967 // The first byte has already been sent.
968 c.writeRecord(recordTypeHandshake, finished.marshal()[1:])
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500969 } else if c.config.Bugs.InterleaveEarlyData {
970 finishedBytes := finished.marshal()
971 c.sendFakeEarlyData(4)
972 c.writeRecord(recordTypeHandshake, finishedBytes[:1])
973 c.sendFakeEarlyData(4)
974 c.writeRecord(recordTypeHandshake, finishedBytes[1:])
David Benjamin7964b182016-07-14 23:36:30 -0400975 } else {
976 c.writeRecord(recordTypeHandshake, finished.marshal())
977 }
David Benjamin02edcd02016-07-27 17:40:37 -0400978 if c.config.Bugs.SendExtraFinished {
979 c.writeRecord(recordTypeHandshake, finished.marshal())
980 }
David Benjaminee51a222016-07-07 18:34:12 -0700981 c.flushHandshake()
Nick Harperb41d2e42016-07-01 17:50:32 -0400982
983 // Switch to application data keys.
Steven Valdeza833c352016-11-01 13:39:36 -0400984 c.out.useTrafficSecret(c.vers, hs.suite, clientTrafficSecret, clientWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -0400985
David Benjamin48891ad2016-12-04 00:02:43 -0500986 c.resumptionSecret = hs.finishedHash.deriveSecret(resumptionLabel)
Nick Harperb41d2e42016-07-01 17:50:32 -0400987 return nil
988}
989
Adam Langley95c29f32014-06-20 12:00:00 -0700990func (hs *clientHandshakeState) doFullHandshake() error {
991 c := hs.c
992
David Benjamin48cae082014-10-27 01:06:24 -0400993 var leaf *x509.Certificate
994 if hs.suite.flags&suitePSK == 0 {
995 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700996 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700997 return err
998 }
Adam Langley95c29f32014-06-20 12:00:00 -0700999
David Benjamin48cae082014-10-27 01:06:24 -04001000 certMsg, ok := msg.(*certificateMsg)
David Benjamin75051442016-07-01 18:58:51 -04001001 if !ok {
David Benjamin48cae082014-10-27 01:06:24 -04001002 c.sendAlert(alertUnexpectedMessage)
1003 return unexpectedMessageError(certMsg, msg)
1004 }
1005 hs.writeServerHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001006
David Benjamin75051442016-07-01 18:58:51 -04001007 if err := hs.verifyCertificates(certMsg); err != nil {
1008 return err
David Benjamin48cae082014-10-27 01:06:24 -04001009 }
David Benjamin75051442016-07-01 18:58:51 -04001010 leaf = c.peerCertificates[0]
David Benjamin48cae082014-10-27 01:06:24 -04001011 }
Adam Langley95c29f32014-06-20 12:00:00 -07001012
Nick Harperb3d51be2016-07-01 11:43:18 -04001013 if hs.serverHello.extensions.ocspStapling {
David Benjamin48cae082014-10-27 01:06:24 -04001014 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001015 if err != nil {
1016 return err
1017 }
1018 cs, ok := msg.(*certificateStatusMsg)
1019 if !ok {
1020 c.sendAlert(alertUnexpectedMessage)
1021 return unexpectedMessageError(cs, msg)
1022 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001023 hs.writeServerHash(cs.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001024
1025 if cs.statusType == statusTypeOCSP {
1026 c.ocspResponse = cs.response
1027 }
1028 }
1029
David Benjamin48cae082014-10-27 01:06:24 -04001030 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001031 if err != nil {
1032 return err
1033 }
1034
1035 keyAgreement := hs.suite.ka(c.vers)
1036
1037 skx, ok := msg.(*serverKeyExchangeMsg)
1038 if ok {
David Benjamin83c0bc92014-08-04 01:23:53 -04001039 hs.writeServerHash(skx.marshal())
David Benjamin48cae082014-10-27 01:06:24 -04001040 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx)
Adam Langley95c29f32014-06-20 12:00:00 -07001041 if err != nil {
1042 c.sendAlert(alertUnexpectedMessage)
1043 return err
1044 }
Steven Valdez5440fe02016-07-18 12:40:30 -04001045 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1046 c.curveID = ecdhe.curveID
1047 }
Adam Langley95c29f32014-06-20 12:00:00 -07001048
Nick Harper60edffd2016-06-21 15:19:24 -07001049 c.peerSignatureAlgorithm = keyAgreement.peerSignatureAlgorithm()
1050
Adam Langley95c29f32014-06-20 12:00:00 -07001051 msg, err = c.readHandshake()
1052 if err != nil {
1053 return err
1054 }
1055 }
1056
1057 var chainToSend *Certificate
1058 var certRequested bool
1059 certReq, ok := msg.(*certificateRequestMsg)
1060 if ok {
1061 certRequested = true
David Benjamin7a41d372016-07-09 11:21:54 -07001062 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
1063 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
1064 }
Adam Langley95c29f32014-06-20 12:00:00 -07001065
David Benjamin83c0bc92014-08-04 01:23:53 -04001066 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001067
David Benjamina6f82632016-07-01 18:44:02 -04001068 chainToSend, err = selectClientCertificate(c, certReq)
1069 if err != nil {
1070 return err
Adam Langley95c29f32014-06-20 12:00:00 -07001071 }
1072
1073 msg, err = c.readHandshake()
1074 if err != nil {
1075 return err
1076 }
1077 }
1078
1079 shd, ok := msg.(*serverHelloDoneMsg)
1080 if !ok {
1081 c.sendAlert(alertUnexpectedMessage)
1082 return unexpectedMessageError(shd, msg)
1083 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001084 hs.writeServerHash(shd.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001085
1086 // If the server requested a certificate then we have to send a
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001087 // Certificate message in TLS, even if it's empty because we don't have
1088 // a certificate to send. In SSL 3.0, skip the message and send a
1089 // no_certificate warning alert.
Adam Langley95c29f32014-06-20 12:00:00 -07001090 if certRequested {
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001091 if c.vers == VersionSSL30 && chainToSend == nil {
David Benjamin053fee92017-01-02 08:30:36 -05001092 c.sendAlert(alertNoCertificate)
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001093 } else if !c.config.Bugs.SkipClientCertificate {
1094 certMsg := new(certificateMsg)
1095 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -04001096 for _, certData := range chainToSend.Certificate {
1097 certMsg.certificates = append(certMsg.certificates, certificateEntry{
1098 data: certData,
1099 })
1100 }
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001101 }
1102 hs.writeClientHash(certMsg.marshal())
1103 c.writeRecord(recordTypeHandshake, certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001104 }
Adam Langley95c29f32014-06-20 12:00:00 -07001105 }
1106
David Benjamin48cae082014-10-27 01:06:24 -04001107 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf)
Adam Langley95c29f32014-06-20 12:00:00 -07001108 if err != nil {
1109 c.sendAlert(alertInternalError)
1110 return err
1111 }
1112 if ckx != nil {
David Benjaminf3ec83d2014-07-21 22:42:34 -04001113 if c.config.Bugs.EarlyChangeCipherSpec < 2 {
David Benjamin83c0bc92014-08-04 01:23:53 -04001114 hs.writeClientHash(ckx.marshal())
David Benjaminf3ec83d2014-07-21 22:42:34 -04001115 }
Adam Langley95c29f32014-06-20 12:00:00 -07001116 c.writeRecord(recordTypeHandshake, ckx.marshal())
1117 }
1118
Nick Harperb3d51be2016-07-01 11:43:18 -04001119 if hs.serverHello.extensions.extendedMasterSecret && c.vers >= VersionTLS10 {
Adam Langley75712922014-10-10 16:23:43 -07001120 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1121 c.extendedMasterSecret = true
1122 } else {
1123 if c.config.Bugs.RequireExtendedMasterSecret {
1124 return errors.New("tls: extended master secret required but not supported by peer")
1125 }
1126 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
1127 }
David Benjamine098ec22014-08-27 23:13:20 -04001128
Adam Langley95c29f32014-06-20 12:00:00 -07001129 if chainToSend != nil {
Adam Langley95c29f32014-06-20 12:00:00 -07001130 certVerify := &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001131 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001132 }
1133
David Benjamin72dc7832015-03-16 17:49:43 -04001134 // Determine the hash to sign.
Nick Harper60edffd2016-06-21 15:19:24 -07001135 privKey := c.config.Certificates[0].PrivateKey
David Benjamin72dc7832015-03-16 17:49:43 -04001136
Nick Harper60edffd2016-06-21 15:19:24 -07001137 if certVerify.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001138 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
Nick Harper60edffd2016-06-21 15:19:24 -07001139 if err != nil {
1140 c.sendAlert(alertInternalError)
1141 return err
Adam Langley95c29f32014-06-20 12:00:00 -07001142 }
Nick Harper60edffd2016-06-21 15:19:24 -07001143 }
1144
1145 if c.vers > VersionSSL30 {
David Benjamin5208fd42016-07-13 21:43:25 -04001146 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, hs.finishedHash.buffer)
David Benjamina95e9f32016-07-08 16:28:04 -07001147 if err == nil && c.config.Bugs.SendSignatureAlgorithm != 0 {
1148 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
1149 }
Nick Harper60edffd2016-06-21 15:19:24 -07001150 } else {
1151 // SSL 3.0's client certificate construction is
1152 // incompatible with signatureAlgorithm.
1153 rsaKey, ok := privKey.(*rsa.PrivateKey)
1154 if !ok {
1155 err = errors.New("unsupported signature type for client certificate")
1156 } else {
1157 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
David Benjamin5208fd42016-07-13 21:43:25 -04001158 if c.config.Bugs.InvalidSignature {
Nick Harper60edffd2016-06-21 15:19:24 -07001159 digest[0] ^= 0x80
1160 }
1161 certVerify.signature, err = rsa.SignPKCS1v15(c.config.rand(), rsaKey, crypto.MD5SHA1, digest)
1162 }
Adam Langley95c29f32014-06-20 12:00:00 -07001163 }
1164 if err != nil {
1165 c.sendAlert(alertInternalError)
1166 return errors.New("tls: failed to sign handshake with client certificate: " + err.Error())
1167 }
Adam Langley95c29f32014-06-20 12:00:00 -07001168
David Benjamin83c0bc92014-08-04 01:23:53 -04001169 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001170 c.writeRecord(recordTypeHandshake, certVerify.marshal())
1171 }
David Benjamin82261be2016-07-07 14:32:50 -07001172 // flushHandshake will be called in sendFinished.
Adam Langley95c29f32014-06-20 12:00:00 -07001173
David Benjamine098ec22014-08-27 23:13:20 -04001174 hs.finishedHash.discardHandshakeBuffer()
1175
Adam Langley95c29f32014-06-20 12:00:00 -07001176 return nil
1177}
1178
David Benjamin75051442016-07-01 18:58:51 -04001179func (hs *clientHandshakeState) verifyCertificates(certMsg *certificateMsg) error {
1180 c := hs.c
1181
1182 if len(certMsg.certificates) == 0 {
1183 c.sendAlert(alertIllegalParameter)
1184 return errors.New("tls: no certificates sent")
1185 }
1186
1187 certs := make([]*x509.Certificate, len(certMsg.certificates))
Steven Valdeza833c352016-11-01 13:39:36 -04001188 for i, certEntry := range certMsg.certificates {
1189 cert, err := x509.ParseCertificate(certEntry.data)
David Benjamin75051442016-07-01 18:58:51 -04001190 if err != nil {
1191 c.sendAlert(alertBadCertificate)
1192 return errors.New("tls: failed to parse certificate from server: " + err.Error())
1193 }
1194 certs[i] = cert
1195 }
1196
1197 if !c.config.InsecureSkipVerify {
1198 opts := x509.VerifyOptions{
1199 Roots: c.config.RootCAs,
1200 CurrentTime: c.config.time(),
1201 DNSName: c.config.ServerName,
1202 Intermediates: x509.NewCertPool(),
1203 }
1204
1205 for i, cert := range certs {
1206 if i == 0 {
1207 continue
1208 }
1209 opts.Intermediates.AddCert(cert)
1210 }
1211 var err error
1212 c.verifiedChains, err = certs[0].Verify(opts)
1213 if err != nil {
1214 c.sendAlert(alertBadCertificate)
1215 return err
1216 }
1217 }
1218
1219 switch certs[0].PublicKey.(type) {
1220 case *rsa.PublicKey, *ecdsa.PublicKey:
1221 break
1222 default:
1223 c.sendAlert(alertUnsupportedCertificate)
1224 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
1225 }
1226
1227 c.peerCertificates = certs
1228 return nil
1229}
1230
Adam Langley95c29f32014-06-20 12:00:00 -07001231func (hs *clientHandshakeState) establishKeys() error {
1232 c := hs.c
1233
1234 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001235 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 -07001236 var clientCipher, serverCipher interface{}
1237 var clientHash, serverHash macFunction
1238 if hs.suite.cipher != nil {
1239 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
1240 clientHash = hs.suite.mac(c.vers, clientMAC)
1241 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
1242 serverHash = hs.suite.mac(c.vers, serverMAC)
1243 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001244 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1245 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001246 }
1247
1248 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
1249 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
1250 return nil
1251}
1252
David Benjamin75101402016-07-01 13:40:23 -04001253func (hs *clientHandshakeState) processServerExtensions(serverExtensions *serverExtensions) error {
1254 c := hs.c
1255
David Benjamin8d315d72016-07-18 01:03:18 +02001256 if c.vers < VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001257 if c.config.Bugs.RequireRenegotiationInfo && serverExtensions.secureRenegotiation == nil {
1258 return errors.New("tls: renegotiation extension missing")
1259 }
David Benjamin75101402016-07-01 13:40:23 -04001260
Nick Harperb41d2e42016-07-01 17:50:32 -04001261 if len(c.clientVerify) > 0 && !c.noRenegotiationInfo() {
1262 var expectedRenegInfo []byte
1263 expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...)
1264 expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...)
1265 if !bytes.Equal(serverExtensions.secureRenegotiation, expectedRenegInfo) {
1266 c.sendAlert(alertHandshakeFailure)
1267 return fmt.Errorf("tls: renegotiation mismatch")
1268 }
David Benjamin75101402016-07-01 13:40:23 -04001269 }
David Benjamincea0ab42016-07-14 12:33:14 -04001270 } else if serverExtensions.secureRenegotiation != nil {
1271 return errors.New("tls: renegotiation info sent in TLS 1.3")
David Benjamin75101402016-07-01 13:40:23 -04001272 }
1273
1274 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
1275 if serverExtensions.customExtension != *expected {
1276 return fmt.Errorf("tls: bad custom extension contents %q", serverExtensions.customExtension)
1277 }
1278 }
1279
1280 clientDidNPN := hs.hello.nextProtoNeg
1281 clientDidALPN := len(hs.hello.alpnProtocols) > 0
1282 serverHasNPN := serverExtensions.nextProtoNeg
1283 serverHasALPN := len(serverExtensions.alpnProtocol) > 0
1284
1285 if !clientDidNPN && serverHasNPN {
1286 c.sendAlert(alertHandshakeFailure)
1287 return errors.New("server advertised unrequested NPN extension")
1288 }
1289
1290 if !clientDidALPN && serverHasALPN {
1291 c.sendAlert(alertHandshakeFailure)
1292 return errors.New("server advertised unrequested ALPN extension")
1293 }
1294
1295 if serverHasNPN && serverHasALPN {
1296 c.sendAlert(alertHandshakeFailure)
1297 return errors.New("server advertised both NPN and ALPN extensions")
1298 }
1299
1300 if serverHasALPN {
1301 c.clientProtocol = serverExtensions.alpnProtocol
1302 c.clientProtocolFallback = false
1303 c.usedALPN = true
1304 }
1305
David Benjamin8d315d72016-07-18 01:03:18 +02001306 if serverHasNPN && c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001307 c.sendAlert(alertHandshakeFailure)
1308 return errors.New("server advertised NPN over TLS 1.3")
1309 }
1310
David Benjamin75101402016-07-01 13:40:23 -04001311 if !hs.hello.channelIDSupported && serverExtensions.channelIDRequested {
1312 c.sendAlert(alertHandshakeFailure)
1313 return errors.New("server advertised unrequested Channel ID extension")
1314 }
1315
David Benjamin8d315d72016-07-18 01:03:18 +02001316 if serverExtensions.extendedMasterSecret && c.vers >= VersionTLS13 {
David Benjamine9077652016-07-13 21:02:08 -04001317 return errors.New("tls: server advertised extended master secret over TLS 1.3")
1318 }
1319
David Benjamin8d315d72016-07-18 01:03:18 +02001320 if serverExtensions.ticketSupported && c.vers >= VersionTLS13 {
Steven Valdez143e8b32016-07-11 13:19:03 -04001321 return errors.New("tls: server advertised ticket extension over TLS 1.3")
1322 }
1323
Steven Valdeza833c352016-11-01 13:39:36 -04001324 if serverExtensions.ocspStapling && c.vers >= VersionTLS13 {
1325 return errors.New("tls: server advertised OCSP in ServerHello over TLS 1.3")
1326 }
1327
David Benjamin53210cb2016-11-16 09:01:48 +09001328 if serverExtensions.ocspStapling && c.config.Bugs.NoOCSPStapling {
1329 return errors.New("tls: server advertised unrequested OCSP extension")
1330 }
1331
Steven Valdeza833c352016-11-01 13:39:36 -04001332 if len(serverExtensions.sctList) > 0 && c.vers >= VersionTLS13 {
1333 return errors.New("tls: server advertised SCTs in ServerHello over TLS 1.3")
1334 }
1335
David Benjamin53210cb2016-11-16 09:01:48 +09001336 if len(serverExtensions.sctList) > 0 && c.config.Bugs.NoSignedCertificateTimestamps {
1337 return errors.New("tls: server advertised unrequested SCTs")
1338 }
1339
David Benjamin75101402016-07-01 13:40:23 -04001340 if serverExtensions.srtpProtectionProfile != 0 {
1341 if serverExtensions.srtpMasterKeyIdentifier != "" {
1342 return errors.New("tls: server selected SRTP MKI value")
1343 }
1344
1345 found := false
1346 for _, p := range c.config.SRTPProtectionProfiles {
1347 if p == serverExtensions.srtpProtectionProfile {
1348 found = true
1349 break
1350 }
1351 }
1352 if !found {
1353 return errors.New("tls: server advertised unsupported SRTP profile")
1354 }
1355
1356 c.srtpProtectionProfile = serverExtensions.srtpProtectionProfile
1357 }
1358
Steven Valdez2d850622017-01-11 11:34:52 -05001359 if c.vers >= VersionTLS13 && c.didResume {
1360 if c.config.Bugs.ExpectEarlyDataAccepted && !serverExtensions.hasEarlyData {
1361 c.sendAlert(alertHandshakeFailure)
1362 return errors.New("tls: server did not accept early data when expected")
1363 }
1364
1365 if !c.config.Bugs.ExpectEarlyDataAccepted && serverExtensions.hasEarlyData {
1366 c.sendAlert(alertHandshakeFailure)
1367 return errors.New("tls: server accepted early data when not expected")
1368 }
1369 }
1370
David Benjamin75101402016-07-01 13:40:23 -04001371 return nil
1372}
1373
Adam Langley95c29f32014-06-20 12:00:00 -07001374func (hs *clientHandshakeState) serverResumedSession() bool {
1375 // If the server responded with the same sessionId then it means the
1376 // sessionTicket is being used to resume a TLS session.
David Benjamind4c349b2017-02-09 14:07:17 -05001377 //
1378 // Note that, if hs.hello.sessionId is a non-nil empty array, this will
1379 // accept an empty session ID from the server as resumption. See
1380 // EmptyTicketSessionID.
Adam Langley95c29f32014-06-20 12:00:00 -07001381 return hs.session != nil && hs.hello.sessionId != nil &&
1382 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
1383}
1384
1385func (hs *clientHandshakeState) processServerHello() (bool, error) {
1386 c := hs.c
1387
Adam Langley95c29f32014-06-20 12:00:00 -07001388 if hs.serverResumedSession() {
David Benjamin4b27d9f2015-05-12 22:42:52 -04001389 // For test purposes, assert that the server never accepts the
1390 // resumption offer on renegotiation.
1391 if c.cipherSuite != nil && c.config.Bugs.FailIfResumeOnRenego {
1392 return false, errors.New("tls: server resumed session on renegotiation")
1393 }
1394
Nick Harperb3d51be2016-07-01 11:43:18 -04001395 if hs.serverHello.extensions.sctList != nil {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001396 return false, errors.New("tls: server sent SCT extension on session resumption")
1397 }
1398
Nick Harperb3d51be2016-07-01 11:43:18 -04001399 if hs.serverHello.extensions.ocspStapling {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001400 return false, errors.New("tls: server sent OCSP extension on session resumption")
1401 }
1402
Adam Langley95c29f32014-06-20 12:00:00 -07001403 // Restore masterSecret and peerCerts from previous state
1404 hs.masterSecret = hs.session.masterSecret
1405 c.peerCertificates = hs.session.serverCertificates
Adam Langley75712922014-10-10 16:23:43 -07001406 c.extendedMasterSecret = hs.session.extendedMasterSecret
Paul Lietar62be8ac2015-09-16 10:03:30 +01001407 c.sctList = hs.session.sctList
1408 c.ocspResponse = hs.session.ocspResponse
David Benjamine098ec22014-08-27 23:13:20 -04001409 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001410 return true, nil
1411 }
Paul Lietar62be8ac2015-09-16 10:03:30 +01001412
Nick Harperb3d51be2016-07-01 11:43:18 -04001413 if hs.serverHello.extensions.sctList != nil {
1414 c.sctList = hs.serverHello.extensions.sctList
Paul Lietar62be8ac2015-09-16 10:03:30 +01001415 }
1416
Adam Langley95c29f32014-06-20 12:00:00 -07001417 return false, nil
1418}
1419
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001420func (hs *clientHandshakeState) readFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001421 c := hs.c
1422
1423 c.readRecord(recordTypeChangeCipherSpec)
1424 if err := c.in.error(); err != nil {
1425 return err
1426 }
1427
1428 msg, err := c.readHandshake()
1429 if err != nil {
1430 return err
1431 }
1432 serverFinished, ok := msg.(*finishedMsg)
1433 if !ok {
1434 c.sendAlert(alertUnexpectedMessage)
1435 return unexpectedMessageError(serverFinished, msg)
1436 }
1437
David Benjaminf3ec83d2014-07-21 22:42:34 -04001438 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
1439 verify := hs.finishedHash.serverSum(hs.masterSecret)
1440 if len(verify) != len(serverFinished.verifyData) ||
1441 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
1442 c.sendAlert(alertHandshakeFailure)
1443 return errors.New("tls: server's Finished message was incorrect")
1444 }
Adam Langley95c29f32014-06-20 12:00:00 -07001445 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001446 c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001447 copy(out, serverFinished.verifyData)
David Benjamin83c0bc92014-08-04 01:23:53 -04001448 hs.writeServerHash(serverFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001449 return nil
1450}
1451
1452func (hs *clientHandshakeState) readSessionTicket() error {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001453 c := hs.c
1454
1455 // Create a session with no server identifier. Either a
1456 // session ID or session ticket will be attached.
1457 session := &ClientSessionState{
1458 vers: c.vers,
1459 cipherSuite: hs.suite.id,
1460 masterSecret: hs.masterSecret,
Nick Harperc9846112016-10-17 15:05:35 -07001461 handshakeHash: hs.finishedHash.Sum(),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001462 serverCertificates: c.peerCertificates,
Paul Lietar62be8ac2015-09-16 10:03:30 +01001463 sctList: c.sctList,
1464 ocspResponse: c.ocspResponse,
Nick Harper0b3625b2016-07-25 16:16:28 -07001465 ticketExpiration: c.config.time().Add(time.Duration(7 * 24 * time.Hour)),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001466 }
1467
Nick Harperb3d51be2016-07-01 11:43:18 -04001468 if !hs.serverHello.extensions.ticketSupported {
David Benjamind98452d2015-06-16 14:16:23 -04001469 if c.config.Bugs.ExpectNewTicket {
1470 return errors.New("tls: expected new ticket")
1471 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001472 if hs.session == nil && len(hs.serverHello.sessionId) > 0 {
1473 session.sessionId = hs.serverHello.sessionId
1474 hs.session = session
1475 }
Adam Langley95c29f32014-06-20 12:00:00 -07001476 return nil
1477 }
1478
David Benjaminc7ce9772015-10-09 19:32:41 -04001479 if c.vers == VersionSSL30 {
1480 return errors.New("tls: negotiated session tickets in SSL 3.0")
1481 }
1482
Adam Langley95c29f32014-06-20 12:00:00 -07001483 msg, err := c.readHandshake()
1484 if err != nil {
1485 return err
1486 }
1487 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
1488 if !ok {
1489 c.sendAlert(alertUnexpectedMessage)
1490 return unexpectedMessageError(sessionTicketMsg, msg)
1491 }
Adam Langley95c29f32014-06-20 12:00:00 -07001492
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001493 session.sessionTicket = sessionTicketMsg.ticket
1494 hs.session = session
Adam Langley95c29f32014-06-20 12:00:00 -07001495
David Benjamind30a9902014-08-24 01:44:23 -04001496 hs.writeServerHash(sessionTicketMsg.marshal())
1497
Adam Langley95c29f32014-06-20 12:00:00 -07001498 return nil
1499}
1500
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001501func (hs *clientHandshakeState) sendFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001502 c := hs.c
1503
David Benjamin0b8d5da2016-07-15 00:39:56 -04001504 var postCCSMsgs [][]byte
David Benjamin83c0bc92014-08-04 01:23:53 -04001505 seqno := hs.c.sendHandshakeSeq
Nick Harperb3d51be2016-07-01 11:43:18 -04001506 if hs.serverHello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001507 nextProto := new(nextProtoMsg)
Nick Harperb3d51be2016-07-01 11:43:18 -04001508 proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.extensions.nextProtos)
Adam Langley95c29f32014-06-20 12:00:00 -07001509 nextProto.proto = proto
1510 c.clientProtocol = proto
1511 c.clientProtocolFallback = fallback
1512
David Benjamin86271ee2014-07-21 16:14:03 -04001513 nextProtoBytes := nextProto.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -04001514 hs.writeHash(nextProtoBytes, seqno)
1515 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001516 postCCSMsgs = append(postCCSMsgs, nextProtoBytes)
Adam Langley95c29f32014-06-20 12:00:00 -07001517 }
1518
Nick Harperb3d51be2016-07-01 11:43:18 -04001519 if hs.serverHello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001520 var resumeHash []byte
1521 if isResume {
1522 resumeHash = hs.session.handshakeHash
1523 }
Nick Harper60a85cb2016-09-23 16:25:11 -07001524 channelIDMsgBytes, err := hs.writeChannelIDMessage(hs.finishedHash.hashForChannelID(resumeHash))
David Benjamind30a9902014-08-24 01:44:23 -04001525 if err != nil {
1526 return err
1527 }
David Benjamin24599a82016-06-30 18:56:53 -04001528 hs.writeHash(channelIDMsgBytes, seqno)
David Benjamind30a9902014-08-24 01:44:23 -04001529 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001530 postCCSMsgs = append(postCCSMsgs, channelIDMsgBytes)
David Benjamind30a9902014-08-24 01:44:23 -04001531 }
1532
Adam Langley95c29f32014-06-20 12:00:00 -07001533 finished := new(finishedMsg)
David Benjaminf3ec83d2014-07-21 22:42:34 -04001534 if c.config.Bugs.EarlyChangeCipherSpec == 2 {
1535 finished.verifyData = hs.finishedHash.clientSum(nil)
1536 } else {
1537 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
1538 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001539 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001540 if c.config.Bugs.BadFinished {
1541 finished.verifyData[0]++
1542 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001543 c.clientVerify = append(c.clientVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001544 hs.finishedBytes = finished.marshal()
1545 hs.writeHash(hs.finishedBytes, seqno)
David Benjamin0b8d5da2016-07-15 00:39:56 -04001546 postCCSMsgs = append(postCCSMsgs, hs.finishedBytes)
David Benjamin86271ee2014-07-21 16:14:03 -04001547
1548 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001549 c.writeRecord(recordTypeHandshake, postCCSMsgs[0][:5])
1550 postCCSMsgs[0] = postCCSMsgs[0][5:]
David Benjamin61672812016-07-14 23:10:43 -04001551 } else if c.config.Bugs.SendUnencryptedFinished {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001552 c.writeRecord(recordTypeHandshake, postCCSMsgs[0])
1553 postCCSMsgs = postCCSMsgs[1:]
David Benjamin86271ee2014-07-21 16:14:03 -04001554 }
David Benjamin582ba042016-07-07 12:33:25 -07001555 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001556
1557 if !c.config.Bugs.SkipChangeCipherSpec &&
1558 c.config.Bugs.EarlyChangeCipherSpec == 0 {
David Benjamin8411b242015-11-26 12:07:28 -05001559 ccs := []byte{1}
1560 if c.config.Bugs.BadChangeCipherSpec != nil {
1561 ccs = c.config.Bugs.BadChangeCipherSpec
1562 }
1563 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamin86271ee2014-07-21 16:14:03 -04001564 }
1565
David Benjamin4189bd92015-01-25 23:52:39 -05001566 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1567 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1568 }
David Benjamindc3da932015-03-12 15:09:02 -04001569 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1570 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1571 return errors.New("tls: simulating post-CCS alert")
1572 }
David Benjamin4189bd92015-01-25 23:52:39 -05001573
David Benjamin0b8d5da2016-07-15 00:39:56 -04001574 if !c.config.Bugs.SkipFinished {
1575 for _, msg := range postCCSMsgs {
1576 c.writeRecord(recordTypeHandshake, msg)
1577 }
David Benjamin02edcd02016-07-27 17:40:37 -04001578
1579 if c.config.Bugs.SendExtraFinished {
1580 c.writeRecord(recordTypeHandshake, finished.marshal())
1581 }
1582
David Benjamin582ba042016-07-07 12:33:25 -07001583 c.flushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -05001584 }
Adam Langley95c29f32014-06-20 12:00:00 -07001585 return nil
1586}
1587
Nick Harper60a85cb2016-09-23 16:25:11 -07001588func (hs *clientHandshakeState) writeChannelIDMessage(channelIDHash []byte) ([]byte, error) {
1589 c := hs.c
1590 channelIDMsg := new(channelIDMsg)
1591 if c.config.ChannelID.Curve != elliptic.P256() {
1592 return nil, fmt.Errorf("tls: Channel ID is not on P-256.")
1593 }
1594 r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, channelIDHash)
1595 if err != nil {
1596 return nil, err
1597 }
1598 channelID := make([]byte, 128)
1599 writeIntPadded(channelID[0:32], c.config.ChannelID.X)
1600 writeIntPadded(channelID[32:64], c.config.ChannelID.Y)
1601 writeIntPadded(channelID[64:96], r)
1602 writeIntPadded(channelID[96:128], s)
1603 if c.config.Bugs.InvalidChannelIDSignature {
1604 channelID[64] ^= 1
1605 }
1606 channelIDMsg.channelID = channelID
1607
1608 c.channelID = &c.config.ChannelID.PublicKey
1609
1610 return channelIDMsg.marshal(), nil
1611}
1612
David Benjamin83c0bc92014-08-04 01:23:53 -04001613func (hs *clientHandshakeState) writeClientHash(msg []byte) {
1614 // writeClientHash is called before writeRecord.
1615 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1616}
1617
1618func (hs *clientHandshakeState) writeServerHash(msg []byte) {
1619 // writeServerHash is called after readHandshake.
1620 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1621}
1622
1623func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) {
1624 if hs.c.isDTLS {
1625 // This is somewhat hacky. DTLS hashes a slightly different format.
1626 // First, the TLS header.
1627 hs.finishedHash.Write(msg[:4])
1628 // Then the sequence number and reassembled fragment offset (always 0).
1629 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1630 // Then the reassembled fragment (always equal to the message length).
1631 hs.finishedHash.Write(msg[1:4])
1632 // And then the message body.
1633 hs.finishedHash.Write(msg[4:])
1634 } else {
1635 hs.finishedHash.Write(msg)
1636 }
1637}
1638
David Benjamina6f82632016-07-01 18:44:02 -04001639// selectClientCertificate selects a certificate for use with the given
1640// certificate, or none if none match. It may return a particular certificate or
1641// nil on success, or an error on internal error.
1642func selectClientCertificate(c *Conn, certReq *certificateRequestMsg) (*Certificate, error) {
1643 // RFC 4346 on the certificateAuthorities field:
1644 // A list of the distinguished names of acceptable certificate
1645 // authorities. These distinguished names may specify a desired
1646 // distinguished name for a root CA or for a subordinate CA; thus, this
1647 // message can be used to describe both known roots and a desired
1648 // authorization space. If the certificate_authorities list is empty
1649 // then the client MAY send any certificate of the appropriate
1650 // ClientCertificateType, unless there is some external arrangement to
1651 // the contrary.
1652
1653 var rsaAvail, ecdsaAvail bool
Nick Harperb41d2e42016-07-01 17:50:32 -04001654 if !certReq.hasRequestContext {
1655 for _, certType := range certReq.certificateTypes {
1656 switch certType {
1657 case CertTypeRSASign:
1658 rsaAvail = true
1659 case CertTypeECDSASign:
1660 ecdsaAvail = true
1661 }
David Benjamina6f82632016-07-01 18:44:02 -04001662 }
1663 }
1664
1665 // We need to search our list of client certs for one
1666 // where SignatureAlgorithm is RSA and the Issuer is in
1667 // certReq.certificateAuthorities
1668findCert:
1669 for i, chain := range c.config.Certificates {
Nick Harperb41d2e42016-07-01 17:50:32 -04001670 if !certReq.hasRequestContext && !rsaAvail && !ecdsaAvail {
David Benjamina6f82632016-07-01 18:44:02 -04001671 continue
1672 }
1673
1674 // Ensure the private key supports one of the advertised
1675 // signature algorithms.
1676 if certReq.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001677 if _, err := selectSignatureAlgorithm(c.vers, chain.PrivateKey, c.config, certReq.signatureAlgorithms); err != nil {
David Benjamina6f82632016-07-01 18:44:02 -04001678 continue
1679 }
1680 }
1681
1682 for j, cert := range chain.Certificate {
1683 x509Cert := chain.Leaf
1684 // parse the certificate if this isn't the leaf
1685 // node, or if chain.Leaf was nil
1686 if j != 0 || x509Cert == nil {
1687 var err error
1688 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
1689 c.sendAlert(alertInternalError)
1690 return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
1691 }
1692 }
1693
Nick Harperb41d2e42016-07-01 17:50:32 -04001694 if !certReq.hasRequestContext {
1695 switch {
1696 case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
1697 case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
1698 default:
1699 continue findCert
1700 }
David Benjamina6f82632016-07-01 18:44:02 -04001701 }
1702
Adam Langley2ff79332017-02-28 13:45:39 -08001703 if expected := c.config.Bugs.ExpectCertificateReqNames; expected != nil {
1704 if !eqByteSlices(expected, certReq.certificateAuthorities) {
1705 return nil, fmt.Errorf("tls: CertificateRequest names differed, got %#v but expected %#v", certReq.certificateAuthorities, expected)
David Benjamina6f82632016-07-01 18:44:02 -04001706 }
1707 }
Adam Langley2ff79332017-02-28 13:45:39 -08001708
1709 return &chain, nil
David Benjamina6f82632016-07-01 18:44:02 -04001710 }
1711 }
1712
1713 return nil, nil
1714}
1715
Adam Langley95c29f32014-06-20 12:00:00 -07001716// clientSessionCacheKey returns a key used to cache sessionTickets that could
1717// be used to resume previously negotiated TLS sessions with a server.
1718func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
1719 if len(config.ServerName) > 0 {
1720 return config.ServerName
1721 }
1722 return serverAddr.String()
1723}
1724
David Benjaminfa055a22014-09-15 16:51:51 -04001725// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
1726// given list of possible protocols and a list of the preference order. The
1727// first list must not be empty. It returns the resulting protocol and flag
Adam Langley95c29f32014-06-20 12:00:00 -07001728// indicating if the fallback case was reached.
David Benjaminfa055a22014-09-15 16:51:51 -04001729func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
1730 for _, s := range preferenceProtos {
1731 for _, c := range protos {
Adam Langley95c29f32014-06-20 12:00:00 -07001732 if s == c {
1733 return s, false
1734 }
1735 }
1736 }
1737
David Benjaminfa055a22014-09-15 16:51:51 -04001738 return protos[0], true
Adam Langley95c29f32014-06-20 12:00:00 -07001739}
David Benjamind30a9902014-08-24 01:44:23 -04001740
1741// writeIntPadded writes x into b, padded up with leading zeros as
1742// needed.
1743func writeIntPadded(b []byte, x *big.Int) {
1744 for i := range b {
1745 b[i] = 0
1746 }
1747 xb := x.Bytes()
1748 copy(b[len(b)-len(xb):], xb)
1749}
Steven Valdeza833c352016-11-01 13:39:36 -04001750
1751func generatePSKBinders(hello *clientHelloMsg, pskCipherSuite *cipherSuite, psk, transcript []byte, config *Config) {
1752 if config.Bugs.SendNoPSKBinder {
1753 return
1754 }
1755
1756 binderLen := pskCipherSuite.hash().Size()
1757 if config.Bugs.SendShortPSKBinder {
1758 binderLen--
1759 }
1760
David Benjaminaedf3032016-12-01 16:47:56 -05001761 numBinders := 1
1762 if config.Bugs.SendExtraPSKBinder {
1763 numBinders++
1764 }
1765
Steven Valdeza833c352016-11-01 13:39:36 -04001766 // Fill hello.pskBinders with appropriate length arrays of zeros so the
1767 // length prefixes are correct when computing the binder over the truncated
1768 // ClientHello message.
David Benjaminaedf3032016-12-01 16:47:56 -05001769 hello.pskBinders = make([][]byte, numBinders)
1770 for i := range hello.pskBinders {
Steven Valdeza833c352016-11-01 13:39:36 -04001771 hello.pskBinders[i] = make([]byte, binderLen)
1772 }
1773
1774 helloBytes := hello.marshal()
1775 binderSize := len(hello.pskBinders)*(binderLen+1) + 2
1776 truncatedHello := helloBytes[:len(helloBytes)-binderSize]
1777 binder := computePSKBinder(psk, resumptionPSKBinderLabel, pskCipherSuite, transcript, truncatedHello)
1778 if config.Bugs.SendShortPSKBinder {
1779 binder = binder[:binderLen]
1780 }
1781 if config.Bugs.SendInvalidPSKBinder {
1782 binder[0] ^= 1
1783 }
1784
1785 for i := range hello.pskBinders {
1786 hello.pskBinders[i] = binder
1787 }
1788
1789 hello.raw = nil
1790}