blob: 91471347030a04e794db536344f08fcec23e5dc1 [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 (
David Benjamin83c0bc92014-08-04 01:23:53 -04008 "bytes"
Adam Langley95c29f32014-06-20 12:00:00 -07009 "crypto"
10 "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 Benjamind30a9902014-08-24 01:44:23 -040018 "math/big"
Adam Langley95c29f32014-06-20 12:00:00 -070019)
20
21// serverHandshakeState contains details of a server handshake in progress.
22// It's discarded once the handshake has completed.
23type serverHandshakeState struct {
24 c *Conn
25 clientHello *clientHelloMsg
26 hello *serverHelloMsg
27 suite *cipherSuite
28 ellipticOk bool
29 ecdsaOk bool
30 sessionState *sessionState
31 finishedHash finishedHash
32 masterSecret []byte
33 certsFromClient [][]byte
34 cert *Certificate
David Benjamin83f90402015-01-27 01:09:43 -050035 finishedBytes []byte
Adam Langley95c29f32014-06-20 12:00:00 -070036}
37
38// serverHandshake performs a TLS handshake as a server.
39func (c *Conn) serverHandshake() error {
40 config := c.config
41
42 // If this is the first server handshake, we generate a random key to
43 // encrypt the tickets with.
44 config.serverInitOnce.Do(config.serverInit)
45
David Benjamin83c0bc92014-08-04 01:23:53 -040046 c.sendHandshakeSeq = 0
47 c.recvHandshakeSeq = 0
48
Adam Langley95c29f32014-06-20 12:00:00 -070049 hs := serverHandshakeState{
50 c: c,
51 }
David Benjaminf25dda92016-07-04 10:05:26 -070052 if err := hs.readClientHello(); err != nil {
53 return err
54 }
Adam Langley95c29f32014-06-20 12:00:00 -070055
David Benjamin8d315d72016-07-18 01:03:18 +020056 if c.vers >= VersionTLS13 {
Nick Harper728eed82016-07-07 17:36:52 -070057 if err := hs.doTLS13Handshake(); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -070058 return err
59 }
Nick Harper728eed82016-07-07 17:36:52 -070060 } else {
61 isResume, err := hs.processClientHello()
62 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -070063 return err
64 }
Nick Harper728eed82016-07-07 17:36:52 -070065
66 // For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3
67 if isResume {
68 // The client has included a session ticket and so we do an abbreviated handshake.
69 if err := hs.doResumeHandshake(); err != nil {
70 return err
71 }
72 if err := hs.establishKeys(); err != nil {
73 return err
74 }
75 if c.config.Bugs.RenewTicketOnResume {
76 if err := hs.sendSessionTicket(); err != nil {
77 return err
78 }
79 }
80 if err := hs.sendFinished(c.firstFinished[:]); err != nil {
81 return err
82 }
83 // Most retransmits are triggered by a timeout, but the final
84 // leg of the handshake is retransmited upon re-receiving a
85 // Finished.
86 if err := c.simulatePacketLoss(func() {
David Benjamin02edcd02016-07-27 17:40:37 -040087 c.sendHandshakeSeq--
Nick Harper728eed82016-07-07 17:36:52 -070088 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
89 c.flushHandshake()
90 }); err != nil {
91 return err
92 }
93 if err := hs.readFinished(nil, isResume); err != nil {
94 return err
95 }
96 c.didResume = true
97 } else {
98 // The client didn't include a session ticket, or it wasn't
99 // valid so we do a full handshake.
100 if err := hs.doFullHandshake(); err != nil {
101 return err
102 }
103 if err := hs.establishKeys(); err != nil {
104 return err
105 }
106 if err := hs.readFinished(c.firstFinished[:], isResume); err != nil {
107 return err
108 }
109 if c.config.Bugs.AlertBeforeFalseStartTest != 0 {
110 c.sendAlert(c.config.Bugs.AlertBeforeFalseStartTest)
111 }
112 if c.config.Bugs.ExpectFalseStart {
113 if err := c.readRecord(recordTypeApplicationData); err != nil {
114 return fmt.Errorf("tls: peer did not false start: %s", err)
115 }
116 }
David Benjaminbed9aae2014-08-07 19:13:38 -0400117 if err := hs.sendSessionTicket(); err != nil {
118 return err
119 }
Nick Harper728eed82016-07-07 17:36:52 -0700120 if err := hs.sendFinished(nil); err != nil {
121 return err
David Benjamine58c4f52014-08-24 03:47:07 -0400122 }
123 }
David Benjamin97a0a082016-07-13 17:57:35 -0400124
125 c.exporterSecret = hs.masterSecret
Adam Langley95c29f32014-06-20 12:00:00 -0700126 }
127 c.handshakeComplete = true
David Benjaminc565ebb2015-04-03 04:06:36 -0400128 copy(c.clientRandom[:], hs.clientHello.random)
129 copy(c.serverRandom[:], hs.hello.random)
Adam Langley95c29f32014-06-20 12:00:00 -0700130
131 return nil
132}
133
David Benjaminf25dda92016-07-04 10:05:26 -0700134// readClientHello reads a ClientHello message from the client and determines
135// the protocol version.
136func (hs *serverHandshakeState) readClientHello() error {
Adam Langley95c29f32014-06-20 12:00:00 -0700137 config := hs.c.config
138 c := hs.c
139
David Benjamin83f90402015-01-27 01:09:43 -0500140 if err := c.simulatePacketLoss(nil); err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700141 return err
David Benjamin83f90402015-01-27 01:09:43 -0500142 }
Adam Langley95c29f32014-06-20 12:00:00 -0700143 msg, err := c.readHandshake()
144 if err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700145 return err
Adam Langley95c29f32014-06-20 12:00:00 -0700146 }
147 var ok bool
148 hs.clientHello, ok = msg.(*clientHelloMsg)
149 if !ok {
150 c.sendAlert(alertUnexpectedMessage)
David Benjaminf25dda92016-07-04 10:05:26 -0700151 return unexpectedMessageError(hs.clientHello, msg)
Adam Langley95c29f32014-06-20 12:00:00 -0700152 }
Adam Langley33ad2b52015-07-20 17:43:53 -0700153 if size := config.Bugs.RequireClientHelloSize; size != 0 && len(hs.clientHello.raw) != size {
David Benjaminf25dda92016-07-04 10:05:26 -0700154 return fmt.Errorf("tls: ClientHello record size is %d, but expected %d", len(hs.clientHello.raw), size)
Feng Lu41aa3252014-11-21 22:47:56 -0800155 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400156
157 if c.isDTLS && !config.Bugs.SkipHelloVerifyRequest {
David Benjamin8bc38f52014-08-16 12:07:27 -0400158 // Per RFC 6347, the version field in HelloVerifyRequest SHOULD
159 // be always DTLS 1.0
David Benjamin83c0bc92014-08-04 01:23:53 -0400160 helloVerifyRequest := &helloVerifyRequestMsg{
David Benjamin8bc38f52014-08-16 12:07:27 -0400161 vers: VersionTLS10,
David Benjamin83c0bc92014-08-04 01:23:53 -0400162 cookie: make([]byte, 32),
163 }
164 if _, err := io.ReadFull(c.config.rand(), helloVerifyRequest.cookie); err != nil {
165 c.sendAlert(alertInternalError)
David Benjaminf25dda92016-07-04 10:05:26 -0700166 return errors.New("dtls: short read from Rand: " + err.Error())
David Benjamin83c0bc92014-08-04 01:23:53 -0400167 }
168 c.writeRecord(recordTypeHandshake, helloVerifyRequest.marshal())
David Benjamin582ba042016-07-07 12:33:25 -0700169 c.flushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400170
David Benjamin83f90402015-01-27 01:09:43 -0500171 if err := c.simulatePacketLoss(nil); err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700172 return err
David Benjamin83f90402015-01-27 01:09:43 -0500173 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400174 msg, err := c.readHandshake()
175 if err != nil {
David Benjaminf25dda92016-07-04 10:05:26 -0700176 return err
David Benjamin83c0bc92014-08-04 01:23:53 -0400177 }
178 newClientHello, ok := msg.(*clientHelloMsg)
179 if !ok {
180 c.sendAlert(alertUnexpectedMessage)
David Benjaminf25dda92016-07-04 10:05:26 -0700181 return unexpectedMessageError(hs.clientHello, msg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400182 }
183 if !bytes.Equal(newClientHello.cookie, helloVerifyRequest.cookie) {
David Benjaminf25dda92016-07-04 10:05:26 -0700184 return errors.New("dtls: invalid cookie")
David Benjamin83c0bc92014-08-04 01:23:53 -0400185 }
David Benjaminf2fedef2014-08-16 01:37:34 -0400186
187 // Apart from the cookie, the two ClientHellos must
188 // match. Note that clientHello.equal compares the
189 // serialization, so we make a copy.
190 oldClientHelloCopy := *hs.clientHello
191 oldClientHelloCopy.raw = nil
192 oldClientHelloCopy.cookie = nil
193 newClientHelloCopy := *newClientHello
194 newClientHelloCopy.raw = nil
195 newClientHelloCopy.cookie = nil
196 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
David Benjaminf25dda92016-07-04 10:05:26 -0700197 return errors.New("dtls: retransmitted ClientHello does not match")
David Benjamin83c0bc92014-08-04 01:23:53 -0400198 }
199 hs.clientHello = newClientHello
200 }
201
David Benjaminc44b1df2014-11-23 12:11:01 -0500202 if config.Bugs.RequireSameRenegoClientVersion && c.clientVersion != 0 {
203 if c.clientVersion != hs.clientHello.vers {
David Benjaminf25dda92016-07-04 10:05:26 -0700204 return fmt.Errorf("tls: client offered different version on renego")
David Benjaminc44b1df2014-11-23 12:11:01 -0500205 }
206 }
Steven Valdezfdd10992016-09-15 16:27:05 -0400207
David Benjaminc44b1df2014-11-23 12:11:01 -0500208 c.clientVersion = hs.clientHello.vers
Steven Valdezfdd10992016-09-15 16:27:05 -0400209
210 // Convert the ClientHello wire version to a protocol version.
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400211 var clientVersion uint16
212 if c.isDTLS {
213 if hs.clientHello.vers <= 0xfefd {
214 clientVersion = VersionTLS12
215 } else if hs.clientHello.vers <= 0xfeff {
216 clientVersion = VersionTLS10
217 }
218 } else {
Steven Valdezfdd10992016-09-15 16:27:05 -0400219 if hs.clientHello.vers >= VersionTLS12 {
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400220 clientVersion = VersionTLS12
221 } else if hs.clientHello.vers >= VersionTLS11 {
222 clientVersion = VersionTLS11
223 } else if hs.clientHello.vers >= VersionTLS10 {
224 clientVersion = VersionTLS10
225 } else if hs.clientHello.vers >= VersionSSL30 {
226 clientVersion = VersionSSL30
227 }
228 }
229
230 if config.Bugs.NegotiateVersion != 0 {
231 c.vers = config.Bugs.NegotiateVersion
232 } else if c.haveVers && config.Bugs.NegotiateVersionOnRenego != 0 {
233 c.vers = config.Bugs.NegotiateVersionOnRenego
Steven Valdezfdd10992016-09-15 16:27:05 -0400234 } else if len(hs.clientHello.supportedVersions) > 0 {
235 // Use the versions extension if supplied.
David Benjamind9791bf2016-09-27 16:39:52 -0400236 var foundVersion, foundGREASE bool
Steven Valdezfdd10992016-09-15 16:27:05 -0400237 for _, extVersion := range hs.clientHello.supportedVersions {
David Benjamind9791bf2016-09-27 16:39:52 -0400238 if isGREASEValue(extVersion) {
239 foundGREASE = true
240 }
Steven Valdezfdd10992016-09-15 16:27:05 -0400241 extVersion, ok = wireToVersion(extVersion, c.isDTLS)
242 if !ok {
243 continue
244 }
David Benjamind9791bf2016-09-27 16:39:52 -0400245 if config.isSupportedVersion(extVersion, c.isDTLS) && !foundVersion {
Steven Valdezfdd10992016-09-15 16:27:05 -0400246 c.vers = extVersion
247 foundVersion = true
248 break
249 }
250 }
251 if !foundVersion {
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400252 c.sendAlert(alertProtocolVersion)
Steven Valdezfdd10992016-09-15 16:27:05 -0400253 return errors.New("tls: client did not offer any supported protocol versions")
254 }
David Benjamind9791bf2016-09-27 16:39:52 -0400255 if config.Bugs.ExpectGREASE && !foundGREASE {
256 return errors.New("tls: no GREASE version value found")
257 }
Steven Valdezfdd10992016-09-15 16:27:05 -0400258 } else {
259 // Otherwise, use the legacy ClientHello version.
260 version := clientVersion
261 if maxVersion := config.maxVersion(c.isDTLS); version > maxVersion {
262 version = maxVersion
263 }
264 if version == 0 || !config.isSupportedVersion(version, c.isDTLS) {
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400265 return fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
266 }
Steven Valdezfdd10992016-09-15 16:27:05 -0400267 c.vers = version
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400268 }
269 c.haveVers = true
David Benjaminc44b1df2014-11-23 12:11:01 -0500270
David Benjamin6ae7f072015-01-26 10:22:13 -0500271 // Reject < 1.2 ClientHellos with signature_algorithms.
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400272 if clientVersion < VersionTLS12 && len(hs.clientHello.signatureAlgorithms) > 0 {
David Benjaminf25dda92016-07-04 10:05:26 -0700273 return fmt.Errorf("tls: client included signature_algorithms before TLS 1.2")
David Benjamin72dc7832015-03-16 17:49:43 -0400274 }
David Benjamin6ae7f072015-01-26 10:22:13 -0500275
David Benjaminf93995b2015-11-05 18:23:20 -0500276 // Check the client cipher list is consistent with the version.
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400277 if clientVersion < VersionTLS12 {
David Benjaminf93995b2015-11-05 18:23:20 -0500278 for _, id := range hs.clientHello.cipherSuites {
279 if isTLS12Cipher(id) {
David Benjaminf25dda92016-07-04 10:05:26 -0700280 return fmt.Errorf("tls: client offered TLS 1.2 cipher before TLS 1.2")
David Benjaminf93995b2015-11-05 18:23:20 -0500281 }
282 }
283 }
284
David Benjamin405da482016-08-08 17:25:07 -0400285 if config.Bugs.ExpectNoTLS12Session {
286 if len(hs.clientHello.sessionId) > 0 {
287 return fmt.Errorf("tls: client offered an unexpected session ID")
288 }
289 if len(hs.clientHello.sessionTicket) > 0 {
290 return fmt.Errorf("tls: client offered an unexpected session ticket")
291 }
292 }
293
294 if config.Bugs.ExpectNoTLS13PSK && len(hs.clientHello.pskIdentities) > 0 {
295 return fmt.Errorf("tls: client offered unexpected PSK identities")
296 }
297
David Benjamin65ac9972016-09-02 21:35:25 -0400298 var scsvFound, greaseFound bool
David Benjaminf25dda92016-07-04 10:05:26 -0700299 for _, cipherSuite := range hs.clientHello.cipherSuites {
300 if cipherSuite == fallbackSCSV {
301 scsvFound = true
David Benjamin65ac9972016-09-02 21:35:25 -0400302 }
303 if isGREASEValue(cipherSuite) {
304 greaseFound = true
David Benjaminf25dda92016-07-04 10:05:26 -0700305 }
306 }
307
308 if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
309 return errors.New("tls: no fallback SCSV found when expected")
310 } else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
311 return errors.New("tls: fallback SCSV found when not expected")
312 }
313
David Benjamin65ac9972016-09-02 21:35:25 -0400314 if !greaseFound && config.Bugs.ExpectGREASE {
315 return errors.New("tls: no GREASE cipher suite value found")
316 }
317
318 greaseFound = false
319 for _, curve := range hs.clientHello.supportedCurves {
320 if isGREASEValue(uint16(curve)) {
321 greaseFound = true
322 break
323 }
324 }
325
326 if !greaseFound && config.Bugs.ExpectGREASE {
327 return errors.New("tls: no GREASE curve value found")
328 }
329
330 if len(hs.clientHello.keyShares) > 0 {
331 greaseFound = false
332 for _, keyShare := range hs.clientHello.keyShares {
333 if isGREASEValue(uint16(keyShare.group)) {
334 greaseFound = true
335 break
336 }
337 }
338
339 if !greaseFound && config.Bugs.ExpectGREASE {
340 return errors.New("tls: no GREASE curve value found")
341 }
342 }
343
David Benjaminf25dda92016-07-04 10:05:26 -0700344 if config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
David Benjamin7a41d372016-07-09 11:21:54 -0700345 hs.clientHello.signatureAlgorithms = config.signSignatureAlgorithms()
David Benjaminf25dda92016-07-04 10:05:26 -0700346 }
347 if config.Bugs.IgnorePeerCurvePreferences {
348 hs.clientHello.supportedCurves = config.curvePreferences()
349 }
350 if config.Bugs.IgnorePeerCipherPreferences {
351 hs.clientHello.cipherSuites = config.cipherSuites()
352 }
353
354 return nil
355}
356
Nick Harper728eed82016-07-07 17:36:52 -0700357func (hs *serverHandshakeState) doTLS13Handshake() error {
358 c := hs.c
359 config := c.config
360
361 hs.hello = &serverHelloMsg{
David Benjamin490469f2016-10-05 22:44:38 -0400362 isDTLS: c.isDTLS,
363 vers: versionToWire(c.vers, c.isDTLS),
364 versOverride: config.Bugs.SendServerHelloVersion,
365 customExtension: config.Bugs.CustomUnencryptedExtension,
366 unencryptedALPN: config.Bugs.SendUnencryptedALPN,
Steven Valdez5440fe02016-07-18 12:40:30 -0400367 }
368
Nick Harper728eed82016-07-07 17:36:52 -0700369 hs.hello.random = make([]byte, 32)
370 if _, err := io.ReadFull(config.rand(), hs.hello.random); err != nil {
371 c.sendAlert(alertInternalError)
372 return err
373 }
374
375 // TLS 1.3 forbids clients from advertising any non-null compression.
376 if len(hs.clientHello.compressionMethods) != 1 || hs.clientHello.compressionMethods[0] != compressionNone {
377 return errors.New("tls: client sent compression method other than null for TLS 1.3")
378 }
379
380 // Prepare an EncryptedExtensions message, but do not send it yet.
381 encryptedExtensions := new(encryptedExtensionsMsg)
Steven Valdez143e8b32016-07-11 13:19:03 -0400382 encryptedExtensions.empty = config.Bugs.EmptyEncryptedExtensions
Nick Harper728eed82016-07-07 17:36:52 -0700383 if err := hs.processClientExtensions(&encryptedExtensions.extensions); err != nil {
384 return err
385 }
386
387 supportedCurve := false
388 var selectedCurve CurveID
389 preferredCurves := config.curvePreferences()
390Curves:
391 for _, curve := range hs.clientHello.supportedCurves {
392 for _, supported := range preferredCurves {
393 if supported == curve {
394 supportedCurve = true
395 selectedCurve = curve
396 break Curves
397 }
398 }
399 }
400
Steven Valdez803c77a2016-09-06 14:13:43 -0400401 if !supportedCurve {
402 c.sendAlert(alertHandshakeFailure)
403 return errors.New("tls: no curve supported by both client and server")
404 }
Nick Harper728eed82016-07-07 17:36:52 -0700405
David Benjamin405da482016-08-08 17:25:07 -0400406 pskIdentities := hs.clientHello.pskIdentities
407 if len(pskIdentities) == 0 && len(hs.clientHello.sessionTicket) > 0 && c.config.Bugs.AcceptAnySession {
Steven Valdez5b986082016-09-01 12:29:49 -0400408 psk := pskIdentity{
409 keModes: []byte{pskDHEKEMode},
410 authModes: []byte{pskAuthMode},
411 ticket: hs.clientHello.sessionTicket,
412 }
413 pskIdentities = []pskIdentity{psk}
David Benjamin405da482016-08-08 17:25:07 -0400414 }
415 for i, pskIdentity := range pskIdentities {
Steven Valdez5b986082016-09-01 12:29:49 -0400416 foundKE := false
417 foundAuth := false
418
419 for _, keMode := range pskIdentity.keModes {
420 if keMode == pskDHEKEMode {
421 foundKE = true
422 }
423 }
424
425 for _, authMode := range pskIdentity.authModes {
426 if authMode == pskAuthMode {
427 foundAuth = true
428 }
429 }
430
431 if !foundKE || !foundAuth {
432 continue
433 }
434
435 sessionState, ok := c.decryptTicket(pskIdentity.ticket)
Nick Harper0b3625b2016-07-25 16:16:28 -0700436 if !ok {
437 continue
438 }
Steven Valdez803c77a2016-09-06 14:13:43 -0400439 if config.Bugs.AcceptAnySession {
440 // Replace the cipher suite with one known to work, to
441 // test cross-version resumption attempts.
442 sessionState.cipherSuite = TLS_AES_128_GCM_SHA256
443 } else {
David Benjamin405da482016-08-08 17:25:07 -0400444 if sessionState.vers != c.vers && c.config.Bugs.AcceptAnySession {
445 continue
446 }
David Benjamin405da482016-08-08 17:25:07 -0400447 if sessionState.ticketExpiration.Before(c.config.time()) {
448 continue
449 }
David Benjamin405da482016-08-08 17:25:07 -0400450
Steven Valdez803c77a2016-09-06 14:13:43 -0400451 cipherSuiteOk := false
452 // Check that the client is still offering the ciphersuite in the session.
453 for _, id := range hs.clientHello.cipherSuites {
454 if id == sessionState.cipherSuite {
455 cipherSuiteOk = true
456 break
457 }
458 }
459 if !cipherSuiteOk {
460 continue
Nick Harper0b3625b2016-07-25 16:16:28 -0700461 }
462 }
David Benjamin405da482016-08-08 17:25:07 -0400463
Steven Valdez803c77a2016-09-06 14:13:43 -0400464 // Check that we also support the ciphersuite from the session.
465 suite := c.tryCipherSuite(sessionState.cipherSuite, c.config.cipherSuites(), c.vers, true, true)
466 if suite == nil {
467 continue
Nick Harper0b3625b2016-07-25 16:16:28 -0700468 }
Steven Valdez803c77a2016-09-06 14:13:43 -0400469
470 hs.sessionState = sessionState
471 hs.suite = suite
472 hs.hello.hasPSKIdentity = true
473 hs.hello.pskIdentity = uint16(i)
David Benjamin7f78df42016-10-05 22:33:19 -0400474 if config.Bugs.SelectPSKIdentityOnResume != 0 {
475 hs.hello.pskIdentity = config.Bugs.SelectPSKIdentityOnResume
476 }
Steven Valdez803c77a2016-09-06 14:13:43 -0400477 c.didResume = true
478 break
Nick Harper728eed82016-07-07 17:36:52 -0700479 }
480
David Benjamin7f78df42016-10-05 22:33:19 -0400481 if config.Bugs.AlwaysSelectPSKIdentity {
482 hs.hello.hasPSKIdentity = true
483 hs.hello.pskIdentity = 0
484 }
485
Nick Harper0b3625b2016-07-25 16:16:28 -0700486 // If not resuming, select the cipher suite.
487 if hs.suite == nil {
488 var preferenceList, supportedList []uint16
489 if config.PreferServerCipherSuites {
490 preferenceList = config.cipherSuites()
491 supportedList = hs.clientHello.cipherSuites
492 } else {
493 preferenceList = hs.clientHello.cipherSuites
494 supportedList = config.cipherSuites()
495 }
496
497 for _, id := range preferenceList {
Steven Valdez803c77a2016-09-06 14:13:43 -0400498 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, true, true); hs.suite != nil {
Nick Harper0b3625b2016-07-25 16:16:28 -0700499 break
500 }
Nick Harper728eed82016-07-07 17:36:52 -0700501 }
502 }
503
504 if hs.suite == nil {
505 c.sendAlert(alertHandshakeFailure)
506 return errors.New("tls: no cipher suite supported by both client and server")
507 }
508
509 hs.hello.cipherSuite = hs.suite.id
Steven Valdez0ee2e112016-07-15 06:51:15 -0400510 if c.config.Bugs.SendCipherSuite != 0 {
511 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
512 }
513
Nick Harper728eed82016-07-07 17:36:52 -0700514 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
515 hs.finishedHash.discardHandshakeBuffer()
516 hs.writeClientHash(hs.clientHello.marshal())
517
Steven Valdez803c77a2016-09-06 14:13:43 -0400518 hs.hello.useCertAuth = hs.sessionState == nil
519
Nick Harper728eed82016-07-07 17:36:52 -0700520 // Resolve PSK and compute the early secret.
Nick Harper0b3625b2016-07-25 16:16:28 -0700521 var psk []byte
Steven Valdez803c77a2016-09-06 14:13:43 -0400522 if hs.sessionState != nil {
Nick Harper0b3625b2016-07-25 16:16:28 -0700523 psk = deriveResumptionPSK(hs.suite, hs.sessionState.masterSecret)
524 hs.finishedHash.setResumptionContext(deriveResumptionContext(hs.suite, hs.sessionState.masterSecret))
525 } else {
526 psk = hs.finishedHash.zeroSecret()
527 hs.finishedHash.setResumptionContext(hs.finishedHash.zeroSecret())
528 }
Nick Harper728eed82016-07-07 17:36:52 -0700529
530 earlySecret := hs.finishedHash.extractKey(hs.finishedHash.zeroSecret(), psk)
531
Steven Valdez803c77a2016-09-06 14:13:43 -0400532 if config.Bugs.OmitServerHelloSignatureAlgorithms {
533 hs.hello.useCertAuth = false
534 } else if config.Bugs.IncludeServerHelloSignatureAlgorithms {
535 hs.hello.useCertAuth = true
536 }
537
538 hs.hello.hasKeyShare = true
539 if hs.sessionState != nil && config.Bugs.NegotiatePSKResumption {
540 hs.hello.hasKeyShare = false
541 }
542 if config.Bugs.MissingKeyShare {
543 hs.hello.hasKeyShare = false
544 }
545
David Benjamin3baa6e12016-10-07 21:10:38 -0400546 firstHelloRetryRequest := true
547
548ResendHelloRetryRequest:
549 var sendHelloRetryRequest bool
550 helloRetryRequest := &helloRetryRequestMsg{
551 vers: versionToWire(c.vers, c.isDTLS),
552 duplicateExtensions: config.Bugs.DuplicateHelloRetryRequestExtensions,
553 }
554
555 if config.Bugs.AlwaysSendHelloRetryRequest {
556 sendHelloRetryRequest = true
557 }
558
559 if config.Bugs.SendHelloRetryRequestCookie != nil {
560 sendHelloRetryRequest = true
561 helloRetryRequest.cookie = config.Bugs.SendHelloRetryRequestCookie
562 }
563
564 if len(config.Bugs.CustomHelloRetryRequestExtension) > 0 {
565 sendHelloRetryRequest = true
566 helloRetryRequest.customExtension = config.Bugs.CustomHelloRetryRequestExtension
567 }
568
569 var selectedKeyShare *keyShareEntry
Steven Valdez803c77a2016-09-06 14:13:43 -0400570 if hs.hello.hasKeyShare {
Nick Harper728eed82016-07-07 17:36:52 -0700571 // Look for the key share corresponding to our selected curve.
Nick Harper728eed82016-07-07 17:36:52 -0700572 for i := range hs.clientHello.keyShares {
573 if hs.clientHello.keyShares[i].group == selectedCurve {
574 selectedKeyShare = &hs.clientHello.keyShares[i]
575 break
576 }
577 }
578
David Benjamine73c7f42016-08-17 00:29:33 -0400579 if config.Bugs.ExpectMissingKeyShare && selectedKeyShare != nil {
580 return errors.New("tls: expected missing key share")
581 }
582
David Benjamin3baa6e12016-10-07 21:10:38 -0400583 if selectedKeyShare == nil {
584 helloRetryRequest.hasSelectedGroup = true
585 helloRetryRequest.selectedGroup = selectedCurve
Steven Valdez5440fe02016-07-18 12:40:30 -0400586 sendHelloRetryRequest = true
587 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400588 }
589
590 if config.Bugs.SendHelloRetryRequestCurve != 0 {
591 helloRetryRequest.hasSelectedGroup = true
592 helloRetryRequest.selectedGroup = config.Bugs.SendHelloRetryRequestCurve
593 sendHelloRetryRequest = true
594 }
595
596 if config.Bugs.SkipHelloRetryRequest {
597 sendHelloRetryRequest = false
598 }
599
600 if sendHelloRetryRequest {
601 hs.writeServerHash(helloRetryRequest.marshal())
602 c.writeRecord(recordTypeHandshake, helloRetryRequest.marshal())
603 c.flushHandshake()
604
605 // Read new ClientHello.
606 newMsg, err := c.readHandshake()
607 if err != nil {
608 return err
Steven Valdez5440fe02016-07-18 12:40:30 -0400609 }
David Benjamin3baa6e12016-10-07 21:10:38 -0400610 newClientHello, ok := newMsg.(*clientHelloMsg)
611 if !ok {
612 c.sendAlert(alertUnexpectedMessage)
613 return unexpectedMessageError(newClientHello, newMsg)
614 }
615 hs.writeClientHash(newClientHello.marshal())
Nick Harperdcfbc672016-07-16 17:47:31 +0200616
David Benjamin3baa6e12016-10-07 21:10:38 -0400617 // Check that the new ClientHello matches the old ClientHello,
618 // except for relevant modifications.
619 //
620 // TODO(davidben): Make this check more precise.
621 oldClientHelloCopy := *hs.clientHello
622 oldClientHelloCopy.raw = nil
623 oldClientHelloCopy.hasEarlyData = false
624 oldClientHelloCopy.earlyDataContext = nil
625 newClientHelloCopy := *newClientHello
626 newClientHelloCopy.raw = nil
Nick Harperdcfbc672016-07-16 17:47:31 +0200627
David Benjamin3baa6e12016-10-07 21:10:38 -0400628 if helloRetryRequest.hasSelectedGroup {
629 newKeyShares := newClientHelloCopy.keyShares
630 if len(newKeyShares) == 0 || newKeyShares[len(newKeyShares)-1].group != helloRetryRequest.selectedGroup {
Nick Harperdcfbc672016-07-16 17:47:31 +0200631 return errors.New("tls: KeyShare from HelloRetryRequest not present in new ClientHello")
632 }
Nick Harperdcfbc672016-07-16 17:47:31 +0200633 selectedKeyShare = &newKeyShares[len(newKeyShares)-1]
David Benjamin3baa6e12016-10-07 21:10:38 -0400634 newClientHelloCopy.keyShares = newKeyShares[:len(newKeyShares)-1]
Nick Harper728eed82016-07-07 17:36:52 -0700635 }
636
David Benjamin3baa6e12016-10-07 21:10:38 -0400637 if len(helloRetryRequest.cookie) > 0 {
638 if !bytes.Equal(newClientHelloCopy.tls13Cookie, helloRetryRequest.cookie) {
639 return errors.New("tls: cookie from HelloRetryRequest not present in new ClientHello")
640 }
641 newClientHelloCopy.tls13Cookie = nil
642 }
643
644 if !oldClientHelloCopy.equal(&newClientHelloCopy) {
645 return errors.New("tls: new ClientHello does not match")
646 }
647
648 if firstHelloRetryRequest && config.Bugs.SecondHelloRetryRequest {
649 firstHelloRetryRequest = false
650 goto ResendHelloRetryRequest
651 }
652 }
653
654 // Resolve ECDHE and compute the handshake secret.
655 var ecdheSecret []byte
656 if hs.hello.hasKeyShare {
Nick Harper728eed82016-07-07 17:36:52 -0700657 // Once a curve has been selected and a key share identified,
658 // the server needs to generate a public value and send it in
659 // the ServerHello.
Steven Valdez5440fe02016-07-18 12:40:30 -0400660 curve, ok := curveForCurveID(selectedCurve)
Nick Harper728eed82016-07-07 17:36:52 -0700661 if !ok {
662 panic("tls: server failed to look up curve ID")
663 }
Steven Valdez5440fe02016-07-18 12:40:30 -0400664 c.curveID = selectedCurve
665
666 var peerKey []byte
667 if config.Bugs.SkipHelloRetryRequest {
668 // If skipping HelloRetryRequest, use a random key to
669 // avoid crashing.
670 curve2, _ := curveForCurveID(selectedCurve)
671 var err error
672 peerKey, err = curve2.offer(config.rand())
673 if err != nil {
674 return err
675 }
676 } else {
677 peerKey = selectedKeyShare.keyExchange
678 }
679
Nick Harper728eed82016-07-07 17:36:52 -0700680 var publicKey []byte
681 var err error
Steven Valdez5440fe02016-07-18 12:40:30 -0400682 publicKey, ecdheSecret, err = curve.accept(config.rand(), peerKey)
Nick Harper728eed82016-07-07 17:36:52 -0700683 if err != nil {
684 c.sendAlert(alertHandshakeFailure)
685 return err
686 }
687 hs.hello.hasKeyShare = true
Steven Valdez0ee2e112016-07-15 06:51:15 -0400688
Steven Valdez5440fe02016-07-18 12:40:30 -0400689 curveID := selectedCurve
Steven Valdez0ee2e112016-07-15 06:51:15 -0400690 if c.config.Bugs.SendCurve != 0 {
691 curveID = config.Bugs.SendCurve
692 }
693 if c.config.Bugs.InvalidECDHPoint {
694 publicKey[0] ^= 0xff
695 }
696
Nick Harper728eed82016-07-07 17:36:52 -0700697 hs.hello.keyShare = keyShareEntry{
Steven Valdez0ee2e112016-07-15 06:51:15 -0400698 group: curveID,
Nick Harper728eed82016-07-07 17:36:52 -0700699 keyExchange: publicKey,
700 }
Steven Valdez143e8b32016-07-11 13:19:03 -0400701
702 if config.Bugs.EncryptedExtensionsWithKeyShare {
703 encryptedExtensions.extensions.hasKeyShare = true
704 encryptedExtensions.extensions.keyShare = keyShareEntry{
705 group: curveID,
706 keyExchange: publicKey,
707 }
708 }
Nick Harper728eed82016-07-07 17:36:52 -0700709 } else {
710 ecdheSecret = hs.finishedHash.zeroSecret()
711 }
712
713 // Send unencrypted ServerHello.
714 hs.writeServerHash(hs.hello.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400715 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
716 helloBytes := hs.hello.marshal()
717 toWrite := make([]byte, 0, len(helloBytes)+1)
718 toWrite = append(toWrite, helloBytes...)
719 toWrite = append(toWrite, typeEncryptedExtensions)
720 c.writeRecord(recordTypeHandshake, toWrite)
721 } else {
722 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
723 }
Nick Harper728eed82016-07-07 17:36:52 -0700724 c.flushHandshake()
725
726 // Compute the handshake secret.
727 handshakeSecret := hs.finishedHash.extractKey(earlySecret, ecdheSecret)
728
729 // Switch to handshake traffic keys.
Steven Valdezc4aa7272016-10-03 12:25:56 -0400730 serverHandshakeTrafficSecret := hs.finishedHash.deriveSecret(handshakeSecret, serverHandshakeTrafficLabel)
731 c.out.useTrafficSecret(c.vers, hs.suite, serverHandshakeTrafficSecret, handshakePhase, serverWrite)
732 clientHandshakeTrafficSecret := hs.finishedHash.deriveSecret(handshakeSecret, clientHandshakeTrafficLabel)
733 c.in.useTrafficSecret(c.vers, hs.suite, clientHandshakeTrafficSecret, handshakePhase, clientWrite)
Nick Harper728eed82016-07-07 17:36:52 -0700734
Steven Valdez803c77a2016-09-06 14:13:43 -0400735 if hs.hello.useCertAuth {
David Benjamin615119a2016-07-06 19:22:55 -0700736 if hs.clientHello.ocspStapling {
737 encryptedExtensions.extensions.ocspResponse = hs.cert.OCSPStaple
738 }
739 if hs.clientHello.sctListSupported {
740 encryptedExtensions.extensions.sctList = hs.cert.SignedCertificateTimestampList
741 }
David Benjamindaa88502016-10-04 16:32:16 -0400742 } else {
743 if config.Bugs.SendOCSPResponseOnResume != nil {
744 encryptedExtensions.extensions.ocspResponse = config.Bugs.SendOCSPResponseOnResume
745 }
746 if config.Bugs.SendSCTListOnResume != nil {
747 encryptedExtensions.extensions.sctList = config.Bugs.SendSCTListOnResume
748 }
David Benjamin615119a2016-07-06 19:22:55 -0700749 }
750
Nick Harper728eed82016-07-07 17:36:52 -0700751 // Send EncryptedExtensions.
752 hs.writeServerHash(encryptedExtensions.marshal())
David Benjamin7964b182016-07-14 23:36:30 -0400753 if config.Bugs.PartialEncryptedExtensionsWithServerHello {
754 // The first byte has already been sent.
755 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()[1:])
756 } else {
757 c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal())
758 }
Nick Harper728eed82016-07-07 17:36:52 -0700759
Steven Valdez803c77a2016-09-06 14:13:43 -0400760 if hs.hello.useCertAuth {
Nick Harper728eed82016-07-07 17:36:52 -0700761 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700762 // Request a client certificate
763 certReq := &certificateRequestMsg{
764 hasSignatureAlgorithm: true,
765 hasRequestContext: true,
David Benjamin8a8349b2016-08-18 02:32:23 -0400766 requestContext: config.Bugs.SendRequestContext,
David Benjamin8d343b42016-07-09 14:26:01 -0700767 }
768 if !config.Bugs.NoSignatureAlgorithms {
David Benjaminf74ec792016-07-13 21:18:49 -0400769 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin8d343b42016-07-09 14:26:01 -0700770 }
771
772 // An empty list of certificateAuthorities signals to
773 // the client that it may send any certificate in response
774 // to our request. When we know the CAs we trust, then
775 // we can send them down, so that the client can choose
776 // an appropriate certificate to give to us.
777 if config.ClientCAs != nil {
778 certReq.certificateAuthorities = config.ClientCAs.Subjects()
779 }
780 hs.writeServerHash(certReq.marshal())
781 c.writeRecord(recordTypeHandshake, certReq.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700782 }
783
784 certMsg := &certificateMsg{
785 hasRequestContext: true,
786 }
787 if !config.Bugs.EmptyCertificateList {
788 certMsg.certificates = hs.cert.Certificate
789 }
David Benjamin1edae6b2016-07-13 16:58:23 -0400790 certMsgBytes := certMsg.marshal()
David Benjamin1edae6b2016-07-13 16:58:23 -0400791 hs.writeServerHash(certMsgBytes)
792 c.writeRecord(recordTypeHandshake, certMsgBytes)
Nick Harper728eed82016-07-07 17:36:52 -0700793
794 certVerify := &certificateVerifyMsg{
795 hasSignatureAlgorithm: true,
796 }
797
798 // Determine the hash to sign.
799 privKey := hs.cert.PrivateKey
800
801 var err error
802 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, config, hs.clientHello.signatureAlgorithms)
803 if err != nil {
804 c.sendAlert(alertInternalError)
805 return err
806 }
807
808 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
809 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
810 if err != nil {
811 c.sendAlert(alertInternalError)
812 return err
813 }
814
Steven Valdez0ee2e112016-07-15 06:51:15 -0400815 if config.Bugs.SendSignatureAlgorithm != 0 {
816 certVerify.signatureAlgorithm = config.Bugs.SendSignatureAlgorithm
817 }
818
Nick Harper728eed82016-07-07 17:36:52 -0700819 hs.writeServerHash(certVerify.marshal())
820 c.writeRecord(recordTypeHandshake, certVerify.marshal())
Steven Valdez803c77a2016-09-06 14:13:43 -0400821 } else if hs.sessionState != nil {
Nick Harper0b3625b2016-07-25 16:16:28 -0700822 // Pick up certificates from the session instead.
David Benjamin5ecb88b2016-10-04 17:51:35 -0400823 if len(hs.sessionState.certificates) > 0 {
Nick Harper0b3625b2016-07-25 16:16:28 -0700824 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
825 return err
826 }
827 }
Nick Harper728eed82016-07-07 17:36:52 -0700828 }
829
830 finished := new(finishedMsg)
Steven Valdezc4aa7272016-10-03 12:25:56 -0400831 finished.verifyData = hs.finishedHash.serverSum(serverHandshakeTrafficSecret)
Nick Harper728eed82016-07-07 17:36:52 -0700832 if config.Bugs.BadFinished {
833 finished.verifyData[0]++
834 }
835 hs.writeServerHash(finished.marshal())
836 c.writeRecord(recordTypeHandshake, finished.marshal())
David Benjamin02edcd02016-07-27 17:40:37 -0400837 if c.config.Bugs.SendExtraFinished {
838 c.writeRecord(recordTypeHandshake, finished.marshal())
839 }
Nick Harper728eed82016-07-07 17:36:52 -0700840 c.flushHandshake()
841
842 // The various secrets do not incorporate the client's final leg, so
843 // derive them now before updating the handshake context.
844 masterSecret := hs.finishedHash.extractKey(handshakeSecret, hs.finishedHash.zeroSecret())
Steven Valdezc4aa7272016-10-03 12:25:56 -0400845 clientTrafficSecret := hs.finishedHash.deriveSecret(masterSecret, clientApplicationTrafficLabel)
846 serverTrafficSecret := hs.finishedHash.deriveSecret(masterSecret, serverApplicationTrafficLabel)
Nick Harper728eed82016-07-07 17:36:52 -0700847
David Benjamin2aad4062016-07-14 23:15:40 -0400848 // Switch to application data keys on write. In particular, any alerts
849 // from the client certificate are sent over these keys.
Steven Valdezc4aa7272016-10-03 12:25:56 -0400850 c.out.useTrafficSecret(c.vers, hs.suite, serverTrafficSecret, applicationPhase, serverWrite)
David Benjamin2aad4062016-07-14 23:15:40 -0400851
Nick Harper728eed82016-07-07 17:36:52 -0700852 // If we requested a client certificate, then the client must send a
853 // certificate message, even if it's empty.
854 if config.ClientAuth >= RequestClientCert {
David Benjamin8d343b42016-07-09 14:26:01 -0700855 msg, err := c.readHandshake()
856 if err != nil {
857 return err
858 }
859
860 certMsg, ok := msg.(*certificateMsg)
861 if !ok {
862 c.sendAlert(alertUnexpectedMessage)
863 return unexpectedMessageError(certMsg, msg)
864 }
865 hs.writeClientHash(certMsg.marshal())
866
867 if len(certMsg.certificates) == 0 {
868 // The client didn't actually send a certificate
869 switch config.ClientAuth {
870 case RequireAnyClientCert, RequireAndVerifyClientCert:
David Benjamin1db9e1b2016-10-07 20:51:43 -0400871 c.sendAlert(alertCertificateRequired)
David Benjamin8d343b42016-07-09 14:26:01 -0700872 return errors.New("tls: client didn't provide a certificate")
873 }
874 }
875
876 pub, err := hs.processCertsFromClient(certMsg.certificates)
877 if err != nil {
878 return err
879 }
880
881 if len(c.peerCertificates) > 0 {
882 msg, err = c.readHandshake()
883 if err != nil {
884 return err
885 }
886
887 certVerify, ok := msg.(*certificateVerifyMsg)
888 if !ok {
889 c.sendAlert(alertUnexpectedMessage)
890 return unexpectedMessageError(certVerify, msg)
891 }
892
David Benjaminf74ec792016-07-13 21:18:49 -0400893 c.peerSignatureAlgorithm = certVerify.signatureAlgorithm
David Benjamin8d343b42016-07-09 14:26:01 -0700894 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
895 if err := verifyMessage(c.vers, pub, config, certVerify.signatureAlgorithm, input, certVerify.signature); err != nil {
896 c.sendAlert(alertBadCertificate)
897 return err
898 }
899 hs.writeClientHash(certVerify.marshal())
900 }
Nick Harper728eed82016-07-07 17:36:52 -0700901 }
902
903 // Read the client Finished message.
904 msg, err := c.readHandshake()
905 if err != nil {
906 return err
907 }
908 clientFinished, ok := msg.(*finishedMsg)
909 if !ok {
910 c.sendAlert(alertUnexpectedMessage)
911 return unexpectedMessageError(clientFinished, msg)
912 }
913
Steven Valdezc4aa7272016-10-03 12:25:56 -0400914 verify := hs.finishedHash.clientSum(clientHandshakeTrafficSecret)
Nick Harper728eed82016-07-07 17:36:52 -0700915 if len(verify) != len(clientFinished.verifyData) ||
916 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
917 c.sendAlert(alertHandshakeFailure)
918 return errors.New("tls: client's Finished message was incorrect")
919 }
David Benjamin97a0a082016-07-13 17:57:35 -0400920 hs.writeClientHash(clientFinished.marshal())
Nick Harper728eed82016-07-07 17:36:52 -0700921
David Benjamin2aad4062016-07-14 23:15:40 -0400922 // Switch to application data keys on read.
Steven Valdezc4aa7272016-10-03 12:25:56 -0400923 c.in.useTrafficSecret(c.vers, hs.suite, clientTrafficSecret, applicationPhase, clientWrite)
Nick Harper728eed82016-07-07 17:36:52 -0700924
Nick Harper728eed82016-07-07 17:36:52 -0700925 c.cipherSuite = hs.suite
David Benjamin97a0a082016-07-13 17:57:35 -0400926 c.exporterSecret = hs.finishedHash.deriveSecret(masterSecret, exporterLabel)
David Benjamin58104882016-07-18 01:25:41 +0200927 c.resumptionSecret = hs.finishedHash.deriveSecret(masterSecret, resumptionLabel)
928
929 // TODO(davidben): Allow configuring the number of tickets sent for
930 // testing.
931 if !c.config.SessionTicketsDisabled {
932 ticketCount := 2
933 for i := 0; i < ticketCount; i++ {
934 c.SendNewSessionTicket()
935 }
936 }
Nick Harper728eed82016-07-07 17:36:52 -0700937 return nil
938}
939
David Benjaminf25dda92016-07-04 10:05:26 -0700940// processClientHello processes the ClientHello message from the client and
941// decides whether we will perform session resumption.
942func (hs *serverHandshakeState) processClientHello() (isResume bool, err error) {
943 config := hs.c.config
944 c := hs.c
945
946 hs.hello = &serverHelloMsg{
947 isDTLS: c.isDTLS,
David Benjamin3c6a1ea2016-09-26 18:30:05 -0400948 vers: versionToWire(c.vers, c.isDTLS),
David Benjaminb1dd8cd2016-09-26 19:20:48 -0400949 versOverride: config.Bugs.SendServerHelloVersion,
David Benjaminf25dda92016-07-04 10:05:26 -0700950 compressionMethod: compressionNone,
951 }
952
953 hs.hello.random = make([]byte, 32)
954 _, err = io.ReadFull(config.rand(), hs.hello.random)
955 if err != nil {
956 c.sendAlert(alertInternalError)
957 return false, err
958 }
David Benjamina128a552016-10-13 14:26:33 -0400959 // Signal downgrades in the server random, per draft-ietf-tls-tls13-16,
960 // section 4.1.3.
Nick Harper85f20c22016-07-04 10:11:59 -0700961 if c.vers <= VersionTLS12 && config.maxVersion(c.isDTLS) >= VersionTLS13 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400962 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS13)
Nick Harper85f20c22016-07-04 10:11:59 -0700963 }
964 if c.vers <= VersionTLS11 && config.maxVersion(c.isDTLS) == VersionTLS12 {
David Benjamin1f61f0d2016-07-10 12:20:35 -0400965 copy(hs.hello.random[len(hs.hello.random)-8:], downgradeTLS12)
Nick Harper85f20c22016-07-04 10:11:59 -0700966 }
David Benjaminf25dda92016-07-04 10:05:26 -0700967
968 foundCompression := false
969 // We only support null compression, so check that the client offered it.
970 for _, compression := range hs.clientHello.compressionMethods {
971 if compression == compressionNone {
972 foundCompression = true
973 break
974 }
975 }
976
977 if !foundCompression {
978 c.sendAlert(alertHandshakeFailure)
979 return false, errors.New("tls: client does not support uncompressed connections")
980 }
David Benjamin7d79f832016-07-04 09:20:45 -0700981
982 if err := hs.processClientExtensions(&hs.hello.extensions); err != nil {
983 return false, err
Adam Langley09505632015-07-30 18:10:13 -0700984 }
Adam Langley95c29f32014-06-20 12:00:00 -0700985
986 supportedCurve := false
987 preferredCurves := config.curvePreferences()
988Curves:
989 for _, curve := range hs.clientHello.supportedCurves {
990 for _, supported := range preferredCurves {
991 if supported == curve {
992 supportedCurve = true
993 break Curves
994 }
995 }
996 }
997
998 supportedPointFormat := false
999 for _, pointFormat := range hs.clientHello.supportedPoints {
1000 if pointFormat == pointFormatUncompressed {
1001 supportedPointFormat = true
1002 break
1003 }
1004 }
1005 hs.ellipticOk = supportedCurve && supportedPointFormat
1006
Adam Langley95c29f32014-06-20 12:00:00 -07001007 _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
1008
David Benjamin4b27d9f2015-05-12 22:42:52 -04001009 // For test purposes, check that the peer never offers a session when
1010 // renegotiating.
1011 if c.cipherSuite != nil && len(hs.clientHello.sessionId) > 0 && c.config.Bugs.FailIfResumeOnRenego {
1012 return false, errors.New("tls: offered resumption on renegotiation")
1013 }
1014
David Benjamindd6fed92015-10-23 17:41:12 -04001015 if c.config.Bugs.FailIfSessionOffered && (len(hs.clientHello.sessionTicket) > 0 || len(hs.clientHello.sessionId) > 0) {
1016 return false, errors.New("tls: client offered a session ticket or ID")
1017 }
1018
Adam Langley95c29f32014-06-20 12:00:00 -07001019 if hs.checkForResumption() {
1020 return true, nil
1021 }
1022
Adam Langley95c29f32014-06-20 12:00:00 -07001023 var preferenceList, supportedList []uint16
1024 if c.config.PreferServerCipherSuites {
1025 preferenceList = c.config.cipherSuites()
1026 supportedList = hs.clientHello.cipherSuites
1027 } else {
1028 preferenceList = hs.clientHello.cipherSuites
1029 supportedList = c.config.cipherSuites()
1030 }
1031
1032 for _, id := range preferenceList {
Steven Valdez803c77a2016-09-06 14:13:43 -04001033 if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
Adam Langley95c29f32014-06-20 12:00:00 -07001034 break
1035 }
1036 }
1037
1038 if hs.suite == nil {
1039 c.sendAlert(alertHandshakeFailure)
1040 return false, errors.New("tls: no cipher suite supported by both client and server")
1041 }
1042
1043 return false, nil
1044}
1045
David Benjamin7d79f832016-07-04 09:20:45 -07001046// processClientExtensions processes all ClientHello extensions not directly
1047// related to cipher suite negotiation and writes responses in serverExtensions.
1048func (hs *serverHandshakeState) processClientExtensions(serverExtensions *serverExtensions) error {
1049 config := hs.c.config
1050 c := hs.c
1051
David Benjamin8d315d72016-07-18 01:03:18 +02001052 if c.vers < VersionTLS13 || config.Bugs.NegotiateRenegotiationInfoAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -07001053 if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
1054 c.sendAlert(alertHandshakeFailure)
1055 return errors.New("tls: renegotiation mismatch")
David Benjamin7d79f832016-07-04 09:20:45 -07001056 }
David Benjamin7d79f832016-07-04 09:20:45 -07001057
Nick Harper728eed82016-07-07 17:36:52 -07001058 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
1059 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.clientVerify...)
1060 serverExtensions.secureRenegotiation = append(serverExtensions.secureRenegotiation, c.serverVerify...)
1061 if c.config.Bugs.BadRenegotiationInfo {
1062 serverExtensions.secureRenegotiation[0] ^= 0x80
1063 }
1064 } else {
1065 serverExtensions.secureRenegotiation = hs.clientHello.secureRenegotiation
1066 }
1067
1068 if c.noRenegotiationInfo() {
1069 serverExtensions.secureRenegotiation = nil
1070 }
David Benjamin7d79f832016-07-04 09:20:45 -07001071 }
1072
1073 serverExtensions.duplicateExtension = c.config.Bugs.DuplicateExtension
1074
1075 if len(hs.clientHello.serverName) > 0 {
1076 c.serverName = hs.clientHello.serverName
1077 }
1078 if len(config.Certificates) == 0 {
1079 c.sendAlert(alertInternalError)
1080 return errors.New("tls: no certificates configured")
1081 }
1082 hs.cert = &config.Certificates[0]
1083 if len(hs.clientHello.serverName) > 0 {
1084 hs.cert = config.getCertificateForName(hs.clientHello.serverName)
1085 }
1086 if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
1087 return errors.New("tls: unexpected server name")
1088 }
1089
1090 if len(hs.clientHello.alpnProtocols) > 0 {
1091 if proto := c.config.Bugs.ALPNProtocol; proto != nil {
1092 serverExtensions.alpnProtocol = *proto
1093 serverExtensions.alpnProtocolEmpty = len(*proto) == 0
1094 c.clientProtocol = *proto
1095 c.usedALPN = true
1096 } else if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
1097 serverExtensions.alpnProtocol = selectedProto
1098 c.clientProtocol = selectedProto
1099 c.usedALPN = true
1100 }
1101 }
Nick Harper728eed82016-07-07 17:36:52 -07001102
David Benjamin0c40a962016-08-01 12:05:50 -04001103 if len(c.config.Bugs.SendALPN) > 0 {
1104 serverExtensions.alpnProtocol = c.config.Bugs.SendALPN
1105 }
1106
David Benjamin8d315d72016-07-18 01:03:18 +02001107 if c.vers < VersionTLS13 || config.Bugs.NegotiateNPNAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -07001108 if len(hs.clientHello.alpnProtocols) == 0 || c.config.Bugs.NegotiateALPNAndNPN {
1109 // Although sending an empty NPN extension is reasonable, Firefox has
1110 // had a bug around this. Best to send nothing at all if
1111 // config.NextProtos is empty. See
1112 // https://code.google.com/p/go/issues/detail?id=5445.
1113 if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
1114 serverExtensions.nextProtoNeg = true
1115 serverExtensions.nextProtos = config.NextProtos
1116 serverExtensions.npnLast = config.Bugs.SwapNPNAndALPN
1117 }
David Benjamin7d79f832016-07-04 09:20:45 -07001118 }
Steven Valdez143e8b32016-07-11 13:19:03 -04001119 }
David Benjamin7d79f832016-07-04 09:20:45 -07001120
David Benjamin8d315d72016-07-18 01:03:18 +02001121 if c.vers < VersionTLS13 || config.Bugs.NegotiateEMSAtAllVersions {
David Benjamin163c9562016-08-29 23:14:17 -04001122 disableEMS := config.Bugs.NoExtendedMasterSecret
1123 if c.cipherSuite != nil {
1124 disableEMS = config.Bugs.NoExtendedMasterSecretOnRenegotiation
1125 }
1126 serverExtensions.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !disableEMS
Steven Valdez143e8b32016-07-11 13:19:03 -04001127 }
David Benjamin7d79f832016-07-04 09:20:45 -07001128
David Benjamin8d315d72016-07-18 01:03:18 +02001129 if c.vers < VersionTLS13 || config.Bugs.NegotiateChannelIDAtAllVersions {
Nick Harper728eed82016-07-07 17:36:52 -07001130 if hs.clientHello.channelIDSupported && config.RequestChannelID {
1131 serverExtensions.channelIDRequested = true
1132 }
David Benjamin7d79f832016-07-04 09:20:45 -07001133 }
1134
1135 if hs.clientHello.srtpProtectionProfiles != nil {
1136 SRTPLoop:
1137 for _, p1 := range c.config.SRTPProtectionProfiles {
1138 for _, p2 := range hs.clientHello.srtpProtectionProfiles {
1139 if p1 == p2 {
1140 serverExtensions.srtpProtectionProfile = p1
1141 c.srtpProtectionProfile = p1
1142 break SRTPLoop
1143 }
1144 }
1145 }
1146 }
1147
1148 if c.config.Bugs.SendSRTPProtectionProfile != 0 {
1149 serverExtensions.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
1150 }
1151
1152 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
1153 if hs.clientHello.customExtension != *expected {
1154 return fmt.Errorf("tls: bad custom extension contents %q", hs.clientHello.customExtension)
1155 }
1156 }
1157 serverExtensions.customExtension = config.Bugs.CustomExtension
1158
Steven Valdez143e8b32016-07-11 13:19:03 -04001159 if c.config.Bugs.AdvertiseTicketExtension {
1160 serverExtensions.ticketSupported = true
1161 }
1162
David Benjamin65ac9972016-09-02 21:35:25 -04001163 if !hs.clientHello.hasGREASEExtension && config.Bugs.ExpectGREASE {
1164 return errors.New("tls: no GREASE extension found")
1165 }
1166
David Benjamin7d79f832016-07-04 09:20:45 -07001167 return nil
1168}
1169
Adam Langley95c29f32014-06-20 12:00:00 -07001170// checkForResumption returns true if we should perform resumption on this connection.
1171func (hs *serverHandshakeState) checkForResumption() bool {
1172 c := hs.c
1173
David Benjamin405da482016-08-08 17:25:07 -04001174 ticket := hs.clientHello.sessionTicket
1175 if len(ticket) == 0 && len(hs.clientHello.pskIdentities) > 0 && c.config.Bugs.AcceptAnySession {
Steven Valdez5b986082016-09-01 12:29:49 -04001176 ticket = hs.clientHello.pskIdentities[0].ticket
David Benjamin405da482016-08-08 17:25:07 -04001177 }
1178 if len(ticket) > 0 {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001179 if c.config.SessionTicketsDisabled {
1180 return false
1181 }
David Benjaminb0c8db72014-09-24 15:19:56 -04001182
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001183 var ok bool
David Benjamin405da482016-08-08 17:25:07 -04001184 if hs.sessionState, ok = c.decryptTicket(ticket); !ok {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001185 return false
1186 }
1187 } else {
1188 if c.config.ServerSessionCache == nil {
1189 return false
1190 }
1191
1192 var ok bool
1193 sessionId := string(hs.clientHello.sessionId)
1194 if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
1195 return false
1196 }
Adam Langley95c29f32014-06-20 12:00:00 -07001197 }
1198
Steven Valdez803c77a2016-09-06 14:13:43 -04001199 if c.config.Bugs.AcceptAnySession {
1200 // Replace the cipher suite with one known to work, to test
1201 // cross-version resumption attempts.
1202 hs.sessionState.cipherSuite = TLS_RSA_WITH_AES_128_CBC_SHA
1203 } else {
David Benjamin405da482016-08-08 17:25:07 -04001204 // Never resume a session for a different SSL version.
1205 if c.vers != hs.sessionState.vers {
1206 return false
Adam Langley95c29f32014-06-20 12:00:00 -07001207 }
David Benjamin405da482016-08-08 17:25:07 -04001208
1209 cipherSuiteOk := false
1210 // Check that the client is still offering the ciphersuite in the session.
1211 for _, id := range hs.clientHello.cipherSuites {
1212 if id == hs.sessionState.cipherSuite {
1213 cipherSuiteOk = true
1214 break
1215 }
1216 }
1217 if !cipherSuiteOk {
1218 return false
1219 }
Adam Langley95c29f32014-06-20 12:00:00 -07001220 }
1221
1222 // Check that we also support the ciphersuite from the session.
Steven Valdez803c77a2016-09-06 14:13:43 -04001223 hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), c.vers, hs.ellipticOk, hs.ecdsaOk)
1224
Adam Langley95c29f32014-06-20 12:00:00 -07001225 if hs.suite == nil {
1226 return false
1227 }
1228
1229 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
1230 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
1231 if needClientCerts && !sessionHasClientCerts {
1232 return false
1233 }
1234 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
1235 return false
1236 }
1237
1238 return true
1239}
1240
1241func (hs *serverHandshakeState) doResumeHandshake() error {
1242 c := hs.c
1243
1244 hs.hello.cipherSuite = hs.suite.id
David Benjaminece3de92015-03-16 18:02:20 -04001245 if c.config.Bugs.SendCipherSuite != 0 {
1246 hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
1247 }
Adam Langley95c29f32014-06-20 12:00:00 -07001248 // We echo the client's session ID in the ServerHello to let it know
1249 // that we're doing a resumption.
1250 hs.hello.sessionId = hs.clientHello.sessionId
Nick Harperb3d51be2016-07-01 11:43:18 -04001251 hs.hello.extensions.ticketSupported = c.config.Bugs.RenewTicketOnResume
Adam Langley95c29f32014-06-20 12:00:00 -07001252
David Benjamin80d1b352016-05-04 19:19:06 -04001253 if c.config.Bugs.SendSCTListOnResume != nil {
Nick Harperb3d51be2016-07-01 11:43:18 -04001254 hs.hello.extensions.sctList = c.config.Bugs.SendSCTListOnResume
David Benjamin80d1b352016-05-04 19:19:06 -04001255 }
1256
David Benjamindaa88502016-10-04 16:32:16 -04001257 if c.config.Bugs.SendOCSPResponseOnResume != nil {
1258 // There is no way, syntactically, to send an OCSP response on a
1259 // resumption handshake.
1260 hs.hello.extensions.ocspStapling = true
1261 }
1262
Adam Langley95c29f32014-06-20 12:00:00 -07001263 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamine098ec22014-08-27 23:13:20 -04001264 hs.finishedHash.discardHandshakeBuffer()
David Benjamin83c0bc92014-08-04 01:23:53 -04001265 hs.writeClientHash(hs.clientHello.marshal())
1266 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001267
1268 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
1269
1270 if len(hs.sessionState.certificates) > 0 {
1271 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
1272 return err
1273 }
1274 }
1275
1276 hs.masterSecret = hs.sessionState.masterSecret
Adam Langley75712922014-10-10 16:23:43 -07001277 c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001278
1279 return nil
1280}
1281
1282func (hs *serverHandshakeState) doFullHandshake() error {
1283 config := hs.c.config
1284 c := hs.c
1285
David Benjamin48cae082014-10-27 01:06:24 -04001286 isPSK := hs.suite.flags&suitePSK != 0
1287 if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001288 hs.hello.extensions.ocspStapling = true
Adam Langley95c29f32014-06-20 12:00:00 -07001289 }
1290
David Benjamin61f95272014-11-25 01:55:35 -05001291 if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
Nick Harperb3d51be2016-07-01 11:43:18 -04001292 hs.hello.extensions.sctList = hs.cert.SignedCertificateTimestampList
David Benjamin61f95272014-11-25 01:55:35 -05001293 }
1294
Nick Harperb3d51be2016-07-01 11:43:18 -04001295 hs.hello.extensions.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
Adam Langley95c29f32014-06-20 12:00:00 -07001296 hs.hello.cipherSuite = hs.suite.id
David Benjamin6095de82014-12-27 01:50:38 -05001297 if config.Bugs.SendCipherSuite != 0 {
1298 hs.hello.cipherSuite = config.Bugs.SendCipherSuite
1299 }
Nick Harperb3d51be2016-07-01 11:43:18 -04001300 c.extendedMasterSecret = hs.hello.extensions.extendedMasterSecret
Adam Langley95c29f32014-06-20 12:00:00 -07001301
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001302 // Generate a session ID if we're to save the session.
Nick Harperb3d51be2016-07-01 11:43:18 -04001303 if !hs.hello.extensions.ticketSupported && config.ServerSessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001304 hs.hello.sessionId = make([]byte, 32)
1305 if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
1306 c.sendAlert(alertInternalError)
1307 return errors.New("tls: short read from Rand: " + err.Error())
1308 }
1309 }
1310
Adam Langley95c29f32014-06-20 12:00:00 -07001311 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
David Benjamin83c0bc92014-08-04 01:23:53 -04001312 hs.writeClientHash(hs.clientHello.marshal())
1313 hs.writeServerHash(hs.hello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001314
David Benjaminabe94e32016-09-04 14:18:58 -04001315 if config.Bugs.SendSNIWarningAlert {
1316 c.SendAlert(alertLevelWarning, alertUnrecognizedName)
1317 }
1318
Adam Langley95c29f32014-06-20 12:00:00 -07001319 c.writeRecord(recordTypeHandshake, hs.hello.marshal())
1320
David Benjamin48cae082014-10-27 01:06:24 -04001321 if !isPSK {
1322 certMsg := new(certificateMsg)
David Benjamin8923c0b2015-06-07 11:42:34 -04001323 if !config.Bugs.EmptyCertificateList {
1324 certMsg.certificates = hs.cert.Certificate
1325 }
David Benjamin48cae082014-10-27 01:06:24 -04001326 if !config.Bugs.UnauthenticatedECDH {
David Benjaminbcb2d912015-02-24 23:45:43 -05001327 certMsgBytes := certMsg.marshal()
David Benjaminbcb2d912015-02-24 23:45:43 -05001328 hs.writeServerHash(certMsgBytes)
1329 c.writeRecord(recordTypeHandshake, certMsgBytes)
David Benjamin48cae082014-10-27 01:06:24 -04001330 }
David Benjamin1c375dd2014-07-12 00:48:23 -04001331 }
Adam Langley95c29f32014-06-20 12:00:00 -07001332
Nick Harperb3d51be2016-07-01 11:43:18 -04001333 if hs.hello.extensions.ocspStapling && !c.config.Bugs.SkipCertificateStatus {
Adam Langley95c29f32014-06-20 12:00:00 -07001334 certStatus := new(certificateStatusMsg)
1335 certStatus.statusType = statusTypeOCSP
1336 certStatus.response = hs.cert.OCSPStaple
David Benjamin83c0bc92014-08-04 01:23:53 -04001337 hs.writeServerHash(certStatus.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001338 c.writeRecord(recordTypeHandshake, certStatus.marshal())
1339 }
1340
1341 keyAgreement := hs.suite.ka(c.vers)
1342 skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
1343 if err != nil {
1344 c.sendAlert(alertHandshakeFailure)
1345 return err
1346 }
Steven Valdez5440fe02016-07-18 12:40:30 -04001347 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1348 c.curveID = ecdhe.curveID
1349 }
David Benjamin9c651c92014-07-12 13:27:45 -04001350 if skx != nil && !config.Bugs.SkipServerKeyExchange {
David Benjamin83c0bc92014-08-04 01:23:53 -04001351 hs.writeServerHash(skx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001352 c.writeRecord(recordTypeHandshake, skx.marshal())
1353 }
1354
1355 if config.ClientAuth >= RequestClientCert {
1356 // Request a client certificate
David Benjamin7b030512014-07-08 17:30:11 -04001357 certReq := &certificateRequestMsg{
1358 certificateTypes: config.ClientCertificateTypes,
1359 }
1360 if certReq.certificateTypes == nil {
1361 certReq.certificateTypes = []byte{
1362 byte(CertTypeRSASign),
1363 byte(CertTypeECDSASign),
1364 }
Adam Langley95c29f32014-06-20 12:00:00 -07001365 }
1366 if c.vers >= VersionTLS12 {
Nick Harper60edffd2016-06-21 15:19:24 -07001367 certReq.hasSignatureAlgorithm = true
1368 if !config.Bugs.NoSignatureAlgorithms {
David Benjamin7a41d372016-07-09 11:21:54 -07001369 certReq.signatureAlgorithms = config.verifySignatureAlgorithms()
David Benjamin000800a2014-11-14 01:43:59 -05001370 }
Adam Langley95c29f32014-06-20 12:00:00 -07001371 }
1372
1373 // An empty list of certificateAuthorities signals to
1374 // the client that it may send any certificate in response
1375 // to our request. When we know the CAs we trust, then
1376 // we can send them down, so that the client can choose
1377 // an appropriate certificate to give to us.
1378 if config.ClientCAs != nil {
1379 certReq.certificateAuthorities = config.ClientCAs.Subjects()
1380 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001381 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001382 c.writeRecord(recordTypeHandshake, certReq.marshal())
1383 }
1384
1385 helloDone := new(serverHelloDoneMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -04001386 hs.writeServerHash(helloDone.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001387 c.writeRecord(recordTypeHandshake, helloDone.marshal())
David Benjamin582ba042016-07-07 12:33:25 -07001388 c.flushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -07001389
1390 var pub crypto.PublicKey // public key for client auth, if any
1391
David Benjamin83f90402015-01-27 01:09:43 -05001392 if err := c.simulatePacketLoss(nil); err != nil {
1393 return err
1394 }
Adam Langley95c29f32014-06-20 12:00:00 -07001395 msg, err := c.readHandshake()
1396 if err != nil {
1397 return err
1398 }
1399
1400 var ok bool
1401 // If we requested a client certificate, then the client must send a
1402 // certificate message, even if it's empty.
1403 if config.ClientAuth >= RequestClientCert {
David Benjamin48cae082014-10-27 01:06:24 -04001404 var certMsg *certificateMsg
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001405 var certificates [][]byte
1406 if certMsg, ok = msg.(*certificateMsg); ok {
1407 if c.vers == VersionSSL30 && len(certMsg.certificates) == 0 {
1408 return errors.New("tls: empty certificate message in SSL 3.0")
1409 }
1410
1411 hs.writeClientHash(certMsg.marshal())
1412 certificates = certMsg.certificates
1413 } else if c.vers != VersionSSL30 {
1414 // In TLS, the Certificate message is required. In SSL
1415 // 3.0, the peer skips it when sending no certificates.
Adam Langley95c29f32014-06-20 12:00:00 -07001416 c.sendAlert(alertUnexpectedMessage)
1417 return unexpectedMessageError(certMsg, msg)
1418 }
Adam Langley95c29f32014-06-20 12:00:00 -07001419
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001420 if len(certificates) == 0 {
Adam Langley95c29f32014-06-20 12:00:00 -07001421 // The client didn't actually send a certificate
1422 switch config.ClientAuth {
1423 case RequireAnyClientCert, RequireAndVerifyClientCert:
1424 c.sendAlert(alertBadCertificate)
1425 return errors.New("tls: client didn't provide a certificate")
1426 }
1427 }
1428
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001429 pub, err = hs.processCertsFromClient(certificates)
Adam Langley95c29f32014-06-20 12:00:00 -07001430 if err != nil {
1431 return err
1432 }
1433
David Benjamin0b7ca7d2016-03-10 15:44:22 -05001434 if ok {
1435 msg, err = c.readHandshake()
1436 if err != nil {
1437 return err
1438 }
Adam Langley95c29f32014-06-20 12:00:00 -07001439 }
1440 }
1441
1442 // Get client key exchange
1443 ckx, ok := msg.(*clientKeyExchangeMsg)
1444 if !ok {
1445 c.sendAlert(alertUnexpectedMessage)
1446 return unexpectedMessageError(ckx, msg)
1447 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001448 hs.writeClientHash(ckx.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001449
David Benjamine098ec22014-08-27 23:13:20 -04001450 preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
1451 if err != nil {
1452 c.sendAlert(alertHandshakeFailure)
1453 return err
1454 }
Adam Langley75712922014-10-10 16:23:43 -07001455 if c.extendedMasterSecret {
1456 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1457 } else {
1458 if c.config.Bugs.RequireExtendedMasterSecret {
1459 return errors.New("tls: extended master secret required but not supported by peer")
1460 }
1461 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
1462 }
David Benjamine098ec22014-08-27 23:13:20 -04001463
Adam Langley95c29f32014-06-20 12:00:00 -07001464 // If we received a client cert in response to our certificate request message,
1465 // the client will send us a certificateVerifyMsg immediately after the
1466 // clientKeyExchangeMsg. This message is a digest of all preceding
1467 // handshake-layer messages that is signed using the private key corresponding
1468 // to the client's certificate. This allows us to verify that the client is in
1469 // possession of the private key of the certificate.
1470 if len(c.peerCertificates) > 0 {
1471 msg, err = c.readHandshake()
1472 if err != nil {
1473 return err
1474 }
1475 certVerify, ok := msg.(*certificateVerifyMsg)
1476 if !ok {
1477 c.sendAlert(alertUnexpectedMessage)
1478 return unexpectedMessageError(certVerify, msg)
1479 }
1480
David Benjaminde620d92014-07-18 15:03:41 -04001481 // Determine the signature type.
Nick Harper60edffd2016-06-21 15:19:24 -07001482 var sigAlg signatureAlgorithm
1483 if certVerify.hasSignatureAlgorithm {
1484 sigAlg = certVerify.signatureAlgorithm
Nick Harper60edffd2016-06-21 15:19:24 -07001485 c.peerSignatureAlgorithm = sigAlg
David Benjaminde620d92014-07-18 15:03:41 -04001486 }
1487
Nick Harper60edffd2016-06-21 15:19:24 -07001488 if c.vers > VersionSSL30 {
David Benjamin1fb125c2016-07-08 18:52:12 -07001489 err = verifyMessage(c.vers, pub, c.config, sigAlg, hs.finishedHash.buffer, certVerify.signature)
Nick Harper60edffd2016-06-21 15:19:24 -07001490 } else {
1491 // SSL 3.0's client certificate construction is
1492 // incompatible with signatureAlgorithm.
1493 rsaPub, ok := pub.(*rsa.PublicKey)
1494 if !ok {
1495 err = errors.New("unsupported key type for client certificate")
1496 } else {
1497 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
1498 err = rsa.VerifyPKCS1v15(rsaPub, crypto.MD5SHA1, digest, certVerify.signature)
David Benjaminde620d92014-07-18 15:03:41 -04001499 }
Adam Langley95c29f32014-06-20 12:00:00 -07001500 }
1501 if err != nil {
1502 c.sendAlert(alertBadCertificate)
1503 return errors.New("could not validate signature of connection nonces: " + err.Error())
1504 }
1505
David Benjamin83c0bc92014-08-04 01:23:53 -04001506 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001507 }
1508
David Benjamine098ec22014-08-27 23:13:20 -04001509 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -07001510
1511 return nil
1512}
1513
1514func (hs *serverHandshakeState) establishKeys() error {
1515 c := hs.c
1516
1517 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
Nick Harper1fd39d82016-06-14 18:14:35 -07001518 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen(c.vers))
Adam Langley95c29f32014-06-20 12:00:00 -07001519
1520 var clientCipher, serverCipher interface{}
1521 var clientHash, serverHash macFunction
1522
1523 if hs.suite.aead == nil {
1524 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
1525 clientHash = hs.suite.mac(c.vers, clientMAC)
1526 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
1527 serverHash = hs.suite.mac(c.vers, serverMAC)
1528 } else {
Nick Harper1fd39d82016-06-14 18:14:35 -07001529 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1530 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley95c29f32014-06-20 12:00:00 -07001531 }
1532
1533 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
1534 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
1535
1536 return nil
1537}
1538
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001539func (hs *serverHandshakeState) readFinished(out []byte, isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001540 c := hs.c
1541
1542 c.readRecord(recordTypeChangeCipherSpec)
1543 if err := c.in.error(); err != nil {
1544 return err
1545 }
1546
Nick Harperb3d51be2016-07-01 11:43:18 -04001547 if hs.hello.extensions.nextProtoNeg {
Adam Langley95c29f32014-06-20 12:00:00 -07001548 msg, err := c.readHandshake()
1549 if err != nil {
1550 return err
1551 }
1552 nextProto, ok := msg.(*nextProtoMsg)
1553 if !ok {
1554 c.sendAlert(alertUnexpectedMessage)
1555 return unexpectedMessageError(nextProto, msg)
1556 }
David Benjamin83c0bc92014-08-04 01:23:53 -04001557 hs.writeClientHash(nextProto.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001558 c.clientProtocol = nextProto.proto
1559 }
1560
Nick Harperb3d51be2016-07-01 11:43:18 -04001561 if hs.hello.extensions.channelIDRequested {
David Benjamind30a9902014-08-24 01:44:23 -04001562 msg, err := c.readHandshake()
1563 if err != nil {
1564 return err
1565 }
David Benjamin24599a82016-06-30 18:56:53 -04001566 channelIDMsg, ok := msg.(*channelIDMsg)
David Benjamind30a9902014-08-24 01:44:23 -04001567 if !ok {
1568 c.sendAlert(alertUnexpectedMessage)
David Benjamin24599a82016-06-30 18:56:53 -04001569 return unexpectedMessageError(channelIDMsg, msg)
David Benjamind30a9902014-08-24 01:44:23 -04001570 }
David Benjamin24599a82016-06-30 18:56:53 -04001571 x := new(big.Int).SetBytes(channelIDMsg.channelID[0:32])
1572 y := new(big.Int).SetBytes(channelIDMsg.channelID[32:64])
1573 r := new(big.Int).SetBytes(channelIDMsg.channelID[64:96])
1574 s := new(big.Int).SetBytes(channelIDMsg.channelID[96:128])
David Benjamind30a9902014-08-24 01:44:23 -04001575 if !elliptic.P256().IsOnCurve(x, y) {
1576 return errors.New("tls: invalid channel ID public key")
1577 }
1578 channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
1579 var resumeHash []byte
1580 if isResume {
1581 resumeHash = hs.sessionState.handshakeHash
1582 }
1583 if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
1584 return errors.New("tls: invalid channel ID signature")
1585 }
1586 c.channelID = channelID
1587
David Benjamin24599a82016-06-30 18:56:53 -04001588 hs.writeClientHash(channelIDMsg.marshal())
David Benjamind30a9902014-08-24 01:44:23 -04001589 }
1590
Adam Langley95c29f32014-06-20 12:00:00 -07001591 msg, err := c.readHandshake()
1592 if err != nil {
1593 return err
1594 }
1595 clientFinished, ok := msg.(*finishedMsg)
1596 if !ok {
1597 c.sendAlert(alertUnexpectedMessage)
1598 return unexpectedMessageError(clientFinished, msg)
1599 }
1600
1601 verify := hs.finishedHash.clientSum(hs.masterSecret)
1602 if len(verify) != len(clientFinished.verifyData) ||
1603 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
1604 c.sendAlert(alertHandshakeFailure)
1605 return errors.New("tls: client's Finished message is incorrect")
1606 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001607 c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001608 copy(out, clientFinished.verifyData)
Adam Langley95c29f32014-06-20 12:00:00 -07001609
David Benjamin83c0bc92014-08-04 01:23:53 -04001610 hs.writeClientHash(clientFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001611 return nil
1612}
1613
1614func (hs *serverHandshakeState) sendSessionTicket() error {
Adam Langley95c29f32014-06-20 12:00:00 -07001615 c := hs.c
Adam Langley95c29f32014-06-20 12:00:00 -07001616 state := sessionState{
David Benjamind30a9902014-08-24 01:44:23 -04001617 vers: c.vers,
1618 cipherSuite: hs.suite.id,
1619 masterSecret: hs.masterSecret,
1620 certificates: hs.certsFromClient,
1621 handshakeHash: hs.finishedHash.server.Sum(nil),
Adam Langley95c29f32014-06-20 12:00:00 -07001622 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001623
Nick Harperb3d51be2016-07-01 11:43:18 -04001624 if !hs.hello.extensions.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001625 if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
1626 c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
1627 }
1628 return nil
1629 }
1630
1631 m := new(newSessionTicketMsg)
1632
David Benjamindd6fed92015-10-23 17:41:12 -04001633 if !c.config.Bugs.SendEmptySessionTicket {
1634 var err error
1635 m.ticket, err = c.encryptTicket(&state)
1636 if err != nil {
1637 return err
1638 }
Adam Langley95c29f32014-06-20 12:00:00 -07001639 }
Adam Langley95c29f32014-06-20 12:00:00 -07001640
David Benjamin83c0bc92014-08-04 01:23:53 -04001641 hs.writeServerHash(m.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -07001642 c.writeRecord(recordTypeHandshake, m.marshal())
1643
1644 return nil
1645}
1646
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001647func (hs *serverHandshakeState) sendFinished(out []byte) error {
Adam Langley95c29f32014-06-20 12:00:00 -07001648 c := hs.c
1649
David Benjamin86271ee2014-07-21 16:14:03 -04001650 finished := new(finishedMsg)
1651 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001652 copy(out, finished.verifyData)
David Benjamin513f0ea2015-04-02 19:33:31 -04001653 if c.config.Bugs.BadFinished {
1654 finished.verifyData[0]++
1655 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001656 c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -05001657 hs.finishedBytes = finished.marshal()
1658 hs.writeServerHash(hs.finishedBytes)
1659 postCCSBytes := hs.finishedBytes
David Benjamin86271ee2014-07-21 16:14:03 -04001660
1661 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
1662 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
1663 postCCSBytes = postCCSBytes[5:]
David Benjamin61672812016-07-14 23:10:43 -04001664 } else if c.config.Bugs.SendUnencryptedFinished {
1665 c.writeRecord(recordTypeHandshake, postCCSBytes)
1666 postCCSBytes = nil
David Benjamin86271ee2014-07-21 16:14:03 -04001667 }
David Benjamin582ba042016-07-07 12:33:25 -07001668 c.flushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -04001669
David Benjamina0e52232014-07-19 17:39:58 -04001670 if !c.config.Bugs.SkipChangeCipherSpec {
David Benjamin8411b242015-11-26 12:07:28 -05001671 ccs := []byte{1}
1672 if c.config.Bugs.BadChangeCipherSpec != nil {
1673 ccs = c.config.Bugs.BadChangeCipherSpec
1674 }
1675 c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamina0e52232014-07-19 17:39:58 -04001676 }
Adam Langley95c29f32014-06-20 12:00:00 -07001677
David Benjamin4189bd92015-01-25 23:52:39 -05001678 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1679 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1680 }
David Benjamindc3da932015-03-12 15:09:02 -04001681 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1682 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1683 return errors.New("tls: simulating post-CCS alert")
1684 }
David Benjamin4189bd92015-01-25 23:52:39 -05001685
David Benjamin61672812016-07-14 23:10:43 -04001686 if !c.config.Bugs.SkipFinished && len(postCCSBytes) > 0 {
David Benjaminb80168e2015-02-08 18:30:14 -05001687 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamin02edcd02016-07-27 17:40:37 -04001688 if c.config.Bugs.SendExtraFinished {
1689 c.writeRecord(recordTypeHandshake, finished.marshal())
1690 }
1691
David Benjamin12d2c482016-07-24 10:56:51 -04001692 if !c.config.Bugs.PackHelloRequestWithFinished {
1693 // Defer flushing until renegotiation.
1694 c.flushHandshake()
1695 }
David Benjaminb3774b92015-01-31 17:16:01 -05001696 }
Adam Langley95c29f32014-06-20 12:00:00 -07001697
David Benjaminc565ebb2015-04-03 04:06:36 -04001698 c.cipherSuite = hs.suite
Adam Langley95c29f32014-06-20 12:00:00 -07001699
1700 return nil
1701}
1702
1703// processCertsFromClient takes a chain of client certificates either from a
1704// Certificates message or from a sessionState and verifies them. It returns
1705// the public key of the leaf certificate.
1706func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
1707 c := hs.c
1708
1709 hs.certsFromClient = certificates
1710 certs := make([]*x509.Certificate, len(certificates))
1711 var err error
1712 for i, asn1Data := range certificates {
1713 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
1714 c.sendAlert(alertBadCertificate)
1715 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
1716 }
1717 }
1718
1719 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
1720 opts := x509.VerifyOptions{
1721 Roots: c.config.ClientCAs,
1722 CurrentTime: c.config.time(),
1723 Intermediates: x509.NewCertPool(),
1724 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
1725 }
1726
1727 for _, cert := range certs[1:] {
1728 opts.Intermediates.AddCert(cert)
1729 }
1730
1731 chains, err := certs[0].Verify(opts)
1732 if err != nil {
1733 c.sendAlert(alertBadCertificate)
1734 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
1735 }
1736
1737 ok := false
1738 for _, ku := range certs[0].ExtKeyUsage {
1739 if ku == x509.ExtKeyUsageClientAuth {
1740 ok = true
1741 break
1742 }
1743 }
1744 if !ok {
1745 c.sendAlert(alertHandshakeFailure)
1746 return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
1747 }
1748
1749 c.verifiedChains = chains
1750 }
1751
1752 if len(certs) > 0 {
1753 var pub crypto.PublicKey
1754 switch key := certs[0].PublicKey.(type) {
1755 case *ecdsa.PublicKey, *rsa.PublicKey:
1756 pub = key
1757 default:
1758 c.sendAlert(alertUnsupportedCertificate)
1759 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
1760 }
1761 c.peerCertificates = certs
1762 return pub, nil
1763 }
1764
1765 return nil, nil
1766}
1767
David Benjamin83c0bc92014-08-04 01:23:53 -04001768func (hs *serverHandshakeState) writeServerHash(msg []byte) {
1769 // writeServerHash is called before writeRecord.
1770 hs.writeHash(msg, hs.c.sendHandshakeSeq)
1771}
1772
1773func (hs *serverHandshakeState) writeClientHash(msg []byte) {
1774 // writeClientHash is called after readHandshake.
1775 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1776}
1777
1778func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
1779 if hs.c.isDTLS {
1780 // This is somewhat hacky. DTLS hashes a slightly different format.
1781 // First, the TLS header.
1782 hs.finishedHash.Write(msg[:4])
1783 // Then the sequence number and reassembled fragment offset (always 0).
1784 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1785 // Then the reassembled fragment (always equal to the message length).
1786 hs.finishedHash.Write(msg[1:4])
1787 // And then the message body.
1788 hs.finishedHash.Write(msg[4:])
1789 } else {
1790 hs.finishedHash.Write(msg)
1791 }
1792}
1793
Adam Langley95c29f32014-06-20 12:00:00 -07001794// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
1795// is acceptable to use.
Steven Valdez803c77a2016-09-06 14:13:43 -04001796func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
Adam Langley95c29f32014-06-20 12:00:00 -07001797 for _, supported := range supportedCipherSuites {
1798 if id == supported {
1799 var candidate *cipherSuite
1800
1801 for _, s := range cipherSuites {
1802 if s.id == id {
1803 candidate = s
1804 break
1805 }
1806 }
1807 if candidate == nil {
1808 continue
1809 }
Steven Valdez803c77a2016-09-06 14:13:43 -04001810
Adam Langley95c29f32014-06-20 12:00:00 -07001811 // Don't select a ciphersuite which we can't
1812 // support for this client.
Steven Valdez803c77a2016-09-06 14:13:43 -04001813 if version >= VersionTLS13 || candidate.flags&suiteTLS13 != 0 {
1814 if version < VersionTLS13 || candidate.flags&suiteTLS13 == 0 {
1815 continue
1816 }
1817 return candidate
David Benjamin5ecb88b2016-10-04 17:51:35 -04001818 }
1819 if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
1820 continue
1821 }
1822 if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
1823 continue
1824 }
1825 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
1826 continue
1827 }
David Benjamin5ecb88b2016-10-04 17:51:35 -04001828 if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
1829 continue
David Benjamin83c0bc92014-08-04 01:23:53 -04001830 }
Adam Langley95c29f32014-06-20 12:00:00 -07001831 return candidate
1832 }
1833 }
1834
1835 return nil
1836}
David Benjaminf93995b2015-11-05 18:23:20 -05001837
1838func isTLS12Cipher(id uint16) bool {
1839 for _, cipher := range cipherSuites {
1840 if cipher.id != id {
1841 continue
1842 }
1843 return cipher.flags&suiteTLS12 != 0
1844 }
1845 // Unknown cipher.
1846 return false
1847}
David Benjamin65ac9972016-09-02 21:35:25 -04001848
1849func isGREASEValue(val uint16) bool {
David Benjamin3c6a1ea2016-09-26 18:30:05 -04001850 return val&0x0f0f == 0x0a0a && val&0xff == val>>8
David Benjamin65ac9972016-09-02 21:35:25 -04001851}