blob: d3ae110cfc29ae3d8a6abb439128f1823dc739e4 [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)
395
396 for _, earlyData := range c.config.Bugs.SendEarlyData {
397 if _, err := c.writeRecord(recordTypeApplicationData, earlyData); err != nil {
398 return err
399 }
400 }
401 }
402
Adam Langley95c29f32014-06-20 12:00:00 -0700403 msg, err := c.readHandshake()
404 if err != nil {
405 return err
406 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400407
408 if c.isDTLS {
409 helloVerifyRequest, ok := msg.(*helloVerifyRequestMsg)
410 if ok {
David Benjaminda4789e2016-10-31 19:23:34 -0400411 if helloVerifyRequest.vers != versionToWire(VersionTLS10, c.isDTLS) {
David Benjamin8bc38f52014-08-16 12:07:27 -0400412 // Per RFC 6347, the version field in
413 // HelloVerifyRequest SHOULD be always DTLS
414 // 1.0. Enforce this for testing purposes.
415 return errors.New("dtls: bad HelloVerifyRequest version")
416 }
417
David Benjamin83c0bc92014-08-04 01:23:53 -0400418 hello.raw = nil
419 hello.cookie = helloVerifyRequest.cookie
420 helloBytes = hello.marshal()
421 c.writeRecord(recordTypeHandshake, helloBytes)
David Benjamin582ba042016-07-07 12:33:25 -0700422 c.flushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400423
David Benjamin83f90402015-01-27 01:09:43 -0500424 if err := c.simulatePacketLoss(nil); err != nil {
425 return err
426 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400427 msg, err = c.readHandshake()
428 if err != nil {
429 return err
430 }
431 }
432 }
433
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400434 var serverWireVersion uint16
Nick Harperdcfbc672016-07-16 17:47:31 +0200435 switch m := msg.(type) {
436 case *helloRetryRequestMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400437 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200438 case *serverHelloMsg:
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400439 serverWireVersion = m.vers
Nick Harperdcfbc672016-07-16 17:47:31 +0200440 default:
441 c.sendAlert(alertUnexpectedMessage)
442 return fmt.Errorf("tls: received unexpected message of type %T when waiting for HelloRetryRequest or ServerHello", msg)
443 }
444
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400445 serverVersion, ok := wireToVersion(serverWireVersion, c.isDTLS)
446 if ok {
Steven Valdezfdd10992016-09-15 16:27:05 -0400447 ok = c.config.isSupportedVersion(serverVersion, c.isDTLS)
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400448 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200449 if !ok {
450 c.sendAlert(alertProtocolVersion)
451 return fmt.Errorf("tls: server selected unsupported protocol version %x", c.vers)
452 }
Steven Valdezfdd10992016-09-15 16:27:05 -0400453 c.vers = serverVersion
Nick Harperdcfbc672016-07-16 17:47:31 +0200454 c.haveVers = true
455
456 helloRetryRequest, haveHelloRetryRequest := msg.(*helloRetryRequestMsg)
457 var secondHelloBytes []byte
458 if haveHelloRetryRequest {
Nick Harperf2511f12016-12-06 16:02:31 -0800459 c.out.resetCipher()
David Benjamin3baa6e12016-10-07 21:10:38 -0400460 if len(helloRetryRequest.cookie) > 0 {
461 hello.tls13Cookie = helloRetryRequest.cookie
462 }
463
Steven Valdez5440fe02016-07-18 12:40:30 -0400464 if c.config.Bugs.MisinterpretHelloRetryRequestCurve != 0 {
David Benjamin3baa6e12016-10-07 21:10:38 -0400465 helloRetryRequest.hasSelectedGroup = true
Steven Valdez5440fe02016-07-18 12:40:30 -0400466 helloRetryRequest.selectedGroup = c.config.Bugs.MisinterpretHelloRetryRequestCurve
467 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400468 if helloRetryRequest.hasSelectedGroup {
469 var hrrCurveFound bool
470 group := helloRetryRequest.selectedGroup
471 for _, curveID := range hello.supportedCurves {
472 if group == curveID {
473 hrrCurveFound = true
474 break
475 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200476 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400477 if !hrrCurveFound || keyShares[group] != nil {
478 c.sendAlert(alertHandshakeFailure)
479 return errors.New("tls: received invalid HelloRetryRequest")
480 }
481 curve, ok := curveForCurveID(group)
482 if !ok {
483 return errors.New("tls: Unable to get curve requested in HelloRetryRequest")
484 }
485 publicKey, err := curve.offer(c.config.rand())
486 if err != nil {
487 return err
488 }
489 keyShares[group] = curve
Steven Valdeza833c352016-11-01 13:39:36 -0400490 hello.keyShares = []keyShareEntry{{
David Benjamin3baa6e12016-10-07 21:10:38 -0400491 group: group,
492 keyExchange: publicKey,
Steven Valdeza833c352016-11-01 13:39:36 -0400493 }}
Nick Harperdcfbc672016-07-16 17:47:31 +0200494 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200495
Steven Valdez5440fe02016-07-18 12:40:30 -0400496 if c.config.Bugs.SecondClientHelloMissingKeyShare {
497 hello.hasKeyShares = false
498 }
499
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500500 hello.hasEarlyData = c.config.Bugs.SendEarlyDataOnSecondClientHello
Nick Harperdcfbc672016-07-16 17:47:31 +0200501 hello.raw = nil
502
Steven Valdeza833c352016-11-01 13:39:36 -0400503 if len(hello.pskIdentities) > 0 {
504 generatePSKBinders(hello, pskCipherSuite, session.masterSecret, append(helloBytes, helloRetryRequest.marshal()...), c.config)
505 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200506 secondHelloBytes = hello.marshal()
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500507
508 if c.config.Bugs.InterleaveEarlyData {
509 c.sendFakeEarlyData(4)
510 c.writeRecord(recordTypeHandshake, secondHelloBytes[:16])
511 c.sendFakeEarlyData(4)
512 c.writeRecord(recordTypeHandshake, secondHelloBytes[16:])
513 } else {
514 c.writeRecord(recordTypeHandshake, secondHelloBytes)
515 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200516 c.flushHandshake()
517
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500518 if c.config.Bugs.SendEarlyDataOnSecondClientHello {
519 c.sendFakeEarlyData(4)
520 }
521
Nick Harperdcfbc672016-07-16 17:47:31 +0200522 msg, err = c.readHandshake()
523 if err != nil {
524 return err
525 }
526 }
527
Adam Langley95c29f32014-06-20 12:00:00 -0700528 serverHello, ok := msg.(*serverHelloMsg)
529 if !ok {
530 c.sendAlert(alertUnexpectedMessage)
531 return unexpectedMessageError(serverHello, msg)
532 }
533
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400534 if serverWireVersion != serverHello.vers {
Adam Langley95c29f32014-06-20 12:00:00 -0700535 c.sendAlert(alertProtocolVersion)
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400536 return fmt.Errorf("tls: server sent non-matching version %x vs %x", serverWireVersion, serverHello.vers)
Adam Langley95c29f32014-06-20 12:00:00 -0700537 }
Adam Langley95c29f32014-06-20 12:00:00 -0700538
Nick Harper85f20c22016-07-04 10:11:59 -0700539 // Check for downgrade signals in the server random, per
David Benjamina128a552016-10-13 14:26:33 -0400540 // draft-ietf-tls-tls13-16, section 4.1.3.
Nick Harper85f20c22016-07-04 10:11:59 -0700541 if c.vers <= VersionTLS12 && c.config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400542 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS13) {
Nick Harper85f20c22016-07-04 10:11:59 -0700543 c.sendAlert(alertProtocolVersion)
544 return errors.New("tls: downgrade from TLS 1.3 detected")
545 }
546 }
547 if c.vers <= VersionTLS11 && c.config.maxVersion(c.isDTLS) >= VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400548 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS12) {
Nick Harper85f20c22016-07-04 10:11:59 -0700549 c.sendAlert(alertProtocolVersion)
550 return errors.New("tls: downgrade from TLS 1.2 detected")
551 }
552 }
553
Nick Harper0b3625b2016-07-25 16:16:28 -0700554 suite := mutualCipherSuite(hello.cipherSuites, serverHello.cipherSuite)
Adam Langley95c29f32014-06-20 12:00:00 -0700555 if suite == nil {
556 c.sendAlert(alertHandshakeFailure)
557 return fmt.Errorf("tls: server selected an unsupported cipher suite")
558 }
559
David Benjamin3baa6e12016-10-07 21:10:38 -0400560 if haveHelloRetryRequest && helloRetryRequest.hasSelectedGroup && helloRetryRequest.selectedGroup != serverHello.keyShare.group {
Nick Harperdcfbc672016-07-16 17:47:31 +0200561 c.sendAlert(alertHandshakeFailure)
562 return errors.New("tls: ServerHello parameters did not match HelloRetryRequest")
563 }
564
Adam Langley95c29f32014-06-20 12:00:00 -0700565 hs := &clientHandshakeState{
566 c: c,
567 serverHello: serverHello,
568 hello: hello,
569 suite: suite,
570 finishedHash: newFinishedHash(c.vers, suite),
Nick Harperb41d2e42016-07-01 17:50:32 -0400571 keyShares: keyShares,
Adam Langley95c29f32014-06-20 12:00:00 -0700572 session: session,
573 }
574
David Benjamin83c0bc92014-08-04 01:23:53 -0400575 hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1)
Nick Harperdcfbc672016-07-16 17:47:31 +0200576 if haveHelloRetryRequest {
577 hs.writeServerHash(helloRetryRequest.marshal())
578 hs.writeClientHash(secondHelloBytes)
579 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400580 hs.writeServerHash(hs.serverHello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700581
David Benjamin8d315d72016-07-18 01:03:18 +0200582 if c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -0400583 if err := hs.doTLS13Handshake(); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700584 return err
585 }
586 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400587 if c.config.Bugs.EarlyChangeCipherSpec > 0 {
588 hs.establishKeys()
589 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
590 }
591
592 if hs.serverHello.compressionMethod != compressionNone {
593 c.sendAlert(alertUnexpectedMessage)
594 return errors.New("tls: server selected unsupported compression format")
595 }
596
597 err = hs.processServerExtensions(&serverHello.extensions)
598 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700599 return err
600 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400601
602 isResume, err := hs.processServerHello()
603 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700604 return err
605 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400606
607 if isResume {
608 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
609 if err := hs.establishKeys(); err != nil {
610 return err
611 }
612 }
613 if err := hs.readSessionTicket(); err != nil {
614 return err
615 }
616 if err := hs.readFinished(c.firstFinished[:]); err != nil {
617 return err
618 }
619 if err := hs.sendFinished(nil, isResume); err != nil {
620 return err
621 }
622 } else {
623 if err := hs.doFullHandshake(); err != nil {
624 return err
625 }
626 if err := hs.establishKeys(); err != nil {
627 return err
628 }
629 if err := hs.sendFinished(c.firstFinished[:], isResume); err != nil {
630 return err
631 }
632 // Most retransmits are triggered by a timeout, but the final
633 // leg of the handshake is retransmited upon re-receiving a
634 // Finished.
635 if err := c.simulatePacketLoss(func() {
David Benjamin02edcd02016-07-27 17:40:37 -0400636 c.sendHandshakeSeq--
Nick Harperb41d2e42016-07-01 17:50:32 -0400637 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
638 c.flushHandshake()
639 }); err != nil {
640 return err
641 }
642 if err := hs.readSessionTicket(); err != nil {
643 return err
644 }
645 if err := hs.readFinished(nil); err != nil {
646 return err
647 }
Adam Langley95c29f32014-06-20 12:00:00 -0700648 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400649
650 if sessionCache != nil && hs.session != nil && session != hs.session {
651 if c.config.Bugs.RequireSessionTickets && len(hs.session.sessionTicket) == 0 {
652 return errors.New("tls: new session used session IDs instead of tickets")
653 }
654 sessionCache.Put(cacheKey, hs.session)
David Benjamin83f90402015-01-27 01:09:43 -0500655 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400656
657 c.didResume = isResume
David Benjamin97a0a082016-07-13 17:57:35 -0400658 c.exporterSecret = hs.masterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700659 }
660
Adam Langley95c29f32014-06-20 12:00:00 -0700661 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400662 c.cipherSuite = suite
663 copy(c.clientRandom[:], hs.hello.random)
664 copy(c.serverRandom[:], hs.serverHello.random)
Paul Lietar4fac72e2015-09-09 13:44:55 +0100665
Adam Langley95c29f32014-06-20 12:00:00 -0700666 return nil
667}
668
Nick Harperb41d2e42016-07-01 17:50:32 -0400669func (hs *clientHandshakeState) doTLS13Handshake() error {
670 c := hs.c
671
672 // Once the PRF hash is known, TLS 1.3 does not require a handshake
673 // buffer.
674 hs.finishedHash.discardHandshakeBuffer()
675
676 zeroSecret := hs.finishedHash.zeroSecret()
677
678 // Resolve PSK and compute the early secret.
679 //
680 // TODO(davidben): This will need to be handled slightly earlier once
681 // 0-RTT is implemented.
Steven Valdez803c77a2016-09-06 14:13:43 -0400682 if hs.serverHello.hasPSKIdentity {
Nick Harper0b3625b2016-07-25 16:16:28 -0700683 // We send at most one PSK identity.
684 if hs.session == nil || hs.serverHello.pskIdentity != 0 {
685 c.sendAlert(alertUnknownPSKIdentity)
686 return errors.New("tls: server sent unknown PSK identity")
687 }
David Benjamin2b02f4b2016-11-16 16:11:47 +0900688 sessionCipher := cipherSuiteFromID(hs.session.cipherSuite)
689 if sessionCipher == nil || sessionCipher.hash() != hs.suite.hash() {
Nick Harper0b3625b2016-07-25 16:16:28 -0700690 c.sendAlert(alertHandshakeFailure)
David Benjamin2b02f4b2016-11-16 16:11:47 +0900691 return errors.New("tls: server resumed an invalid session for the cipher suite")
Nick Harper0b3625b2016-07-25 16:16:28 -0700692 }
David Benjamin48891ad2016-12-04 00:02:43 -0500693 hs.finishedHash.addEntropy(hs.session.masterSecret)
Nick Harper0b3625b2016-07-25 16:16:28 -0700694 c.didResume = true
Nick Harperb41d2e42016-07-01 17:50:32 -0400695 } else {
David Benjamin48891ad2016-12-04 00:02:43 -0500696 hs.finishedHash.addEntropy(zeroSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400697 }
698
Steven Valdeza833c352016-11-01 13:39:36 -0400699 if !hs.serverHello.hasKeyShare {
700 c.sendAlert(alertUnsupportedExtension)
701 return errors.New("tls: server omitted KeyShare on resumption.")
702 }
703
Nick Harperb41d2e42016-07-01 17:50:32 -0400704 // Resolve ECDHE and compute the handshake secret.
Steven Valdez803c77a2016-09-06 14:13:43 -0400705 if !c.config.Bugs.MissingKeyShare && !c.config.Bugs.SecondClientHelloMissingKeyShare {
Nick Harperb41d2e42016-07-01 17:50:32 -0400706 curve, ok := hs.keyShares[hs.serverHello.keyShare.group]
707 if !ok {
708 c.sendAlert(alertHandshakeFailure)
709 return errors.New("tls: server selected an unsupported group")
710 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400711 c.curveID = hs.serverHello.keyShare.group
Nick Harperb41d2e42016-07-01 17:50:32 -0400712
David Benjamin48891ad2016-12-04 00:02:43 -0500713 ecdheSecret, err := curve.finish(hs.serverHello.keyShare.keyExchange)
Nick Harperb41d2e42016-07-01 17:50:32 -0400714 if err != nil {
715 return err
716 }
David Benjamin48891ad2016-12-04 00:02:43 -0500717 hs.finishedHash.addEntropy(ecdheSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400718 } else {
David Benjamin48891ad2016-12-04 00:02:43 -0500719 hs.finishedHash.addEntropy(zeroSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400720 }
721
Nick Harperf2511f12016-12-06 16:02:31 -0800722 // Derive handshake traffic keys and switch read key to handshake
723 // traffic key.
David Benjamin48891ad2016-12-04 00:02:43 -0500724 clientHandshakeTrafficSecret := hs.finishedHash.deriveSecret(clientHandshakeTrafficLabel)
David Benjamin48891ad2016-12-04 00:02:43 -0500725 serverHandshakeTrafficSecret := hs.finishedHash.deriveSecret(serverHandshakeTrafficLabel)
Steven Valdeza833c352016-11-01 13:39:36 -0400726 c.in.useTrafficSecret(c.vers, hs.suite, serverHandshakeTrafficSecret, serverWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -0400727
728 msg, err := c.readHandshake()
729 if err != nil {
730 return err
731 }
732
733 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
734 if !ok {
735 c.sendAlert(alertUnexpectedMessage)
736 return unexpectedMessageError(encryptedExtensions, msg)
737 }
738 hs.writeServerHash(encryptedExtensions.marshal())
739
740 err = hs.processServerExtensions(&encryptedExtensions.extensions)
741 if err != nil {
742 return err
743 }
744
745 var chainToSend *Certificate
David Benjamin8d343b42016-07-09 14:26:01 -0700746 var certReq *certificateRequestMsg
Steven Valdeza833c352016-11-01 13:39:36 -0400747 if c.didResume {
Nick Harper0b3625b2016-07-25 16:16:28 -0700748 // Copy over authentication from the session.
749 c.peerCertificates = hs.session.serverCertificates
750 c.sctList = hs.session.sctList
751 c.ocspResponse = hs.session.ocspResponse
David Benjamin44b33bc2016-07-01 22:40:23 -0400752 } else {
Nick Harperb41d2e42016-07-01 17:50:32 -0400753 msg, err := c.readHandshake()
754 if err != nil {
755 return err
756 }
757
David Benjamin8d343b42016-07-09 14:26:01 -0700758 var ok bool
759 certReq, ok = msg.(*certificateRequestMsg)
Nick Harperb41d2e42016-07-01 17:50:32 -0400760 if ok {
David Benjamin8a8349b2016-08-18 02:32:23 -0400761 if len(certReq.requestContext) != 0 {
762 return errors.New("tls: non-empty certificate request context sent in handshake")
763 }
764
David Benjaminb62d2872016-07-18 14:55:02 +0200765 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
766 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
767 }
768
Nick Harperb41d2e42016-07-01 17:50:32 -0400769 hs.writeServerHash(certReq.marshal())
Nick Harperb41d2e42016-07-01 17:50:32 -0400770
771 chainToSend, err = selectClientCertificate(c, certReq)
772 if err != nil {
773 return err
774 }
775
776 msg, err = c.readHandshake()
777 if err != nil {
778 return err
779 }
780 }
781
782 certMsg, ok := msg.(*certificateMsg)
783 if !ok {
784 c.sendAlert(alertUnexpectedMessage)
785 return unexpectedMessageError(certMsg, msg)
786 }
787 hs.writeServerHash(certMsg.marshal())
788
David Benjamin53210cb2016-11-16 09:01:48 +0900789 // Check for unsolicited extensions.
790 for i, cert := range certMsg.certificates {
791 if c.config.Bugs.NoOCSPStapling && cert.ocspResponse != nil {
792 c.sendAlert(alertUnsupportedExtension)
793 return errors.New("tls: unexpected OCSP response in the server certificate")
794 }
795 if c.config.Bugs.NoSignedCertificateTimestamps && cert.sctList != nil {
796 c.sendAlert(alertUnsupportedExtension)
797 return errors.New("tls: unexpected SCT list in the server certificate")
798 }
799 if i > 0 && c.config.Bugs.ExpectNoExtensionsOnIntermediate && (cert.ocspResponse != nil || cert.sctList != nil) {
800 c.sendAlert(alertUnsupportedExtension)
801 return errors.New("tls: unexpected extensions in the server certificate")
802 }
803 }
804
Nick Harperb41d2e42016-07-01 17:50:32 -0400805 if err := hs.verifyCertificates(certMsg); err != nil {
806 return err
807 }
808 leaf := c.peerCertificates[0]
Steven Valdeza833c352016-11-01 13:39:36 -0400809 c.ocspResponse = certMsg.certificates[0].ocspResponse
810 c.sctList = certMsg.certificates[0].sctList
811
Nick Harperb41d2e42016-07-01 17:50:32 -0400812 msg, err = c.readHandshake()
813 if err != nil {
814 return err
815 }
816 certVerifyMsg, ok := msg.(*certificateVerifyMsg)
817 if !ok {
818 c.sendAlert(alertUnexpectedMessage)
819 return unexpectedMessageError(certVerifyMsg, msg)
820 }
821
David Benjaminf74ec792016-07-13 21:18:49 -0400822 c.peerSignatureAlgorithm = certVerifyMsg.signatureAlgorithm
Nick Harperb41d2e42016-07-01 17:50:32 -0400823 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
David Benjamin1fb125c2016-07-08 18:52:12 -0700824 err = verifyMessage(c.vers, leaf.PublicKey, c.config, certVerifyMsg.signatureAlgorithm, input, certVerifyMsg.signature)
Nick Harperb41d2e42016-07-01 17:50:32 -0400825 if err != nil {
826 return err
827 }
828
829 hs.writeServerHash(certVerifyMsg.marshal())
830 }
831
832 msg, err = c.readHandshake()
833 if err != nil {
834 return err
835 }
836 serverFinished, ok := msg.(*finishedMsg)
837 if !ok {
838 c.sendAlert(alertUnexpectedMessage)
839 return unexpectedMessageError(serverFinished, msg)
840 }
841
Steven Valdezc4aa7272016-10-03 12:25:56 -0400842 verify := hs.finishedHash.serverSum(serverHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400843 if len(verify) != len(serverFinished.verifyData) ||
844 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
845 c.sendAlert(alertHandshakeFailure)
846 return errors.New("tls: server's Finished message was incorrect")
847 }
848
849 hs.writeServerHash(serverFinished.marshal())
850
851 // The various secrets do not incorporate the client's final leg, so
852 // derive them now before updating the handshake context.
David Benjamin48891ad2016-12-04 00:02:43 -0500853 hs.finishedHash.addEntropy(zeroSecret)
854 clientTrafficSecret := hs.finishedHash.deriveSecret(clientApplicationTrafficLabel)
855 serverTrafficSecret := hs.finishedHash.deriveSecret(serverApplicationTrafficLabel)
David Benjamincdb6fe92017-02-07 16:06:48 -0500856 c.exporterSecret = hs.finishedHash.deriveSecret(exporterLabel)
857
858 // Switch to application data keys on read. In particular, any alerts
859 // from the client certificate are read over these keys.
Nick Harper7cd0a972016-12-02 11:08:40 -0800860 c.in.useTrafficSecret(c.vers, hs.suite, serverTrafficSecret, serverWrite)
861
862 // If we're expecting 0.5-RTT messages from the server, read them
863 // now.
David Benjamin794cc592017-03-25 22:24:23 -0500864 if encryptedExtensions.extensions.hasEarlyData {
865 // BoringSSL will always send two tickets half-RTT when
866 // negotiating 0-RTT.
867 for i := 0; i < shimConfig.HalfRTTTickets; i++ {
868 msg, err := c.readHandshake()
869 if err != nil {
870 return fmt.Errorf("tls: error reading half-RTT ticket: %s", err)
871 }
872 newSessionTicket, ok := msg.(*newSessionTicketMsg)
873 if !ok {
874 return errors.New("tls: expected half-RTT ticket")
875 }
876 if err := c.processTLS13NewSessionTicket(newSessionTicket, hs.suite); err != nil {
877 return err
878 }
Nick Harper7cd0a972016-12-02 11:08:40 -0800879 }
David Benjamin794cc592017-03-25 22:24:23 -0500880 for _, expectedMsg := range c.config.Bugs.ExpectHalfRTTData {
881 if err := c.readRecord(recordTypeApplicationData); err != nil {
882 return err
883 }
884 if !bytes.Equal(c.input.data[c.input.off:], expectedMsg) {
885 return errors.New("ExpectHalfRTTData: did not get expected message")
886 }
887 c.in.freeBlock(c.input)
888 c.input = nil
Nick Harper7cd0a972016-12-02 11:08:40 -0800889 }
Nick Harper7cd0a972016-12-02 11:08:40 -0800890 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400891
Nick Harperf2511f12016-12-06 16:02:31 -0800892 // Send EndOfEarlyData and then switch write key to handshake
893 // traffic key.
David Benjamin32c89272017-03-26 13:54:21 -0500894 if c.out.cipher != nil && !c.config.Bugs.SkipEndOfEarlyData {
Nick Harperf2511f12016-12-06 16:02:31 -0800895 c.sendAlert(alertEndOfEarlyData)
896 }
897 c.out.useTrafficSecret(c.vers, hs.suite, clientHandshakeTrafficSecret, clientWrite)
898
Steven Valdez0ee2e112016-07-15 06:51:15 -0400899 if certReq != nil && !c.config.Bugs.SkipClientCertificate {
David Benjamin8d343b42016-07-09 14:26:01 -0700900 certMsg := &certificateMsg{
901 hasRequestContext: true,
902 requestContext: certReq.requestContext,
903 }
904 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -0400905 for _, certData := range chainToSend.Certificate {
906 certMsg.certificates = append(certMsg.certificates, certificateEntry{
907 data: certData,
908 extraExtension: c.config.Bugs.SendExtensionOnCertificate,
909 })
910 }
David Benjamin8d343b42016-07-09 14:26:01 -0700911 }
912 hs.writeClientHash(certMsg.marshal())
913 c.writeRecord(recordTypeHandshake, certMsg.marshal())
914
915 if chainToSend != nil {
916 certVerify := &certificateVerifyMsg{
917 hasSignatureAlgorithm: true,
918 }
919
920 // Determine the hash to sign.
921 privKey := chainToSend.PrivateKey
922
923 var err error
924 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
925 if err != nil {
926 c.sendAlert(alertInternalError)
927 return err
928 }
929
930 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
931 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
932 if err != nil {
933 c.sendAlert(alertInternalError)
934 return err
935 }
Steven Valdez0ee2e112016-07-15 06:51:15 -0400936 if c.config.Bugs.SendSignatureAlgorithm != 0 {
937 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
938 }
David Benjamin8d343b42016-07-09 14:26:01 -0700939
940 hs.writeClientHash(certVerify.marshal())
941 c.writeRecord(recordTypeHandshake, certVerify.marshal())
942 }
Nick Harperb41d2e42016-07-01 17:50:32 -0400943 }
944
Nick Harper60a85cb2016-09-23 16:25:11 -0700945 if encryptedExtensions.extensions.channelIDRequested {
946 channelIDHash := crypto.SHA256.New()
947 channelIDHash.Write(hs.finishedHash.certificateVerifyInput(channelIDContextTLS13))
948 channelIDMsgBytes, err := hs.writeChannelIDMessage(channelIDHash.Sum(nil))
949 if err != nil {
950 return err
951 }
952 hs.writeClientHash(channelIDMsgBytes)
953 c.writeRecord(recordTypeHandshake, channelIDMsgBytes)
954 }
955
Nick Harperb41d2e42016-07-01 17:50:32 -0400956 // Send a client Finished message.
957 finished := new(finishedMsg)
Steven Valdezc4aa7272016-10-03 12:25:56 -0400958 finished.verifyData = hs.finishedHash.clientSum(clientHandshakeTrafficSecret)
Nick Harperb41d2e42016-07-01 17:50:32 -0400959 if c.config.Bugs.BadFinished {
960 finished.verifyData[0]++
961 }
David Benjamin97a0a082016-07-13 17:57:35 -0400962 hs.writeClientHash(finished.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400963 if c.config.Bugs.PartialClientFinishedWithClientHello {
964 // The first byte has already been sent.
965 c.writeRecord(recordTypeHandshake, finished.marshal()[1:])
Steven Valdeza4ee74d2016-11-29 13:36:45 -0500966 } else if c.config.Bugs.InterleaveEarlyData {
967 finishedBytes := finished.marshal()
968 c.sendFakeEarlyData(4)
969 c.writeRecord(recordTypeHandshake, finishedBytes[:1])
970 c.sendFakeEarlyData(4)
971 c.writeRecord(recordTypeHandshake, finishedBytes[1:])
David Benjamin7964b182016-07-14 23:36:30 -0400972 } else {
973 c.writeRecord(recordTypeHandshake, finished.marshal())
974 }
David Benjamin02edcd02016-07-27 17:40:37 -0400975 if c.config.Bugs.SendExtraFinished {
976 c.writeRecord(recordTypeHandshake, finished.marshal())
977 }
David Benjaminee51a222016-07-07 18:34:12 -0700978 c.flushHandshake()
Nick Harperb41d2e42016-07-01 17:50:32 -0400979
980 // Switch to application data keys.
Steven Valdeza833c352016-11-01 13:39:36 -0400981 c.out.useTrafficSecret(c.vers, hs.suite, clientTrafficSecret, clientWrite)
Nick Harperb41d2e42016-07-01 17:50:32 -0400982
David Benjamin48891ad2016-12-04 00:02:43 -0500983 c.resumptionSecret = hs.finishedHash.deriveSecret(resumptionLabel)
Nick Harperb41d2e42016-07-01 17:50:32 -0400984 return nil
985}
986
Adam Langley95c29f32014-06-20 12:00:00 -0700987func (hs *clientHandshakeState) doFullHandshake() error {
988 c := hs.c
989
David Benjamin48cae082014-10-27 01:06:24 -0400990 var leaf *x509.Certificate
991 if hs.suite.flags&suitePSK == 0 {
992 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700993 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700994 return err
995 }
Adam Langley95c29f32014-06-20 12:00:00 -0700996
David Benjamin48cae082014-10-27 01:06:24 -0400997 certMsg, ok := msg.(*certificateMsg)
David Benjamin75051442016-07-01 18:58:51 -0400998 if !ok {
David Benjamin48cae082014-10-27 01:06:24 -0400999 c.sendAlert(alertUnexpectedMessage)
1000 return unexpectedMessageError(certMsg, msg)
1001 }
1002 hs.writeServerHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001003
David Benjamin75051442016-07-01 18:58:51 -04001004 if err := hs.verifyCertificates(certMsg); err != nil {
1005 return err
David Benjamin48cae082014-10-27 01:06:24 -04001006 }
David Benjamin75051442016-07-01 18:58:51 -04001007 leaf = c.peerCertificates[0]
David Benjamin48cae082014-10-27 01:06:24 -04001008 }
Adam Langley95c29f32014-06-20 12:00:00 -07001009
Nick Harperb3d51be2016-07-01 11:43:18 -04001010 if hs.serverHello.extensions.ocspStapling {
David Benjamin48cae082014-10-27 01:06:24 -04001011 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001012 if err != nil {
1013 return err
1014 }
1015 cs, ok := msg.(*certificateStatusMsg)
1016 if !ok {
1017 c.sendAlert(alertUnexpectedMessage)
1018 return unexpectedMessageError(cs, msg)
1019 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001020 hs.writeServerHash(cs.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001021
1022 if cs.statusType == statusTypeOCSP {
1023 c.ocspResponse = cs.response
1024 }
1025 }
1026
David Benjamin48cae082014-10-27 01:06:24 -04001027 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001028 if err != nil {
1029 return err
1030 }
1031
1032 keyAgreement := hs.suite.ka(c.vers)
1033
1034 skx, ok := msg.(*serverKeyExchangeMsg)
1035 if ok {
David Benjamin83c0bc92014-08-04 01:23:53 -04001036 hs.writeServerHash(skx.marshal())
David Benjamin48cae082014-10-27 01:06:24 -04001037 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx)
Adam Langley95c29f32014-06-20 12:00:00 -07001038 if err != nil {
1039 c.sendAlert(alertUnexpectedMessage)
1040 return err
1041 }
Steven Valdez5440fe02016-07-18 12:40:30 -04001042 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1043 c.curveID = ecdhe.curveID
1044 }
Adam Langley95c29f32014-06-20 12:00:00 -07001045
Nick Harper60edffd2016-06-21 15:19:24 -07001046 c.peerSignatureAlgorithm = keyAgreement.peerSignatureAlgorithm()
1047
Adam Langley95c29f32014-06-20 12:00:00 -07001048 msg, err = c.readHandshake()
1049 if err != nil {
1050 return err
1051 }
1052 }
1053
1054 var chainToSend *Certificate
1055 var certRequested bool
1056 certReq, ok := msg.(*certificateRequestMsg)
1057 if ok {
1058 certRequested = true
David Benjamin7a41d372016-07-09 11:21:54 -07001059 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
1060 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
1061 }
Adam Langley95c29f32014-06-20 12:00:00 -07001062
David Benjamin83c0bc92014-08-04 01:23:53 -04001063 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001064
David Benjamina6f82632016-07-01 18:44:02 -04001065 chainToSend, err = selectClientCertificate(c, certReq)
1066 if err != nil {
1067 return err
Adam Langley95c29f32014-06-20 12:00:00 -07001068 }
1069
1070 msg, err = c.readHandshake()
1071 if err != nil {
1072 return err
1073 }
1074 }
1075
1076 shd, ok := msg.(*serverHelloDoneMsg)
1077 if !ok {
1078 c.sendAlert(alertUnexpectedMessage)
1079 return unexpectedMessageError(shd, msg)
1080 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001081 hs.writeServerHash(shd.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001082
1083 // If the server requested a certificate then we have to send a
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001084 // Certificate message in TLS, even if it's empty because we don't have
1085 // a certificate to send. In SSL 3.0, skip the message and send a
1086 // no_certificate warning alert.
Adam Langley95c29f32014-06-20 12:00:00 -07001087 if certRequested {
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001088 if c.vers == VersionSSL30 && chainToSend == nil {
David Benjamin053fee92017-01-02 08:30:36 -05001089 c.sendAlert(alertNoCertificate)
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001090 } else if !c.config.Bugs.SkipClientCertificate {
1091 certMsg := new(certificateMsg)
1092 if chainToSend != nil {
Steven Valdeza833c352016-11-01 13:39:36 -04001093 for _, certData := range chainToSend.Certificate {
1094 certMsg.certificates = append(certMsg.certificates, certificateEntry{
1095 data: certData,
1096 })
1097 }
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001098 }
1099 hs.writeClientHash(certMsg.marshal())
1100 c.writeRecord(recordTypeHandshake, certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001101 }
Adam Langley95c29f32014-06-20 12:00:00 -07001102 }
1103
David Benjamin48cae082014-10-27 01:06:24 -04001104 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf)
Adam Langley95c29f32014-06-20 12:00:00 -07001105 if err != nil {
1106 c.sendAlert(alertInternalError)
1107 return err
1108 }
1109 if ckx != nil {
David Benjaminf3ec83d2014-07-21 22:42:34 -04001110 if c.config.Bugs.EarlyChangeCipherSpec < 2 {
David Benjamin83c0bc92014-08-04 01:23:53 -04001111 hs.writeClientHash(ckx.marshal())
David Benjaminf3ec83d2014-07-21 22:42:34 -04001112 }
Adam Langley95c29f32014-06-20 12:00:00 -07001113 c.writeRecord(recordTypeHandshake, ckx.marshal())
1114 }
1115
Nick Harperb3d51be2016-07-01 11:43:18 -04001116 if hs.serverHello.extensions.extendedMasterSecret && c.vers >= VersionTLS10 {
Adam Langley75712922014-10-10 16:23:43 -07001117 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1118 c.extendedMasterSecret = true
1119 } else {
1120 if c.config.Bugs.RequireExtendedMasterSecret {
1121 return errors.New("tls: extended master secret required but not supported by peer")
1122 }
1123 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
1124 }
David Benjamine098ec22014-08-27 23:13:20 -04001125
Adam Langley95c29f32014-06-20 12:00:00 -07001126 if chainToSend != nil {
Adam Langley95c29f32014-06-20 12:00:00 -07001127 certVerify := &certificateVerifyMsg{
Nick Harper60edffd2016-06-21 15:19:24 -07001128 hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley95c29f32014-06-20 12:00:00 -07001129 }
1130
David Benjamin72dc7832015-03-16 17:49:43 -04001131 // Determine the hash to sign.
Nick Harper60edffd2016-06-21 15:19:24 -07001132 privKey := c.config.Certificates[0].PrivateKey
David Benjamin72dc7832015-03-16 17:49:43 -04001133
Nick Harper60edffd2016-06-21 15:19:24 -07001134 if certVerify.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001135 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
Nick Harper60edffd2016-06-21 15:19:24 -07001136 if err != nil {
1137 c.sendAlert(alertInternalError)
1138 return err
Adam Langley95c29f32014-06-20 12:00:00 -07001139 }
Nick Harper60edffd2016-06-21 15:19:24 -07001140 }
1141
1142 if c.vers > VersionSSL30 {
David Benjamin5208fd42016-07-13 21:43:25 -04001143 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, hs.finishedHash.buffer)
David Benjamina95e9f32016-07-08 16:28:04 -07001144 if err == nil && c.config.Bugs.SendSignatureAlgorithm != 0 {
1145 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
1146 }
Nick Harper60edffd2016-06-21 15:19:24 -07001147 } else {
1148 // SSL 3.0's client certificate construction is
1149 // incompatible with signatureAlgorithm.
1150 rsaKey, ok := privKey.(*rsa.PrivateKey)
1151 if !ok {
1152 err = errors.New("unsupported signature type for client certificate")
1153 } else {
1154 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
David Benjamin5208fd42016-07-13 21:43:25 -04001155 if c.config.Bugs.InvalidSignature {
Nick Harper60edffd2016-06-21 15:19:24 -07001156 digest[0] ^= 0x80
1157 }
1158 certVerify.signature, err = rsa.SignPKCS1v15(c.config.rand(), rsaKey, crypto.MD5SHA1, digest)
1159 }
Adam Langley95c29f32014-06-20 12:00:00 -07001160 }
1161 if err != nil {
1162 c.sendAlert(alertInternalError)
1163 return errors.New("tls: failed to sign handshake with client certificate: " + err.Error())
1164 }
Adam Langley95c29f32014-06-20 12:00:00 -07001165
David Benjamin83c0bc92014-08-04 01:23:53 -04001166 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001167 c.writeRecord(recordTypeHandshake, certVerify.marshal())
1168 }
David Benjamin82261be2016-07-07 14:32:50 -07001169 // flushHandshake will be called in sendFinished.
Adam Langley95c29f32014-06-20 12:00:00 -07001170
David Benjamine098ec22014-08-27 23:13:20 -04001171 hs.finishedHash.discardHandshakeBuffer()
1172
Adam Langley95c29f32014-06-20 12:00:00 -07001173 return nil
1174}
1175
David Benjamin75051442016-07-01 18:58:51 -04001176func (hs *clientHandshakeState) verifyCertificates(certMsg *certificateMsg) error {
1177 c := hs.c
1178
1179 if len(certMsg.certificates) == 0 {
1180 c.sendAlert(alertIllegalParameter)
1181 return errors.New("tls: no certificates sent")
1182 }
1183
1184 certs := make([]*x509.Certificate, len(certMsg.certificates))
Steven Valdeza833c352016-11-01 13:39:36 -04001185 for i, certEntry := range certMsg.certificates {
1186 cert, err := x509.ParseCertificate(certEntry.data)
David Benjamin75051442016-07-01 18:58:51 -04001187 if err != nil {
1188 c.sendAlert(alertBadCertificate)
1189 return errors.New("tls: failed to parse certificate from server: " + err.Error())
1190 }
1191 certs[i] = cert
1192 }
1193
1194 if !c.config.InsecureSkipVerify {
1195 opts := x509.VerifyOptions{
1196 Roots: c.config.RootCAs,
1197 CurrentTime: c.config.time(),
1198 DNSName: c.config.ServerName,
1199 Intermediates: x509.NewCertPool(),
1200 }
1201
1202 for i, cert := range certs {
1203 if i == 0 {
1204 continue
1205 }
1206 opts.Intermediates.AddCert(cert)
1207 }
1208 var err error
1209 c.verifiedChains, err = certs[0].Verify(opts)
1210 if err != nil {
1211 c.sendAlert(alertBadCertificate)
1212 return err
1213 }
1214 }
1215
1216 switch certs[0].PublicKey.(type) {
1217 case *rsa.PublicKey, *ecdsa.PublicKey:
1218 break
1219 default:
1220 c.sendAlert(alertUnsupportedCertificate)
1221 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
1222 }
1223
1224 c.peerCertificates = certs
1225 return nil
1226}
1227
Adam Langley95c29f32014-06-20 12:00:00 -07001228func (hs *clientHandshakeState) establishKeys() error {
1229 c := hs.c
1230
1231 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001232 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 -07001233 var clientCipher, serverCipher interface{}
1234 var clientHash, serverHash macFunction
1235 if hs.suite.cipher != nil {
1236 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
1237 clientHash = hs.suite.mac(c.vers, clientMAC)
1238 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
1239 serverHash = hs.suite.mac(c.vers, serverMAC)
1240 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001241 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1242 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001243 }
1244
1245 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
1246 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
1247 return nil
1248}
1249
David Benjamin75101402016-07-01 13:40:23 -04001250func (hs *clientHandshakeState) processServerExtensions(serverExtensions *serverExtensions) error {
1251 c := hs.c
1252
David Benjamin8d315d72016-07-18 01:03:18 +02001253 if c.vers < VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001254 if c.config.Bugs.RequireRenegotiationInfo && serverExtensions.secureRenegotiation == nil {
1255 return errors.New("tls: renegotiation extension missing")
1256 }
David Benjamin75101402016-07-01 13:40:23 -04001257
Nick Harperb41d2e42016-07-01 17:50:32 -04001258 if len(c.clientVerify) > 0 && !c.noRenegotiationInfo() {
1259 var expectedRenegInfo []byte
1260 expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...)
1261 expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...)
1262 if !bytes.Equal(serverExtensions.secureRenegotiation, expectedRenegInfo) {
1263 c.sendAlert(alertHandshakeFailure)
1264 return fmt.Errorf("tls: renegotiation mismatch")
1265 }
David Benjamin75101402016-07-01 13:40:23 -04001266 }
David Benjamincea0ab42016-07-14 12:33:14 -04001267 } else if serverExtensions.secureRenegotiation != nil {
1268 return errors.New("tls: renegotiation info sent in TLS 1.3")
David Benjamin75101402016-07-01 13:40:23 -04001269 }
1270
1271 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
1272 if serverExtensions.customExtension != *expected {
1273 return fmt.Errorf("tls: bad custom extension contents %q", serverExtensions.customExtension)
1274 }
1275 }
1276
1277 clientDidNPN := hs.hello.nextProtoNeg
1278 clientDidALPN := len(hs.hello.alpnProtocols) > 0
1279 serverHasNPN := serverExtensions.nextProtoNeg
1280 serverHasALPN := len(serverExtensions.alpnProtocol) > 0
1281
1282 if !clientDidNPN && serverHasNPN {
1283 c.sendAlert(alertHandshakeFailure)
1284 return errors.New("server advertised unrequested NPN extension")
1285 }
1286
1287 if !clientDidALPN && serverHasALPN {
1288 c.sendAlert(alertHandshakeFailure)
1289 return errors.New("server advertised unrequested ALPN extension")
1290 }
1291
1292 if serverHasNPN && serverHasALPN {
1293 c.sendAlert(alertHandshakeFailure)
1294 return errors.New("server advertised both NPN and ALPN extensions")
1295 }
1296
1297 if serverHasALPN {
1298 c.clientProtocol = serverExtensions.alpnProtocol
1299 c.clientProtocolFallback = false
1300 c.usedALPN = true
1301 }
1302
David Benjamin8d315d72016-07-18 01:03:18 +02001303 if serverHasNPN && c.vers >= VersionTLS13 {
Nick Harperb41d2e42016-07-01 17:50:32 -04001304 c.sendAlert(alertHandshakeFailure)
1305 return errors.New("server advertised NPN over TLS 1.3")
1306 }
1307
David Benjamin75101402016-07-01 13:40:23 -04001308 if !hs.hello.channelIDSupported && serverExtensions.channelIDRequested {
1309 c.sendAlert(alertHandshakeFailure)
1310 return errors.New("server advertised unrequested Channel ID extension")
1311 }
1312
David Benjamin8d315d72016-07-18 01:03:18 +02001313 if serverExtensions.extendedMasterSecret && c.vers >= VersionTLS13 {
David Benjamine9077652016-07-13 21:02:08 -04001314 return errors.New("tls: server advertised extended master secret over TLS 1.3")
1315 }
1316
David Benjamin8d315d72016-07-18 01:03:18 +02001317 if serverExtensions.ticketSupported && c.vers >= VersionTLS13 {
Steven Valdez143e8b32016-07-11 13:19:03 -04001318 return errors.New("tls: server advertised ticket extension over TLS 1.3")
1319 }
1320
Steven Valdeza833c352016-11-01 13:39:36 -04001321 if serverExtensions.ocspStapling && c.vers >= VersionTLS13 {
1322 return errors.New("tls: server advertised OCSP in ServerHello over TLS 1.3")
1323 }
1324
David Benjamin53210cb2016-11-16 09:01:48 +09001325 if serverExtensions.ocspStapling && c.config.Bugs.NoOCSPStapling {
1326 return errors.New("tls: server advertised unrequested OCSP extension")
1327 }
1328
Steven Valdeza833c352016-11-01 13:39:36 -04001329 if len(serverExtensions.sctList) > 0 && c.vers >= VersionTLS13 {
1330 return errors.New("tls: server advertised SCTs in ServerHello over TLS 1.3")
1331 }
1332
David Benjamin53210cb2016-11-16 09:01:48 +09001333 if len(serverExtensions.sctList) > 0 && c.config.Bugs.NoSignedCertificateTimestamps {
1334 return errors.New("tls: server advertised unrequested SCTs")
1335 }
1336
David Benjamin75101402016-07-01 13:40:23 -04001337 if serverExtensions.srtpProtectionProfile != 0 {
1338 if serverExtensions.srtpMasterKeyIdentifier != "" {
1339 return errors.New("tls: server selected SRTP MKI value")
1340 }
1341
1342 found := false
1343 for _, p := range c.config.SRTPProtectionProfiles {
1344 if p == serverExtensions.srtpProtectionProfile {
1345 found = true
1346 break
1347 }
1348 }
1349 if !found {
1350 return errors.New("tls: server advertised unsupported SRTP profile")
1351 }
1352
1353 c.srtpProtectionProfile = serverExtensions.srtpProtectionProfile
1354 }
1355
Steven Valdez2d850622017-01-11 11:34:52 -05001356 if c.vers >= VersionTLS13 && c.didResume {
1357 if c.config.Bugs.ExpectEarlyDataAccepted && !serverExtensions.hasEarlyData {
1358 c.sendAlert(alertHandshakeFailure)
1359 return errors.New("tls: server did not accept early data when expected")
1360 }
1361
1362 if !c.config.Bugs.ExpectEarlyDataAccepted && serverExtensions.hasEarlyData {
1363 c.sendAlert(alertHandshakeFailure)
1364 return errors.New("tls: server accepted early data when not expected")
1365 }
1366 }
1367
David Benjamin75101402016-07-01 13:40:23 -04001368 return nil
1369}
1370
Adam Langley95c29f32014-06-20 12:00:00 -07001371func (hs *clientHandshakeState) serverResumedSession() bool {
1372 // If the server responded with the same sessionId then it means the
1373 // sessionTicket is being used to resume a TLS session.
David Benjamind4c349b2017-02-09 14:07:17 -05001374 //
1375 // Note that, if hs.hello.sessionId is a non-nil empty array, this will
1376 // accept an empty session ID from the server as resumption. See
1377 // EmptyTicketSessionID.
Adam Langley95c29f32014-06-20 12:00:00 -07001378 return hs.session != nil && hs.hello.sessionId != nil &&
1379 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
1380}
1381
1382func (hs *clientHandshakeState) processServerHello() (bool, error) {
1383 c := hs.c
1384
Adam Langley95c29f32014-06-20 12:00:00 -07001385 if hs.serverResumedSession() {
David Benjamin4b27d9f2015-05-12 22:42:52 -04001386 // For test purposes, assert that the server never accepts the
1387 // resumption offer on renegotiation.
1388 if c.cipherSuite != nil && c.config.Bugs.FailIfResumeOnRenego {
1389 return false, errors.New("tls: server resumed session on renegotiation")
1390 }
1391
Nick Harperb3d51be2016-07-01 11:43:18 -04001392 if hs.serverHello.extensions.sctList != nil {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001393 return false, errors.New("tls: server sent SCT extension on session resumption")
1394 }
1395
Nick Harperb3d51be2016-07-01 11:43:18 -04001396 if hs.serverHello.extensions.ocspStapling {
Paul Lietar62be8ac2015-09-16 10:03:30 +01001397 return false, errors.New("tls: server sent OCSP extension on session resumption")
1398 }
1399
Adam Langley95c29f32014-06-20 12:00:00 -07001400 // Restore masterSecret and peerCerts from previous state
1401 hs.masterSecret = hs.session.masterSecret
1402 c.peerCertificates = hs.session.serverCertificates
Adam Langley75712922014-10-10 16:23:43 -07001403 c.extendedMasterSecret = hs.session.extendedMasterSecret
Paul Lietar62be8ac2015-09-16 10:03:30 +01001404 c.sctList = hs.session.sctList
1405 c.ocspResponse = hs.session.ocspResponse
David Benjamine098ec22014-08-27 23:13:20 -04001406 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001407 return true, nil
1408 }
Paul Lietar62be8ac2015-09-16 10:03:30 +01001409
Nick Harperb3d51be2016-07-01 11:43:18 -04001410 if hs.serverHello.extensions.sctList != nil {
1411 c.sctList = hs.serverHello.extensions.sctList
Paul Lietar62be8ac2015-09-16 10:03:30 +01001412 }
1413
Adam Langley95c29f32014-06-20 12:00:00 -07001414 return false, nil
1415}
1416
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001417func (hs *clientHandshakeState) readFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001418 c := hs.c
1419
1420 c.readRecord(recordTypeChangeCipherSpec)
1421 if err := c.in.error(); err != nil {
1422 return err
1423 }
1424
1425 msg, err := c.readHandshake()
1426 if err != nil {
1427 return err
1428 }
1429 serverFinished, ok := msg.(*finishedMsg)
1430 if !ok {
1431 c.sendAlert(alertUnexpectedMessage)
1432 return unexpectedMessageError(serverFinished, msg)
1433 }
1434
David Benjaminf3ec83d2014-07-21 22:42:34 -04001435 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
1436 verify := hs.finishedHash.serverSum(hs.masterSecret)
1437 if len(verify) != len(serverFinished.verifyData) ||
1438 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
1439 c.sendAlert(alertHandshakeFailure)
1440 return errors.New("tls: server's Finished message was incorrect")
1441 }
Adam Langley95c29f32014-06-20 12:00:00 -07001442 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001443 c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001444 copy(out, serverFinished.verifyData)
David Benjamin83c0bc92014-08-04 01:23:53 -04001445 hs.writeServerHash(serverFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001446 return nil
1447}
1448
1449func (hs *clientHandshakeState) readSessionTicket() error {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001450 c := hs.c
1451
1452 // Create a session with no server identifier. Either a
1453 // session ID or session ticket will be attached.
1454 session := &ClientSessionState{
1455 vers: c.vers,
1456 cipherSuite: hs.suite.id,
1457 masterSecret: hs.masterSecret,
Nick Harperc9846112016-10-17 15:05:35 -07001458 handshakeHash: hs.finishedHash.Sum(),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001459 serverCertificates: c.peerCertificates,
Paul Lietar62be8ac2015-09-16 10:03:30 +01001460 sctList: c.sctList,
1461 ocspResponse: c.ocspResponse,
Nick Harper0b3625b2016-07-25 16:16:28 -07001462 ticketExpiration: c.config.time().Add(time.Duration(7 * 24 * time.Hour)),
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001463 }
1464
Nick Harperb3d51be2016-07-01 11:43:18 -04001465 if !hs.serverHello.extensions.ticketSupported {
David Benjamind98452d2015-06-16 14:16:23 -04001466 if c.config.Bugs.ExpectNewTicket {
1467 return errors.New("tls: expected new ticket")
1468 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001469 if hs.session == nil && len(hs.serverHello.sessionId) > 0 {
1470 session.sessionId = hs.serverHello.sessionId
1471 hs.session = session
1472 }
Adam Langley95c29f32014-06-20 12:00:00 -07001473 return nil
1474 }
1475
David Benjaminc7ce9772015-10-09 19:32:41 -04001476 if c.vers == VersionSSL30 {
1477 return errors.New("tls: negotiated session tickets in SSL 3.0")
1478 }
1479
Adam Langley95c29f32014-06-20 12:00:00 -07001480 msg, err := c.readHandshake()
1481 if err != nil {
1482 return err
1483 }
1484 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
1485 if !ok {
1486 c.sendAlert(alertUnexpectedMessage)
1487 return unexpectedMessageError(sessionTicketMsg, msg)
1488 }
Adam Langley95c29f32014-06-20 12:00:00 -07001489
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001490 session.sessionTicket = sessionTicketMsg.ticket
1491 hs.session = session
Adam Langley95c29f32014-06-20 12:00:00 -07001492
David Benjamind30a9902014-08-24 01:44:23 -04001493 hs.writeServerHash(sessionTicketMsg.marshal())
1494
Adam Langley95c29f32014-06-20 12:00:00 -07001495 return nil
1496}
1497
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001498func (hs *clientHandshakeState) sendFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001499 c := hs.c
1500
David Benjamin0b8d5da2016-07-15 00:39:56 -04001501 var postCCSMsgs [][]byte
David Benjamin83c0bc92014-08-04 01:23:53 -04001502 seqno := hs.c.sendHandshakeSeq
Nick Harperb3d51be2016-07-01 11:43:18 -04001503 if hs.serverHello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001504 nextProto := new(nextProtoMsg)
Nick Harperb3d51be2016-07-01 11:43:18 -04001505 proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.extensions.nextProtos)
Adam Langley95c29f32014-06-20 12:00:00 -07001506 nextProto.proto = proto
1507 c.clientProtocol = proto
1508 c.clientProtocolFallback = fallback
1509
David Benjamin86271ee2014-07-21 16:14:03 -04001510 nextProtoBytes := nextProto.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -04001511 hs.writeHash(nextProtoBytes, seqno)
1512 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001513 postCCSMsgs = append(postCCSMsgs, nextProtoBytes)
Adam Langley95c29f32014-06-20 12:00:00 -07001514 }
1515
Nick Harperb3d51be2016-07-01 11:43:18 -04001516 if hs.serverHello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001517 var resumeHash []byte
1518 if isResume {
1519 resumeHash = hs.session.handshakeHash
1520 }
Nick Harper60a85cb2016-09-23 16:25:11 -07001521 channelIDMsgBytes, err := hs.writeChannelIDMessage(hs.finishedHash.hashForChannelID(resumeHash))
David Benjamind30a9902014-08-24 01:44:23 -04001522 if err != nil {
1523 return err
1524 }
David Benjamin24599a82016-06-30 18:56:53 -04001525 hs.writeHash(channelIDMsgBytes, seqno)
David Benjamind30a9902014-08-24 01:44:23 -04001526 seqno++
David Benjamin0b8d5da2016-07-15 00:39:56 -04001527 postCCSMsgs = append(postCCSMsgs, channelIDMsgBytes)
David Benjamind30a9902014-08-24 01:44:23 -04001528 }
1529
Adam Langley95c29f32014-06-20 12:00:00 -07001530 finished := new(finishedMsg)
David Benjaminf3ec83d2014-07-21 22:42:34 -04001531 if c.config.Bugs.EarlyChangeCipherSpec == 2 {
1532 finished.verifyData = hs.finishedHash.clientSum(nil)
1533 } else {
1534 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
1535 }
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001536 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001537 if c.config.Bugs.BadFinished {
1538 finished.verifyData[0]++
1539 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001540 c.clientVerify = append(c.clientVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001541 hs.finishedBytes = finished.marshal()
1542 hs.writeHash(hs.finishedBytes, seqno)
David Benjamin0b8d5da2016-07-15 00:39:56 -04001543 postCCSMsgs = append(postCCSMsgs, hs.finishedBytes)
David Benjamin86271ee2014-07-21 16:14:03 -04001544
1545 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001546 c.writeRecord(recordTypeHandshake, postCCSMsgs[0][:5])
1547 postCCSMsgs[0] = postCCSMsgs[0][5:]
David Benjamin61672812016-07-14 23:10:43 -04001548 } else if c.config.Bugs.SendUnencryptedFinished {
David Benjamin0b8d5da2016-07-15 00:39:56 -04001549 c.writeRecord(recordTypeHandshake, postCCSMsgs[0])
1550 postCCSMsgs = postCCSMsgs[1:]
David Benjamin86271ee2014-07-21 16:14:03 -04001551 }
David Benjamin582ba042016-07-07 12:33:25 -07001552 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001553
1554 if !c.config.Bugs.SkipChangeCipherSpec &&
1555 c.config.Bugs.EarlyChangeCipherSpec == 0 {
David Benjamin8411b242015-11-26 12:07:28 -05001556 ccs := []byte{1}
1557 if c.config.Bugs.BadChangeCipherSpec != nil {
1558 ccs = c.config.Bugs.BadChangeCipherSpec
1559 }
1560 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamin86271ee2014-07-21 16:14:03 -04001561 }
1562
David Benjamin4189bd92015-01-25 23:52:39 -05001563 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1564 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1565 }
David Benjamindc3da932015-03-12 15:09:02 -04001566 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1567 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1568 return errors.New("tls: simulating post-CCS alert")
1569 }
David Benjamin4189bd92015-01-25 23:52:39 -05001570
David Benjamin0b8d5da2016-07-15 00:39:56 -04001571 if !c.config.Bugs.SkipFinished {
1572 for _, msg := range postCCSMsgs {
1573 c.writeRecord(recordTypeHandshake, msg)
1574 }
David Benjamin02edcd02016-07-27 17:40:37 -04001575
1576 if c.config.Bugs.SendExtraFinished {
1577 c.writeRecord(recordTypeHandshake, finished.marshal())
1578 }
1579
David Benjamin582ba042016-07-07 12:33:25 -07001580 c.flushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -05001581 }
Adam Langley95c29f32014-06-20 12:00:00 -07001582 return nil
1583}
1584
Nick Harper60a85cb2016-09-23 16:25:11 -07001585func (hs *clientHandshakeState) writeChannelIDMessage(channelIDHash []byte) ([]byte, error) {
1586 c := hs.c
1587 channelIDMsg := new(channelIDMsg)
1588 if c.config.ChannelID.Curve != elliptic.P256() {
1589 return nil, fmt.Errorf("tls: Channel ID is not on P-256.")
1590 }
1591 r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, channelIDHash)
1592 if err != nil {
1593 return nil, err
1594 }
1595 channelID := make([]byte, 128)
1596 writeIntPadded(channelID[0:32], c.config.ChannelID.X)
1597 writeIntPadded(channelID[32:64], c.config.ChannelID.Y)
1598 writeIntPadded(channelID[64:96], r)
1599 writeIntPadded(channelID[96:128], s)
1600 if c.config.Bugs.InvalidChannelIDSignature {
1601 channelID[64] ^= 1
1602 }
1603 channelIDMsg.channelID = channelID
1604
1605 c.channelID = &c.config.ChannelID.PublicKey
1606
1607 return channelIDMsg.marshal(), nil
1608}
1609
David Benjamin83c0bc92014-08-04 01:23:53 -04001610func (hs *clientHandshakeState) writeClientHash(msg []byte) {
1611 // writeClientHash is called before writeRecord.
1612 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1613}
1614
1615func (hs *clientHandshakeState) writeServerHash(msg []byte) {
1616 // writeServerHash is called after readHandshake.
1617 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1618}
1619
1620func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) {
1621 if hs.c.isDTLS {
1622 // This is somewhat hacky. DTLS hashes a slightly different format.
1623 // First, the TLS header.
1624 hs.finishedHash.Write(msg[:4])
1625 // Then the sequence number and reassembled fragment offset (always 0).
1626 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1627 // Then the reassembled fragment (always equal to the message length).
1628 hs.finishedHash.Write(msg[1:4])
1629 // And then the message body.
1630 hs.finishedHash.Write(msg[4:])
1631 } else {
1632 hs.finishedHash.Write(msg)
1633 }
1634}
1635
David Benjamina6f82632016-07-01 18:44:02 -04001636// selectClientCertificate selects a certificate for use with the given
1637// certificate, or none if none match. It may return a particular certificate or
1638// nil on success, or an error on internal error.
1639func selectClientCertificate(c *Conn, certReq *certificateRequestMsg) (*Certificate, error) {
1640 // RFC 4346 on the certificateAuthorities field:
1641 // A list of the distinguished names of acceptable certificate
1642 // authorities. These distinguished names may specify a desired
1643 // distinguished name for a root CA or for a subordinate CA; thus, this
1644 // message can be used to describe both known roots and a desired
1645 // authorization space. If the certificate_authorities list is empty
1646 // then the client MAY send any certificate of the appropriate
1647 // ClientCertificateType, unless there is some external arrangement to
1648 // the contrary.
1649
1650 var rsaAvail, ecdsaAvail bool
Nick Harperb41d2e42016-07-01 17:50:32 -04001651 if !certReq.hasRequestContext {
1652 for _, certType := range certReq.certificateTypes {
1653 switch certType {
1654 case CertTypeRSASign:
1655 rsaAvail = true
1656 case CertTypeECDSASign:
1657 ecdsaAvail = true
1658 }
David Benjamina6f82632016-07-01 18:44:02 -04001659 }
1660 }
1661
1662 // We need to search our list of client certs for one
1663 // where SignatureAlgorithm is RSA and the Issuer is in
1664 // certReq.certificateAuthorities
1665findCert:
1666 for i, chain := range c.config.Certificates {
Nick Harperb41d2e42016-07-01 17:50:32 -04001667 if !certReq.hasRequestContext && !rsaAvail && !ecdsaAvail {
David Benjamina6f82632016-07-01 18:44:02 -04001668 continue
1669 }
1670
1671 // Ensure the private key supports one of the advertised
1672 // signature algorithms.
1673 if certReq.hasSignatureAlgorithm {
David Benjamin0a8deb22016-07-09 21:02:01 -07001674 if _, err := selectSignatureAlgorithm(c.vers, chain.PrivateKey, c.config, certReq.signatureAlgorithms); err != nil {
David Benjamina6f82632016-07-01 18:44:02 -04001675 continue
1676 }
1677 }
1678
1679 for j, cert := range chain.Certificate {
1680 x509Cert := chain.Leaf
1681 // parse the certificate if this isn't the leaf
1682 // node, or if chain.Leaf was nil
1683 if j != 0 || x509Cert == nil {
1684 var err error
1685 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
1686 c.sendAlert(alertInternalError)
1687 return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
1688 }
1689 }
1690
Nick Harperb41d2e42016-07-01 17:50:32 -04001691 if !certReq.hasRequestContext {
1692 switch {
1693 case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
1694 case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
1695 default:
1696 continue findCert
1697 }
David Benjamina6f82632016-07-01 18:44:02 -04001698 }
1699
Adam Langley2ff79332017-02-28 13:45:39 -08001700 if expected := c.config.Bugs.ExpectCertificateReqNames; expected != nil {
1701 if !eqByteSlices(expected, certReq.certificateAuthorities) {
1702 return nil, fmt.Errorf("tls: CertificateRequest names differed, got %#v but expected %#v", certReq.certificateAuthorities, expected)
David Benjamina6f82632016-07-01 18:44:02 -04001703 }
1704 }
Adam Langley2ff79332017-02-28 13:45:39 -08001705
1706 return &chain, nil
David Benjamina6f82632016-07-01 18:44:02 -04001707 }
1708 }
1709
1710 return nil, nil
1711}
1712
Adam Langley95c29f32014-06-20 12:00:00 -07001713// clientSessionCacheKey returns a key used to cache sessionTickets that could
1714// be used to resume previously negotiated TLS sessions with a server.
1715func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
1716 if len(config.ServerName) > 0 {
1717 return config.ServerName
1718 }
1719 return serverAddr.String()
1720}
1721
David Benjaminfa055a22014-09-15 16:51:51 -04001722// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
1723// given list of possible protocols and a list of the preference order. The
1724// first list must not be empty. It returns the resulting protocol and flag
Adam Langley95c29f32014-06-20 12:00:00 -07001725// indicating if the fallback case was reached.
David Benjaminfa055a22014-09-15 16:51:51 -04001726func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
1727 for _, s := range preferenceProtos {
1728 for _, c := range protos {
Adam Langley95c29f32014-06-20 12:00:00 -07001729 if s == c {
1730 return s, false
1731 }
1732 }
1733 }
1734
David Benjaminfa055a22014-09-15 16:51:51 -04001735 return protos[0], true
Adam Langley95c29f32014-06-20 12:00:00 -07001736}
David Benjamind30a9902014-08-24 01:44:23 -04001737
1738// writeIntPadded writes x into b, padded up with leading zeros as
1739// needed.
1740func writeIntPadded(b []byte, x *big.Int) {
1741 for i := range b {
1742 b[i] = 0
1743 }
1744 xb := x.Bytes()
1745 copy(b[len(b)-len(xb):], xb)
1746}
Steven Valdeza833c352016-11-01 13:39:36 -04001747
1748func generatePSKBinders(hello *clientHelloMsg, pskCipherSuite *cipherSuite, psk, transcript []byte, config *Config) {
1749 if config.Bugs.SendNoPSKBinder {
1750 return
1751 }
1752
1753 binderLen := pskCipherSuite.hash().Size()
1754 if config.Bugs.SendShortPSKBinder {
1755 binderLen--
1756 }
1757
David Benjaminaedf3032016-12-01 16:47:56 -05001758 numBinders := 1
1759 if config.Bugs.SendExtraPSKBinder {
1760 numBinders++
1761 }
1762
Steven Valdeza833c352016-11-01 13:39:36 -04001763 // Fill hello.pskBinders with appropriate length arrays of zeros so the
1764 // length prefixes are correct when computing the binder over the truncated
1765 // ClientHello message.
David Benjaminaedf3032016-12-01 16:47:56 -05001766 hello.pskBinders = make([][]byte, numBinders)
1767 for i := range hello.pskBinders {
Steven Valdeza833c352016-11-01 13:39:36 -04001768 hello.pskBinders[i] = make([]byte, binderLen)
1769 }
1770
1771 helloBytes := hello.marshal()
1772 binderSize := len(hello.pskBinders)*(binderLen+1) + 2
1773 truncatedHello := helloBytes[:len(helloBytes)-binderSize]
1774 binder := computePSKBinder(psk, resumptionPSKBinderLabel, pskCipherSuite, transcript, truncatedHello)
1775 if config.Bugs.SendShortPSKBinder {
1776 binder = binder[:binderLen]
1777 }
1778 if config.Bugs.SendInvalidPSKBinder {
1779 binder[0] ^= 1
1780 }
1781
1782 for i := range hello.pskBinders {
1783 hello.pskBinders[i] = binder
1784 }
1785
1786 hello.raw = nil
1787}